问:
C#: Remove Excess Text From String
Okay, so after looking around here on SO, I have found a solution that meets about 95% of my requirement, although I believe it may need to be redone at this point.

ISSUE

Say I have a value range supplied as "1000 - 1009 ABC1 ABC SOMETHING ELSE" where I just need the 1000 - 1009 part. I need to be able to remove excess characters from the string supplied, even if they truly are accepted characters, but only if they are part of secondary strings with text. (Sorry if that description seems odd, my mind isn't full power today.)

CURRENT SOLUTION

I currently have a simple method utilizing Linq to return only accepted characters, however this will return "1000 - 10091" which is not the range I am needing. I've thought about looping through the strings individual characters and comparing to previous characters as I go using IsDigit and IsLetter to my advantage, but then comes the issue of replacing the unacceptable characters or removing them. I think if I gave it a day or two I could figure it out with a clear mind, but it needs to be done by the end of the day, and I am banging my head against the keyboard.

```<code>void RemoveExcessText(ref string val) {
    string allowedChars = "0123456789-+>";
    val = new string(val.Where(c => allowedChars.Contains(c)).ToArray());
}

// Alternatively?
char previousChar = ' ';
for (int i = 0; i < val.Length; i++) {
    if (char.IsLetter(val[i])) {
        previousChar = val[i];
        val.Remove(i, 1);
    } else if (char.IsDigit(val[i])) {
        if (char.IsLetter(previousChar)) {
            val.Remove(i, 1);
        }
    }
}
</code>```

But how do I calculate white space and leave in the +, -, and > charactrers? I am losing my mind on this one today.

答:
You could match this with a regular expression.  \d{1,4} means match a decimal digit at least once up to 4 times.  Followed by space, hyphen, space, and 1 to 4 digits again, then anything else.  Only the part inside parenthesis is output in your results.

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

public class Program
{
    public static void Main()
    {
        var pattern = @"(^\d{1,4} - \d{1,4}).*";
        string input = ("1000 - 1009 ABC1 ABC SOMETHING ELSE");
        string replacement = "$1";
        string result = Regex.Replace(input, pattern, replacement);
        Console.WriteLine(result);
    }
}
</code>```

https://dotnetfiddle.net/cZGlX4

Title: C#: Remove Excess Text From String

Body:
Okay, so after looking around here on SO, I have found a solution that meets about 95% of my requirement, although I believe it may need to be redone at this point.

ISSUE

Say I have a value range supplied as "1000 - 1009 ABC1 ABC SOMETHING ELSE" where I just need the 1000 - 1009 part. I need to be able to remove excess characters from the string supplied, even if they truly are accepted characters, but only if they are part of secondary strings with text. (Sorry if that description seems odd, my mind isn't full power today.)

CURRENT SOLUTION

I currently have a simple method utilizing Linq to return only accepted characters, however this will return "1000 - 10091" which is not the range I am needing. I've thought about looping through the strings individual characters and comparing to previous characters as I go using IsDigit and IsLetter to my advantage, but then comes the issue of replacing the unacceptable characters or removing them. I think if I gave it a day or two I could figure it out with a clear mind, but it needs to be done by the end of the day, and I am banging my head against the keyboard.

void RemoveExcessText(ref string val) {
    string allowedChars = "0123456789-+>";
    val = new string(val.Where(c => allowedChars.Contains(c)).ToArray());
}

// Alternatively?
char previousChar = ' ';
for (int i = 0; i < val.Length; i++) {
    if (char.IsLetter(val[i])) {
        previousChar = val[i];
        val.Remove(i, 1);
    } else if (char.IsDigit(val[i])) {
        if (char.IsLetter(previousChar)) {
            val.Remove(i, 1);
        }
    }
}

But how do I calculate white space and leave in the +, -, and > charactrers? I am losing my mind on this one today.

Body:
You could match this with a regular expression.  \d{1,4} means match a decimal digit at least once up to 4 times.  Followed by space, hyphen, space, and 1 to 4 digits again, then anything else.  Only the part inside parenthesis is output in your results.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var pattern = @"(^\d{1,4} - \d{1,4}).*";
        string input = ("1000 - 1009 ABC1 ABC SOMETHING ELSE");
        string replacement = "$1";
        string result = Regex.Replace(input, pattern, replacement);
        Console.WriteLine(result);
    }
}

https://dotnetfiddle.net/cZGlX4


来源: stackexchange

问:
Access Many-to-Many field within Django template
I have the following blog project :

models.py:

```<code>from django.db import models
from django.utils import timezone

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)
    categories = models.ManyToManyField('Category')

    def __str__(self):
        return self.title

