问:
PyCharm: Cannot find reference 'xxx' in 'turtle.py'
I try to draw a pentacle with built-in lib turtle.

Environment:

Windows 10

Python 3.5

PyCharm Community Edition 2017.1.5

code:

```<code>import turtle

turtle.fillcolor('red')
turtle.begin_fill()
while True:
    turtle.forward(200)
    turtle.right(144)
    if abs(turtle.pos()) < 1:
        break
turtle.end_fill()
</code>```

All of the method in turtle, including the 'fillcolor', 'begin_fill', 'forward', 'right', and 'pos', etc, are warned by PyCharm with "Cannot find reference 'xxx' in 'turtle.py'" and the auto-complete on these methods failed along with the warnings. But it's strange that the script can run normally and correctly as expected.

I've searched SO for answers, and there are a few related questions but not the same, actually:

Cannot find reference 'xxx' in '__init__.py'

Unresolved reference 'print'

All of the answers to the questions above cannot solve this problem.

According to the first batch of comments and answers, some more info provided as below:

I almost believe I'm using turtle for Python 3.x, because there is only one turtle.py file in my laptop, under the dir 'C:\Python35\Lib'. BTW, if it's still possible I'm using turtle for Python 2.x, how can I check this info and how can I update this builtin lib in the default dir?

I almost believe I'm not using the virtualenv, and the interpreter for my proj is Python 3.5.2

(Unfortunatly, I still cannot upload image)

答:
The problem is in \Lib\turtle.py.

Magic variable all is defines as follows:

```<code>__all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
           _tg_utilities + ['Terminator']) # + _math_functions)
</code>```

And PyCharm does not execute this code while scanning packages. So PyCharm can not define which functions can be used in module-level.

So you can change turtle.py:

```<code># __all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
#            _tg_utilities + ['Terminator']) # + _math_functions)
__all__ = ['ScrolledCanvas', 'TurtleScreen', 'Screen', 'RawTurtle', 'Turtle', 'RawPen', 'Pen', 'Shape', 'Vec2D', 'back',
           'backward', 'begin_fill', 'begin_poly', 'bk', 'addshape', 'bgcolor', 'bgpic', 'bye', 'clearscreen',
           'colormode', 'delay', 'exitonclick', 'getcanvas', 'getshapes', 'listen', 'mainloop', 'mode', 'numinput',
           'onkey', 'onkeypress', 'onkeyrelease', 'onscreenclick', 'ontimer', 'register_shape', 'resetscreen',
           'screensize', 'setup', 'Terminator', 'setworldcoordinates', 'textinput', 'title', 'tracer', 'turtles',
           'update', 'window_height', 'window_width', 'write_docstringdict', 'done', 'circle', 'clear', 'clearstamp',
           'clearstamps', 'clone', 'color', 'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd',
           'fillcolor', 'filling', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly', 'getturtle', 'goto',
           'heading', 'hideturtle', 'home', 'ht', 'isdown', 'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease',
           'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pu', 'radians', 'right', 'reset',
           'resizemode', 'rt', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setx',
           'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'speed', 'st', 'stamp', 'tilt',
           'tiltangle', 'towards', 'turtlesize', 'undo', 'undobufferentries', 'up', 'width', 'write', 'xcor', 'ycor']
</code>```

Also you can use Turtle class:

```<code>T = turtle.Turtle()
T.fillcolor('red')
etc
</code>```

Body:
I try to draw a pentacle with built-in lib turtle.

Environment:

Windows 10

Python 3.5

PyCharm Community Edition 2017.1.5

code:

import turtle

turtle.fillcolor('red')
turtle.begin_fill()
while True:
    turtle.forward(200)
    turtle.right(144)
    if abs(turtle.pos()) < 1:
        break
turtle.end_fill()

All of the method in turtle, including the 'fillcolor', 'begin_fill', 'forward', 'right', and 'pos', etc, are warned by PyCharm with "Cannot find reference 'xxx' in 'turtle.py'" and the auto-complete on these methods failed along with the warnings. But it's strange that the script can run normally and correctly as expected.

I've searched SO for answers, and there are a few related questions but not the same, actually:

Cannot find reference 'xxx' in '__init__.py'

Unresolved reference 'print'

All of the answers to the questions above cannot solve this problem.

According to the first batch of comments and answers, some more info provided as below:

I almost believe I'm using turtle for Python 3.x, because there is only one turtle.py file in my laptop, under the dir 'C:\Python35\Lib'. BTW, if it's still possible I'm using turtle for Python 2.x, how can I check this info and how can I update this builtin lib in the default dir?

I almost believe I'm not using the virtualenv, and the interpreter for my proj is Python 3.5.2

(Unfortunatly, I still cannot upload image)

Body:
The problem is in \Lib\turtle.py.

Magic variable all is defines as follows:

__all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
           _tg_utilities + ['Terminator']) # + _math_functions)

And PyCharm does not execute this code while scanning packages. So PyCharm can not define which functions can be used in module-level.

So you can change turtle.py:

# __all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
#            _tg_utilities + ['Terminator']) # + _math_functions)
__all__ = ['ScrolledCanvas', 'TurtleScreen', 'Screen', 'RawTurtle', 'Turtle', 'RawPen', 'Pen', 'Shape', 'Vec2D', 'back',
           'backward', 'begin_fill', 'begin_poly', 'bk', 'addshape', 'bgcolor', 'bgpic', 'bye', 'clearscreen',
           'colormode', 'delay', 'exitonclick', 'getcanvas', 'getshapes', 'listen', 'mainloop', 'mode', 'numinput',
           'onkey', 'onkeypress', 'onkeyrelease', 'onscreenclick', 'ontimer', 'register_shape', 'resetscreen',
           'screensize', 'setup', 'Terminator', 'setworldcoordinates', 'textinput', 'title', 'tracer', 'turtles',
           'update', 'window_height', 'window_width', 'write_docstringdict', 'done', 'circle', 'clear', 'clearstamp',
           'clearstamps', 'clone', 'color', 'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd',
           'fillcolor', 'filling', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly', 'getturtle', 'goto',
           'heading', 'hideturtle', 'home', 'ht', 'isdown', 'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease',
           'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pu', 'radians', 'right', 'reset',
           'resizemode', 'rt', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setx',
           'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'speed', 'st', 'stamp', 'tilt',
           'tiltangle', 'towards', 'turtlesize', 'undo', 'undobufferentries', 'up', 'width', 'write', 'xcor', 'ycor']

Also you can use Turtle class:

T = turtle.Turtle()
T.fillcolor('red')
etc


来源: stackexchange

问:
ReactJS material-ui TextField apply css
Im using material-ui with Reactjs. I want to apply on a TextField some custom styles using css. Specifically I want to change the color of the TextField underline and TextField label when I click the input.

I know that I could do it inline with the component but I want to use className and css.

Any ideas ?

Thanks

答:
Since material-ui uses inline styles in JS, its not very convinient and easy to do a custom styling of components by css classes, but its still possible with !important keyword.

First you need to add cutom css class to TextField:

```<code><TextField
  id="text-field-default"
  className="text-field-custom"
  defaultValue="Default Value"
/>
</code>```

Then, for example, underline style can be overriden like that:

```<code>.text-field-custom>input:focus+div>hr {
  border-bottom: 2px solid rgb(0, 0, 0) !important;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: ReactJS material-ui TextField apply css

Body:
Since material-ui uses inline styles in JS, its not very convinient and easy to do a custom styling of components by css classes, but its still possible with !important keyword.

First you need to add cutom css class to TextField:

<TextField
  id="text-field-default"
  className="text-field-custom"
  defaultValue="Default Value"
/>

Then, for example, underline style can be overriden like that:

.text-field-custom>input:focus+div>hr {
  border-bottom: 2px solid rgb(0, 0, 0) !important;
}


问:
Typo 3 Scheduler task: Prevent the task from accessing a class repository if there are no records of that class?
So basically i'm using a Scheduler task in which i first create an object of each class repository and use the function findAll() on each:

```<code>/** @var CustomerRepository $apprep2 */
$apprep2 = $objectManager->get(\Cjk\Icingaconfgen\Domain\Repository\ApplianceRepository::class);
/** @var Typo3QuerySettings $querySettings */
$querySettings = $objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$apprep2->setDefaultQuerySettings($querySettings);
$appliances = $apprep2->findAll();
</code>```

Then i use each repository object in a foreach loop to access specific properties of each record in the repository (to write them into a file - but that's another story) like this:

```<code>foreach($appliances as $appliance)
{
    if($appliance->getKundeuid() == $kunde->getUid())
    {

        $name = $appliance->getIpv4intern();
        $address = $appliance->getIpv4extern();
        $file = '/etc/icinga2/conf.d/hosts/'.$kunde->getName().'/Appliance_'. $appliance->getIpv4intern().'_'.$kunde->getKundennummer() . '.conf';

        $code_a = 'object Host "';
        $code_b = '" {
        import "generic-host"
        address = "';
        $code_c = '"
        vars.notification["mail"] = {
            groups = [ "icingaadmins" ]
        }
        }';
        $fp = fopen("{$file}", 'wb');
        fwrite($fp, $code_a . $name . $code_b . $address . $code_c);
        fclose($fp);
    }
}
</code>```

My problem is: The moment i don't have any record of let's say the class "appliance" Typo 3 throws me an error becauuse there is no "appliance" record it wants to access.

```<code>Oops, an error occurred!
Call to a member function getIpv4intern() on null
</code>```

Using an if condition like:

```<code>if($appliances != null){...}
</code>```

...Still makes the task trying to call "getIpv4intern()"...

What can i do to prevent the task using the foreach loop (or any other part of my code that tries to access the record, if the record is empty?

答:
I solved the problem myself: Instead of using

```<code>if($appliances != null){...}
</code>```

I simply checked if a record in the repository is empty:

```<code>foreach($appliances as $appliance)
{
    \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump(!empty($appliance));

    if(!empty($appliance)){

    if($appliance->getKundeuid() == $kunde->getUid())
    {
        $name = $appliance->getIpv4intern();
        $address = $appliance->getIpv4extern();
        $file = '/etc/icinga2/conf.d/hosts/'.$kunde->getName().'/Appliance_'. $appliance->getIpv4intern().'_'.$kunde->getKundennummer() . '.conf';

        $code_a = 'object Host "';
        $code_b = '" {
        import "generic-host"
        address = "';
        $code_c = '"
        vars.notification["mail"] = {
            groups = [ "icingaadmins" ]
        }
        }';
        $fp = fopen("{$file}", 'wb');
        fwrite($fp, $code_a . $name . $code_b . $address . $code_c);
        fclose($fp);
    }
}
}
</code>```

Body:
So basically i'm using a Scheduler task in which i first create an object of each class repository and use the function findAll() on each:

/** @var CustomerRepository $apprep2 */
$apprep2 = $objectManager->get(\Cjk\Icingaconfgen\Domain\Repository\ApplianceRepository::class);
/** @var Typo3QuerySettings $querySettings */
$querySettings = $objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$apprep2->setDefaultQuerySettings($querySettings);
$appliances = $apprep2->findAll();

Then i use each repository object in a foreach loop to access specific properties of each record in the repository (to write them into a file - but that's another story) like this:

foreach($appliances as $appliance)
{
    if($appliance->getKundeuid() == $kunde->getUid())
    {

        $name = $appliance->getIpv4intern();
        $address = $appliance->getIpv4extern();
        $file = '/etc/icinga2/conf.d/hosts/'.$kunde->getName().'/Appliance_'. $appliance->getIpv4intern().'_'.$kunde->getKundennummer() . '.conf';

        $code_a = 'object Host "';
        $code_b = '" {
        import "generic-host"
        address = "';
        $code_c = '"
        vars.notification["mail"] = {
            groups = [ "icingaadmins" ]
        }
        }';
        $fp = fopen("{$file}", 'wb');
        fwrite($fp, $code_a . $name . $code_b . $address . $code_c);
        fclose($fp);
    }
}

My problem is: The moment i don't have any record of let's say the class "appliance" Typo 3 throws me an error becauuse there is no "appliance" record it wants to access.

Oops, an error occurred!
Call to a member function getIpv4intern() on null

Using an if condition like:

if($appliances != null){...}

...Still makes the task trying to call "getIpv4intern()"...

What can i do to prevent the task using the foreach loop (or any other part of my code that tries to access the record, if the record is empty?

Body:
I solved the problem myself: Instead of using

if($appliances != null){...}

I simply checked if a record in the repository is empty:

foreach($appliances as $appliance)
{
    \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump(!empty($appliance));

    if(!empty($appliance)){

    if($appliance->getKundeuid() == $kunde->getUid())
    {
        $name = $appliance->getIpv4intern();
        $address = $appliance->getIpv4extern();
        $file = '/etc/icinga2/conf.d/hosts/'.$kunde->getName().'/Appliance_'. $appliance->getIpv4intern().'_'.$kunde->getKundennummer() . '.conf';

        $code_a = 'object Host "';
        $code_b = '" {
        import "generic-host"
        address = "';
        $code_c = '"
        vars.notification["mail"] = {
            groups = [ "icingaadmins" ]
        }
        }';
        $fp = fopen("{$file}", 'wb');
        fwrite($fp, $code_a . $name . $code_b . $address . $code_c);
        fclose($fp);
    }
}
}


问:
Get first 9 elements from Google RSS feed xml in PHP
I'm currently working with Google RSS feeds. I received this XML response.

```<code><rss version="2.0">
<channel>
<generator>NFE/1.0</generator>
<title>blockchain - Google News</title>
<link>...</link>
<language>en</language>
<webMaster>news-feedback@google.com</webMaster>
<copyright>©2017 Google</copyright>
<pubDate>Fri, 17 Nov 2017 09:41:26 GMT</pubDate>
<lastBuildDate>Fri, 17 Nov 2017 09:41:26 GMT</lastBuildDate>
<image>...</image>
<description>Google News</description>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</channel>
</rss>
</code>```

I'm using this foreach() to loop through all items:

```<code>$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

foreach ($rss->channel->item as $item) {
    echo $item->title."<br/>";
    echo $item->link."<br/>";
    echo $item->pubDate."<br/>";
}
</code>```

But this foreach returns me all items.

How can I get only first 9 items from this XML?

答:
Easy and quick fix:-

```<code>$i = 0;
foreach ($rss->channel->item as $item) {
  if($i<9){
    echo $item->title."<br/>";
    echo $item->link."<br/>";
    echo $item->pubDate."<br/>";
  }
 $i++;
}
</code>```

Better solution is:-

```<code>$array = array_slice($rss->channel->item,0,9);

foreach ($array as $item) {
  echo $item->title."<br/>";
  echo $item->link."<br/>";
  echo $item->pubDate."<br/>";
}
</code>```

Reference:- PHP manual: array_slice

Body:
I'm currently working with Google RSS feeds. I received this XML response.

<rss version="2.0">
<channel>
<generator>NFE/1.0</generator>
<title>blockchain - Google News</title>
<link>...</link>
<language>en</language>
<webMaster>news-feedback@google.com</webMaster>
<copyright>©2017 Google</copyright>
<pubDate>Fri, 17 Nov 2017 09:41:26 GMT</pubDate>
<lastBuildDate>Fri, 17 Nov 2017 09:41:26 GMT</lastBuildDate>
<image>...</image>
<description>Google News</description>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
<item>...</item>
</channel>
</rss>

I'm using this foreach() to loop through all items:

$rss = simplexml_load_file('https://news.google.com/news/rss/headlines/section/q/blockchain/blockchain?ned=us&hl=en&gl=US');

foreach ($rss->channel->item as $item) {
    echo $item->title."
";
    echo $item->link."
";
    echo $item->pubDate."
";
}

But this foreach returns me all items.

How can I get only first 9 items from this XML?

Body:
Easy and quick fix:-

$i = 0;
foreach ($rss->channel->item as $item) {
  if($i<9){
    echo $item->title."<br/>";
    echo $item->link."<br/>";
    echo $item->pubDate."<br/>";
  }
 $i++;
}

Better solution is:-

$array = array_slice($rss->channel->item,0,9);

foreach ($array as $item) {
  echo $item->title."<br/>";
  echo $item->link."<br/>";
  echo $item->pubDate."<br/>";
}

Reference:- PHP manual: array_slice

ContentLicense: CC BY-SA 4.0


问:
Join two Collections with LINQ with Contains operator
I have following two classes

```<code>Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type
</code>```

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

```<code> var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();
</code>```

答:
You can's use Enumerable.Join if the join condition is a Contains on another collection. You could use SelectMany(from...from in query syntax) on the Guid-collection first though:

```<code>var allDIDs = from d in D_Collection from id in d.CIds select new { dObj = d, id };
var cToUpdate = from c in C_Collection
                join dID in allDIDs
                on c.Id equals dID.id
                select new { cObj = c, dType = dID.dObj.Type };

foreach (var x in cToUpdate.Distinct())
    x.cObj.Type = x.dType;
</code>```

or use this query:

```<code>var cToUpdate = C_Collection
    .Select(c => new {
        cObj = c,
        FirstmatchingIdType = D_Collection
          .FirstOrDefault(d => d.CIds.Contains(c.Id))?.Type
     })
    .Where(x => x.FirstmatchingIdType != null);

foreach(var x in cToUpdate)
    x.cObj.Type = x.FirstmatchingIdType;
</code>```

Body:
I have following two classes

Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

 var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();

Body:
You can's use Enumerable.Join if the join condition is a Contains on another collection. You could use SelectMany(from...from in query syntax) on the Guid-collection first though:

var allDIDs = from d in D_Collection from id in d.CIds select new { dObj = d, id };
var cToUpdate = from c in C_Collection
                join dID in allDIDs
                on c.Id equals dID.id
                select new { cObj = c, dType = dID.dObj.Type };

foreach (var x in cToUpdate.Distinct())
    x.cObj.Type = x.dType;

or use this query:

var cToUpdate = C_Collection
    .Select(c => new {
        cObj = c,
        FirstmatchingIdType = D_Collection
          .FirstOrDefault(d => d.CIds.Contains(c.Id))?.Type
     })
    .Where(x => x.FirstmatchingIdType != null);

foreach(var x in cToUpdate)
    x.cObj.Type = x.FirstmatchingIdType;


问:
Using filter design pattern for dynamically creating a filter criteria
I have a requirement to search a collection of objects (say, reservations) based on one or more of the following search criteria. I'm planning to use the filter pattern to implement this.

Search options: firstname, lastname, phone, email

The requirement is - if the user specifies only the fistname filter, use only firstname to filter. If the user specifies both firstname and phone, use both (and criteria) to filter. If all 4 options are specified use all 4.

I've created the classes for all 4 search criterion. I'm in doubt as to how to use it. For example,

```<code>ISearchCriteria searchCriteria;

   if(firstName != null)
   {
            searchCriteria= new FirstNameSearchCriteria(CurrentClient);
   }

   if(lastName!= null)
   {
           //what do I do here? I have an AndCriteria class which accepts two ISearchCriteria objects. How do I use it?
   }
</code>```

What's the correct way to handle this search scenario?

答:
You should design the solution of your problem statement by using Intercepting Filter Pattern.

Below is the code using with Intercepting Filter Pattern:

```<code>public class Person
{

    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String Phone { get; set; }
    public String Email { get; set; }
}