class Category(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

    # Change the name in Admin from categorys to categories
    class Meta:
        verbose_name_plural = "categories"
</code>```

views.py:

```<code>from django.shortcuts import render
from .models import Post, Category, Comment

def getPosts(request):

    posting = Post.objects.all().order_by('-pub_date')
    categories = Category.objects.all()

    context = {
        'posting':posting,
        'categories':categories,
              }
    return render(request, 'posts/getPosts.html', context)
</code>```

getPosts.html template :

```<code>    {% if posting %}
        {% for article in posting %}
            <h3>{{article.title}}</h3>
            <ul>{{article.body}}</ul>
            <ul>Posted : {{article.pub_date}}</ul>

            <ul>
                <em>Found in category : </em>

                {{ article.categories }}
                {{ article.categories.all }}
                {% for category in categories %}
                    {{category.title}}
                {% endfor %}
            </ul>
        {% endfor %}
    {% endif %}
</code>```

I have three posts, which all display properly, but

{{article.categories}} is giving me:

```<code>posts.Category.None
</code>```

{{article.categories.all}} gives me

```<code>QuerySet [<Category: Diving>]
</code>```

And the second loop outputs the list of all categories, which I expected as just a test run:

```<code>Kit & Packing Diving Places Tips Private
</code>```

I am trying to simply pull through the category name for each post, which has been selected in the admin panel and saved through the admin panel.

I have tried what feels like a thousand different suggestions, such as changing the view to category = post.category_set.all(), and have been researching this for days now, but am getting no-where.

答:
You already have the right answer; article.categories.all, which you should loop over.

```<code>{% for category in article.categories.all %}
    {{category.title}}
{% endfor %}
</code>```

You don't need the categories value in the view at all.

ContentLicense: CC BY-SA 3.0

Body:
I have the following blog project :

models.py:

from django.db import models
from django.utils import timezone

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)
    categories = models.ManyToManyField('Category')

    def __str__(self):
        return self.title

class Category(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

    # Change the name in Admin from categorys to categories
    class Meta:
        verbose_name_plural = "categories"

views.py:

from django.shortcuts import render
from .models import Post, Category, Comment

def getPosts(request):

    posting = Post.objects.all().order_by('-pub_date')
    categories = Category.objects.all()

    context = {
        'posting':posting,
        'categories':categories,
              }
    return render(request, 'posts/getPosts.html', context)

getPosts.html template :

    {% if posting %}
        {% for article in posting %}

{{article.title}}

{{article.body}}

Posted : {{article.pub_date}}

                Found in category :

                {{ article.categories }}
                {{ article.categories.all }}
                {% for category in categories %}
                    {{category.title}}
                {% endfor %}

        {% endfor %}
    {% endif %}

I have three posts, which all display properly, but

{{article.categories}} is giving me:

posts.Category.None

{{article.categories.all}} gives me

QuerySet [<Category: Diving>]

And the second loop outputs the list of all categories, which I expected as just a test run:

Kit & Packing Diving Places Tips Private

I am trying to simply pull through the category name for each post, which has been selected in the admin panel and saved through the admin panel.

I have tried what feels like a thousand different suggestions, such as changing the view to category = post.category_set.all(), and have been researching this for days now, but am getting no-where.

Body:
You already have the right answer; article.categories.all, which you should loop over.

{% for category in article.categories.all %}
    {{category.title}}
{% endfor %}

You don't need the categories value in the view at all.


问:
How to create a class which uses member functions defined in another class C++
I'm new to object oriented programming and am struggling a bit with how best to write classes.

I am trying to abstract the idea of sorting to objects that are not just lists of numbers. I have an abstract base class, SortableContainer, which contains all the necessary virtual functions for comparing and swapping elements, along with some overloaded operators. I then have two classes derived from that, MVector and CoordinateArray. Both of these derived classes have proper definitions for all the virtual functions in the base class. Everything up to this point has worked just fine. MVector just stores vector-like objects and CoordinateArray stores vectors of coordinates onto which a notion of 'less than' has been defined.

My problem now is that I have created a new class, Life, which I want to use to implement the game of life using a CoordinateArray object to store the alive cells. The outline of my Life class looks like this:

```<code>class Life
{
public:
   CoordinateArray LiveCells;

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

When I create a Life object and initialise it with the coordinates of some alive cells, none of the member functions defined in the CoordinateArray derived class will work. How can I fix this? Do I have to derive the Life class from the SortableContainer class and then override all the pure virtual functions? Any help or direction to help will be much appreciated.

答: It would be useful to see the declaration of CoordinateArray. However, I suspect you need to make public methods in CoordinateArray. If the methods are declared private (i.e., they come after private: in your class declaration), then they can only be used inside the class's own scope. If they're declared public (underneath public:), then they can be used in any scope. (As a sidenote, there is one other classification, protected, which means they can be used by the class and any of its subclasses.)

Body:
I'm new to object oriented programming and am struggling a bit with how best to write classes.

I am trying to abstract the idea of sorting to objects that are not just lists of numbers. I have an abstract base class, SortableContainer, which contains all the necessary virtual functions for comparing and swapping elements, along with some overloaded operators. I then have two classes derived from that, MVector and CoordinateArray. Both of these derived classes have proper definitions for all the virtual functions in the base class. Everything up to this point has worked just fine. MVector just stores vector-like objects and CoordinateArray stores vectors of coordinates onto which a notion of 'less than' has been defined.

My problem now is that I have created a new class, Life, which I want to use to implement the game of life using a CoordinateArray object to store the alive cells. The outline of my Life class looks like this:

class Life
{
public:
   CoordinateArray LiveCells;

   Life();
};

When I create a Life object and initialise it with the coordinates of some alive cells, none of the member functions defined in the CoordinateArray derived class will work. How can I fix this? Do I have to derive the Life class from the SortableContainer class and then override all the pure virtual functions? Any help or direction to help will be much appreciated.


问:
Why does solr add new document while updating?
```<code>curl 'http://localhost/solr/collection/update?commit=true'
-H 'Content-type:application/json'
-d
'[
  {
    "id":"11111",
    "price":{"set":1000}
  }
]'
</code>```

If id:11111 exists, price value is updated. It's ok.

If id:11111 doesn't exist, new document is created in solr index. This behavior is not desirable. I expect error with some text like: document you tried to update does not exist.
I cannot understand what is wrong.

Solr version: 4.8.0.

Part of schema.xml:

```<code><field name="id" type="string"  indexed="true" stored="true" required="true"/>
<uniqueKey>id</uniqueKey>
</code>```

答:
that is how the current implementation of Atomic updates seems to work. I concur it might be desirable to get an error...You should raise the issue in the user mailing list, and see what commiters think, maybe they agree with you that an error should be raised, they'll ask you to open a jira then.

Oh, just noticed the 4.8 version, that is quite old, can you by any chance test the behaviour in current versions?

Body:
curl 'http://localhost/solr/collection/update?commit=true'
-H 'Content-type:application/json'
-d
'[
  {
    "id":"11111",
    "price":{"set":1000}
  }
]'

If id:11111 exists, price value is updated. It's ok.

If id:11111 doesn't exist, new document is created in solr index. This behavior is not desirable. I expect error with some text like: document you tried to update does not exist.
I cannot understand what is wrong.

Solr version: 4.8.0.

Part of schema.xml:

<field name="id" type="string"  indexed="true" stored="true" required="true"/>
<uniqueKey>id</uniqueKey>


问:
What platforms do Google Protocol Buffers support?
Google state that:

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data

I searched for an explicit list of platforms and/or operating systems officially supported by Protocol Buffers but I couldn't find it. Ironically the closest thing I found was the following information in the Wikipedia page:

Operating system: Any

Platforms: Cross-platform

Is it safe to say that Protocol Buffers support any platform/OS?

答:
Operating system is going to be any mainstream OS. If you're running something esoteric, you might get the same problems that you get with anything else.

Platform is similar; google offer support for a range of platforms, and a much wider list is provided by community owned projects. A list is here: https://github.com/google/protobuf/blob/master/docs/third_party.md

Ultimately, the wire specification is documented and doesn't depend on OS or platform, so worst case if you're using a custom language on a custom OS, then you could still implement your own decoder as long as that language has some mechanism to talk arbitrary binary data or can interop to one of the other prebuilt libraries.


问:
Javascript Interval functions not working
I am currently working on a clicker game for a game dev class I attend, and I can not figure out why my interval functions refuse to work.

What I am trying to achieve with this:

every 100 milliseconds a variable will increase by a number, multiplied by another variable, lets use 10, and i for example.

The code I tried:

```<code>var interval = setInterval( increment, 100);

function increment(){
  money += 10 * i;
  document.getElementById("money").innerHTML = money;
  document.getElementById("i").innerHTML = i;
}
</code>```

This is refusing to work, and I was wondering if it was a problem with defining the variable, or just with the syntax.

Any suggestion?

答:
You have to define your two variables "money" and "i" with a default value.
Currently you are trying to increment a variable undefined with an undefined value ..
Do like bellow : </p>

```<code>var interval = setInterval( increment, 100);
var money = 0
var i = 10;
function increment(){
 money += 10 * i
 document.getElementById("money").innerHTML = money;
 document.getElementById("i").innerHTML = i;
}
</code>```

Body:
I am currently working on a clicker game for a game dev class I attend, and I can not figure out why my interval functions refuse to work.

What I am trying to achieve with this:

every 100 milliseconds a variable will increase by a number, multiplied by another variable, lets use 10, and i for example.

The code I tried:

var interval = setInterval( increment, 100);

function increment(){
  money += 10 * i;
  document.getElementById("money").innerHTML = money;
  document.getElementById("i").innerHTML = i;
}

This is refusing to work, and I was wondering if it was a problem with defining the variable, or just with the syntax.

Any suggestion?

Body:
You have to define your two variables "money" and "i" with a default value.
Currently you are trying to increment a variable undefined with an undefined value ..
Do like bellow :

var interval = setInterval( increment, 100);
var money = 0
var i = 10;
function increment(){
 money += 10 * i
 document.getElementById("money").innerHTML = money;
 document.getElementById("i").innerHTML = i;
}


问:
Excel Email Database Replace function
I have an Excel database of email addresses and names. I need to extract the domain name from the email address, and put it into a new column.

i.e:

```<code>col a: joeschmoe@email.com
col b: www.email.com
</code>```

Where col a is what I currently have, and col b is my goal. I basically need to delete anything at and before the @ symbol, and replace with www..

Is there any way I can do this in Excel in an automated process? I am using Excel 2008 for Mac.

答:
put this in column B1 and drag all the way down:</p>

```<code>="www." & MID(A1,FIND("@",A1)+1,LEN(A1))
</code>```

Title: Excel Email Database Replace function

Body:
I have an Excel database of email addresses and names. I need to extract the domain name from the email address, and put it into a new column.

i.e:

col a: joeschmoe@email.com
col b: www.email.com

Where col a is what I currently have, and col b is my goal. I basically need to delete anything at and before the @ symbol, and replace with www..

Is there any way I can do this in Excel in an automated process? I am using Excel 2008 for Mac.

Body:
put this in column B1 and drag all the way down:

="www." & MID(A1,FIND("@",A1)+1,LEN(A1))

ContentLicense: CC BY-SA 2.5


问:
What is the difference between router.METHOD() and router.route() methods in Express
I've seen code written both ways.

```<code>router.get(path, callback)
</code>```

and

```<code>router.route(path).get(callback)
</code>```

From the surrounding code they look equivalent.  The docs are here:

router.route

and

router.METHOD

where method can be get, post, etc.

Why are there two ways to do this?  I've read the docs and they did not help so much.

答:
router.METHOD(path)

router.methods() provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST

```<code>router.get(path,callback);
</code>```

router.route(path)

Returns an instance of a single route which you can then use to handle HTTP methods.

Also it avoids duplicate route naming and thus typing errors.

Thus using the instance you can define all http handlers at one go. like

```<code>router.route(path).get(callback).put(callback).post(callback).delete(callback);
</code>```

Body:
I've seen code written both ways.

router.get(path, callback)

and

router.route(path).get(callback)

From the surrounding code they look equivalent.  The docs are here:

router.route

and

router.METHOD

where method can be get, post, etc.

Why are there two ways to do this?  I've read the docs and they did not help so much.

Body:
router.METHOD(path)

router.methods() provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST

router.get(path,callback);

router.route(path)

Returns an instance of a single route which you can then use to handle HTTP methods.

Also it avoids duplicate route naming and thus typing errors.

Thus using the instance you can define all http handlers at one go. like

router.route(path).get(callback).put(callback).post(callback).delete(callback);


问:
Symfony 2.8: CollectionType - do not delete old entries
I want to submit a form, each time I want a new entries being added to a database, but do not delete old ones.

Let's say I have an inventory entity, which contains a serial numbers collection.

Inventory form builder

```<code>$builder
    ->add('quantity', IntegerType::class)
    ->add('inventorySerialNumbers', CollectionType::class, array(
        'entry_type' => InventorySerialNumberType::class,
        'allow_add' => true,
        'allow_delete' => false,
        'by_reference' => false,
    ))
;
</code>```

Inventory serial number property:

```<code>/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="InventorySerialNumber", mappedBy="inventory", cascade={"persist"})
 */
protected $inventorySerialNumbers;
</code>```

So, I want to create a new inventory - I send a quantity and 2 inventorySerialNumbers and all data is being added correctly. But if I want to add one more entry, I will send a quantity 1 and one inventorySerialNumbers  item, as a result I will get only one latest entry stored in the database.

Seems that Symfony ignoring cascade={"persist"} and 'allow_delete' => false

答:
A Form action will add or modify an entity. In this case, I think you're overwriting an entity instead of creating a new one (option 1) or modifying an existing one (option 2).

Option 1: add new items only

Create a simple form that will add a Inventory. A user will fill in the form and creates a new Inventory. After submitting the form, you will end up with two records in your database. If you want to know how many items you have, you have to sum up those values.

Option 2: allow users to modify items

If you want to allow your users to delete serial numbers or lower the quantity, you'll havo to create a editAction. Unfortunately I couldn't find a good example on Symfony's website, but here are two recources you should look at:

Easy Edit Form

Generating a CRUD Controller Based on a Doctrine Entity

Body:
I want to submit a form, each time I want a new entries being added to a database, but do not delete old ones.

Let's say I have an inventory entity, which contains a serial numbers collection.

Inventory form builder

$builder
    ->add('quantity', IntegerType::class)
    ->add('inventorySerialNumbers', CollectionType::class, array(
        'entry_type' => InventorySerialNumberType::class,
        'allow_add' => true,
        'allow_delete' => false,
        'by_reference' => false,
    ))
;

Inventory serial number property:

/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="InventorySerialNumber", mappedBy="inventory", cascade={"persist"})
 */
protected $inventorySerialNumbers;

So, I want to create a new inventory - I send a quantity and 2 inventorySerialNumbers and all data is being added correctly. But if I want to add one more entry, I will send a quantity 1 and one inventorySerialNumbers  item, as a result I will get only one latest entry stored in the database.

Seems that Symfony ignoring cascade={"persist"} and 'allow_delete' => false


问:
text-overflow ellipsis is not working properly
I recently changed my news ticker to a CSS version.  My problem is the I am trying to use the "text-overflow: ellipsis" and it just is not working.  I have tried placing the styles everywhere without success.  Can anyone help me?  I have created a basic codepen.  The class in GREEN is my problem.

https://codepen.io/lepew/pen/pdwNaL

body {
  background-color: black;
}

#page_Wrap {
  /* Flexbox setup */
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  xflex-flow: column nowrap;
  -webkit-flex-flow: column;
  -moz-flex-flow: column;
  -ms-flex-flow: column;
  flex-flow: column;
  /* Basic styling */
  width: 94%;
  margin: 0 auto;
  max-width: 1280px;
  border: 1px solid red;
}

header {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-flex: 0;
  -moz-box-flex: 0;
  -ms-flex: 0;
  -webkit-flex: 0;
  flex: 0;
  min-height: 100px;
}

#head_Logo,
#head_Note {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 77px;
  flex: 0 0 77px;
  width: 77px;
  height: 90px;
  border: 1px solid yellow;
}

#head_Area {
  -webkit-box-flex: 2;
  -ms-flex: 2;
  flex: 2;
  -webkit-flex-flow: column nowrap;
  -moz-flex-flow: column nowrap;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  min-width: 0;
}

.wrap_News {
  height: 45px;
  border: 1px solid lime;
}

.news_Area {
  color: #0FF;
  position: absolute;
  overflow: hidden;
  xmargin-right: 115px;
  xright: 0;
  xleft: 116px;
  opacity: 0;
  -moz-opacity: 0;
  filter: alpha(opacity=0);
}

.news_Text {
  padding: 0 5px;
  font: bold 18px Arial, Helvetica, sans-serif;
  height: 45px;
  overflow: hidden;
  line-height: 45px;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.wrap_News:hover .news_Area {
  -webkit-animation-play-state: paused;
  -moz-animation-play-state: paused;
  -o-animation-play-state: paused;
  animation-play-state: paused;
}

.news_Area:nth-child(1) {
  -webkit-animation: cycle 15s 0s infinite linear;
  -moz-animation: cycle 15s 0s infinite linear;
  -o-animation: cycle 15s 0s infinite linear;
  animation: cycle 15s 0s infinite linear;
}

.news_Area:nth-child(2) {
  -webkit-animation: cycle 15s 5s infinite linear;
  -moz-animation: cycle 15s 5s infinite linear;
  -o-animation: cycle 15s 5s infinite linear;
  animation: cycle 15s 5s infinite linear;
}

.news_Area:nth-child(3) {
  -webkit-animation: cycle 15s 10s infinite linear;
  -moz-animation: cycle 15s 10s infinite linear;
  -o-animation: cycle 15s 10s infinite linear;
  animation: cycle 15s 10s infinite linear;
}

@keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-moz-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-webkit-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-ms-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-o-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page_Wrap">

  <header>
    <div id="head_Logo">
    </div>
    <!-- end of #head_Logo -->

    <div id="head_Area">

      <div class="wrap_News">
        <div class="news_Area">
          <div class="news_Text">This is top secret.  Read more</div>
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">
            This is to see what happens if a lot of text is placed here and is just blah blah blah blah blah blah.
          </div>
          <!-- end of #wrap_News -->
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">Part 3 here</div>
        </div>
        <!-- end of #news_Area -->
      </div>
      <!-- end of #wrap_News -->

    </div>
    <!-- end of #head_Area -->
    <div id="head_Note">
      <!--  HERE  -->
    </div>
    <!-- end of #head_Note -->
  </header>
  <!-- end of #header -->

</div>
<!-- end of #page_Wrap --></code>```

答:
Using this css might help</p>

```<code>.wrap_News {
    height: 90px;
    border: 1px solid lime;
}
.news_Text {
    padding: 0 5px;
    font: bold 18px Arial, Helvetica, sans-serif;
    overflow: hidden;
    line-height: 100px;
    white-space: nowrap;
    text-overflow: ellipsis;
    min-height: 100px;
}
</code>```

Body:
I recently changed my news ticker to a CSS version.  My problem is the I am trying to use the "text-overflow: ellipsis" and it just is not working.  I have tried placing the styles everywhere without success.  Can anyone help me?  I have created a basic codepen.  The class in GREEN is my problem.

https://codepen.io/lepew/pen/pdwNaL

body {
  background-color: black;
}

#page_Wrap {
  /* Flexbox setup */
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  xflex-flow: column nowrap;
  -webkit-flex-flow: column;
  -moz-flex-flow: column;
  -ms-flex-flow: column;
  flex-flow: column;
  /* Basic styling */
  width: 94%;
  margin: 0 auto;
  max-width: 1280px;
  border: 1px solid red;
}

header {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-flex: 0;
  -moz-box-flex: 0;
  -ms-flex: 0;
  -webkit-flex: 0;
  flex: 0;
  min-height: 100px;
}

#head_Logo,
#head_Note {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 77px;
  flex: 0 0 77px;
  width: 77px;
  height: 90px;
  border: 1px solid yellow;
}

#head_Area {
  -webkit-box-flex: 2;
  -ms-flex: 2;
  flex: 2;
  -webkit-flex-flow: column nowrap;
  -moz-flex-flow: column nowrap;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  min-width: 0;
}

.wrap_News {
  height: 45px;
  border: 1px solid lime;
}

.news_Area {
  color: #0FF;
  position: absolute;
  overflow: hidden;
  xmargin-right: 115px;
  xright: 0;
  xleft: 116px;
  opacity: 0;
  -moz-opacity: 0;
  filter: alpha(opacity=0);
}

.news_Text {
  padding: 0 5px;
  font: bold 18px Arial, Helvetica, sans-serif;
  height: 45px;
  overflow: hidden;
  line-height: 45px;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.wrap_News:hover .news_Area {
  -webkit-animation-play-state: paused;
  -moz-animation-play-state: paused;
  -o-animation-play-state: paused;
  animation-play-state: paused;
}

.news_Area:nth-child(1) {
  -webkit-animation: cycle 15s 0s infinite linear;
  -moz-animation: cycle 15s 0s infinite linear;
  -o-animation: cycle 15s 0s infinite linear;
  animation: cycle 15s 0s infinite linear;
}

.news_Area:nth-child(2) {
  -webkit-animation: cycle 15s 5s infinite linear;
  -moz-animation: cycle 15s 5s infinite linear;
  -o-animation: cycle 15s 5s infinite linear;
  animation: cycle 15s 5s infinite linear;
}

.news_Area:nth-child(3) {
  -webkit-animation: cycle 15s 10s infinite linear;
  -moz-animation: cycle 15s 10s infinite linear;
  -o-animation: cycle 15s 10s infinite linear;
  animation: cycle 15s 10s infinite linear;
}

@keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-moz-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-webkit-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-ms-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-o-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

This is top secret.  Read more

            This is to see what happens if a lot of text is placed here and is just blah blah blah blah blah blah.

Part 3 here

Body:
Using this css might help

.wrap_News {
    height: 90px;
    border: 1px solid lime;
}
.news_Text {
    padding: 0 5px;
    font: bold 18px Arial, Helvetica, sans-serif;
    overflow: hidden;
    line-height: 100px;
    white-space: nowrap;
    text-overflow: ellipsis;
    min-height: 100px;
}


问:
Non-trivial geolocation query db caching
I first have to say that I really am a rookie in caching, so please do elaborate on any explanation and bear with me if my question is stupid.

I have a server with pretty limited resources, so I'm really interested in caching db-queries as effectively as I can. My issue is this:

I have a MYSQL DB with a table for geolocations, there are columns (lat and lng) - I only indexed lat since a query will always have both lat and lng, and only 1 index can be effectively used to my understanding (?).

The queries are very alternating in coordinates like

```<code>select lat, lng
where lat BETWEEN 123123123 AND 312412312 AND lng BETWEEN 235124231 AND 34123124
</code>```

where the long numbers that are the boundaries of the BETWEEN query are constantly changing, so IS there a way to cache this the smart way, so that the cache doesn't have to be a complete query match, but the values of previous between queries can be held against a new to save some db resources?

I hope you get my question - if not please ask.

Thank you so much

Update 24/01/2011

Now that I've gotten some response I want to know what the most efficient way of querying would be.

Would the Between query with int values execute faster or

would the radius calculation with point values execute faster

if 1. then how would the optimal index look like?

答: I think to do significantly better you'll need to characterize your data better.  If you've got data that's uniformly distributed across longitude and latitude, with no correlation, and if your queries are similarly distributed and independent - you're stuck.  But if your data or your queries cluster in interesting ways, you may find that you can introduce new columns that make at least some queries quicker.  If most queries happen within some hard range, maybe you can set that data aside - add a flag, link it to some other table, even put the frequently-requested data into its own table.  Can you tell us any more about the data?</p>

Body:
I first have to say that I really am a rookie in caching, so please do elaborate on any explanation and bear with me if my question is stupid.

I have a server with pretty limited resources, so I'm really interested in caching db-queries as effectively as I can. My issue is this:

I have a MYSQL DB with a table for geolocations, there are columns (lat and lng) - I only indexed lat since a query will always have both lat and lng, and only 1 index can be effectively used to my understanding (?).

The queries are very alternating in coordinates like

select lat, lng
where lat BETWEEN 123123123 AND 312412312 AND lng BETWEEN 235124231 AND 34123124

where the long numbers that are the boundaries of the BETWEEN query are constantly changing, so IS there a way to cache this the smart way, so that the cache doesn't have to be a complete query match, but the values of previous between queries can be held against a new to save some db resources?

I hope you get my question - if not please ask.

Thank you so much

Update 24/01/2011

Now that I've gotten some response I want to know what the most efficient way of querying would be.

Would the Between query with int values execute faster or

would the radius calculation with point values execute faster

if 1. then how would the optimal index look like?


问:
What is the fastest way to compute an RBF kernel in python?
I would like to compute an RBF or "Gaussian" kernel for a data matrix X with n rows and d columns. The resulting square kernel matrix is given by:

```<code>K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)
</code>```

var and gamma are scalars.

What is the fastest way to do this in python?

答:
I am going to present four different methods for computing such a kernel, followed by a comparison of their run-time.

Using pure numpy

Here, I use the fact that ||x-y||^2 = ||x||^2 + ||y||^2 - 2 * x^T * y.

import numpy as np

X_norm = np.sum(X ** 2, axis = -1)
K = var * np.exp(-gamma * (X_norm[:,None] + X_norm[None,:] - 2 * np.dot(X, X.T)))
```

<h1>Using numexpr</h1>

<p><code>numexpr</code> is a python package that allows for efficient and parallelized array operations on numpy arrays. We can use it as follows to perform the same computation as above:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
import numexpr as ne

X_norm = np.sum(X ** 2, axis = -1)
K = ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
        'A' : X_norm[:,None],
        'B' : X_norm[None,:],
        'C' : np.dot(X, X.T),
        'g' : gamma,
        'v' : var
})
</code>```

Using scipy.spatial.distance.pdist

We could also use scipy.spatial.distance.pdist to compute a non-redundant array of pairwise squared euclidean distances, compute the kernel on that array and then transform it to a square matrix:

import numpy as np
from scipy.spatial.distance import pdist, squareform

K = squareform(var * np.exp(-gamma * pdist(X, 'sqeuclidean')))
K[np.arange(K.shape[0]), np.arange(K.shape[1])] = var
```

<h1>Using <code>sklearn.metrics.pairwise.rbf_kernel</code></h1>

<p><code>sklearn</code> provides a built-in method for direct computation of an RBF kernel:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
from sklearn.metrics.pairwise import rbf_kernel

K = var * rbf_kernel(X, gamma = gamma)
</code>```

Run-time comparison

I use 25,000 random samples of 512 dimensions for testing and perform experiments on an Intel Core i7-7700HQ (4 cores @ 2.8 GHz). More precisely:

X = np.random.randn(25000, 512)
gamma = 0.01
var = 5.0
```

<p>Each method is run 7 times and the mean and standard deviation of the time per execution is reported.</p>

<pre class="lang-none prettyprint-override"><code>|               Method                |       Time        |
|-------------------------------------|-------------------|
| numpy                               | 24.2 s ± 1.06 s   |
| numexpr                             | 8.89 s ± 314 ms   |
| scipy.spatial.distance.pdist        | 2min 59s ± 312 ms |
| sklearn.metrics.pairwise.rbf_kernel | 13.9 s ± 757 ms   |
</code>```

First of all, scipy.spatial.distance.pdist is surprisingly slow.

numexpr is almost 3 times faster than the pure numpy method, but this speed-up factor will vary with the number of available CPUs.

sklearn.metrics.pairwise.rbf_kernel is not the fastest way, but only a bit slower than numexpr.

Body:
I would like to compute an RBF or "Gaussian" kernel for a data matrix X with n rows and d columns. The resulting square kernel matrix is given by:

K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2)