public interface ICriteria
{
         List<Person> MeetCriteria(List<Person> persons);
}

  public class CriteriaFirstName : ICriteria
    {
        private string searchCriteria;
        public CriteriaFirstName(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }
        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.FirstName.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }

    public class CriteriaLastName : ICriteria
    {
        private string searchCriteria;
        public CriteriaLastName(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }

        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.LastName.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }
    }

 public class CriteriaLastPhone : ICriteria
    {
        private string searchCriteria;
        CriteriaLastPhone(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }

        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.Phone.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }
    }

   public class CriteriaEmail : ICriteria
    {
        private string searchCriteria;
        public CriteriaEmail(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }
        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.Email.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }
    }

public class AndCriteria : ICriteria
{
    private ICriteria criteria;
    private ICriteria otherCriteria;

    public AndCriteria(ICriteria criteria, ICriteria otherCriteria)
    {
        this.criteria = criteria;
        this.otherCriteria = otherCriteria;
    }

    public List<Person> MeetCriteria(List<Person> persons)
    {
        List<Person> firstCriteriaPersons = criteria.MeetCriteria(persons);
        return otherCriteria.MeetCriteria(firstCriteriaPersons);
    }
}

public class OrCriteria : ICriteria
{
    private ICriteria criteria;
    private ICriteria otherCriteria;

    public OrCriteria(ICriteria criteria, ICriteria otherCriteria)
    {
        this.criteria = criteria;
        this.otherCriteria = otherCriteria;
    }

    public List<Person> MeetCriteria(List<Person> persons)
    {
        List<Person> firstCriteriaItems = criteria.MeetCriteria(persons);
        List<Person> otherCriteriaItems = otherCriteria.MeetCriteria(persons);

        foreach (var otherItems in otherCriteriaItems)
        {
            if (!firstCriteriaItems.Contains(otherItems))
            {
                firstCriteriaItems.Add(otherItems);
            }
        }

        return firstCriteriaItems;
    }

}
</code>```

Driver Code:

```<code>class Program
{
    static void Main(string[] args)
    {
        List<Person> persons = new List<Person>();

        persons.Add(new Person { FirstName = "Robert", LastName = "kerry", Phone = "1234", Email = "cddd@xyz.com"});
        persons.Add(new Person { FirstName = "Robert", LastName = "Sam", Phone = "1234", Email = "sam@xyz.com" });
        persons.Add(new Person { FirstName = "Jon", LastName = "Kam", Phone = "1234", Email = "john@xyz.com" });

        Console.WriteLine("---Search by First and Last Name----");
        ICriteria firstName = new CriteriaFirstName("Robert");
        ICriteria lastName = new CriteriaLastName("Kerry");
        ICriteria fullName = new AndCriteria(firstName, lastName);
        var searchedData = fullName.MeetCriteria(persons);

        //Search by First and last name (And criteria)
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        //Search by first name and email. (And Criteria)
        firstName = new CriteriaFirstName("Robert");
        var email = new CriteriaEmail("sam@xyz.com");
        fullName = new AndCriteria(firstName, email);
        searchedData = fullName.MeetCriteria(persons);
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        Console.WriteLine("---Search by First Name Only----");
        firstName = new CriteriaFirstName("Robert");
        searchedData = firstName.MeetCriteria(persons);
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        Console.WriteLine("---Search by First Name or email ----");
        //Search by first name . (or Criteria)
        firstName = new CriteriaFirstName("Robert");
        email = new CriteriaEmail("john@xyz.com");
        fullName = new OrCriteria(firstName, email);
        searchedData = fullName.MeetCriteria(persons);
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        Console.ReadKey();
    }
}
</code>```

Body:
I have a requirement to search a collection of objects (say, reservations) based on one or more of the following search criteria. I'm planning to use the filter pattern to implement this.

Search options: firstname, lastname, phone, email

The requirement is - if the user specifies only the fistname filter, use only firstname to filter. If the user specifies both firstname and phone, use both (and criteria) to filter. If all 4 options are specified use all 4.

I've created the classes for all 4 search criterion. I'm in doubt as to how to use it. For example,

ISearchCriteria searchCriteria;

   if(firstName != null)
   {
            searchCriteria= new FirstNameSearchCriteria(CurrentClient);
   }

   if(lastName!= null)
   {
           //what do I do here? I have an AndCriteria class which accepts two ISearchCriteria objects. How do I use it?
   }

What's the correct way to handle this search scenario?

Body:
You should design the solution of your problem statement by using Intercepting Filter Pattern.

Below is the code using with Intercepting Filter Pattern:

public class Person
{

    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String Phone { get; set; }
    public String Email { get; set; }
}

public interface ICriteria
{
         List<Person> MeetCriteria(List<Person> persons);
}

  public class CriteriaFirstName : ICriteria
    {
        private string searchCriteria;
        public CriteriaFirstName(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }
        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.FirstName.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }

    public class CriteriaLastName : ICriteria
    {
        private string searchCriteria;
        public CriteriaLastName(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }

        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.LastName.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }
    }

 public class CriteriaLastPhone : ICriteria
    {
        private string searchCriteria;
        CriteriaLastPhone(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }

        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.Phone.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }
    }

   public class CriteriaEmail : ICriteria
    {
        private string searchCriteria;
        public CriteriaEmail(string searchCriteria)
        {
            this.searchCriteria = searchCriteria;
        }
        public List<Person> MeetCriteria(List<Person> persons)
        {
            List<Person> personsData = new List<Person>();
            foreach (var item in persons)
            {
                if (item.Email.ToUpper().Equals(searchCriteria.ToUpper()))
                {
                    personsData.Add(item);
                }
            }

            return personsData;
        }
    }

public class AndCriteria : ICriteria
{
    private ICriteria criteria;
    private ICriteria otherCriteria;

    public AndCriteria(ICriteria criteria, ICriteria otherCriteria)
    {
        this.criteria = criteria;
        this.otherCriteria = otherCriteria;
    }

    public List<Person> MeetCriteria(List<Person> persons)
    {
        List<Person> firstCriteriaPersons = criteria.MeetCriteria(persons);
        return otherCriteria.MeetCriteria(firstCriteriaPersons);
    }
}

public class OrCriteria : ICriteria
{
    private ICriteria criteria;
    private ICriteria otherCriteria;

    public OrCriteria(ICriteria criteria, ICriteria otherCriteria)
    {
        this.criteria = criteria;
        this.otherCriteria = otherCriteria;
    }

    public List<Person> MeetCriteria(List<Person> persons)
    {
        List<Person> firstCriteriaItems = criteria.MeetCriteria(persons);
        List<Person> otherCriteriaItems = otherCriteria.MeetCriteria(persons);

        foreach (var otherItems in otherCriteriaItems)
        {
            if (!firstCriteriaItems.Contains(otherItems))
            {
                firstCriteriaItems.Add(otherItems);
            }
        }

        return firstCriteriaItems;
    }

}

Driver Code:

class Program
{
    static void Main(string[] args)
    {
        List<Person> persons = new List<Person>();

        persons.Add(new Person { FirstName = "Robert", LastName = "kerry", Phone = "1234", Email = "cddd@xyz.com"});
        persons.Add(new Person { FirstName = "Robert", LastName = "Sam", Phone = "1234", Email = "sam@xyz.com" });
        persons.Add(new Person { FirstName = "Jon", LastName = "Kam", Phone = "1234", Email = "john@xyz.com" });

        Console.WriteLine("---Search by First and Last Name----");
        ICriteria firstName = new CriteriaFirstName("Robert");
        ICriteria lastName = new CriteriaLastName("Kerry");
        ICriteria fullName = new AndCriteria(firstName, lastName);
        var searchedData = fullName.MeetCriteria(persons);

        //Search by First and last name (And criteria)
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        //Search by first name and email. (And Criteria)
        firstName = new CriteriaFirstName("Robert");
        var email = new CriteriaEmail("sam@xyz.com");
        fullName = new AndCriteria(firstName, email);
        searchedData = fullName.MeetCriteria(persons);
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        Console.WriteLine("---Search by First Name Only----");
        firstName = new CriteriaFirstName("Robert");
        searchedData = firstName.MeetCriteria(persons);
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        Console.WriteLine("---Search by First Name or email ----");
        //Search by first name . (or Criteria)
        firstName = new CriteriaFirstName("Robert");
        email = new CriteriaEmail("john@xyz.com");
        fullName = new OrCriteria(firstName, email);
        searchedData = fullName.MeetCriteria(persons);
        foreach (var person in searchedData)
        {
            Console.WriteLine(person.FirstName);
            Console.WriteLine(person.LastName);
            Console.WriteLine(person.Phone);
        }

        Console.ReadKey();
    }
}


问:
Disable Apache 503 response when Tomcat is down
We have some independent servers, connected behind a hardware balancer. Each one of the machines is running Apache 2.2, Tomcat 5.0 and mod_proxy_ajp as the connector.

Everything works fine, but when Tomcat is shutdown, Apache returns error code 503 (as it's expected to do, I guess). The problem is our load balancer, which doesn't interpret error codes. It just thinks "oh, server at machine X has answered -503 blah blah blah, whatever- to my request, it seems to be working, let's keep sending people to that server".

Is there any way to tell Apache not to return anything in this case, instead of the 503 error?

答:
I have the same problem. For me the easiest way was to setup Apache to return a 404 error.
To change the balancer configuration I have to send a request to the Communication department and to sit waiting for the answer.</p>

ContentLicense: CC BY-SA 2.5


问:
perl command line substitute of strings
perl has convenient command line syntax for substitution of files

```<code>perl -pe 's/key/replace/g' file
</code>```

I am wondering what is the one liner syntax for substitution of string?

```<code>perl -pe 's/key/replace/g' string
</code>```

doesn't work. It will complain

Can't open ppp: No such file or directory.

答:
You probably want to remove the -p option as that is wrapping your code up inside a while(<>) loop. For perl <> means read in files specified on the command line or STDIN if there aren't any. So your "string" (which I'm guessing was "ppp" when you tried it) is being treated like a filename.

Instead if you want to pass in non-filenames you probably want something like:

```<code>perl -e 'print join(" ",map{ s/key/replace/g; $_ } @ARGV),"\n"' string
</code>```

Title: perl command line substitute of strings

Body:
perl has convenient command line syntax for substitution of files

perl -pe 's/key/replace/g' file

I am wondering what is the one liner syntax for substitution of string?

perl -pe 's/key/replace/g' string

doesn't work. It will complain

Can't open ppp: No such file or directory.

Body:
You probably want to remove the -p option as that is wrapping your code up inside a while(<>) loop. For perl <> means read in files specified on the command line or STDIN if there aren't any. So your "string" (which I'm guessing was "ppp" when you tried it) is being treated like a filename.

Instead if you want to pass in non-filenames you probably want something like:

perl -e 'print join(" ",map{ s/key/replace/g; $_ } @ARGV),"\n"' string


问:
Data validation in server by socket.io and node.js then POST a from
I have a form like this:

```<code><form method='post' action='next' onsubmit="return validateMyForm();" >
    <input type="text" id="data" />