var and gamma are scalars.

What is the fastest way to do this in python?

Body:
I am going to present four different methods for computing such a kernel, followed by a comparison of their run-time.

Using pure numpy

Here, I use the fact that ||x-y||^2 = ||x||^2 + ||y||^2 - 2 * x^T * y.

import numpy as np

X_norm = np.sum(X ** 2, axis = -1)
K = var * np.exp(-gamma * (X_norm[:,None] + X_norm[None,:] - 2 * np.dot(X, X.T)))

Using numexpr

numexpr is a python package that allows for efficient and parallelized array operations on numpy arrays. We can use it as follows to perform the same computation as above:

import numpy as np
import numexpr as ne

X_norm = np.sum(X ** 2, axis = -1)
K = ne.evaluate('v * exp(-g * (A + B - 2 * C))', {
        'A' : X_norm[:,None],
        'B' : X_norm[None,:],
        'C' : np.dot(X, X.T),
        'g' : gamma,
        'v' : var
})

Using scipy.spatial.distance.pdist

We could also use scipy.spatial.distance.pdist to compute a non-redundant array of pairwise squared euclidean distances, compute the kernel on that array and then transform it to a square matrix:

import numpy as np
from scipy.spatial.distance import pdist, squareform

K = squareform(var * np.exp(-gamma * pdist(X, 'sqeuclidean')))
K[np.arange(K.shape[0]), np.arange(K.shape[1])] = var

Using sklearn.metrics.pairwise.rbf_kernel

sklearn provides a built-in method for direct computation of an RBF kernel:

import numpy as np
from sklearn.metrics.pairwise import rbf_kernel

K = var * rbf_kernel(X, gamma = gamma)

Run-time comparison

I use 25,000 random samples of 512 dimensions for testing and perform experiments on an Intel Core i7-7700HQ (4 cores @ 2.8 GHz). More precisely:

X = np.random.randn(25000, 512)
gamma = 0.01
var = 5.0

Each method is run 7 times and the mean and standard deviation of the time per execution is reported.

|               Method                |       Time        |
|-------------------------------------|-------------------|
| numpy                               | 24.2 s ± 1.06 s   |
| numexpr                             | 8.89 s ± 314 ms   |
| scipy.spatial.distance.pdist        | 2min 59s ± 312 ms |
| sklearn.metrics.pairwise.rbf_kernel | 13.9 s ± 757 ms   |

First of all, scipy.spatial.distance.pdist is surprisingly slow.

numexpr is almost 3 times faster than the pure numpy method, but this speed-up factor will vary with the number of available CPUs.

sklearn.metrics.pairwise.rbf_kernel is not the fastest way, but only a bit slower than numexpr.


问:
elasticsearch time query for hour of the day
I am using elasticsearch python client.

I have a date range field in my index. I want docs between 12pm to 2pm. So, This is the query I wrote,

```<code>query = {"query":"filter": [{"range" : { "status_time_frame" : {"gte" : "10/11/2017","lte" : "13/11/2017", "relation":"within"}}}],{"script":{"source": "doc.status_time_frame.status_time_frame.getHourOfDay() >= min && doc.status_time_frame.status_time_frame.getHourOfDay() <= max","params": {"min":12,"max":14}}}}
</code>```

But it is giving me syntax error when I try to run it.

```<code>  File "vehicle-report-query-elastic.py", line 3
    query = {"query":{"filter": [{"range" : { "status_time_frame" : {"gte" : "10/11/2017","lte" : "13/11/2017", "relation":"within"}}}],{"script":{"source": "doc.status_time_frame.status_time_frame.getHourOfDay() >= min && doc.status_time_frame.status_time_frame.getHourOfDay() <= max","params": {"min":12,"max":14}}}}}

                                                                                ^
SyntaxError: invalid syntax
</code>```

What am I doing wrong?

答:
The correct query should look like this:</p>

```<code>{
  "query": {
    "filter": [
      {
        "range": {
          "status_time_frame": {
            "gte": "10/11/2017",
            "lte": "13/11/2017"
          }
        }
      },
      {
        "script": {
          "source": "doc.status_time_frame.status_time_frame.getHourOfDay() >= min && doc.status_time_frame.status_time_frame.getHourOfDay() <= max",
          "params": {
            "min": 12,
            "max": 14
          }
        }
      }
    ]
  }
}
</code>```

Body:
I am using elasticsearch python client.

I have a date range field in my index. I want docs between 12pm to 2pm. So, This is the query I wrote,

query = {"query":"filter": [{"range" : { "status_time_frame" : {"gte" : "10/11/2017","lte" : "13/11/2017", "relation":"within"}}}],{"script":{"source": "doc.status_time_frame.status_time_frame.getHourOfDay() >= min && doc.status_time_frame.status_time_frame.getHourOfDay() <= max","params": {"min":12,"max":14}}}}

But it is giving me syntax error when I try to run it.

  File "vehicle-report-query-elastic.py", line 3
    query = {"query":{"filter": [{"range" : { "status_time_frame" : {"gte" : "10/11/2017","lte" : "13/11/2017", "relation":"within"}}}],{"script":{"source": "doc.status_time_frame.status_time_frame.getHourOfDay() >= min && doc.status_time_frame.status_time_frame.getHourOfDay() <= max","params": {"min":12,"max":14}}}}}

                                                                                ^
SyntaxError: invalid syntax

What am I doing wrong?

Body:
The correct query should look like this:

{
  "query": {
    "filter": [
      {
        "range": {
          "status_time_frame": {
            "gte": "10/11/2017",
            "lte": "13/11/2017"
          }
        }
      },
      {
        "script": {
          "source": "doc.status_time_frame.status_time_frame.getHourOfDay() >= min && doc.status_time_frame.status_time_frame.getHourOfDay() <= max",
          "params": {
            "min": 12,
            "max": 14
          }
        }
      }
    ]
  }
}


问:
C++ copy constructor double call on member initialization
Consider the below code, where a composing class with another class as its member is being instantiated:

```<code>class CopyAble {
private:
    int mem1;
public:
    CopyAble(int n1) : mem1(n1) {
        cout << "Inside the CopyAble constructor" << endl;
    }
    CopyAble(const CopyAble& obj) {
        cout << "Inside the CopyAble copy constructor" << endl;
        this->mem1 = obj.mem1;
        return *this;
    }

    CopyAble& operator=(const CopyAble& obj) {
        cout << "Inside the  CopyAble assignment constructor" << endl;
        this->mem1 = obj.mem1;
    }
    ~CopyAble() {};
};

class CopyAbleComposer {
    private:
        CopyAble memObj;
    public:
        CopyAbleComposer(CopyAble m1) : memObj(m1) {
            cout << "Composing the composer" << endl;
        }
        ~CopyAbleComposer() {}
};

int main()
{
    CopyAble ca(10);
    CopyAbleComposer cac(ca);
    return 0;
}
</code>```

When I run this, I get the output:

```<code>Inside the CopyAble constructor
Inside the CopyAble copy constructor
Inside the CopyAble copy constructor
Composing the composer
</code>```

Which means that the CopyAble copy constructor is being run twice - once when the CopyAble object is passed into the CopyAbleComposer constructor, and again when the initializer memObj(m1) runs.

Is this an idiomatic use of the copy constructor? It seems very inefficient that the copy constructor runs twice when we try to initialize a member object with a passed-in object of the same type, and it seems like a trap a lot of C++ programmers can easily fall into without realizing it.

EDIT: I don't think this is a duplicate of the question regarding passing a reference into the copy constructor. Here, we are being forced to pass a reference into a regular constructor to avoid duplicate object creation, my question was that is this generally known that class constructors in C++ should have objects passed in by reference to avoid this kind of duplicate copy?

答:
Pass-by-value and the associated copying is a pretty widely known property of C++. Actually, in the past C++ was criticized for this gratuitious copying, which happened silently, was hard to avoid and could lead to decreased performance. This is  humorously mentioned e.g. here:

You accidentally create a dozen instances of yourself and shoot them all in the foot. Providing emergency medical assistance is impossible since you can't tell which are bitwise copies and which are just pointing at others and saying, "That's me, over there."

C++98

When any function/method is declared to receive an argument by value, this sort of copying happens. It doesn't matter if it's a constructor, a "stand-alone" function or a method. To avoid this, use a const reference:

```<code>CopyAbleComposer(const CopyAble& m1) : memObj(m1)
{
    ...
}
</code>```

Note: even if you rearrange your code as below, one copy always remains. This has been a major deficiency in C++ for a long time.

```<code>CopyAbleComposer cac(CopyAble(10)); // initializing mem1 by a temporary object
</code>```

C++11

C++11 introduced move semantics, which replaces the additional copy by a "move" operation, which is supposed to be more efficient than copy: in the common case where an object allocates memory dynamically, "move" only reassigns some pointers, while "copy" allocates and deallocates memory.

To benefit from optimization offered by move semantics, you should undo the "optimization" you maybe did for C++98, and pass arguments by value. In addition, when initializing the mem1 member, you should invoke the move constructor:

```<code>    CopyAbleComposer(CopyAble m1) : memObj(std::move(m1)) {
        cout << "Composing the composer" << endl;
    }
</code>```

Finally, you should implement the move constructor:

```<code>CopyAble(CopyAble&& obj) {
    cout << "Inside the CopyAble move constructor" << endl;
    this->mem1 = obj.mem1;
}
</code>```

Then you should see that the "copy" message doesn't appear, and is replaced by the "move" message.

See this question for more details.

Note: In all these examples, the CopyAble objects are assumed to be much more complex, with copy and move constructors doing non-trivial work (typically, resource management). In modern C++, resource management is considered a separate concern, in the context of separation of concerns. That is, any class that needs a non-default copy or move constructor, should be as small as possible. This is also called the Rule of Zero.

Body:
Consider the below code, where a composing class with another class as its member is being instantiated:

class CopyAble {
private:
    int mem1;
public:
    CopyAble(int n1) : mem1(n1) {
        cout << "Inside the CopyAble constructor" << endl;
    }
    CopyAble(const CopyAble& obj) {
        cout << "Inside the CopyAble copy constructor" << endl;
        this->mem1 = obj.mem1;
        return *this;
    }

    CopyAble& operator=(const CopyAble& obj) {
        cout << "Inside the  CopyAble assignment constructor" << endl;
        this->mem1 = obj.mem1;
    }
    ~CopyAble() {};
};

class CopyAbleComposer {
    private:
        CopyAble memObj;
    public:
        CopyAbleComposer(CopyAble m1) : memObj(m1) {
            cout << "Composing the composer" << endl;
        }
        ~CopyAbleComposer() {}
};

int main()
{
    CopyAble ca(10);
    CopyAbleComposer cac(ca);
    return 0;
}

When I run this, I get the output:

Inside the CopyAble constructor
Inside the CopyAble copy constructor
Inside the CopyAble copy constructor
Composing the composer

Which means that the CopyAble copy constructor is being run twice - once when the CopyAble object is passed into the CopyAbleComposer constructor, and again when the initializer memObj(m1) runs.

Is this an idiomatic use of the copy constructor? It seems very inefficient that the copy constructor runs twice when we try to initialize a member object with a passed-in object of the same type, and it seems like a trap a lot of C++ programmers can easily fall into without realizing it.

EDIT: I don't think this is a duplicate of the question regarding passing a reference into the copy constructor. Here, we are being forced to pass a reference into a regular constructor to avoid duplicate object creation, my question was that is this generally known that class constructors in C++ should have objects passed in by reference to avoid this kind of duplicate copy?

Body:
Pass-by-value and the associated copying is a pretty widely known property of C++. Actually, in the past C++ was criticized for this gratuitious copying, which happened silently, was hard to avoid and could lead to decreased performance. This is  humorously mentioned e.g. here:

You accidentally create a dozen instances of yourself and shoot them all in the foot. Providing emergency medical assistance is impossible since you can't tell which are bitwise copies and which are just pointing at others and saying, "That's me, over there."

C++98

When any function/method is declared to receive an argument by value, this sort of copying happens. It doesn't matter if it's a constructor, a "stand-alone" function or a method. To avoid this, use a const reference:

CopyAbleComposer(const CopyAble& m1) : memObj(m1)
{
    ...
}

Note: even if you rearrange your code as below, one copy always remains. This has been a major deficiency in C++ for a long time.

CopyAbleComposer cac(CopyAble(10)); // initializing mem1 by a temporary object

C++11

C++11 introduced move semantics, which replaces the additional copy by a "move" operation, which is supposed to be more efficient than copy: in the common case where an object allocates memory dynamically, "move" only reassigns some pointers, while "copy" allocates and deallocates memory.

To benefit from optimization offered by move semantics, you should undo the "optimization" you maybe did for C++98, and pass arguments by value. In addition, when initializing the mem1 member, you should invoke the move constructor:

    CopyAbleComposer(CopyAble m1) : memObj(std::move(m1)) {
        cout << "Composing the composer" << endl;
    }

Finally, you should implement the move constructor:

CopyAble(CopyAble&& obj) {
    cout << "Inside the CopyAble move constructor" << endl;
    this->mem1 = obj.mem1;
}

Then you should see that the "copy" message doesn't appear, and is replaced by the "move" message.

See this question for more details.

Note: In all these examples, the CopyAble objects are assumed to be much more complex, with copy and move constructors doing non-trivial work (typically, resource management). In modern C++, resource management is considered a separate concern, in the context of separation of concerns. That is, any class that needs a non-default copy or move constructor, should be as small as possible. This is also called the Rule of Zero.


问:
Text too big in android studio on monitor in windows 10
Im running android studio on a surface 4 pro, which has a higher resolution than my desktop monitor.

When i dock the surface, the text in Android studio is massive, and i cant find a way to make it a more acceptable size.

I would appreciate pointers from anyone who has already faced this.

Thanks

答: You can try to follow this post, if does not work, then do ctrl+alt+s and from Keymap assign a combination of keys to enlarge and diminish the text in a class</p>


问:
Convert mp4 voice file to WAV stream
I used this code to resample file and save it but the file sounds like fast-forward recording:</p>

```<code>using (MediaFoundationReader reader = new MediaFoundationReader(url))
{
    using (ResamplerDmoStream resampledReader = new ResamplerDmoStream(reader, new WaveFormat(16000, 16, 1)))
        {
            using (WaveFileWriter waveWriter = new WaveFileWriter(@"c:\test.wav", resampledReader.WaveFormat))
                {
                    resampledReader.CopyTo(waveWriter);
                }
         }
}
</code>```

答:
I'm not sure what resampling means, but if you need to get the wav from a video, this works...</p>

```<code>using (var video = new MediaFoundationReader(file))
{
    file = TempWav;
    WaveFileWriter.CreateWaveFile(file, video);
}
</code>```

Title: Convert mp4 voice file to WAV stream

Body:
I used this code to resample file and save it but the file sounds like fast-forward recording:

using (MediaFoundationReader reader = new MediaFoundationReader(url))
{
    using (ResamplerDmoStream resampledReader = new ResamplerDmoStream(reader, new WaveFormat(16000, 16, 1)))
        {
            using (WaveFileWriter waveWriter = new WaveFileWriter(@"c:\test.wav", resampledReader.WaveFormat))
                {
                    resampledReader.CopyTo(waveWriter);
                }
         }
}

Body:
I'm not sure what resampling means, but if you need to get the wav from a video, this works...

using (var video = new MediaFoundationReader(file))
{
    file = TempWav;
    WaveFileWriter.CreateWaveFile(file, video);
}


问:
Ignoring directory vs ignoring directory with wildcard
I am working on a project that requires ignoring certain directories. Is there a difference between:

```<code>path/to/mydir/*
</code>```

and this:

```<code>path/to/mydir/
</code>```

The way I understand it, is the upper path ignores all files within mydir including the contents of subdirectories while the non-wildstar example ignores all top level files without including the files within subdirectories.

Is this a correct way of thinking about it? When would I want to use one over the other? I'd like to resolve this confusion once and for all.

Thanks in advance!

答:
Is there a difference between:

```<code>path/to/mydir/*
</code>```

and

```<code>path/to/mydir/
</code>```

Yes.  Git has some funny (as in peculiar) behaviors for entries in .gitignore files.  They start to show up when we use the un-ignore directives, !path/to/mydir/file for instance.

The way I understand it, is the upper path ignores all files within mydir including the contents of subdirectories while the non-wildstar example ignores all top level files without including the files within subdirectories.

Unignore directives show that this isn't quite right.  In particular, if you ignore a directory, you cannot unignore a file within that directory.  However, if you ignore all files and sub-directories within a directory, you can unignore a file within the directory (but not its subdirectories, unless you explicitly un-ignore one of those too).

When would I want to use one over the other?