<input type="submit" />
<p id="result"></p>
</code>```

and this code for interact with node.js:

```<code>socket = io.connect();
function vlidateMyForm(){
    var data = $('data').val();
    socket.emit('login',{data: data});   // check dataBase in server
    return false;
}

socket.on('responseLogin',function(result){
    if(result){    // if data is valid
        // submit form
    }
    else{   // data invalid
        $('#result').html('field is not valid')
    }
});
</code>```

I want to submit my form, when the result is true. What should I do to solve this problem?

答: Change socket.on('responseLogin',function(result){... to socket.on('login',function(result){... should fix your problem

Body:
I have a form like this:

<form method='post' action='next' onsubmit="return validateMyForm();" >
    <input type="text" id="data" />
<input type="submit" />

and this code for interact with node.js:

socket = io.connect();
function vlidateMyForm(){
    var data = $('data').val();
    socket.emit('login',{data: data});   // check dataBase in server
    return false;
}

socket.on('responseLogin',function(result){
    if(result){    // if data is valid
        // submit form
    }
    else{   // data invalid
        $('#result').html('field is not valid')
    }
});

I want to submit my form, when the result is true. What should I do to solve this problem?


问:
How to trigger an action once the push notification banner is clicked on foreground
As of now i get the push notifications and displaying the banner when im in both foreground and background states. But though its works fine in the background, when I'm in foreground im unable to trigger an action to open a specific view controller once i click the banner (should open only if i click the banner). How would i do this. My code as bellow </p>

```<code>func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
    {

        print("Recived: \(userInfo)")

        completionHandler(.newData)

        if state == .background {
            if mediaId != nil{
                DispatchQueue.main.async {
                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
                    let mP3ViewController = storyboard.instantiateViewController(withIdentifier:"MP3ViewController") as! MP3ViewController
                    mP3ViewController.media_ID = mediaId
                    self.navigationController?.pushViewController(mP3ViewController, animated:true)

                }

            }
        }else if state == .active {
      //What sould i do here to get the click

            print("Running on foreground")
            UIApplication.shared.applicationIconBadgeNumber = 0
            let count = 0
            UserDefaults.standard.setValue(count, forKey: "PUSH_COUNT")
            UserDefaults.standard.synchronize()

        }

    }
</code>```

答:
Try this
Implement UNUserNotificationCenterDelegate  in your AppDelegate class

```<code>class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
}
</code>```

Add bellow method in AppDelegate class

```<code>    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("didReceive response")
        completionHandler()
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresent notification")

        completionHandler([.badge, .alert, .sound])
    }
</code>```

Above method will call while push notification appear in foreground.

Edit:-

Add this method called by interactive notification delegate

```<code>func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) {
        print("identifier = \(identifier)")
    }
</code>```

Edit2 :

```<code>func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], withResponseInfo responseInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
        print("identifier = \(identifier)")
    }
</code>```

Body:
As of now i get the push notifications and displaying the banner when im in both foreground and background states. But though its works fine in the background, when I'm in foreground im unable to trigger an action to open a specific view controller once i click the banner (should open only if i click the banner). How would i do this. My code as bellow

func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
    {

        print("Recived: \(userInfo)")

        completionHandler(.newData)

        if state == .background {
            if mediaId != nil{
                DispatchQueue.main.async {
                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
                    let mP3ViewController = storyboard.instantiateViewController(withIdentifier:"MP3ViewController") as! MP3ViewController
                    mP3ViewController.media_ID = mediaId
                    self.navigationController?.pushViewController(mP3ViewController, animated:true)

                }

            }
        }else if state == .active {
      //What sould i do here to get the click

            print("Running on foreground")
            UIApplication.shared.applicationIconBadgeNumber = 0
            let count = 0
            UserDefaults.standard.setValue(count, forKey: "PUSH_COUNT")
            UserDefaults.standard.synchronize()

        }

    }

Body:
Try this
Implement UNUserNotificationCenterDelegate  in your AppDelegate class

class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
}

Add bellow method in AppDelegate class

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("didReceive response")
        completionHandler()
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresent notification")

        completionHandler([.badge, .alert, .sound])
    }

Above method will call while push notification appear in foreground.

Edit:-

Add this method called by interactive notification delegate

func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) {
        print("identifier = \(identifier)")
    }

Edit2 :

func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], withResponseInfo responseInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
        print("identifier = \(identifier)")
    }


问:
How to activate found cell with find function?
I am trying to create a Macro that will find each cell that contains a specific value (e.g.:Location) then deletes the whole row of that cell. There will be multiple cells that contain that value and I want all of them deleted so I have created a loop but because of the way I've done it, it breaks after the last one and it doesn't carry on with the last bit of the macro. I cannot find another way around so I am hoping someone will be smarter than me and can help me out with this one. The code looks like this now:</p>

```<code>  Do
   If Cells.Find(What:="Location").Activate Then
    ActiveCell.EntireRow.Select
    Selection.Delete
   Else MsgBox ("All headers deleted")
   End If
  Loop
</code>```

答:
Use FindNext. In this example it builds up the found cells to be deleted and set them all to a variable. Then it deletes them all in one go - This is much faster if you have many cells to delete then doing them one by one.

```<code>Dim DelRng As Range, fndCell As Range
Dim firstAddress As String

With ActiveSheet
    Set fndCell = .Cells.Find(What:="Location")
    If Not fndCell Is Nothing Then
        firstAddress = fndCell.Address
        Do
            If DelRng Is Nothing Then
                Set DelRng = fndCell
            Else
                Set DelRng = Union(DelRng, fndCell)
            End If
            Set fndCell = .Cells.FindNext(fndCell)
        Loop Until fndCell.Address = firstAddress
    End If
    If Not DelRng Is Nothing Then
        DelRng.EntireRow.Delete
        MsgBox ("All headers deleted")
    Else
        MsgBox ("No headers found")
    End If
End With
</code>```

Body:
I am trying to create a Macro that will find each cell that contains a specific value (e.g.:Location) then deletes the whole row of that cell. There will be multiple cells that contain that value and I want all of them deleted so I have created a loop but because of the way I've done it, it breaks after the last one and it doesn't carry on with the last bit of the macro. I cannot find another way around so I am hoping someone will be smarter than me and can help me out with this one. The code looks like this now:

  Do
   If Cells.Find(What:="Location").Activate Then
    ActiveCell.EntireRow.Select
    Selection.Delete
   Else MsgBox ("All headers deleted")
   End If
  Loop

Body:
Use FindNext. In this example it builds up the found cells to be deleted and set them all to a variable. Then it deletes them all in one go - This is much faster if you have many cells to delete then doing them one by one.

Dim DelRng As Range, fndCell As Range
Dim firstAddress As String

With ActiveSheet
    Set fndCell = .Cells.Find(What:="Location")
    If Not fndCell Is Nothing Then
        firstAddress = fndCell.Address
        Do
            If DelRng Is Nothing Then
                Set DelRng = fndCell
            Else
                Set DelRng = Union(DelRng, fndCell)
            End If
            Set fndCell = .Cells.FindNext(fndCell)
        Loop Until fndCell.Address = firstAddress
    End If
    If Not DelRng Is Nothing Then
        DelRng.EntireRow.Delete
        MsgBox ("All headers deleted")
    Else
        MsgBox ("No headers found")
    End If
End With


问:
Can I make my app open another app AND click a button in it?
Let's say there is a pre-existing Android app on my phone that has a button on its home screen that I can click. I know there is a way to launch that app from an app I am creating, but is there a way to click the button as well automatically? Is there a parameter I can pass in, and how would I go about using it?</p>

答:
You can't have your apps push a button on another app. That would be a giantic security leak.

However, the other app might have options on how to call it. It will depend on that other app. You would call the other app with an Intent, then use putExtra to provide extra parameters.


问:
IOS - push data instead of notifications using APNS
When I have loaded new data onto my server, I want to push a file onto my iPhone app.
Is that possible with APNS or is that only for notification of the availabillity of new data on the server(and the app must then connect to the server and download data)? </p>

答:
A push notification can only carry a very small brutto payload (256 Byte, IIRC). So no, you cannot push a file via APN (unless it's so tiny that you can cram it into the JSON body).

Edit: It is 256 Byte. See the docs.


问:
how to programatically upgrade (or be notified) of new versions of external tools?
I am running a large number of federated tools on AWS EC2s, what is the best practice for automatically getting latest version of these tools installed on the 'dev env' EC2s rather than specifying a particular version per tool to install in the AWS startup scripts?

Not talking about java libraries here...some example tools I would like latest versions of auto-maintained for:

Apache Spark

Apache Hive

Presto (by Facebook)

Kafka

..etc

答:
You can write shell scripts for your each tool which contains steps to install new version , uninstall old version . and run it through ansible on all your ec2-instances.
Link</p>


问:
Javascript classes in ES6, how to import them within other js-files and in html files?
Obviously, I am a beginner and trying to figure out basic staff, so please bear with me!

I have all these files (index.html, app.js and calc.js) in the same folder and their content is shown below.

I have 2 issues:

1: why in file (app.js), importing class Calc and creating a new instance of it works, whereas in file (calc.js) similar process doesn't work with class Test?

2: how could I use the class "Calc" for example in the *.html file?

Note: I am using chrome (62.0.3202.94 (Official Build) (64-bit)) on mac OS 10.13

```<code>// app.js
import { Calc } from './calc.js';