Use path/to/mydir/* if you want (for whatever reason) Git to open the directory path/to/mydir and read its contents, during status-checking and automatic git adding.  If you don't un-ignore particular paths underneath path/to/mydir, this won't make any difference.

Long description and background

Let's start with the first peculiarity, even though it's not directly part of this question: .gitignore doesn't really mean ignore.  It means something more like:  Don't automatically add, and especially don't complain, about some particular set of files being untracked.  However, it also means, in some cases, Don't even look inside this directory.

Git does not store directories in commits.  A commit stores only files.  When Git goes to extract a commit into a work-tree, it will simply create any directories needed to hold those files.

The files contained within any existing commit are fixed: unchangeable and permanent (well, as permanent as the commit anyway).  Whatever is in the commit, and however those files got inside it, they are there forever (until the commit itself is garbage-collected, if ever).  So they're not really interesting in terms of a .gitignore file.  What's in .gitignore has no effect upon them: they're already committed.

The files that go into a new commit are determined by the contents of the index at the time you run git commit.1  At this point, the contents of a .gitignore file are again irrelevant: if something—some particular path-name and blob-ID pairing—is in the index, it goes into the commit.  If something isn't in the index, it doesn't go into the commit.

This, then, gets us to the definition of an untracked file: An untracked file is a file that is not in the index.  As soon as you git add a file to the index, it's tracked, and as soon as you git rm --cached a file from the index, it's untracked.  Note that this means that the set of tracked files changes!  Untracked is not a permanent thing: it depends on what's in the index right now.

By being "not in" the index, it will be "not in" the commit.  That would make it, in effect, ignored.  But Git complains about it: Hey, this file is untracked!  Don't you want to add it now?  Whine!  Whine!  Enter .gitignore: this gives Git a list of files to avoid complaining about.

But that's for files.  What about directories?

Well, Git doesn't actually store directories, and it doesn't matter if you have an empty directory.  Git won't whine and complain about it, and Git won't store it.  Git will only store files.  But all files live within directories.2  If we could just list the directory, that would make our lives easier.  So we can.

If that were all there was to it, things would be less strange.  But that's not quite the end of the story.  Git tries to be fast, and to be fast, it's important to avoid actually looking at the files that are being stored.  File system operations in general are pretty slow.  So, in the index that Git uses to track files, Git keeps a bunch of secondary information about those files, that it uses to avoid looking at them if it can.  As a result, Git actually only opens and reads directories if it "has to".

Git will open and read the top level directory of the work-tree to find out which files and directories it contains.  For each file, if the file is in the index, all is good: the file is tracked.  If the file isn't in the index, it's untracked, and Git should maybe complain.  Now we check the .gitignore file to find ignore and un-ignore directives.  If the file is ignored, and not subsequently un-ignored, Git will complain:

```<code>?? dir/file
</code>```

(for --short output from git status).

For a directory, though, well, the directory automatically isn't in the index.3  But it could be ignored, and if it is ignored, why then, perhaps we don't have to read it at all.  That would be really fast—so that's what Git does.

If the directory is ignored, Git doesn't bother opening and reading it to find more files.  This means it cannot and will not find any files within that directory, and therefore will never check to see if any of those files are ignored and not later un-ignored.

If the directory itself isn't ignored, Git does open and read it.  It then checks each file and sub-directory, one by one, that lives inside that directory, the same way it did for the top level (using the same code, recursively).  So if you have dir/* ignored, but dir/important subsequently un-ignored, and dir/important exists, Git will discover it, and whine about it being untracked if it's a file, or read its files if it's a directory.

There's still a little bit more

That covers untracked file detection, but what about git add itself?  We can run:

```<code>git add .
</code>```

or:

```<code>git add '*'    # quoted to keep the shell from expanding it
</code>```

or:

```<code>git add --all
</code>```

and have git add do the directory-scanning and git adding.  Here, the code is pretty similar, except instead of merely complaining about untracked files, Git will automatically git add (copy into the index) the updated content of any already-tracked files,4 and add for the first time any untracked-but-not-ignored files.

Again, if a directory itself is ignored, Git won't look inside it (though if there are already files in the index that are listed in an ignored directory, Git will check to see if they should be removed, as in footnote 4).  Note also that if you git add xyzzy, where xyzzy is a file, and xyzzy is currently both untracked and ignored, git add will by default complain and reject the add attempt.  You can use --force to override this: the file will go into the index, and thus become tracked, and now .gitignore has no effect on it.

Side note: pathname matching

Git does glob style pathname matching.  The * character matches any part of a file or directory name but does not "cross a slash".  Ending a glob pattern with a slash limits Git's matching so that it matches only directories.  Hence:

```<code>$ cat .gitignore
*
!*/
</code>```

tells Git to ignore everything (all files and directories) but then to un-ignore directories.  Since Git has to be opening and reading the directory at this point, it must pass each file and directory name to the ignore-pattern-matcher, so each file will be ignored, and each directory will be ignored-but-unignored, so Git will then look inside each sub-directory.

1Since git commit takes flag and/or path name arguments that can add files to the index, this is just a tiny bit over-simplified.  We can fix this by saying "at the time git commit makes the commit" instead, leaving room for git commit to modify the index a bit first.

2Technically, directories store name and file-identity pairings, rather than storing the actual files.  The details vary from one file system to another.

3Modern Git actually can, optionally, cache data about directories in the index, but these special entries are not supposed to affect its observable behavior.

4Note that the existing content, or previously-added content, of these already-tracked files is already in the index.  This just replaces them with the new content.  If the work-tree file has been removed, Git notices this case and also removes the index version of the file, a la git rm --cached.  To do this, Git has to read the index, as well as reading through the directories in question—but Git already has to read the index anyway, to see if these files are untracked.

Body:
I am working on a project that requires ignoring certain directories. Is there a difference between:

path/to/mydir/*

and this:

path/to/mydir/

The way I understand it, is the upper path ignores all files within mydir including the contents of subdirectories while the non-wildstar example ignores all top level files without including the files within subdirectories.

Is this a correct way of thinking about it? When would I want to use one over the other? I'd like to resolve this confusion once and for all.

Thanks in advance!

Body:
Is there a difference between:

path/to/mydir/*

and

path/to/mydir/

Yes.  Git has some funny (as in peculiar) behaviors for entries in .gitignore files.  They start to show up when we use the un-ignore directives, !path/to/mydir/file for instance.

The way I understand it, is the upper path ignores all files within mydir including the contents of subdirectories while the non-wildstar example ignores all top level files without including the files within subdirectories.

Unignore directives show that this isn't quite right.  In particular, if you ignore a directory, you cannot unignore a file within that directory.  However, if you ignore all files and sub-directories within a directory, you can unignore a file within the directory (but not its subdirectories, unless you explicitly un-ignore one of those too).

When would I want to use one over the other?

Use path/to/mydir/* if you want (for whatever reason) Git to open the directory path/to/mydir and read its contents, during status-checking and automatic git adding.  If you don't un-ignore particular paths underneath path/to/mydir, this won't make any difference.

Long description and background

Let's start with the first peculiarity, even though it's not directly part of this question: .gitignore doesn't really mean ignore.  It means something more like:  Don't automatically add, and especially don't complain, about some particular set of files being untracked.  However, it also means, in some cases, Don't even look inside this directory.

Git does not store directories in commits.  A commit stores only files.  When Git goes to extract a commit into a work-tree, it will simply create any directories needed to hold those files.

The files contained within any existing commit are fixed: unchangeable and permanent (well, as permanent as the commit anyway).  Whatever is in the commit, and however those files got inside it, they are there forever (until the commit itself is garbage-collected, if ever).  So they're not really interesting in terms of a .gitignore file.  What's in .gitignore has no effect upon them: they're already committed.

The files that go into a new commit are determined by the contents of the index at the time you run git commit.1  At this point, the contents of a .gitignore file are again irrelevant: if something—some particular path-name and blob-ID pairing—is in the index, it goes into the commit.  If something isn't in the index, it doesn't go into the commit.

This, then, gets us to the definition of an untracked file: An untracked file is a file that is not in the index.  As soon as you git add a file to the index, it's tracked, and as soon as you git rm --cached a file from the index, it's untracked.  Note that this means that the set of tracked files changes!  Untracked is not a permanent thing: it depends on what's in the index right now.

By being "not in" the index, it will be "not in" the commit.  That would make it, in effect, ignored.  But Git complains about it: Hey, this file is untracked!  Don't you want to add it now?  Whine!  Whine!  Enter .gitignore: this gives Git a list of files to avoid complaining about.

But that's for files.  What about directories?

Well, Git doesn't actually store directories, and it doesn't matter if you have an empty directory.  Git won't whine and complain about it, and Git won't store it.  Git will only store files.  But all files live within directories.2  If we could just list the directory, that would make our lives easier.  So we can.

If that were all there was to it, things would be less strange.  But that's not quite the end of the story.  Git tries to be fast, and to be fast, it's important to avoid actually looking at the files that are being stored.  File system operations in general are pretty slow.  So, in the index that Git uses to track files, Git keeps a bunch of secondary information about those files, that it uses to avoid looking at them if it can.  As a result, Git actually only opens and reads directories if it "has to".

Git will open and read the top level directory of the work-tree to find out which files and directories it contains.  For each file, if the file is in the index, all is good: the file is tracked.  If the file isn't in the index, it's untracked, and Git should maybe complain.  Now we check the .gitignore file to find ignore and un-ignore directives.  If the file is ignored, and not subsequently un-ignored, Git will complain:

?? dir/file

(for --short output from git status).

For a directory, though, well, the directory automatically isn't in the index.3  But it could be ignored, and if it is ignored, why then, perhaps we don't have to read it at all.  That would be really fast—so that's what Git does.

If the directory is ignored, Git doesn't bother opening and reading it to find more files.  This means it cannot and will not find any files within that directory, and therefore will never check to see if any of those files are ignored and not later un-ignored.

If the directory itself isn't ignored, Git does open and read it.  It then checks each file and sub-directory, one by one, that lives inside that directory, the same way it did for the top level (using the same code, recursively).  So if you have dir/* ignored, but dir/important subsequently un-ignored, and dir/important exists, Git will discover it, and whine about it being untracked if it's a file, or read its files if it's a directory.

There's still a little bit more

That covers untracked file detection, but what about git add itself?  We can run:

git add .

or:

git add '*'    # quoted to keep the shell from expanding it

or:

git add --all

and have git add do the directory-scanning and git adding.  Here, the code is pretty similar, except instead of merely complaining about untracked files, Git will automatically git add (copy into the index) the updated content of any already-tracked files,4 and add for the first time any untracked-but-not-ignored files.

Again, if a directory itself is ignored, Git won't look inside it (though if there are already files in the index that are listed in an ignored directory, Git will check to see if they should be removed, as in footnote 4).  Note also that if you git add xyzzy, where xyzzy is a file, and xyzzy is currently both untracked and ignored, git add will by default complain and reject the add attempt.  You can use --force to override this: the file will go into the index, and thus become tracked, and now .gitignore has no effect on it.

Side note: pathname matching

Git does glob style pathname matching.  The * character matches any part of a file or directory name but does not "cross a slash".  Ending a glob pattern with a slash limits Git's matching so that it matches only directories.  Hence:

$ cat .gitignore
*
!*/

tells Git to ignore everything (all files and directories) but then to un-ignore directories.  Since Git has to be opening and reading the directory at this point, it must pass each file and directory name to the ignore-pattern-matcher, so each file will be ignored, and each directory will be ignored-but-unignored, so Git will then look inside each sub-directory.

1Since git commit takes flag and/or path name arguments that can add files to the index, this is just a tiny bit over-simplified.  We can fix this by saying "at the time git commit makes the commit" instead, leaving room for git commit to modify the index a bit first.

2Technically, directories store name and file-identity pairings, rather than storing the actual files.  The details vary from one file system to another.

3Modern Git actually can, optionally, cache data about directories in the index, but these special entries are not supposed to affect its observable behavior.

4Note that the existing content, or previously-added content, of these already-tracked files is already in the index.  This just replaces them with the new content.  If the work-tree file has been removed, Git notices this case and also removes the index version of the file, a la git rm --cached.  To do this, Git has to read the index, as well as reading through the directories in question—but Git already has to read the index anyway, to see if these files are untracked.


问:
Unable to bulk insert using NHibernate
I've tried adding bulk inserting to my application, but the Batcher is still NonBatchingBatcher with a BatchSize of 1.

This is using C#3, NH3RC1 and MySql 5.1

I've added this to my SessionFactory

```<code><property name="adonet.batch_size">100</property>
</code>```

And my code goes pretty much like this

```<code>var session = SessionManager.GetStatelessSession(type);
var tx = session.BeginTransaction();
session.Insert(instance);
</code>```

I'm using HILO identity generation for the instances in question, but not for all instances on the database. The SessionFactory.OpenStatelessSession doesn't take a type, so it can't really know it can do batching on this type, or...?

After some digging into NHibernate, I found something in SettingsFactory.CreateBatcherFactory that might give some additional info

```<code>// It defaults to the NonBatchingBatcher
System.Type tBatcher = typeof (NonBatchingBatcherFactory);

// Environment.BatchStrategy == "adonet.factory_class", but I haven't
// defined this in my config file
string batcherClass = PropertiesHelper.GetString(Environment.BatchStrategy, properties, null);
if (string.IsNullOrEmpty(batcherClass))
{
    if (batchSize > 0)
    {
        // MySqlDriver doesn't implement IEmbeddedBatcherFactoryProvider,
        // so it still uses NonBatchingFactory
        IEmbeddedBatcherFactoryProvider ebfp = connectionProvider.Driver as IEmbeddedBatcherFactoryProvider;
</code>```

Could my configuration be wrong?

```<code>  <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="my application name">
      <property name="adonet.batch_size">100</property>
      <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
      <property name="connection.connection_string">my connection string
      </property>
      <property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
      <!-- To avoid "The column 'Reserved Word' does not belong to the table : ReservedWords" -->
      <property name="hbm2ddl.keywords">none</property>
    </session-factory>
  </hibernate-configuration>
</code>```

答:
IIRC, batching is currently supported for Oracle and SqlServer only.

As almost any other aspect of NH, this is extensible, so you can write your own IBatcher/IBatcherFactory and inject them via configuration.

Sidenote: current version of NH is 3.0 GA.

Title: Unable to bulk insert using NHibernate

Body:
I've tried adding bulk inserting to my application, but the Batcher is still NonBatchingBatcher with a BatchSize of 1.

This is using C#3, NH3RC1 and MySql 5.1

I've added this to my SessionFactory

<property name="adonet.batch_size">100</property>

And my code goes pretty much like this

var session = SessionManager.GetStatelessSession(type);
var tx = session.BeginTransaction();
session.Insert(instance);

I'm using HILO identity generation for the instances in question, but not for all instances on the database. The SessionFactory.OpenStatelessSession doesn't take a type, so it can't really know it can do batching on this type, or...?

After some digging into NHibernate, I found something in SettingsFactory.CreateBatcherFactory that might give some additional info

// It defaults to the NonBatchingBatcher
System.Type tBatcher = typeof (NonBatchingBatcherFactory);

// Environment.BatchStrategy == "adonet.factory_class", but I haven't
// defined this in my config file
string batcherClass = PropertiesHelper.GetString(Environment.BatchStrategy, properties, null);
if (string.IsNullOrEmpty(batcherClass))
{
    if (batchSize > 0)
    {
        // MySqlDriver doesn't implement IEmbeddedBatcherFactoryProvider,
        // so it still uses NonBatchingFactory
        IEmbeddedBatcherFactoryProvider ebfp = connectionProvider.Driver as IEmbeddedBatcherFactoryProvider;

Could my configuration be wrong?

  <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="my application name">
      <property name="adonet.batch_size">100</property>
      <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
      <property name="connection.connection_string">my connection string
      </property>
      <property name="dialect">NHibernate.Dialect.MySQL5Dialect</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>

      <property name="hbm2ddl.keywords">none</property>
    </session-factory>
  </hibernate-configuration>


问:
Error when fetching last months trending repositories in Swift 4.0 - Github API
I am translating the following curl to Swift but unfortunately I am getting the following error when running on PlayGround:

Optional(["errors": <__NSSingleObjectArrayI 0x60c00000da70>({
    code = invalid;
    field = q;
    message = "\"`date\" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.";
    resource = Search;
}), "documentation_url": https://developer.github.com/v3/search/,
     "message": Validation Failed])

This is the following cUrl,. It does work when executing it the Terminal.

curl -G https://api.github.com/search/repositories --data-urlencode "q=created:>`date -v-1m '+%Y-%m-%d'`" --data-urlencode "sort=stars" --data-urlencode "order=desc" -H "Accept: application/json"

This is my request:

```<code>    let sessionConfig = URLSessionConfiguration.default

    let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

    guard var urlComponent = URLComponents(string: "https://api.github.com/search/repositories") else { return }
    let items = [
        URLQueryItem(name: "q", value: "created:>`date -v-1m '+%Y-%m-%d'`"),
        URLQueryItem(name: "sort", value: "stars"),
        URLQueryItem(name: "order", value: "desc")
    ]

    urlComponent.queryItems = items
    guard let url = urlComponent.url else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    // Headers
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

    // Form URL-Encoded Body

    /* Start a new Task */
    let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
        if (error == nil) {
            // Success
            let statusCode = (response as! HTTPURLResponse).statusCode
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
                print(json)
            } catch {
                print(error)
            }
        }
        else {
            // Failure
            print("URL Session Task Failed: %@", error!.localizedDescription);
        }
    })
    task.resume()
    session.finishTasksAndInvalidate()
</code>```

答:
The cURL runs a script on the terminal, hence, it passes the date -1m as the q parameter. For example, if the date of this answer is 2017-11-13, date -v-1m '+%Y-%m-%d' will be 2017-10-13

```<code>let items = [
    URLQueryItem(name: "q", value: "created:>2017-10-13"),
    URLQueryItem(name: "sort", value: "stars"),
    URLQueryItem(name: "order", value: "desc")
]
</code>```

Body:
I am translating the following curl to Swift but unfortunately I am getting the following error when running on PlayGround:

Optional(["errors": <__NSSingleObjectArrayI 0x60c00000da70>({
    code = invalid;
    field = q;
    message = "\"`date\" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.";
    resource = Search;
}), "documentation_url": https://developer.github.com/v3/search/,
     "message": Validation Failed])

This is the following cUrl,. It does work when executing it the Terminal.

curl -G https://api.github.com/search/repositories --data-urlencode "q=created:>`date -v-1m '+%Y-%m-%d'`" --data-urlencode "sort=stars" --data-urlencode "order=desc" -H "Accept: application/json"

This is my request:

    let sessionConfig = URLSessionConfiguration.default

    let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

    guard var urlComponent = URLComponents(string: "https://api.github.com/search/repositories") else { return }
    let items = [
        URLQueryItem(name: "q", value: "created:>`date -v-1m '+%Y-%m-%d'`"),
        URLQueryItem(name: "sort", value: "stars"),
        URLQueryItem(name: "order", value: "desc")
    ]

    urlComponent.queryItems = items
    guard let url = urlComponent.url else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "GET"

    // Headers
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

    // Form URL-Encoded Body

    /* Start a new Task */
    let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
        if (error == nil) {
            // Success
            let statusCode = (response as! HTTPURLResponse).statusCode
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
                print(json)
            } catch {
                print(error)
            }
        }
        else {
            // Failure
            print("URL Session Task Failed: %@", error!.localizedDescription);
        }
    })
    task.resume()
    session.finishTasksAndInvalidate()

Body:
The cURL runs a script on the terminal, hence, it passes the date -1m as the q parameter. For example, if the date of this answer is 2017-11-13, date -v-1m '+%Y-%m-%d' will be 2017-10-13

let items = [
    URLQueryItem(name: "q", value: "created:>2017-10-13"),
    URLQueryItem(name: "sort", value: "stars"),
    URLQueryItem(name: "order", value: "desc")
]


答:
You can only use the ellipse overflow if certain conditions are true. The main one your having issues with is that your width is not fixed.

See Spudley's Answer here for more details

Based off your codepen your could add the following JS (I used jQuery in this example) to give the element a css fixed width that is still dynamic to your page size.

```<code>$( document ).ready(function() {
    // resize the div based on your parent element that is the right size
    function resizeHandler() {
        var width = $(".wrap_News")[0].offsetWidth;
        $(".news_Text").css("width", "" + width + "px");
    }

    // register for changing the width when window size changes
    $(window).resize(resizeHandler);

    // call once on page load
    resizeHandler();
});
</code>```