class Test {
    static hello() {
        console.log("hello from class1");
    }
}

let c = new Calc(); // this works!

console.log(c.sum(2, 3) + 1); // 6

export { Test };
</code>```

and

```<code>// calc.js
import { Test } from "./app.js";

class Calc {
    sum(a, b) {
        return a + b;
    }
}

let t = new Test(); // Uncaught ReferenceError: Test is not defined
t.hello();

export { Calc };
</code>```

Finally the HTML file:

```<code><html>

<head>
    <meta charset="utf-8" />
    <script src="./app.js" type="module"></script>
    <script src="./calc.js" type="module"></script>
</head>

<body>
    <h1>ES6</h1>
<script>
    let c = new Calc();
    // simulate input summation from two textboxes for example
    console.log(c.sum(2, 1)); //Uncaught ReferenceError: Calc is not defined
</script>
</body>

</html>
</code>```

答:
Problem 1:

You have a circular dependency - app.js imports calc.js, but calc.js imports app.js.

Usually the module system will ensure all of a module's dependencies are executed before the module itself, but this is impossible when your dependency tree has cycles - it has to pick one of them to run first. In this case, calc.js is run first, at which point Test isn't yet defined!

There are ways to work around this if you're careful, but cyclic dependencies are pretty much always a sign that you're structuring your code wrong - the best solution is to reorganize it so you no longer have a cycle.

Problem 2:

ES2016 modules don't execute in the global scope. If you want to make something available to the window as a whole, you need to be explicit:

```<code>window.Calc = Calc;
</code>```

Body:
Obviously, I am a beginner and trying to figure out basic staff, so please bear with me!

I have all these files (index.html, app.js and calc.js) in the same folder and their content is shown below.

I have 2 issues:

1: why in file (app.js), importing class Calc and creating a new instance of it works, whereas in file (calc.js) similar process doesn't work with class Test?

2: how could I use the class "Calc" for example in the *.html file?

Note: I am using chrome (62.0.3202.94 (Official Build) (64-bit)) on mac OS 10.13

// app.js
import { Calc } from './calc.js';

class Test {
    static hello() {
        console.log("hello from class1");
    }
}

let c = new Calc(); // this works!

console.log(c.sum(2, 3) + 1); // 6

export { Test };

and

// calc.js
import { Test } from "./app.js";

class Calc {
    sum(a, b) {
        return a + b;
    }
}

let t = new Test(); // Uncaught ReferenceError: Test is not defined
t.hello();

export { Calc };

Finally the HTML file:

    <meta charset="utf-8" />

ES6

Body:
Problem 1:

You have a circular dependency - app.js imports calc.js, but calc.js imports app.js.

Usually the module system will ensure all of a module's dependencies are executed before the module itself, but this is impossible when your dependency tree has cycles - it has to pick one of them to run first. In this case, calc.js is run first, at which point Test isn't yet defined!

There are ways to work around this if you're careful, but cyclic dependencies are pretty much always a sign that you're structuring your code wrong - the best solution is to reorganize it so you no longer have a cycle.

Problem 2:

ES2016 modules don't execute in the global scope. If you want to make something available to the window as a whole, you need to be explicit:

window.Calc = Calc;


问:
Using existing field values in django update query
I want to update a bunch of rows in a table to set the id = self.id. How would I do the below?

```<code>from metadataorder.tasks.models import Task
tasks = Task.objects.filter(task_definition__cascades=False)
        .update(shared_task_id=self.id)
</code>```

The equivalent SQL would be:

```<code>update tasks_task t join tasks_taskdefinition d
    on t.task_definition_id = d.id
set t.shared_task_id = t.id
    where d.cascades = 0
</code>```

答:
I stumbled upon this topic and noticed Django's limitation of updates with foreign keys, so I now use raw SQL in Django:</p>

```<code>from django.db import connection
with connection.cursor() as cursor:
    cursor.execute("UPDATE a JOIN b ON a.b_id = b.id SET a.myField = b.myField")
</code>```

Body:
I want to update a bunch of rows in a table to set the id = self.id. How would I do the below?

from metadataorder.tasks.models import Task
tasks = Task.objects.filter(task_definition__cascades=False)
        .update(shared_task_id=self.id)

The equivalent SQL would be:

update tasks_task t join tasks_taskdefinition d
    on t.task_definition_id = d.id
set t.shared_task_id = t.id
    where d.cascades = 0

Body:
I stumbled upon this topic and noticed Django's limitation of updates with foreign keys, so I now use raw SQL in Django:

from django.db import connection
with connection.cursor() as cursor:
    cursor.execute("UPDATE a JOIN b ON a.b_id = b.id SET a.myField = b.myField")


问:
Is there a way to send an object over a GET request?
I wanna make a server-side database query based on the following data from the client:

```<code>const passengers = {
  adults: 5,
  teens: 1,
  kids: 2,
  babies: 3,
  pets: 0
};
</code>```

What I know

I'm aware that I can send all the properties as individual query parameters, but I'm going to be sending some other ones and I'm interested in:

Grouping some of the data I send.

The capability of sending more complex objects with nested properties.

I'm also aware that I can switch to a POST request that accepts a JSON body, but I was willing to stick with GET since the response is a list of the queried entity and I think that GET suits better that concept as POST is rather meant for creating elements.

Is using POST the only option or can I solve this with a GET request?

答: There's nothing stopping you from putting a json string in the query parameters, not ideal but I think it will be more reliable than adding a body to a get request</p>

Body:
I wanna make a server-side database query based on the following data from the client:

const passengers = {
  adults: 5,
  teens: 1,
  kids: 2,
  babies: 3,
  pets: 0
};

What I know

I'm aware that I can send all the properties as individual query parameters, but I'm going to be sending some other ones and I'm interested in:

Grouping some of the data I send.

The capability of sending more complex objects with nested properties.

I'm also aware that I can switch to a POST request that accepts a JSON body, but I was willing to stick with GET since the response is a list of the queried entity and I think that GET suits better that concept as POST is rather meant for creating elements.

Is using POST the only option or can I solve this with a GET request?


问:
How can I make my animation transition smoothly?
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="headline">
  <div class="box">
    <span class="panel">Test Panel</span>
  </div>
</div></code>```

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

答:
Try this Out</p>

```<code>headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
animation: all infinite;
  0%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  50%{
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
  100%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}
</code>```

Body:
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}

    Test Panel

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

Body:
Try this Out

headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
animation: all infinite;
  0%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  50%{
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
  100%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}


问:
How to create a rectangle with two rounded corners?
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.</p>

```<code> rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);
</code>```

答:
A bit wasteful but first draw a rounded rectangle with all 4 corners rounded, then draw second, regular rectangle radius height below to draw over the bottom rounded corners

```<code>Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
float radius = 20f;

@Override
public void onDraw(Canvas canvas) {
    // Draw the top part that has rounded corners with twice the height of the radius
    canvas.drawRoundRect(0f, 0f, 100f, 2 * radius, radius, radius, paint);
    // Draw the bottom part, partly on top of the top part
    canvas.drawRect(0f, radius, 100f, 100f, paint);
}
</code>```

A tiny bit of math needed to account for the desired height but shouldn't be that hard :)

Body:
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.

 rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);

Body:
A bit wasteful but first draw a rounded rectangle with all 4 corners rounded, then draw second, regular rectangle radius height below to draw over the bottom rounded corners

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
float radius = 20f;

@Override
public void onDraw(Canvas canvas) {
    // Draw the top part that has rounded corners with twice the height of the radius
    canvas.drawRoundRect(0f, 0f, 100f, 2 * radius, radius, radius, paint);
    // Draw the bottom part, partly on top of the top part
    canvas.drawRect(0f, radius, 100f, 100f, paint);
}

A tiny bit of math needed to account for the desired height but shouldn't be that hard :)


问:
Check if field exists in json type column PostgreSQL
How do you check if a json field in Postgres has a certain element?

I have tried with json->>'attribute' is not null and doesn't work.

答:
While this works. It is better to use special operator ?:

```<code>WHERE your_column_name::jsonb ? 'attribute'
</code>```

NOTE: Only for jsonb type.

Body:
While this works. It is better to use special operator ?:

WHERE your_column_name::jsonb ? 'attribute'

NOTE: Only for jsonb type.


问:
notepad++ ctrl-shift-t opens file instead of coping line to clipboard. Why?
Here it says http://docs.notepad-plus-plus.org/index.php/Keyboard_And_Mouse_Shortcuts Ctrl-Shift-T  Copy current line to clipboard  and it did it, before i upgrade to 7.3.2, now it just opens some text file (maybe previously opened i don't recognize the pattern) any suggestions on how to make it do what it should do? Thanks!</p>

答:
In recent versions of Notepad++ (e.g. v7.5.1), the following shortcut can be used to copy the current line: Ctrl+Shift+X

In the Shortcut mapper of Notepad++ this is found under Scintilla commands:

Name: SCI_LINECOPY

Shortcut: Ctrl+Shift+X


问:
Update without touching timestamps (Laravel)
Is it possible to update a user without touching the timestamps?

I don't want to disable the timestamps completly..

grtz

答:
If you need to update single model queries:

```<code>$product->timestamps = false;
$product->save();
</code>```

or

```<code>$product->save(['timestamps' => false]);
</code>```

If you need to update multiple model queries use

```<code>DB::table('products')->...->update(...)
</code>```

instead of

```<code>Product::...->update(...)
</code>```

Body:
If you need to update single model queries:

$product->timestamps = false;
$product->save();

or

$product->save(['timestamps' => false]);

If you need to update multiple model queries use

DB::table('products')->...->update(...)

instead of

Product::...->update(...)


问:
Powershell Excel ComObject Open Custom Delimiters
I am facing a problem on the Powershell Excel ComObject where I am unable to accept a delimiter other than comma ,. Some of the external .csv files received use a different delimiter such as semicolon ;, pipeline | etc.

So, is there any solution on it to make it accepting custom delimiters? I tried using Import-Csv $fileloop -Delimiter ';' and it works. However I wish to remain using -ComObject to proceed as my script are all written using ComObject, and I need it to parse and check for columns and rows and some extra function.

Below is the relevant code snippet of opening .csv file for further processes:

```<code>$path      = "C:\Users\1.csv"
$objexcel  = New-Object -ComObject Excel.Application
$workbook  = $objexcel.Workbook.Open($path)
$worksheet = $workbook.activesheet
$colMax    = ($WorkSheet.UsedRange.Columns).count
$intcolMax = $colMax
$intRowMax = ($WorkSheet.UsedRange.Rows).count
.....
</code>```

I did research on some related topics and tested, none of them were working:

PowerShell Workbooks.Open with delimiter semicolon

https://kb.paessler.com/en/topic/2293-i-have-trouble-opening-csv-files-with-microsoft-excel-is-there-a-quick-way-to-fix-this

Testing results:

 1. The script need high portability, which means the script will pass to another users to use, so need to avoid using setting method on the region & language settings on windows.

 2. The script need process large size and large amount of .csv file, hence need to avoid using method such as Import-Csv $fileloop -Delimiter ';'| Export-Csv $commadelimiteroutput -Delimiter ',' to rebuild a new .csv file into comma delimiter and then use the ComObject to process.

If this is lacking information or not clear, kindly let me know.

答:
Instead of using the Open method, use OpenText. This allows the ability to set custom delimiters but this is not required as it also allows $true/$false for some standard delimiters.

Set the argument for semicolon ;delimiter to $true, and other delimiters to $false.

```<code>$objexcel.WorkBooks.OpenText(`
                $path,        # Filename
                2,            # Origin
                1,            # StartRow
                1,            # DataType
                1,            # TextQualifier
                $false,       # ConsecutiveDelimiter
                $false,       # Tab
                $true,        # Semicolon
                $false,       # Comma
                $false,       # Space
                $false,       # Other - $true/$false
                $false,       # OtherChar - specify the character if Other is $true
                @(@(3,3),@(1,2))         # FieldInfo
)
</code>```

For FieldInfo, you can get the enumerations here. I have used the same example as documentation example  specifying column 3 as and xlMDYFormat column 1 as xlTextFormat, but in PowerShell.

Body:
I am facing a problem on the Powershell Excel ComObject where I am unable to accept a delimiter other than comma ,. Some of the external .csv files received use a different delimiter such as semicolon ;, pipeline | etc.

So, is there any solution on it to make it accepting custom delimiters? I tried using Import-Csv $fileloop -Delimiter ';' and it works. However I wish to remain using -ComObject to proceed as my script are all written using ComObject, and I need it to parse and check for columns and rows and some extra function.

Below is the relevant code snippet of opening .csv file for further processes:

$path      = "C:\Users\1.csv"
$objexcel  = New-Object -ComObject Excel.Application
$workbook  = $objexcel.Workbook.Open($path)
$worksheet = $workbook.activesheet
$colMax    = ($WorkSheet.UsedRange.Columns).count
$intcolMax = $colMax
$intRowMax = ($WorkSheet.UsedRange.Rows).count
.....

I did research on some related topics and tested, none of them were working:

PowerShell Workbooks.Open with delimiter semicolon

https://kb.paessler.com/en/topic/2293-i-have-trouble-opening-csv-files-with-microsoft-excel-is-there-a-quick-way-to-fix-this

Testing results:

 1. The script need high portability, which means the script will pass to another users to use, so need to avoid using setting method on the region & language settings on windows.

 2. The script need process large size and large amount of .csv file, hence need to avoid using method such as Import-Csv $fileloop -Delimiter ';'| Export-Csv $commadelimiteroutput -Delimiter ',' to rebuild a new .csv file into comma delimiter and then use the ComObject to process.

If this is lacking information or not clear, kindly let me know.

Body:
Instead of using the Open method, use OpenText. This allows the ability to set custom delimiters but this is not required as it also allows $true/$false for some standard delimiters.

Set the argument for semicolon ;delimiter to $true, and other delimiters to $false.

$objexcel.WorkBooks.OpenText(`
                $path,        # Filename
                2,            # Origin
                1,            # StartRow
                1,            # DataType
                1,            # TextQualifier
                $false,       # ConsecutiveDelimiter
                $false,       # Tab
                $true,        # Semicolon
                $false,       # Comma
                $false,       # Space
                $false,       # Other - $true/$false
                $false,       # OtherChar - specify the character if Other is $true
                @(@(3,3),@(1,2))         # FieldInfo
)

For FieldInfo, you can get the enumerations here. I have used the same example as documentation example  specifying column 3 as and xlMDYFormat column 1 as xlTextFormat, but in PowerShell.


问:
Getting FRF from FFT
I have the FFT of a sensor output data. Is there any way to get frequncy response function FRF from this. I dont have any input data. Plz help.</p>

答: If you don't have any knowledge of the input data then you can't really calculate the frequency response. However if you happen to know that input signal is e.g. white noise, then you can at least get an approximation of the magnitude of the frequency response.

Title: Getting FRF from FFT


问:
Atomic operation on the circular global buffer in cuda
I am implementing a circular global memory to enable all threads read/write data to the same buffer simultaneously. It is a very simple producer/consumer algorithm in cpu. But i found something wrong in my cuda code.
The circular buffer was defined as follows:

```<code>#define BLOCK_NUM 1024
#define THREAD_NUM 64
#define BUFFER_SIZE BLOCK_NUM*THREAD_NUM*10
struct Stack {
    bool bDirty[BUFFER_SIZE];
    unsigned int index;
    unsigned int iStackSize;
}
</code>```

The read device is implemented as

```<code>__device__ void read(Stack *pStack) {
    unsigned int index = atomicDec(&pStack->index, BUFFER_SIZE-1);
    if(- -index >= BUFFER_SIZE)
        index = BUFFER_SIZE - 1;
    // check
    if(pStack->bDirty[index] == false) {
        printf(“no data\n”);
        return;
    }
    //set read flag
    pStack->bDirty[index] = false;
    atomicSub(&pStack->iStackSize, 1);
}
</code>```

The write device function is:

```<code>__device__ void write(Stack *pStack) {
    unsigned int index = atomicInc(&pStack->index, BUFFER_SIZE - 1);
    //check
    if(pStack->bDirty[index] == true) {
        printf(“why dirty\n”);
        return;
    }
    pStack->bDirty[index] = true;
    atomicAdd(&pStack->iStackSize, 1);
}
</code>```

In order to test the read/write function in a more robust way, I write the following kernels:

```<code>__global__ void kernelWrite(Stack *pStack) {
    if(threadIdx.x != 0) //make write less than thread number for testing purpose
        write(pStack);
}

__global__ void kernelRead(Stack *pStack) {
    read(pStack);
    __syncthreads();
    if(threadIdx.x % 3 != 0) // make write less than read
        write(pStack);
    __syncthreads();
}
</code>```

In the main function, I used a dead loop to test if the read/write is atomic.

```<code>int main() {
    Stack *pHostStack = (Stack*)malloc(sizeof(Stack));
    Stack *pStack;
    cudaMalloc(&pStack, sizeof(Stack));
    cudaMemset(pStack, 0, sizeof(Stack));

    while(true) { //dead loop
        kernelWrite<<<BLOCK_NUM, THREAD_NUM>>>(pStack);
        cudaDeviceSynchonize();
        cudaMemcpy(pHostStack, pStack, sizeof(Stack), cudaMemcpyDeviceToHost);
        while(pHost->iStackSize >= BLOCK_NUM*THREAD_NUM) {
             kernelRead<<<BLOCK_NUM, THREAD_NUM>>>(pStack);
                   cudaDeviceSynchonize();
                   cudaMemcpy(pHostStack, pStack, sizeof(Stack), cudaMemcpyDeviceToHost);
         }
    return 0;
}
</code>```

When I execute the above code, I got error msg “why dirty” and “no data”. What is wrong to the read/write logic?

By the way, I do not map the thread ID to the linear buffer address because in my application maybe only 10% threads write to the buffer, it is unpredictable/random.

答: The key problem is that the atomic operation is not real atomic because of reading and writing to the same buffer. The weird thing is that when the total thread number is less then 4096, no error message will be shown.</p>