Fork of your codepen showing this here.

Title: text-overflow ellipsis is not working properly

Body:
You can only use the ellipse overflow if certain conditions are true. The main one your having issues with is that your width is not fixed.

See Spudley's Answer here for more details

Based off your codepen your could add the following JS (I used jQuery in this example) to give the element a css fixed width that is still dynamic to your page size.

$( document ).ready(function() {
    // resize the div based on your parent element that is the right size
    function resizeHandler() {
        var width = $(".wrap_News")[0].offsetWidth;
        $(".news_Text").css("width", "" + width + "px");
    }

    // register for changing the width when window size changes
    $(window).resize(resizeHandler);

    // call once on page load
    resizeHandler();
});

Fork of your codepen showing this here.


问:
How to handling login redirects back to app from multiple social login accounts swift?
I am making an app that allows user to login from different platforms such as google, Facebook , twitter etc. In the App delegate we have to implement a function application:openURL:options: for each of the platforms.
Currently my function looks like this.

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    // Todo handle based on the the arguments and return the bool value to be checked on iPHONE with facebook, google and twitter app
    let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

    GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: [:])

    Twitter.sharedInstance().application(app, open: url, options: options)

    return handled
}
</code>```

As seen above I am returning handled that is the Facebook's redirect handle result. Google and twitter returns a bool value too.
What is the safest and correct way to return handle bool value of Facebook, google and twitter for the above function?

答:
Try this approach</p>

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

     let facebookDidHandle = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

     let googleDidhandle = GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: [:])

     let twitterDidHandle = Twitter.sharedInstance().application(app, open: url, options: options)

     return googleDidHandle || facebookDidHandle || twitterDidHandle
}
</code>```

Body:
I am making an app that allows user to login from different platforms such as google, Facebook , twitter etc. In the App delegate we have to implement a function application:openURL:options: for each of the platforms.
Currently my function looks like this.

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    // Todo handle based on the the arguments and return the bool value to be checked on iPHONE with facebook, google and twitter app
    let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

    GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: [:])

    Twitter.sharedInstance().application(app, open: url, options: options)

    return handled
}

As seen above I am returning handled that is the Facebook's redirect handle result. Google and twitter returns a bool value too.
What is the safest and correct way to return handle bool value of Facebook, google and twitter for the above function?

Body:
Try this approach

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

     let facebookDidHandle = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

     let googleDidhandle = GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: [:])

     let twitterDidHandle = Twitter.sharedInstance().application(app, open: url, options: options)

     return googleDidHandle || facebookDidHandle || twitterDidHandle
}


问:
regex for email validation Not Working with Subdomains?
I'm using the following for email validation:

```<code>var filter = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/; // For Email Validation

if (filter.test(emailInputVal))) {console.log('good')}
</code>```

For some reason the above does not work with emails that have a subdomain Any ideas why?

```<code>xxxx@xxx.xxx.com
</code>```

Thanks

答:
Your last component is: any length word, then one or two instances of (dot, two-or-three-letter word).   I would expect "xxxx@xxx.xxx.com" to work, but perhaps not more realistic examples like "xxxx@xxx.example.com" because your domain name is not a two-or-three-letter word.

Do yourself a favor: use simply /^[^@ ]+@[^@ ]+\.[^@ ]+$/  More about this: http://nedbatchelder.com/blog/200908/humane_email_validation.html

Body:
I'm using the following for email validation:

var filter = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/; // For Email Validation

if (filter.test(emailInputVal))) {console.log('good')}

For some reason the above does not work with emails that have a subdomain Any ideas why?

xxxx@xxx.xxx.com

Thanks


问:
What's the best way of generating a random number in a discontinuous range?
Is there a better way than:

```<code>#define BOUND 7

int r;
int e = 1;

r = rand() % BOUND;

while (r == e){

    r = rand() % BOUND;
}
</code>```

for generating numbers in a range except for a value e?

答:
To generate a pseudo-random number in a range with a uniform distribution among values, it is much more reliable to use the magnitude of the value returned by rand() rather than its remainder for the division rand() % BOUND:

```<code>int r = (long long)rand() * BOUND / (RAND_MAX + 1LL);
</code>```

rand() returns a value between 0 and RAND_MAX included: the division must use RAND_MAX + 1LL so the result is in range 0 included .. BOUND excluded (as commented by chux).

If you want to exclude a given value, reduce the range by one and adjust the result:

```<code>#define BOUND 7

int r = (long long)rand() * (BOUND - 1) / (RAND_MAX + 1LL);
if (r >= 1) { // shift values 1..5 to 2..6
    r += 1;
}
</code>```

Here is a more general version:

```<code>// select a random value from a set
int set[] = { 0, 2, 3, 4, 5, 6 };
int r = set[(long long)rand() * (sizeof(set) / sizeof(*set)) / (RAND_MAX + 1LL)];
</code>```

Body:
Is there a better way than:

#define BOUND 7

int r;
int e = 1;

r = rand() % BOUND;

while (r == e){

    r = rand() % BOUND;
}

for generating numbers in a range except for a value e?

Body:
To generate a pseudo-random number in a range with a uniform distribution among values, it is much more reliable to use the magnitude of the value returned by rand() rather than its remainder for the division rand() % BOUND:

int r = (long long)rand() * BOUND / (RAND_MAX + 1LL);

rand() returns a value between 0 and RAND_MAX included: the division must use RAND_MAX + 1LL so the result is in range 0 included .. BOUND excluded (as commented by chux).

If you want to exclude a given value, reduce the range by one and adjust the result:

#define BOUND 7

int r = (long long)rand() * (BOUND - 1) / (RAND_MAX + 1LL);
if (r >= 1) { // shift values 1..5 to 2..6
    r += 1;
}

Here is a more general version:

// select a random value from a set
int set[] = { 0, 2, 3, 4, 5, 6 };
int r = set[(long long)rand() * (sizeof(set) / sizeof(*set)) / (RAND_MAX + 1LL)];


问:
Can scikit's f1_score's avg macro/micro be used for multi-labeled clustering?
It seems like the scikitlearn's f1_score avg micro/macro (http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html) is based on  multi-label data classifier, but I was wondering if the same could be used for multi-label clustering?

The data I'm working with is clustered using scikit's kmeans on 50.000 timeseries(ts). So I end out with clusters in the form: c1{ts_1, ts_2 ...}, c2{ts_20, ts_21 ...} etc.

Each time series can have one too many labels, which I would like to use as a golden standard for the f1 avg micro and macro scores. A cluster's time series can then be substituted by its labels(L): c1{(L_1, L_2), (L_2), (L_2), (L_3, L_4, L_5)...}

Can the f1 avg micro and macro scores be applied to clustering of such a dataset, or is there other scores i should be looking at instead?

答:
No. Because the clusterings use own "labels" (often 0...k), and there is no 1 on 1 match to classification labels.

Clustering just is nor classification. The term "unsupervised classification" is very misleading, as the differences can be quite substantial. That is why nobody in clustering seems to use this term.

Use any of the established cluster evaluation metrics instead.


问:
Conversion failed when converting varchar value to data type int in SQL
I am having some difficulty getting the difference between two time values in SQL. I want to select all the values that have less than 5 seconds difference between the start and stop of the date value.

My data looks like this

```<code>Stop
-----------------------
2017-10-04 16:32:06:000

Start
-----------------------
2017-10-04 16:32:02:000
</code>```

The above scenario would be one of those calls. My code in the where clause to obtain only values in the data that are less than 5 seconds:

```<code>  datediff(second, cast(stop as int), cast(start as int)) < 5
</code>```

I also tried just datediff without the cast as int and still received the same error:

Conversion failed when converting the varchar vlue '2017-10-04 20:58:46:000' to data type int

答:
This should work, you don't need the casts to get the diff in seconds ...

```<code>select datediff (SECOND,start, stop) from test
</code>```

Just tot test it ...

```<code>select 1
where ((select datediff (SECOND,start, stop) from test) > 5)
</code>```

datediff() query:

test table:

Body:
I am having some difficulty getting the difference between two time values in SQL. I want to select all the values that have less than 5 seconds difference between the start and stop of the date value.

My data looks like this

Stop
-----------------------
2017-10-04 16:32:06:000

Start
-----------------------
2017-10-04 16:32:02:000

The above scenario would be one of those calls. My code in the where clause to obtain only values in the data that are less than 5 seconds:

  datediff(second, cast(stop as int), cast(start as int)) < 5

I also tried just datediff without the cast as int and still received the same error:

Conversion failed when converting the varchar vlue '2017-10-04 20:58:46:000' to data type int

Body:
This should work, you don't need the casts to get the diff in seconds ...

select datediff (SECOND,start, stop) from test

Just tot test it ...

select 1
where ((select datediff (SECOND,start, stop) from test) > 5)

datediff() query:

test table:


问:
Use grep to match a pattern in a line only once
I have this:

```<code> echo 12345 | grep -o '[[:digit:]]\{1,4\}'
</code>```

Which gives this:

```<code>1234
5
</code>```

I understand whats happening. How do I stop grep from trying to continue matching after 1 successful match?

How do I get only

```<code>1234
</code>```

答:
If – as in your example – your numeric expression will appear at the beginning of the string you're starting with, you could just add a start-of-line anchor ^:

```<code>echo 12345 | grep -o '^\([[:digit:]]\)\{1,4\}'
</code>```

Depending on which exact digits you want, an end-of-line anchor $ might help also.

Body:
I have this:

 echo 12345 | grep -o '[[:digit:]]\{1,4\}'

Which gives this:

1234
5

I understand whats happening. How do I stop grep from trying to continue matching after 1 successful match?

How do I get only

1234

Body:
If – as in your example – your numeric expression will appear at the beginning of the string you're starting with, you could just add a start-of-line anchor ^:

echo 12345 | grep -o '^\([[:digit:]]\)\{1,4\}'

Depending on which exact digits you want, an end-of-line anchor $ might help also.