Body:
I am implementing a circular global memory to enable all threads read/write data to the same buffer simultaneously. It is a very simple producer/consumer algorithm in cpu. But i found something wrong in my cuda code.
The circular buffer was defined as follows:

#define BLOCK_NUM 1024
#define THREAD_NUM 64
#define BUFFER_SIZE BLOCK_NUM*THREAD_NUM*10
struct Stack {
    bool bDirty[BUFFER_SIZE];
    unsigned int index;
    unsigned int iStackSize;
}

The read device is implemented as

__device__ void read(Stack *pStack) {
    unsigned int index = atomicDec(&pStack->index, BUFFER_SIZE-1);
    if(- -index >= BUFFER_SIZE)
        index = BUFFER_SIZE - 1;
    // check
    if(pStack->bDirty[index] == false) {
        printf(“no data\n”);
        return;
    }
    //set read flag
    pStack->bDirty[index] = false;
    atomicSub(&pStack->iStackSize, 1);
}

The write device function is:

__device__ void write(Stack *pStack) {
    unsigned int index = atomicInc(&pStack->index, BUFFER_SIZE - 1);
    //check
    if(pStack->bDirty[index] == true) {
        printf(“why dirty\n”);
        return;
    }
    pStack->bDirty[index] = true;
    atomicAdd(&pStack->iStackSize, 1);
}

In order to test the read/write function in a more robust way, I write the following kernels:

__global__ void kernelWrite(Stack *pStack) {
    if(threadIdx.x != 0) //make write less than thread number for testing purpose
        write(pStack);
}

__global__ void kernelRead(Stack *pStack) {
    read(pStack);
    __syncthreads();
    if(threadIdx.x % 3 != 0) // make write less than read
        write(pStack);
    __syncthreads();
}

In the main function, I used a dead loop to test if the read/write is atomic.

int main() {
    Stack *pHostStack = (Stack*)malloc(sizeof(Stack));
    Stack *pStack;
    cudaMalloc(&pStack, sizeof(Stack));
    cudaMemset(pStack, 0, sizeof(Stack));

    while(true) { //dead loop
        kernelWrite<<<BLOCK_NUM, THREAD_NUM>>>(pStack);
        cudaDeviceSynchonize();
        cudaMemcpy(pHostStack, pStack, sizeof(Stack), cudaMemcpyDeviceToHost);
        while(pHost->iStackSize >= BLOCK_NUM*THREAD_NUM) {
             kernelRead<<<BLOCK_NUM, THREAD_NUM>>>(pStack);
                   cudaDeviceSynchonize();
                   cudaMemcpy(pHostStack, pStack, sizeof(Stack), cudaMemcpyDeviceToHost);
         }
    return 0;
}

When I execute the above code, I got error msg “why dirty” and “no data”. What is wrong to the read/write logic?

By the way, I do not map the thread ID to the linear buffer address because in my application maybe only 10% threads write to the buffer, it is unpredictable/random.


问:
CopyMemory crashes Excel application
A bit of background first.

I'm trying to merge multiple 2D arrays. Usualy I would loop through each element of new array and add them to existing array or place arrays' values on separate sheet and create new array from it but I'm working with large data.

Not long ago I found CopyMemory function and got realy excited by it, I've tested it on simple chunks of data first.

```<code>Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Sub Test()
    Dim varr0(), varr1(), Border As Long
    varr0 = Application.Transpose(Range("a1").CurrentRegion.Value)
    Border = UBound(varr0, 2)
    varr1 = Application.Transpose(Range("a21").CurrentRegion.Value)
    ReDim Preserve varr0(1 To UBound(varr0, 1), 1 To UBound(varr0, 2) + UBound(varr1, 2))
    CopyMemory varr0(1, Border + 1), varr1(1, 1), UBound(varr1, 1) * UBound(varr1, 2) * 16
    Range(Cells(1, 10), Cells(1, 10).Offset(UBound(varr0, 2) - 1, UBound(varr0, 1) - 1)).Value = Application.Transpose(varr0)
End Sub
</code>```

Clearly it was a success (or so I thought) and I decided to work with pieces of my actual data, from there it went downhill.

```<code>Sub Test_2()
    Dim varr0(), varr1(), Border As Long, ws As Worksheet
    varr0 = Application.Transpose(ThisWorkbook.Worksheets("Sheet1").Range("a1").CurrentRegion.Value)
    Border = UBound(varr0, 2)
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Sheet1" Then
            varr1 = Application.Transpose(ws.Range("a1").CurrentRegion.Value)
            ReDim Preserve varr0(1 To UBound(varr0), 1 To UBound(varr0) + UBound(varr1))
            CopyMemory varr0(1, Border + 1), varr1(1, 1), UBound(varr1, 1) * UBound(varr1, 2) * 16
            Border = UBound(varr0, 2)
        End If
    Next
    ThisWorkbook.Worksheets("ws1").Range(Cells(1, 11), Cells(1, 11).Offset(UBound(varr0, 2) - 1, UBound(varr0, 1) - 1)).Value = Application.Transpose(varr0)
End Sub
</code>```

Whenever I execute it, Excel crashes (it doesn't identify the error but warns that something went wrong (thanks cap)).

The only thing I can think of is that new data had strings in it.

Per Source Variant requires only 16 bytes.

My question(s) is:

How do I make it work as intended?

What flaw of my logic causes Excel to crash?

Is it possible to merge two arrays without

Loops (or at least without iterating through whole array)

Use of sheets

Update:

It seems I was calculating memory to copy incorrectly so I slightly modified my macro.

```<code>Sub Test_6()
    Dim varr0(), varr1(), Border As Long, ws As Worksheet, MemUsage As Long
    varr0 = Application.Transpose(ThisWorkbook.Worksheets("Sheet1").Range("a1").CurrentRegion.Value)
    Border = UBound(varr0, 2)
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Sheet1" Then
            varr1 = Application.Transpose(ws.Range("a1").CurrentRegion.Value)
            ReDim Preserve varr0(1 To UBound(varr0, 1), 1 To UBound(varr0, 2) + UBound(varr1, 2))
            MemUsage = VarPtr(varr1(UBound(varr1, 1), UBound(varr1, 2))) - VarPtr(varr1(1, 1))
            CopyMemory varr0(1, Border + 1), varr1(1, 1), MemUsage + 16 + Len(varr1(UBound(varr1, 1), UBound(varr1, 2)))
            Border = UBound(varr0, 2)
        End If
    Next
    ThisWorkbook.Worksheets("Sheet1").Range(Cells(1, 11), Cells(1, 11).Offset(UBound(varr0, 2) - 1, UBound(varr0, 1) - 1)).Value = Application.Transpose(varr0)
End Sub
</code>```

In watch window I can clearly see that merge was successful, but shortly after CopyMemory line Excel crashes again.

答:
I can only guess that the API is reading a contiguous range of bytes in memory whereas the operating system may store large portions of data at split locations. Remember that VBA is using APIs to do its work. Once you override VBA and try to do the same job better the onus of proof is on you.

The following code will write the values of non-contiguous ranges of any source into a worksheet it creates. Note that the number of ranges is unlimited but is hard-coded.

```<code>Private Sub TestAppend()
    ' 17 Nov 2017

    Dim WsS As Worksheet, WsT As Worksheet          ' Source and Target
    Dim Arr() As Variant
    Dim Rl As Long                                  ' last row
    Dim i As Long

    Set WsS = ActiveSheet
    On Error Resume Next
    Set WsT = Worksheets("Temp")
    If Err Then
        Set WsT = Worksheets.Add(Sheet1)
        WsT.Name = "Temp"
    End If
    On Error GoTo 0

    ReDim Arr(1)
    Arr(0) = Range("A1").CurrentRegion.Value
    Arr(1) = Range("E1").CurrentRegion.Value

    For i = 0 To UBound(Arr)
        With WsT
            Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
            .Cells(Rl, "A").Resize(UBound(Arr(i)), UBound(Arr(i), 2)).Value = Arr(i)
        End With
    Next i
End Sub
</code>```

Title: CopyMemory crashes Excel application

Body:
A bit of background first.

I'm trying to merge multiple 2D arrays. Usualy I would loop through each element of new array and add them to existing array or place arrays' values on separate sheet and create new array from it but I'm working with large data.

Not long ago I found CopyMemory function and got realy excited by it, I've tested it on simple chunks of data first.

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Sub Test()
    Dim varr0(), varr1(), Border As Long
    varr0 = Application.Transpose(Range("a1").CurrentRegion.Value)
    Border = UBound(varr0, 2)
    varr1 = Application.Transpose(Range("a21").CurrentRegion.Value)
    ReDim Preserve varr0(1 To UBound(varr0, 1), 1 To UBound(varr0, 2) + UBound(varr1, 2))
    CopyMemory varr0(1, Border + 1), varr1(1, 1), UBound(varr1, 1) * UBound(varr1, 2) * 16
    Range(Cells(1, 10), Cells(1, 10).Offset(UBound(varr0, 2) - 1, UBound(varr0, 1) - 1)).Value = Application.Transpose(varr0)
End Sub

Clearly it was a success (or so I thought) and I decided to work with pieces of my actual data, from there it went downhill.

Sub Test_2()
    Dim varr0(), varr1(), Border As Long, ws As Worksheet
    varr0 = Application.Transpose(ThisWorkbook.Worksheets("Sheet1").Range("a1").CurrentRegion.Value)
    Border = UBound(varr0, 2)
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Sheet1" Then
            varr1 = Application.Transpose(ws.Range("a1").CurrentRegion.Value)
            ReDim Preserve varr0(1 To UBound(varr0), 1 To UBound(varr0) + UBound(varr1))
            CopyMemory varr0(1, Border + 1), varr1(1, 1), UBound(varr1, 1) * UBound(varr1, 2) * 16
            Border = UBound(varr0, 2)
        End If
    Next
    ThisWorkbook.Worksheets("ws1").Range(Cells(1, 11), Cells(1, 11).Offset(UBound(varr0, 2) - 1, UBound(varr0, 1) - 1)).Value = Application.Transpose(varr0)
End Sub

Whenever I execute it, Excel crashes (it doesn't identify the error but warns that something went wrong (thanks cap)).

The only thing I can think of is that new data had strings in it.

Per Source Variant requires only 16 bytes.

My question(s) is:

How do I make it work as intended?

What flaw of my logic causes Excel to crash?

Is it possible to merge two arrays without

Loops (or at least without iterating through whole array)

Use of sheets

Update:

It seems I was calculating memory to copy incorrectly so I slightly modified my macro.

Sub Test_6()
    Dim varr0(), varr1(), Border As Long, ws As Worksheet, MemUsage As Long
    varr0 = Application.Transpose(ThisWorkbook.Worksheets("Sheet1").Range("a1").CurrentRegion.Value)
    Border = UBound(varr0, 2)
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Sheet1" Then
            varr1 = Application.Transpose(ws.Range("a1").CurrentRegion.Value)
            ReDim Preserve varr0(1 To UBound(varr0, 1), 1 To UBound(varr0, 2) + UBound(varr1, 2))
            MemUsage = VarPtr(varr1(UBound(varr1, 1), UBound(varr1, 2))) - VarPtr(varr1(1, 1))
            CopyMemory varr0(1, Border + 1), varr1(1, 1), MemUsage + 16 + Len(varr1(UBound(varr1, 1), UBound(varr1, 2)))
            Border = UBound(varr0, 2)
        End If
    Next
    ThisWorkbook.Worksheets("Sheet1").Range(Cells(1, 11), Cells(1, 11).Offset(UBound(varr0, 2) - 1, UBound(varr0, 1) - 1)).Value = Application.Transpose(varr0)
End Sub

In watch window I can clearly see that merge was successful, but shortly after CopyMemory line Excel crashes again.

Body:
I can only guess that the API is reading a contiguous range of bytes in memory whereas the operating system may store large portions of data at split locations. Remember that VBA is using APIs to do its work. Once you override VBA and try to do the same job better the onus of proof is on you.

The following code will write the values of non-contiguous ranges of any source into a worksheet it creates. Note that the number of ranges is unlimited but is hard-coded.

Private Sub TestAppend()
    ' 17 Nov 2017

    Dim WsS As Worksheet, WsT As Worksheet          ' Source and Target
    Dim Arr() As Variant
    Dim Rl As Long                                  ' last row
    Dim i As Long

    Set WsS = ActiveSheet
    On Error Resume Next
    Set WsT = Worksheets("Temp")
    If Err Then
        Set WsT = Worksheets.Add(Sheet1)
        WsT.Name = "Temp"
    End If
    On Error GoTo 0

    ReDim Arr(1)
    Arr(0) = Range("A1").CurrentRegion.Value
    Arr(1) = Range("E1").CurrentRegion.Value

    For i = 0 To UBound(Arr)
        With WsT
            Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
            .Cells(Rl, "A").Resize(UBound(Arr(i)), UBound(Arr(i), 2)).Value = Arr(i)
        End With
    Next i
End Sub


问:
Outlier Analysis Python: Is there a better/more efficient way?
I am trying to do my outlier analysis in Python. Since I have multiple dataframes with varying length, I want to deduct 2.5% of both the tail and head when the dataframe has 10 observations, 0.25% when it has 100 etc. Currently, I have some code that seems to work. However, I still have the feeling it could be a little bit more efficient. This is mainly because of the last 2 lines. I feel like the filter could be done in one line. Also, I am unsure if the .loc is of good use here. Perhaps there is a better way to do this? Does anyone have suggestions?

This is my first question, so please let me know if there is anything I can improve with my question =)

Currently, this is my code:

```<code>    df_filtered_3['variable'] = df_filtered_3['variable1'] / df_filtered_3['variable2']

    if len(df_filtered_3.index) <= 10:
        low = .025
        high = .0975
    elif len(df_filtered_3.index) <= 100:
        low = .0025
        high = .00975
    elif len(df_filtered_3.index) <= 1000:
        low = .00025
        high = .000975
    elif len(df_filtered_3.index) <= 10000:
        low = .000025
        high = .0000975
    else:
        low = .0000025
        high = .00000975

    quant_df = df_filtered_3.quantile([low, high])
    df_filtered_3 = df_filtered_3.loc[df_filtered_3['variable'] > int(quant_df.loc[low, 'variable']), :]
    df_filtered_3 = df_filtered_3.loc[df_filtered_3['variable'] < int(quant_df.loc[high, 'variable']), :]
</code>```

Body:
I am trying to do my outlier analysis in Python. Since I have multiple dataframes with varying length, I want to deduct 2.5% of both the tail and head when the dataframe has 10 observations, 0.25% when it has 100 etc. Currently, I have some code that seems to work. However, I still have the feeling it could be a little bit more efficient. This is mainly because of the last 2 lines. I feel like the filter could be done in one line. Also, I am unsure if the .loc is of good use here. Perhaps there is a better way to do this? Does anyone have suggestions?

This is my first question, so please let me know if there is anything I can improve with my question =)

Currently, this is my code:

    df_filtered_3['variable'] = df_filtered_3['variable1'] / df_filtered_3['variable2']

    if len(df_filtered_3.index) <= 10:
        low = .025
        high = .0975
    elif len(df_filtered_3.index) <= 100:
        low = .0025
        high = .00975
    elif len(df_filtered_3.index) <= 1000:
        low = .00025
        high = .000975
    elif len(df_filtered_3.index) <= 10000:
        low = .000025
        high = .0000975
    else:
        low = .0000025
        high = .00000975

    quant_df = df_filtered_3.quantile([low, high])
    df_filtered_3 = df_filtered_3.loc[df_filtered_3['variable'] > int(quant_df.loc[low, 'variable']), :]
    df_filtered_3 = df_filtered_3.loc[df_filtered_3['variable'] < int(quant_df.loc[high, 'variable']), :]

Body:
You can write it shorter, but not necessarily faster:

In [57]: coefs = np.array([.025, .0975])

In [58]: coefs / pd.cut([len(df.index)], [0, 10, 100, 1000, 10000, np.inf], labels=[1, 10, 100, 1000, 10000], right=True)[0]
Out[58]: array([ 0.025 ,  0.0975])

Examples:

In [59]: coefs / pd.cut([105], [0, 10, 100, 1000, 10000, np.inf], labels=[1, 10, 100, 1000, 10000], right=True)[0]
Out[59]: array([ 0.00025 ,  0.000975])

In [60]: coefs / pd.cut([1005], [0, 10, 100, 1000, 10000, np.inf], labels=[1, 10, 100, 1000, 10000], right=True)[0]
Out[60]: array([  2.50000000e-05,   9.75000000e-05])


问:
Generic enum conform to ExpressibleByNilLiteral in swift
I have an enumeration defined as:

```<code>enum Context<T> {
    case some(T)
    case error(Error)
    case none
}
</code>```

To make it expressible by nil, I've created this extension:

```<code>extension Context: ExpressibleByNilLiteral {
    init(nilLiteral: ()) {
        self = .none
    }
}
</code>```

Then I have another class that exposes a method that should take as an argument the Context:

```<code>func start<T>(context: Context<T>)
</code>```

If I try to use it passing nil as a context the compiler shows me an error saying:

```<code>Generic parameter 'T' could not be inferred
</code>```

I've already seen some answer about it, but they don't seem to work.

I do not understand if it is not possible to do or if I'm doing in it in wrong way.

答:
The type inferrer needs to determine T and it can not possibly do so from seeing nil (or .none, for that matter) alone -- which type should it choose?

You need to make T concrete, e.g. by

```<code>start(context: nil as Context<Int>)
</code>```

Note again that passing .none has the same problem so the issue is not with ExpressibleByNilLiteral at all.

In real use, other parameters or even the return value may be used to determine T. For instance, if you have a function

```<code>func get<T>(context: Context<T>) throws -> T?
</code>```

then lines like

```<code>let v: Int? = get(context: nil)
</code>```

work perfectly well.

Side note: why use a nil literal as alias for .none? Using the latter avoids confusion while reading your code: let v: Context<Int> = nil is, on first sight, invalid Swift.

Body:
I have an enumeration defined as:

enum Context<T> {
    case some(T)
    case error(Error)
    case none
}

To make it expressible by nil, I've created this extension:

extension Context: ExpressibleByNilLiteral {
    init(nilLiteral: ()) {
        self = .none
    }
}

Then I have another class that exposes a method that should take as an argument the Context:

func start<T>(context: Context<T>)

If I try to use it passing nil as a context the compiler shows me an error saying:

Generic parameter 'T' could not be inferred

I've already seen some answer about it, but they don't seem to work.

I do not understand if it is not possible to do or if I'm doing in it in wrong way.

Body:
The type inferrer needs to determine T and it can not possibly do so from seeing nil (or .none, for that matter) alone -- which type should it choose?

You need to make T concrete, e.g. by

start(context: nil as Context<Int>)

Note again that passing .none has the same problem so the issue is not with ExpressibleByNilLiteral at all.

In real use, other parameters or even the return value may be used to determine T. For instance, if you have a function

func get<T>(context: Context<T>) throws -> T?

then lines like

let v: Int? = get(context: nil)

work perfectly well.

Side note: why use a nil literal as alias for .none? Using the latter avoids confusion while reading your code: let v: Context<Int> = nil is, on first sight, invalid Swift.