答:
```<code>  function GetDays($sStartDate, $sEndDate){
      // Firstly, format the provided dates.
      // This function works best with YYYY-MM-DD
      // but other date formats will work thanks
      // to strtotime().
      $sStartDate = gmdate("Y-m-d", strtotime($sStartDate));
      $sEndDate = gmdate("Y-m-d", strtotime($sEndDate));

      // Start the variable off with the start date
     $aDays[] = $sStartDate;

     // Set a 'temp' variable, sCurrentDate, with
     // the start date - before beginning the loop
     $sCurrentDate = $sStartDate;

     // While the current date is less than the end date
     while($sCurrentDate < $sEndDate){
       // Add a day to the current date
       $sCurrentDate = gmdate("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate)));

       // Add this new day to the aDays array
       $aDays[] = $sCurrentDate;
     }

     // Once the loop has finished, return the
     // array of days.
     return $aDays;
   }
</code>```

use like

```<code>GetDays('2007-01-01', '2007-01-31');
</code>```

Title: PHP: Return all dates between two dates in an array

Body:
Expected Input:

getDatesFromRange( '2010-10-01', '2010-10-05' );

Expected Output:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )

Body:
  function GetDays($sStartDate, $sEndDate){
      // Firstly, format the provided dates.
      // This function works best with YYYY-MM-DD
      // but other date formats will work thanks
      // to strtotime().
      $sStartDate = gmdate("Y-m-d", strtotime($sStartDate));
      $sEndDate = gmdate("Y-m-d", strtotime($sEndDate));

      // Start the variable off with the start date
     $aDays[] = $sStartDate;

     // Set a 'temp' variable, sCurrentDate, with
     // the start date - before beginning the loop
     $sCurrentDate = $sStartDate;

     // While the current date is less than the end date
     while($sCurrentDate < $sEndDate){
       // Add a day to the current date
       $sCurrentDate = gmdate("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate)));

       // Add this new day to the aDays array
       $aDays[] = $sCurrentDate;
     }

     // Once the loop has finished, return the
     // array of days.
     return $aDays;
   }

use like

GetDays('2007-01-01', '2007-01-31');


来源: stackexchange

问:
How clicking on a thumbnail image produces a larger image so quickly
I am developing an android app which needs to load a big image quickly. Using Instagram on Android I have noticed a feature they have that I cannot figure out how it works. Instagram users have a feed which displays usually a scroll list with a bunch of small thumbnails:

When you click an thumbnail image you get sent to another page(assuming fragment) that shows a bigger version of the image which appears instantly (to the human eye it looks instant)

You can scroll through all these thumbnails which means a lot of thumbnails display very quickly which I can understand because the images are small and sending over the network would be relatively quick. The problem I am understanding is how the larger images appear so quickly!? When the app downloaded the thumbnails are the larger images downloaded at the same time (I do not think this is the case because it would be such a waste of network traffic since most users on't click on every thumbnail? What technique is being used to have such fast response times for large images? I thought it maybe because of cache, but it happens when I click a picture I have never seen before.I is so fast it looks like it even is not hitting the network.

答:
How clicking on a thumbnail image produces a a larger image so quickly?

Uses faster CDN networks to fetch images

Uses Fresco for image loading which implements progressive image loading

Uses RecyclerView, image loading is triggered when ever you stop scrolling.

Probably uses webp and jpg image formats

Images are cached for later use

ContentLicense: CC BY-SA 3.0


问:
Digits with leading zero in date and time
I found this Javascript script online which refreshes the time every second and displays it. I want the program to display digits with leading zero. Currently it's showing 6/8/2017 - 19:8:54 but I want it to show 06/08/2017 - 19:08:54.</p>
```<code><script type="text/javascript">
    function display_c(){
        var refresh=1000; // Refresh rate in milli seconds
        mytime =setTimeout('display_ct()',refresh)
    }

    function display_ct() {
        var strcount
        var x = new Date()
        var x1=x.getDate() + "/" + x.getMonth() + "/" + x.getYear();
        x1 = x1 + " - " + x.getHours( )+ ":" + x.getMinutes() + ":" +
        x.getSeconds();
        document.getElementById('ct').innerHTML = x1;

        tt=display_c();
    }
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use the following:

var x1 =   ('0' + x.getDate()).slice(-2)      + '/'
         + ('0' + (x.getMonth()+1)).slice(-2) + '/'
         + x.getFullYear()                    + '-'
         + ('0' + x.getHours()).slice(-2)     + ':'
         + ('0' + x.getMinutes()).slice(-2)   + ':'
         + ('0' + x.getSeconds()).slice(-2);


问:
How to give user an option to customize site according to their own needs?
I'm creating a website of my own, in which I would like to add a feature where user can customize the site according to them like, by changing background color, font, font-color etc by using a customization widget. (just like twitter having this feature). I tried to Google to find any external api's for this but didn't got any. My project is based on Angular2. The question is not based on programming, but it will be very much helpful if someone can suggest me any approaches for this idea. Thank you!  </p>

答:
Angular 2 allows you to dynamically change css. you can create your own custom widgets to allow users to change css as they please. Simply bind your css values to a variable and pass it.

```<code>@Component({
  selector: 'my-app',
  template: `
    <div [style.background-color]="chosenColor">
      <button (click)="Blue()">blue</button>
      <button (click)="Red()">red</button>
      <button (click)="Yellow()">yellow</button>
    </div>
  `,
})
export class App {
  chosenColor = "";
  constructor() {}
  Red(){
    this.chosenColor = "red"
  }
  Blue(){
    this.chosenColor = "blue"
  }
  Yellow(){
    this.chosenColor = "yellow"
  }
</code>```

Here is a basic plunker to get you started... https://plnkr.co/edit/SdkpENReJPJJ5HRejnM9?p=preview

Body:
Angular 2 allows you to dynamically change css. you can create your own custom widgets to allow users to change css as they please. Simply bind your css values to a variable and pass it.

@Component({
  selector: 'my-app',
  template: `
    <div [style.background-color]="chosenColor">
      <button (click)="Blue()">blue</button>
      <button (click)="Red()">red</button>
      <button (click)="Yellow()">yellow</button>
    </div>
  `,
})
export class App {
  chosenColor = "";
  constructor() {}
  Red(){
    this.chosenColor = "red"
  }
  Blue(){
    this.chosenColor = "blue"
  }
  Yellow(){
    this.chosenColor = "yellow"
  }

Here is a basic plunker to get you started... https://plnkr.co/edit/SdkpENReJPJJ5HRejnM9?p=preview


问:
Symfony 2 - Generate Slugs with Gedmo\Slug
I have just installed the doctrine extensions to use Sluggable.

I make this :

composer.json

```<code>"stof/doctrine-extensions-bundle": "1.2.*@dev"
</code>```

AppKernel.php

```<code>new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
</code>```

app/config/config.yml

```<code>stof_doctrine_extensions:
    orm:
        default:
            sluggable: true
</code>```

Djoo\AppliBundle\Entity\Nomenclature.php

```<code>namespace Djoo\AppliBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\DBAL\Types\SmallIntType;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Nomenclature
 *
 *
 * @ORM\Table(name="app_nomenclature")
 * @ORM\Entity
 */
class Nomenclature
{
    .....
    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=200, nullable=false)
     */
    private $titre;

    /**
     * @var string
     *
     * @ORM\Column(name="finess", type="string", length=10, nullable=true)
     */
    private $finess;

    /**
     * @Gedmo\Slug(fields={"titre","finess"},suffix=".html")
     * @ORM\Column(length=128, unique=true,nullable=true)
     */
    private $slug;

    public function getSlug() {
        return $this->slug;
    }

    public function setSlug($slug){
        $this->slug = $slug;
        return $this;
    }

}
</code>```

In my controller i make this to generate slug for old values in my datatable :

```<code>$filterBuilder = $this->get('doctrine.orm.entity_manager')>getRepository('DjooAppliBundle:Nomenclature')->createQueryBuilder('e')->orderBy('e.titre', 'asc');
$query = $filterBuilder->getQuery();
$nomenclatures = $query->getResult();

foreach($nomenclatures as $nomenclaturee){
    $nomenclature->setSlug(null);
    $this->get('doctrine.orm.entity_manager')->persist($nomenclature);
    $this->get('doctrine.orm.entity_manager')->flush();
 }
</code>```

I have no error, but my old values are a null slug. I try to create a new element and i have a good slug. Have you and idea ?

Thanks

答:
Why it didn't work for OP, but worked for others (eg. @gregor):

When creating slug, your first instinct is to create slug property with this column configuration:

```<code> ..

 @ORM\Column(unique=true, nullable=false)
 private $slug;
 ..
</code>```

When running app/console doctrine:schema:update and this will result in 2 sql statements:

```<code>ALTER TABLE ... ADD slug ... NOT NULL
CREATE UNIQUE INDEX...`.
</code>```

By default column slug will be filled with value '' (empty string) which would make 2nd statement to fail with (Duplicate entry '') error.  Now you have two choices:

Choice A: Ignore failure of the 2nd statement

If you ignore the error, and later try generating slugs manually using the documented method $entity->setSlug(null) everything would work. It would work because by using $entity->setSlug(null) you would let Doctrine know that propertyslug was changed  (from '' to null) and this in turn would trigger internally $uow->propertyChanged() and $uow->scheduleForUpdate() (Thanks to @Sebastian Radu for his example). The Sluggable extension will notice this change as well and will regenerate the slug. Now as all the slugs are unique, next time you run app/console doc:schema:update it will succeed in creating index on slug and your schema will be fully in sync.

Choice B: Modify slug field to be nullable
After noticing error your instinct would be to mark slug field as nullable, so that index creation succeeds:

```<code> ..

 @ORM\Column(unique=true, nullable=true)
 private $slug;
 ..
</code>```

This would result in slug column having NULL as it's default value. Now as you try using documented $entity->setSlug(null) approach it won't work (just as OP has posted). This happens because when $entity->slug property is already NULL. Thus when you use $entity->setSlug(null) no changes are detected by Doctrine, and thus Sluggable regeneration behaviour is never triggered. In order to trigger the changes there were two answers:

hack with adding space to the slug source properties $entity -> setTitre($titre." "); (but this would result in extra space you would have to trim after)

approach by @Sebastian Radu, where he shows how to tell Doctrine directly that the field was changed (I personally prefer this one and wonder why it was unfairly downvoted)

Hope this helps you understand a bit better the inner workings of Doctrine and extensions.

Body:
I have just installed the doctrine extensions to use Sluggable.

I make this :

composer.json

"stof/doctrine-extensions-bundle": "1.2.*@dev"

AppKernel.php

new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),

app/config/config.yml

stof_doctrine_extensions:
    orm:
        default:
            sluggable: true

Djoo\AppliBundle\Entity\Nomenclature.php

namespace Djoo\AppliBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\DBAL\Types\SmallIntType;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Nomenclature
 *
 *
 * @ORM\Table(name="app_nomenclature")
 * @ORM\Entity
 */
class Nomenclature
{
    .....
    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=200, nullable=false)
     */
    private $titre;

    /**
     * @var string
     *
     * @ORM\Column(name="finess", type="string", length=10, nullable=true)
     */
    private $finess;

    /**
     * @Gedmo\Slug(fields={"titre","finess"},suffix=".html")
     * @ORM\Column(length=128, unique=true,nullable=true)
     */
    private $slug;

    public function getSlug() {
        return $this->slug;
    }

    public function setSlug($slug){
        $this->slug = $slug;
        return $this;
    }

}

In my controller i make this to generate slug for old values in my datatable :

$filterBuilder = $this->get('doctrine.orm.entity_manager')>getRepository('DjooAppliBundle:Nomenclature')->createQueryBuilder('e')->orderBy('e.titre', 'asc');
$query = $filterBuilder->getQuery();
$nomenclatures = $query->getResult();

foreach($nomenclatures as $nomenclaturee){
    $nomenclature->setSlug(null);
    $this->get('doctrine.orm.entity_manager')->persist($nomenclature);
    $this->get('doctrine.orm.entity_manager')->flush();
 }

I have no error, but my old values are a null slug. I try to create a new element and i have a good slug. Have you and idea ?

Thanks

Body:
Why it didn't work for OP, but worked for others (eg. @gregor):

When creating slug, your first instinct is to create slug property with this column configuration:

 ..

 @ORM\Column(unique=true, nullable=false)
 private $slug;
 ..

When running app/console doctrine:schema:update and this will result in 2 sql statements:

ALTER TABLE ... ADD slug ... NOT NULL
CREATE UNIQUE INDEX...`.

By default column slug will be filled with value '' (empty string) which would make 2nd statement to fail with (Duplicate entry '') error.  Now you have two choices:

Choice A: Ignore failure of the 2nd statement

If you ignore the error, and later try generating slugs manually using the documented method $entity->setSlug(null) everything would work. It would work because by using $entity->setSlug(null) you would let Doctrine know that propertyslug was changed  (from '' to null) and this in turn would trigger internally $uow->propertyChanged() and $uow->scheduleForUpdate() (Thanks to @Sebastian Radu for his example). The Sluggable extension will notice this change as well and will regenerate the slug. Now as all the slugs are unique, next time you run app/console doc:schema:update it will succeed in creating index on slug and your schema will be fully in sync.

Choice B: Modify slug field to be nullable
After noticing error your instinct would be to mark slug field as nullable, so that index creation succeeds:

 ..

 @ORM\Column(unique=true, nullable=true)
 private $slug;
 ..

This would result in slug column having NULL as it's default value. Now as you try using documented $entity->setSlug(null) approach it won't work (just as OP has posted). This happens because when $entity->slug property is already NULL. Thus when you use $entity->setSlug(null) no changes are detected by Doctrine, and thus Sluggable regeneration behaviour is never triggered. In order to trigger the changes there were two answers:

hack with adding space to the slug source properties $entity -> setTitre($titre." "); (but this would result in extra space you would have to trim after)

approach by @Sebastian Radu, where he shows how to tell Doctrine directly that the field was changed (I personally prefer this one and wonder why it was unfairly downvoted)

Hope this helps you understand a bit better the inner workings of Doctrine and extensions.


问:
python : how to variables many strings in one line in csv file
I have multiple variables and I need to write them in CSV file , but CSV reads a sequences, so it writes every character in one line, and I need all of variables in one line with space separating between them
 For example, if I have these variables:

```<code>pdate=30/03/2017
ptime=17:17:30
outlet1= 12345
outlet2=6789
</code>```

so i want them in CSV like this:

```<code>30/03/2017   17:17:30    12345    6789
</code>```

and if I got more data, it will write them in the next line like :

```<code>30/03/2017   17:17:30    12345    6789
30/03/2017   17:19:10    34354    4335
</code>```

I managed to do it by turning every variable to index inside one list and used "zip" to write all the lists in one line, but I would like to see if there is another way to do that ?
here is my code

```<code>    outlet1.append(12345)
    outlet2.append(6789)
    pdate.append("30/03.2017")
    ptime.append("17:17:30")
    with open('file.csv','a') as f:
            writer = csv.writer(f,delimiter=' ');
            writer.writerows(zip(pdate,ptime,outlet1,outlet2))
        f.close()
</code>```

答:
Because you are zipping strings. When you iterate over a string, you iterate over the individual characters. Just use writer.writerow([pdate, ptime, outlet1, outlet2])

Note, it is writer.writerow instead of writer.writerows

Body:
I have multiple variables and I need to write them in CSV file , but CSV reads a sequences, so it writes every character in one line, and I need all of variables in one line with space separating between them
 For example, if I have these variables:

pdate=30/03/2017
ptime=17:17:30
outlet1= 12345
outlet2=6789

so i want them in CSV like this:

30/03/2017   17:17:30    12345    6789

and if I got more data, it will write them in the next line like :

30/03/2017   17:17:30    12345    6789
30/03/2017   17:19:10    34354    4335

I managed to do it by turning every variable to index inside one list and used "zip" to write all the lists in one line, but I would like to see if there is another way to do that ?
here is my code

    outlet1.append(12345)
    outlet2.append(6789)
    pdate.append("30/03.2017")
    ptime.append("17:17:30")
    with open('file.csv','a') as f:
            writer = csv.writer(f,delimiter=' ');
            writer.writerows(zip(pdate,ptime,outlet1,outlet2))
        f.close()


问:
not allowed to connect to this MariaDB server in php
I try connect my remote server database in php but it's give bellow error

Host 'xx.xxx.xx.xx' is not allowed to connect to this MariaDB server in

My connection code like this

```<code>$servername = "my_server_address";
$username = "my_username";
$password = "my_password";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
</code>```

答:
If your credentials are valid, you most likely need to configure MariaDB for remote client access.

See Configuring MariaDB for Remote Client Access

Body:
I try connect my remote server database in php but it's give bellow error

Host 'xx.xxx.xx.xx' is not allowed to connect to this MariaDB server in

My connection code like this

$servername = "my_server_address";
$username = "my_username";
$password = "my_password";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


问:
Prevent title space changing when animating with descender letters
I am trying to animate some monthly data using gganimate. The plots are working great, except that the presence of descenders (letters that go below the baseline, i.e. g, j, p, q, and y) changes the amount of space that the title takes up. This, in turn, moves the baseline of the title just a bit, which detracts from the animation. That is, the title noticably "jumps" up a bit when there is a descender in the title.

An example:

```<code>myDF <-
  data.frame(
    Date = seq(as.Date("2015-01-15")
               , as.Date("2015-12-15")
               , "1 month")
    , x = 1:12
    , y = 1:12
  )

myDF$frame <-
  factor(format(myDF$Date, "%Y-%b")
         , levels = paste0("2015-", month.abb))

toAnimate <-
  ggplot(
    myDF
    , aes(x = x
          , y = y
          , frame = frame)
  ) +
  geom_point() +
  theme_gray()

gganimate::gganimate(toAnimate)
</code>```

Using an older version of gganimate the issue was more obvious(and did not require the inclusion of the year to demonstrate), as it moved the plot instead of the title:

```<code>gganimate::gg_animate(toAnimate)
</code>```

I can "fix" the issue by using all caps (which has no descenders), but I don't particularly like the look of all caps for this (particularly as part of larger titles for the actual use case). I could also prepend the frame title with something that already has a descender e.g. ggtitle("Timeperiod: ") though I'd rather not add irrelevant text just to workaround this issue (adding "Timeperiod: " is what I have gone with for now though).

I've looked through the help on theme in ggplot2, but I am not seeing anything that looks like it would address this issue.

答:
It looks like the title only gets the height of the text, and not the font's height, when reserving space for the title.

So you could instead use geom_text to place a title somewhere in the plot. For example, if I do:

```<code>ggplot(myDF, aes(x=x,y=y, label=frame)) +
   geom_point()+theme_gray() +
   geom_text(x=2.5,y=5,aes(label=frame),adj=0)
</code>```

(just as a ggplot, not animated yet...) I can see all the 2015's exactly overlapping, and the descenders of the month names are clearly there, and the text baseline is constant.

So if you can put your title in a handy space on the plot, you could use that, and use title_frame=FALSE in your gganimate.

I'd also consider a bug/enhancement report to ggplot2. If you make the title large enough it actually stomps on the plot:

```<code>ggplot(myDF, aes(x=x,y=y)) +geom_point()+theme(plot.title=element_text(size=rel(10),debug=TRUE)) + labs(title="y")
</code>```

Body:
I am trying to animate some monthly data using gganimate. The plots are working great, except that the presence of descenders (letters that go below the baseline, i.e. g, j, p, q, and y) changes the amount of space that the title takes up. This, in turn, moves the baseline of the title just a bit, which detracts from the animation. That is, the title noticably "jumps" up a bit when there is a descender in the title.

An example:

myDF <-
  data.frame(
    Date = seq(as.Date("2015-01-15")
               , as.Date("2015-12-15")
               , "1 month")
    , x = 1:12
    , y = 1:12
  )

myDF$frame <-
  factor(format(myDF$Date, "%Y-%b")
         , levels = paste0("2015-", month.abb))

toAnimate <-
  ggplot(
    myDF
    , aes(x = x
          , y = y
          , frame = frame)
  ) +
  geom_point() +
  theme_gray()

gganimate::gganimate(toAnimate)

Using an older version of gganimate the issue was more obvious(and did not require the inclusion of the year to demonstrate), as it moved the plot instead of the title:

gganimate::gg_animate(toAnimate)

I can "fix" the issue by using all caps (which has no descenders), but I don't particularly like the look of all caps for this (particularly as part of larger titles for the actual use case). I could also prepend the frame title with something that already has a descender e.g. ggtitle("Timeperiod: ") though I'd rather not add irrelevant text just to workaround this issue (adding "Timeperiod: " is what I have gone with for now though).

I've looked through the help on theme in ggplot2, but I am not seeing anything that looks like it would address this issue.

Body:
It looks like the title only gets the height of the text, and not the font's height, when reserving space for the title.

So you could instead use geom_text to place a title somewhere in the plot. For example, if I do:

ggplot(myDF, aes(x=x,y=y, label=frame)) +
   geom_point()+theme_gray() +
   geom_text(x=2.5,y=5,aes(label=frame),adj=0)

(just as a ggplot, not animated yet...) I can see all the 2015's exactly overlapping, and the descenders of the month names are clearly there, and the text baseline is constant.

So if you can put your title in a handy space on the plot, you could use that, and use title_frame=FALSE in your gganimate.

I'd also consider a bug/enhancement report to ggplot2. If you make the title large enough it actually stomps on the plot:

ggplot(myDF, aes(x=x,y=y)) +geom_point()+theme(plot.title=element_text(size=rel(10),debug=TRUE)) + labs(title="y")


问:
Android auto DHU - Failed to read from transport - disconnect. Exiting
When I try to connect the android auto DHU, following error occurs.
before running the DHU, I have done following steps.

connected USB with mobile

android auto app is running

adb forward tcp:5277 tcp:5277

./../extras/google/auto/desktop-head-unit

4th step getting an error :-

desktop-head-unit[54345:3905939] 00:05:51.597 WARNING:  140: This application, or a library it uses, is using the deprecated Carbon Component Manager for hosting Audio Units. Support for this will be removed in a future release. Also, this makes the host incompatible with version 3 audio units. Please transition to the API's in AudioComponent.h.
Connecting over ADB to localhost:5277...connected.

Failed to read from transport - disconnect. Exiting...

Android Studio Version : 2.2.3
Mobile : nexus 5
Android Version : 6.0.1

Please suggest.

答:
Try to restart adb like the command "adb kill-server" and then set the tcp again.
Check if you started the head unit from the companion app</p>


问:
Multidimensional Arrays Nested to Unlimited Depth
I have a multidimensional array nested to an unknown/unlimited depth.
I'd like to be able to loop through every element.
I don't want to use, foreach(){foreach(){foreach(){}}} as I don't know the depth.

I'm eventually looking for all nested arrays called "xyz".  Has anyone got any suggestions?

答:
Take a look to the RecursiveIteratorIterator interface.</p>

```<code>$interface = new RecursiveIteratorIterator( new RecursiveArrayIterator($your_array) );
foreach($interface as $k=>$v) { /* your function*/  }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Take a look to the RecursiveIteratorIterator interface.

$interface = new RecursiveIteratorIterator( new RecursiveArrayIterator($your_array) );
foreach($interface as $k=>$v) { /* your function*/  }


问:
C# WinForms - Determine when void method returns
I'm trying to figure out how to determine best practice when a void method returns for a program I'm working on. Basically the program has a call to a 3rd party grid to tell it to save the contents to an Excel sheet. The method to save the grid is a void method grid.SaveExcel(string filename, ...). I was thinking it would require the use of the await and async commands but have read in multiple places that this isn't best practice. I'm curious how you would go about doing this correctly as I'm a noob in terms of await, async, Lamda, Invoke, Action, Task, delegate stuff in C# and think I'm just confusing myself. I basically know how to open SQL connections, populate a grid, handle button event handlers, build basic classes, etc (very basic stuff).

I basically want to call the grid.SaveExcel method and then update a progress bar while I'm waiting for the saving of the grid to complete. Once it completes, I want to move on to the next few lines of code. Can someone help point me in the right direction and show me some code to attempt to accomplish this? Thanks in advance!

答:
You can invoke your function on a BackgroundWorker.
https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx

This class will then automatically raise an event on completion, as well as allow you to report progress during execution that will also raise events on your object invocation thread. Here's a run through of setting one up:
https://www.dotnetperls.com/backgroundworker

All of this is assuming you do indeed need this process to be asynchronous.If you do not, you can simply invoke your save, and then immediately follow it with whatever post-save functionality you desire. If the save takes less than 200ms, you'd be better off just inlining it with the UI.


问:
How to pull data from database in a template-within-a-template? [F3]
I'm building a simple quiz application in F3.

Each quiz has many questions. Each question has many (possibly different) options. I've set up my MySQL database and tables correctly as such: (1) Quizzes_table, (2) Questions_table, (3) QuestionOptions_table, (4)... and a few others to record the user responses, etc.

I am not sure how to use the F3 structure to call the options for each question up properly from within the wider question template. Here's how the mockup looks like: http://www.gauravkeerthi.com/reallymeh-mockup/quiz1.html

And this is the project git: https://github.com/gauravkeerthi/reallymeh

QuizController.php:  (for now I've hardcoded the quiz1.html link for testing purposes)

```<code>class QuizController extends Controller {

    function beforeroute() {
        // session management if required
        // render header
        echo \Template::instance()->render('header.html');
    }

    function render($f3){
        $quizzes = new Quizzes($this->db);
        $quiz = $quizzes->getById(1)[0];
        $f3->set('quiz',$quiz);

        $thisquiz = new Questions($this->db);
        $questions = $thisquiz->getByQuizId(1);
        $f3->set('questions',$questions);

        echo \Template::instance()->render('quiz1.html');
    }
}
</code>```

This is the section within the quiz1.html that calls up the  options:

```<code><repeat group="{{ @questions }}" key="{{ @count }}" value="{{ @question }}">
     <div class="row">
        <div class="col-md-6">
           <h5>{{ @count + 1 }}. {{ @question.text }}</h5>
        </div>
        <div class="col-md-6">
           <select class="form-control bg-silver">
              <include href="options.html" with="id={{@question.id}}" />
           </select>
        </div>
     </div>
</repeat>
</code>```

And this is where I am stuck: I want to achieve something like a "QuestionOptionsController" where I use a getByQuestionId($question.id) and pull all the data from the QuestionOptions and populate the select with the database. So in essence, I want the options to look something like this (but it is obviously wrong because I have no way to pull the correct data now).

My desired options.html with the data pulled from the table into @options:

```<code><repeat group="{{@options}}" value="{{@option}}">
   <option>{{@option.text }}</option>
</repeat>
</code>```

How do I pull the data into @options correctly? Should I use the QuizController and just pull ALL the relevant QuestionOptions_Table data into the view and then sort it out inside the view (seems messy to me) or is there a better way?

答:
You could create a QuestionsOptions model and implement a getOptions() method in your Questions model.

```<code>class Questions extends \DB\SQL\Mapper {

  function getOptions() {
    $options=new QuestionsOptions($this->db);
    return $options->find(['question=?',$this->id],['order'=>'weight']);
    // NB: field names to be adjusted
  }

  ...

  function __construct(\DB\SQL $db) {
    parent::__construct($db,'Questions_table');
  }

}
</code>```

and then in your quiz1.html template:

```<code><select class="form-control bg-silver">
  <repeat group="@question.getOptions()" value="@option">
    <option>{{ @option.text | esc }}</option>
  </repeat>
</select>
</code>```

UPDATE:

As you underlined it in your comment, this solution may be considered as breaking separation of concerns. If we think about it, that's the whole idea of passing the model object to the view which breaks it: not only getOptions() can be called from within the view, but also save()...

In order to have a stricter separation of concerns, I advise to cast the model before passing it to the view. That also brings the advantage of HTML encoding everything properly.

So your controller would look like:

```<code>function render($f3){
    $quizzes = new Quizzes($this->db);
    $quiz = $quizzes->getById(1)[0];
    $f3->set('quiz',$quiz->cast());

    $thisquiz = new Questions($this->db);
    $questions = [];
    foreach ($thisquiz->getByQuizId(1) as $question) {
      $options = [];
      foreach ($question->getOptions() as $option)
        $options[] = $option->cast();
      $questions[] = $question->cast()+['options => $options];
    }
    $f3->set('questions',$questions);

    echo \Template::instance()->render('quiz1.html');
}
</code>```

And your view would look like:

```<code><select class="form-control bg-silver">
  <repeat group="@question.options" value="@option">
    <option>{{ @option.text }}</option>
  </repeat>
</select>
</code>```

As you can see, the controller code looks a bit more complex now. But now your view does only manipulate arrays and HTML-encoded strings.

Body:
I'm building a simple quiz application in F3.

Each quiz has many questions. Each question has many (possibly different) options. I've set up my MySQL database and tables correctly as such: (1) Quizzes_table, (2) Questions_table, (3) QuestionOptions_table, (4)... and a few others to record the user responses, etc.

I am not sure how to use the F3 structure to call the options for each question up properly from within the wider question template. Here's how the mockup looks like: http://www.gauravkeerthi.com/reallymeh-mockup/quiz1.html

And this is the project git: https://github.com/gauravkeerthi/reallymeh

QuizController.php:  (for now I've hardcoded the quiz1.html link for testing purposes)

class QuizController extends Controller {

    function beforeroute() {
        // session management if required
        // render header
        echo \Template::instance()->render('header.html');
    }

    function render($f3){
        $quizzes = new Quizzes($this->db);
        $quiz = $quizzes->getById(1)[0];
        $f3->set('quiz',$quiz);

        $thisquiz = new Questions($this->db);
        $questions = $thisquiz->getByQuizId(1);
        $f3->set('questions',$questions);

        echo \Template::instance()->render('quiz1.html');
    }
}

This is the section within the quiz1.html that calls up the  options:

<repeat group="{{ @questions }}" key="{{ @count }}" value="{{ @question }}">

{{ @count + 1 }}. {{ @question.text }}

           <select class="form-control bg-silver">
              <include href="options.html" with="id={{@question.id}}" />
           </select>

</repeat>

And this is where I am stuck: I want to achieve something like a "QuestionOptionsController" where I use a getByQuestionId($question.id) and pull all the data from the QuestionOptions and populate the select with the database. So in essence, I want the options to look something like this (but it is obviously wrong because I have no way to pull the correct data now).

My desired options.html with the data pulled from the table into @options:

<repeat group="{{@options}}" value="{{@option}}">
   <option>{{@option.text }}</option>
</repeat>

How do I pull the data into @options correctly? Should I use the QuizController and just pull ALL the relevant QuestionOptions_Table data into the view and then sort it out inside the view (seems messy to me) or is there a better way?

Body:
You could create a QuestionsOptions model and implement a getOptions() method in your Questions model.

class Questions extends \DB\SQL\Mapper {

  function getOptions() {
    $options=new QuestionsOptions($this->db);
    return $options->find(['question=?',$this->id],['order'=>'weight']);
    // NB: field names to be adjusted
  }

  ...

  function __construct(\DB\SQL $db) {
    parent::__construct($db,'Questions_table');
  }

}

and then in your quiz1.html template:

<select class="form-control bg-silver">
  <repeat group="@question.getOptions()" value="@option">
    <option>{{ @option.text | esc }}</option>
  </repeat>
</select>

UPDATE:

As you underlined it in your comment, this solution may be considered as breaking separation of concerns. If we think about it, that's the whole idea of passing the model object to the view which breaks it: not only getOptions() can be called from within the view, but also save()...

In order to have a stricter separation of concerns, I advise to cast the model before passing it to the view. That also brings the advantage of HTML encoding everything properly.

So your controller would look like:

function render($f3){
    $quizzes = new Quizzes($this->db);
    $quiz = $quizzes->getById(1)[0];
    $f3->set('quiz',$quiz->cast());

    $thisquiz = new Questions($this->db);
    $questions = [];
    foreach ($thisquiz->getByQuizId(1) as $question) {
      $options = [];
      foreach ($question->getOptions() as $option)
        $options[] = $option->cast();
      $questions[] = $question->cast()+['options => $options];
    }
    $f3->set('questions',$questions);

    echo \Template::instance()->render('quiz1.html');
}

And your view would look like:

<select class="form-control bg-silver">
  <repeat group="@question.options" value="@option">
    <option>{{ @option.text }}</option>
  </repeat>
</select>

As you can see, the controller code looks a bit more complex now. But now your view does only manipulate arrays and HTML-encoded strings.


问:
Regex Replacing : to ":" etc
I've got a bunch of strings like:

```<code>"Hello, here's a test colon:. Here's a test semi-colon;"
</code>```

I would like to replace that with

```<code>"Hello, here's a test colon:. Here's a test semi-colon;"
</code>```

And so on for all printable ASCII values.

At present I'm using boost::regex_search to match &#(\d+);, building up a string as I process each match in turn (including appending the substring containing no matches since the last match I found).

Can anyone think of a better way of doing it? I'm open to non-regex methods, but regex seemed a reasonably sensible approach in this case.

Thanks,

Dom

答:
Here's another Perl's one-liner (see @mrree's answer):

a test file:

```
$ cat ent.txt
Hello, � here's a test colon:.
Here's a test semi-colon; 'ƒ'
```

the one-liner:

```
$ perl -pe's~&#(1?\d\d);~
> sub{ return chr($1) if (31 < $1 && $1 < 127); $& }->()~eg' ent.txt
```

or using more specific regex:

```
$ perl -pe"s~&#(1(?:[01][0-9]|2[0-6])|3[2-9]|[4-9][0-9]);~chr($1)~eg" ent.txt
```

both one-liners produce the same output:

```
Hello, � here's a test colon:.
Here's a test semi-colon; 'ƒ'
```

OwnerDisplayName: Dominic Rodger

Title: Regex Replacing : to ":" etc

Body:
I've got a bunch of strings like:

"Hello, here's a test colon:. Here's a test semi-colon;"

I would like to replace that with

"Hello, here's a test colon:. Here's a test semi-colon;"

And so on for all printable ASCII values.

At present I'm using boost::regex_search to match &#(\d+);, building up a string as I process each match in turn (including appending the substring containing no matches since the last match I found).

Can anyone think of a better way of doing it? I'm open to non-regex methods, but regex seemed a reasonably sensible approach in this case.

Thanks,

Dom

LastEditorDisplayName: PEZ

Body:
Here's another Perl's one-liner (see @mrree's answer):

a test file:

$ cat ent.txt
Hello, &#12; here's a test colon&#58;.
Here's a test semi-colon&#59; '&#131;'

the one-liner:

$ perl -pe's~&#(1?\d\d);~
> sub{ return chr($1) if (31 < $1 && $1 < 127); $& }->()~eg' ent.txt

or using more specific regex:

$ perl -pe"s~&#(1(?:[01][0-9]|2[0-6])|3[2-9]|[4-9][0-9]);~chr($1)~eg" ent.txt

both one-liners produce the same output:

Hello, &#12; here's a test colon:.
Here's a test semi-colon; '&#131;'

OwnerDisplayName: J.F. Sebastian

LastEditorDisplayName: J.F. Sebastian


问:
Browser caching of static resources (js, css): is it a real problem?
I wonder whether caching static resources by browsers (pretty much fresh: IE8, FF 3.6) is a real problem of development web application (when from time to time fresh version of webapp is going live and development continues).

Taking into account that serving static content by server is correct in terms of appropriate headers (last-modified, etags and etc.) and response codes (304 when not modified and 200 with body when changes exist).

Can be there any situations when serving html is fresh, while static still taken from browser cache?

答:
Unless you provide an Expires header, the browser should check for a new version each time the content is loaded, so it shouldn't be a problem (assuming the server gives the correct response).

But to be absolutely sure, you can give each version of your javascript/css a different filename, and change the filename in the HTML when you update. Then when the browser loads the HTML it will have to load the correct resources.


问:
Issues on bundling (angular2 + webpack bundling)
Here is my package.json. I added the dependencies for webpack.I had a confusion whether my denpendencies and scripts correct?. Because, when i do npm start, it starts bundling and started the angular2 project on browser, there i had an issue that Cannot get app.bundle.js, i have provided the index.html,webpack.config.js below,..

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "build": "rimraf dist && webpack --config webpack.config.js --progress",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "peerDependencies": {
    "uglify-js": "^2.8.0",
    "webpack": "^1.9 || ^2 || ^2.1.0-beta || ^2.2.0-rc"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.4",
    "core-js": "^2.4.1",
    "glob": "^7.1.1",
    "ng2-spin-kit": "^1.3.0",
    "ng2-toastr": "^1.5.1",
    "reflect-metadata": "^0.1.10",
    "rxjs": "5.0.1",
    "systemjs": "0.19.40",
    "webpack": "^2.2.1",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "@types/jasmine": "2.5.36",
    "@types/node": "^6.0.46",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.0",
    "babel-preset-env": "^1.2.1",
    "canonical-path": "0.0.2",
    "concurrently": "^3.2.0",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "lite-server": "^2.2.2",
    "lodash": "^4.16.4",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "tslint": "^3.15.1",
    "typescript": "~2.0.10",
    "webpack": "^2.2.1",
    "webpack-dev-server": "2.4.1",
    "webpack-merge": "^3.0.0"
  },
  "repository": {}
}```
</div>
</div>
</p>

<blockquote>
  <p>"build": "rimraf dist && webpack --config webpack.config.js
  --progress"</p>
</blockquote>

<p>And the webpack.config.js file is</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var webpack = require('webpack'),
  glob = require('glob');

module.exports = {

  entry: {
    'myPages': glob.sync('./src/**/*.js'), // here including js files from src folder
  },
  output: {
    path: './dist',
    filename: 'app.bundle.js',
    library: "node_modules",
  },
  target: 'web',
  module: {
    loaders: [{
        test: /\.node$/,
        loader: 'node-loader'
      },
      // Javascript: js, jsx
      {
        test: /\.jsx?$/,
        use: 'babel-loader'
      },
      // CSS: scss, css

      {
        test: /\.css$/,
        loader: "style!css"
      },
      // HTML: htm, html
      {
        test: /\.html?$/,
        loader: "file?name=[name].[ext]"
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
    })
  ]
};</code>```

The webpack.config.js gives the bundled output file named 'dist/app.bundle.js'(inside the dist folder), but i had an issue in inserting the app.bundle.js file into the html page, my index.html is

<!DOCTYPE html>

    <title>Angular_E&O</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <base href="/E&O">
    <link rel="stylesheet" href="styles.css">
    <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" />

    <mainapp>content loading..</mainapp>

```
</div>
</div>
</p>

<blockquote>
  <p>index.html is invoked</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><script src="dist/app.bundle.js"></script></code>```

in this script line i got error, that it could not get
  app.bundle.js, even i checked the path was also right

As i am begginer to the webpack bundling, please help me out,..

答:
please add the bundled js file after the root tag
like this</p>

```<code><mainapp>content loading..</mainapp>
<script src="dist/app.bundle.js"></script>
</code>```

Body:
Here is my package.json. I added the dependencies for webpack.I had a confusion whether my denpendencies and scripts correct?. Because, when i do npm start, it starts bundling and started the angular2 project on browser, there i had an issue that Cannot get app.bundle.js, i have provided the index.html,webpack.config.js below,..

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
  "scripts": {
    "build": "rimraf dist && webpack --config webpack.config.js --progress",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "peerDependencies": {
    "uglify-js": "^2.8.0",
    "webpack": "^1.9 || ^2 || ^2.1.0-beta || ^2.2.0-rc"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.4",
    "core-js": "^2.4.1",
    "glob": "^7.1.1",
    "ng2-spin-kit": "^1.3.0",
    "ng2-toastr": "^1.5.1",
    "reflect-metadata": "^0.1.10",
    "rxjs": "5.0.1",
    "systemjs": "0.19.40",
    "webpack": "^2.2.1",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "@types/jasmine": "2.5.36",
    "@types/node": "^6.0.46",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.0",
    "babel-preset-env": "^1.2.1",
    "canonical-path": "0.0.2",
    "concurrently": "^3.2.0",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "lite-server": "^2.2.2",
    "lodash": "^4.16.4",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "tslint": "^3.15.1",
    "typescript": "~2.0.10",
    "webpack": "^2.2.1",
    "webpack-dev-server": "2.4.1",
    "webpack-merge": "^3.0.0"
  },
  "repository": {}
}

"build": "rimraf dist && webpack --config webpack.config.js
  --progress"

And the webpack.config.js file is

var webpack = require('webpack'),
  glob = require('glob');

module.exports = {

  entry: {
    'myPages': glob.sync('./src/**/*.js'), // here including js files from src folder
  },
  output: {
    path: './dist',
    filename: 'app.bundle.js',
    library: "node_modules",
  },
  target: 'web',
  module: {
    loaders: [{
        test: /\.node$/,
        loader: 'node-loader'
      },
      // Javascript: js, jsx
      {
        test: /\.jsx?$/,
        use: 'babel-loader'
      },
      // CSS: scss, css

      {
        test: /\.css$/,
        loader: "style!css"
      },
      // HTML: htm, html
      {
        test: /\.html?$/,
        loader: "file?name=[name].[ext]"
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
    })
  ]
};

The webpack.config.js gives the bundled output file named 'dist/app.bundle.js'(inside the dist folder), but i had an issue in inserting the app.bundle.js file into the html page, my index.html is

<!DOCTYPE html>

    <title>Angular_E&O</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <base href="/E&O">
    <link rel="stylesheet" href="styles.css">
    <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" />

    <mainapp>content loading..</mainapp>

index.html is invoked

in this script line i got error, that it could not get
  app.bundle.js, even i checked the path was also right

As i am begginer to the webpack bundling, please help me out,..

Body:
please add the bundled js file after the root tag
like this

<mainapp>content loading..</mainapp>
<script src="dist/app.bundle.js"></script>


问:
Hostname was NOT found in DNS cache for port 8080 but fine on port 80?
I am testing an API I have made using Springboot from my laptop (192.168.1.217:8080) and I am trying to get a cURL request via SSH from my Raspberry Pi.

Here is the error I am receiving when I try to send the request via port 8080 which it seems to not like:

```<code>pi@raspberrypi:~ $ curl -v 192.168.1.217:8080/api
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...
</code>```

However cURL does work for the same IP but with port 80:

```<code>pi@raspberrypi:~ $ curl -v 192.168.1.217
* Rebuilt URL to: 192.168.1.217/
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...
* Connected to 192.168.1.217 (192.168.1.217) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.38.0
> Host: 192.168.1.217
> Accept: */*
>
< HTTP/1.1 302 Found
< Date: Thu, 30 Mar 2017 17:20:43 GMT
* Server Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38 is not blacklisted
< Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38
< X-Powered-By: PHP/5.5.38
< Location: http://192.168.1.217/dashboard/
< Content-Length: 0
< Content-Type: text/html
<
* Connection #0 to host 192.168.1.217 left intact
pi@raspberrypi:~ $
</code>```

I've tried looking around but to no avail... anybody have any suggestions as to why I cannot find my own hostname in the DNS cache?

Cheers

答:
curl without a protocol prefix presumes HTTP port 80.

To use another port, where it does not make that assumption, all you need to do is change your command's URL to be like this:

```<code>curl -v http://192.168.1.217:8080/api
</code>```

Here is a decent article on the subject:  Using CURL For Testing Web Applications

Body:
I am testing an API I have made using Springboot from my laptop (192.168.1.217:8080) and I am trying to get a cURL request via SSH from my Raspberry Pi.

Here is the error I am receiving when I try to send the request via port 8080 which it seems to not like:

pi@raspberrypi:~ $ curl -v 192.168.1.217:8080/api
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...

However cURL does work for the same IP but with port 80:

pi@raspberrypi:~ $ curl -v 192.168.1.217
* Rebuilt URL to: 192.168.1.217/
* Hostname was NOT found in DNS cache
*   Trying 192.168.1.217...
* Connected to 192.168.1.217 (192.168.1.217) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.38.0
> Host: 192.168.1.217
> Accept: */*
>
< HTTP/1.1 302 Found
< Date: Thu, 30 Mar 2017 17:20:43 GMT
* Server Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38 is not blacklisted
< Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.5.38
< X-Powered-By: PHP/5.5.38
< Location: http://192.168.1.217/dashboard/
< Content-Length: 0
< Content-Type: text/html
<
* Connection #0 to host 192.168.1.217 left intact
pi@raspberrypi:~ $

I've tried looking around but to no avail... anybody have any suggestions as to why I cannot find my own hostname in the DNS cache?

Cheers

Body:
curl without a protocol prefix presumes HTTP port 80.

To use another port, where it does not make that assumption, all you need to do is change your command's URL to be like this:

curl -v http://192.168.1.217:8080/api

Here is a decent article on the subject:  Using CURL For Testing Web Applications


问:
Maria DB : Alter a field to a PERSISTENT Calculated
I have created a table and I wish to make a Computed Column from the concatenated values of three other fields in the table.

I want this Computed Field to take place at INSERT or UPDATE, so I am specifying PERSISTENT

I have tried the following code (in various ways) in phpMyAdmin but always get errors, which seem to be referencing immediately after ALTER table

I did not see a way of doing this when adding the field in phpMyAdmin, so I hoped I could ALTER it.

```<code>Alter TABLE 'tlImages'
CHANGE COLUMN tlImageQuery
AS CONCAT(tlImgTitle,"~",tlImgDescrip,"~",tlImgWhereWhen) PERSISTENT;
</code>```

MariaDB version 10.0.29-MariaDB-cll-lve - MariaDB Server

phpMyAdmin . Version information: 4.0.10.18

答:
First, lose single quotes around the table name, they are not suitable for this purpose. Use backticks or nothing.

You will still get a syntax error further in the statement, because AS clause should be in brackets. Add them.

You will still get a syntax error because you are missing column type before the AS (...) clause, add it.

You will still get a syntax error because CHANGE COLUMN needs two column names, old and new, use MODIFY instead.

```<code>Alter TABLE `tlImages`
  MODIFY COLUMN tlImageQuery VARCHAR(128)
  AS (CONCAT(tlImgTitle,"~",tlImgDescrip,"~",tlImgWhereWhen)) PERSISTENT
;
</code>```

(Type VARCHAR(128) is given just as an example).

Body:
I have created a table and I wish to make a Computed Column from the concatenated values of three other fields in the table.

I want this Computed Field to take place at INSERT or UPDATE, so I am specifying PERSISTENT

I have tried the following code (in various ways) in phpMyAdmin but always get errors, which seem to be referencing immediately after ALTER table

I did not see a way of doing this when adding the field in phpMyAdmin, so I hoped I could ALTER it.

Alter TABLE 'tlImages'
CHANGE COLUMN tlImageQuery
AS CONCAT(tlImgTitle,"~",tlImgDescrip,"~",tlImgWhereWhen) PERSISTENT;

MariaDB version 10.0.29-MariaDB-cll-lve - MariaDB Server

phpMyAdmin . Version information: 4.0.10.18

Body:
First, lose single quotes around the table name, they are not suitable for this purpose. Use backticks or nothing.

You will still get a syntax error further in the statement, because AS clause should be in brackets. Add them.

You will still get a syntax error because you are missing column type before the AS (...) clause, add it.

You will still get a syntax error because CHANGE COLUMN needs two column names, old and new, use MODIFY instead.

Alter TABLE `tlImages`
  MODIFY COLUMN tlImageQuery VARCHAR(128)
  AS (CONCAT(tlImgTitle,"~",tlImgDescrip,"~",tlImgWhereWhen)) PERSISTENT
;

(Type VARCHAR(128) is given just as an example).


问:
Odoo 10 - Account move line import
In Odoo 8, we could import CSV data for "Account moves" and "Account move lines".

I'm migrating to Odoo 10 : i found how to import "Account moves" but where can i import the line of my moves (there's no "Import" button on the view of Account move lines) ?

Thanx.

Christophe

答:
In account.move.line default tree view create='false' is set.

If in tree view create='false' is set  then odoo will hide Create and Import button.

The following is odoo default view.

```<code>    <record id="view_move_line_tree" model="ir.ui.view">
        <field name="name">account.move.line.tree</field>
        <field name="model">account.move.line</field>
        <field eval="1" name="priority"/>
        <field name="arch" type="xml">
            <tree string="Journal Items" create="false">
                <field name="date"/>
                <field name="move_id" required="0"/>
                <field name="journal_id" options='{"no_open":True}'/>
                <field name="name"/>
                <field name="ref"/>
                <field name="statement_id" invisible="1"/>
                <field name="partner_id"/>
                <field name="account_id" options='{"no_open":True}' domain="[('company_id', '=', company_id)]"/>
                <field name="analytic_account_id" groups="analytic.group_analytic_accounting"/>
                <field name="reconciled" invisible="1"/>
                <field name="full_reconcile_id"/>
                <field name="debit" sum="Total Debit"/>
                <field name="credit" sum="Total Credit"/>
                <field name="amount_currency" readonly="True" groups="base.group_multi_currency"/>
                <field name="currency_id" readonly="True" invisible="1" />
                <field name="date_maturity"/>
                <field name="company_currency_id" invisible="1"/>
                <field name="company_id" invisible="1"/>
            </tree>
        </field>
    </record>
</code>```

You can override above Tree view in your module and remove create='false'.

```<code>    <record id="account.view_move_line_tree" model="ir.ui.view">
        <field name="name">account.move.line.tree</field>
        <field name="model">account.move.line</field>
        <field eval="1" name="priority"/>
        <field name="arch" type="xml">
            <tree string="Journal Items">
                <field name="date"/>
                <field name="move_id" required="0"/>
                <field name="journal_id" options='{"no_open":True}'/>
                <field name="name"/>
                <field name="ref"/>
                <field name="statement_id" invisible="1"/>
                <field name="partner_id"/>
                <field name="account_id" options='{"no_open":True}' domain="[('company_id', '=', company_id)]"/>
                <field name="analytic_account_id" groups="analytic.group_analytic_accounting"/>
                <field name="reconciled" invisible="1"/>
                <field name="full_reconcile_id"/>
                <field name="debit" sum="Total Debit"/>
                <field name="credit" sum="Total Credit"/>
                <field name="amount_currency" readonly="True" groups="base.group_multi_currency"/>
                <field name="currency_id" readonly="True" invisible="1" />
                <field name="date_maturity"/>
                <field name="company_currency_id" invisible="1"/>
                <field name="company_id" invisible="1"/>
            </tree>
        </field>
    </record>
</code>```

After that You can import CSV file.

You can import account.move.line & account.move in same file, I have attached import format.

You can export any existing account move from Action in tree view and select all required field.Just export it.

If you want to import account.move.line and account.move using different file then you must inherit account.move.line create method and set check_move_validity is False.

```<code>    if self._context.get('check_move_validity', True):
        move.with_context(context)._post_validate()
</code>```

Above condition is odoo base module account.move.line create method condtion.When account.move.line is create at that time system is checking if check_move_validity is False then system will not try to reconcile single move line.

You need to inherit create and write method in custom module,after that line by line import work as well.

```<code>@api.model
def create(self, vals):
    move_line = super(AccountMoveLine, self.with_context(check_move_validity=False)).create(vals)
    return move_line

@api.multi
def write(self, vals):
    move_line = super(AccountMoveLine, self.with_context(check_move_validity=False)).write(vals)
    return move_line
</code>```

This may help you.

Title: Odoo 10 - Account move line import

Body:
In account.move.line default tree view create='false' is set.

If in tree view create='false' is set  then odoo will hide Create and Import button.

The following is odoo default view.

    <record id="view_move_line_tree" model="ir.ui.view">
        <field name="name">account.move.line.tree</field>
        <field name="model">account.move.line</field>
        <field eval="1" name="priority"/>
        <field name="arch" type="xml">
            <tree string="Journal Items" create="false">
                <field name="date"/>
                <field name="move_id" required="0"/>
                <field name="journal_id" options='{"no_open":True}'/>
                <field name="name"/>
                <field name="ref"/>
                <field name="statement_id" invisible="1"/>
                <field name="partner_id"/>
                <field name="account_id" options='{"no_open":True}' domain="[('company_id', '=', company_id)]"/>
                <field name="analytic_account_id" groups="analytic.group_analytic_accounting"/>
                <field name="reconciled" invisible="1"/>
                <field name="full_reconcile_id"/>
                <field name="debit" sum="Total Debit"/>
                <field name="credit" sum="Total Credit"/>
                <field name="amount_currency" readonly="True" groups="base.group_multi_currency"/>
                <field name="currency_id" readonly="True" invisible="1" />
                <field name="date_maturity"/>
                <field name="company_currency_id" invisible="1"/>
                <field name="company_id" invisible="1"/>
            </tree>
        </field>
    </record>

You can override above Tree view in your module and remove create='false'.

    <record id="account.view_move_line_tree" model="ir.ui.view">
        <field name="name">account.move.line.tree</field>
        <field name="model">account.move.line</field>
        <field eval="1" name="priority"/>
        <field name="arch" type="xml">
            <tree string="Journal Items">
                <field name="date"/>
                <field name="move_id" required="0"/>
                <field name="journal_id" options='{"no_open":True}'/>
                <field name="name"/>
                <field name="ref"/>
                <field name="statement_id" invisible="1"/>
                <field name="partner_id"/>
                <field name="account_id" options='{"no_open":True}' domain="[('company_id', '=', company_id)]"/>
                <field name="analytic_account_id" groups="analytic.group_analytic_accounting"/>
                <field name="reconciled" invisible="1"/>
                <field name="full_reconcile_id"/>
                <field name="debit" sum="Total Debit"/>
                <field name="credit" sum="Total Credit"/>
                <field name="amount_currency" readonly="True" groups="base.group_multi_currency"/>
                <field name="currency_id" readonly="True" invisible="1" />
                <field name="date_maturity"/>
                <field name="company_currency_id" invisible="1"/>
                <field name="company_id" invisible="1"/>
            </tree>
        </field>
    </record>

After that You can import CSV file.

You can import account.move.line & account.move in same file, I have attached import format.

You can export any existing account move from Action in tree view and select all required field.Just export it.

If you want to import account.move.line and account.move using different file then you must inherit account.move.line create method and set check_move_validity is False.

    if self._context.get('check_move_validity', True):
        move.with_context(context)._post_validate()

Above condition is odoo base module account.move.line create method condtion.When account.move.line is create at that time system is checking if check_move_validity is False then system will not try to reconcile single move line.

You need to inherit create and write method in custom module,after that line by line import work as well.

@api.model
def create(self, vals):
    move_line = super(AccountMoveLine, self.with_context(check_move_validity=False)).create(vals)
    return move_line

@api.multi
def write(self, vals):
    move_line = super(AccountMoveLine, self.with_context(check_move_validity=False)).write(vals)
    return move_line

This may help you.


问:
What does the jsr keyword mean?
I'm looking at some Java code, and I've noticed the following:

```<code>if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}
</code>```

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?

答:
You are most likely looking at the results of decompiling some code which the decompiler wasn't able to cope with.  JSR is the mnemonic for the jump subroutine bytecode; see this page for a listing.  So jsr 432 may mean call a private method at bytecode address 432.  However, the decompiler cannot figure that out, so maybe the method is synthetic, or something else is going on.

EDIT

Googled example you found is definitely decompiler output, and it looks like the part with the JSRs is either cause by obfuscation, byte code modification / generation, or by a decompiler stuffup.

Title: What does the jsr keyword mean?

Body:
I'm looking at some Java code, and I've noticed the following:

if (!foo(bar, baz, qux)) {
    i = 0; jsr 433;
}

javac chokes on it, saying it's not a statement and that a semicolon is expected after the keyword jsr.

I did some Googling, and I found some code containing the same thing, which leads me to believe it's there intentionally (even though they weren't able to get it to compile either). So what does jsr do? How does one get code containing it to compile?


问:
How does partitioning of DStreams ( for updateStateByKey() ) work and how to verify it?
I am using updateStateByKey() operation to maintain state in my Spark Streaming application. The input data is coming through a Kafka topic.

I want to understand how are DStreams partitioned?

How does the partitioning work with mapWithState() or updateStatebyKey() method?

In updateStateByKey() does the old state and the new values against a given key processed on same node ?

How frequent is the shuffle for updateStateByKey() method ?

The state I have to maintaining contains ~ 100000 keys and I want to avoid shuffle every time I update the state , any tips to do it ?

答: updateStateByKey takes a Partitioner as it's second argument. http://spark.apache.org/docs/1.6.0/api/scala/index.html#org.apache.spark.streaming.dstream.PairDStreamFunctions</p>


问:
Itunes Connect can't delete app
I can't delete a App in Itunes Connect, I am the Team Agent and my App has the status Preparing for Submission. But there isn't a Delete App button. Can anyone help please ?

答: Actually we can not delete app directly from iTunes until app rejected from apple. First submit the app for review process after that if your app rejected or except by apple then you can remove it from apple store.</p>

Title: Itunes Connect can't delete app


问:
Azure Functions dll referencing
How can I use the "#r" preprocessor directive to reference dlls from another container?

Common #r usage will only search for dlls inside the container on my function app resource group.

答:
I think your goal could be achieved in a better way.

If you want to find your Azure Files account, go to <functionapp>.azurewebsites.net/Envand look for APPSETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING and APPSETTING_WEBSITE_CONTENTSHARE.

To access the reference across functions, create a nuget package for your dll and create a project.json for each function (How can I use NuGet packages in my Azure Functions? / Access Nuget Packages hosted in private Nuget server in Azure Functions)

Using precompiled functions is another good option for managing your references by moving development locally & using normal web app deployment: https://github.com/Azure/azure-webjobs-sdk-script/wiki/Precompiled-functions and https://aka.ms/precompiled-functions.

Title: Azure Functions dll referencing


答:
No matter what your account prevelages are, you can't delete an app on Preparing for Submission status.

According to the iTunes Connect Developer Guide.

Apps that have not been approved yet can’t be deleted

So, for now, you need to sitback and wait for the review result. Once you got the result(whatever accepted or rejected) you can delete your app.

Update 2018: You can now delete unused/never submitted apps from App Store Connect

Title: Itunes Connect can't delete app

Body: I can't delete a App in Itunes Connect, I am the Team Agent and my App has the status Preparing for Submission. But there isn't a Delete App button. Can anyone help please ?


问:
Using delphi code in java
I have an old yet very complicated algorithm written is Delphi that i want to use as a service for a java project.

My plan is to build a site that can serve the algorithms benefits through a web interface without re-writing the code due to it's complicity.

I have seen many options for doing the exact opposite (that's make sense) but couldn't find what I was looking for.

答:
I use the same through a Mormot server: https://synopse.info/
It allow me to execute procedures and get results (in binary or json for example) along side of others cool things...

Or you cam use TIdHttpServer, and call your old procedures like an webservice, like mormot but vastly more restricted

Title: Using delphi code in java


问:
Search specific annotations in mapView
In my project i have a mapView with a lot of annotations & i would like to add a search functionality to the map so i can search those annotations and quickly find the annotation i want.

I followed a tutorial i found on the web but it searches globally (MKLocalSearch) and not the annotations.

I tried looking for a tutorial \ Help for my problem but i couldn't get any help for a long time now.
Here is my search code :

I've made these annotations :

```<code>let LitzmanLocation = CLLocationCoordinate2DMake(32.100668,34.775192)
        // Drop a pin
        let Litzman = MKPointAnnotation()
        Litzman.coordinate = LitzmanLocation
        Litzman.title = "Litzman Bar"
        Litzman.subtitle = "נמל תל אביב 18,תל אביב"
        mapView.addAnnotation(Litzman)

        let ShalvataLocation = CLLocationCoordinate2DMake(32.101145,34.775163)
        // Drop a pin
        let Shalvata = MKPointAnnotation()
        Shalvata.coordinate = ShalvataLocation
        Shalvata.title = "Shalvata"
        Shalvata.subtitle = "האנגר 28,נמל תל אביב"
        mapView.addAnnotation(Shalvata)

        let MarkidLocation = CLLocationCoordinate2DMake(32.074961,34.781679)
        // Drop a pin
        let Markid = MKPointAnnotation()
        Markid.coordinate = MarkidLocation
        Markid.title = "Markid"
        Markid.subtitle = "אבן גבירול 30,תל אביב"
        mapView.addAnnotation(Markid)
</code>```

Currently the search i have:

MapViewController:

```<code>    //All my Map code is here
    }
    }
    }
    extension MapViewController: HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark){
        // cache the pin
        selectedPin = placemark
        // clear existing pins
        let annotation = MKPointAnnotation()
        annotation.coordinate = placemark.coordinate
        annotation.title = placemark.name
        if let _ = placemark.locality,
            let _ = placemark.administrativeArea {
            annotation.subtitle = ""
        }
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.01, 0.01)
        let region = MKCoordinateRegionMake(placemark.coordinate, span)
        mapView.setRegion(region, animated: true)
    }
}
</code>```

SearchTable:

```<code>import UIKit
import MapKit

class LocationSearchTable : UITableViewController {

    var matchingItems = [CustomAnnotations]()
    var mapView: MKMapView? = nil

    var handleMapSearchDelegate:HandleMapSearch? = nil

    func parseAddress(selectedItem:MKPlacemark) -> String {
        // put a space between "4" and "Melrose Place"
        let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : ""
        // put a comma between street and city/state
        let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : ""
        // put a space between "Washington" and "DC"
        let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : ""
        let addressLine = String(
            format:"%@%@%@%@%@%@%@",
            // street number
            selectedItem.subThoroughfare ?? "",
            firstSpace,
            // street name
            selectedItem.thoroughfare ?? "",
            comma,
            // city
            selectedItem.locality ?? "",
            secondSpace,
            // state
            selectedItem.administrativeArea ?? ""
        )
        return addressLine
    }

    func search(keywords:String) {
        self.matchingItems.removeAll()
        for annotation in self.mapView!.annotations {
            if annotation.isKindOfClass(CustomAnnotations) {
                //Just an example here for searching annotation by title, you could add other filtering actions else.
                if (annotation.title??.rangeOfString(keywords) != nil) {
                    self.matchingItems.append(annotation as! CustomAnnotations)
                }
            }
        }
        self.tableView.reloadData()
    }

}

extension LocationSearchTable : UISearchResultsUpdating {
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        guard let mapView = mapView,
            let searchBarText = searchController.searchBar.text else { return }
        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = searchBarText
        request.region = mapView.region
        let search = MKLocalSearch(request: request)
        search.startWithCompletionHandler { response, _ in
            guard let response = response else {
                return
            }
            self.matchingItems = response.mapItems
            self.tableView.reloadData()
        }
    }

}

extension LocationSearchTable {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return matchingItems.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MapSearchCell", forIndexPath: indexPath)
        let selectedItem = matchingItems[indexPath.row]
        cell.textLabel?.text = selectedItem.title
        cell.detailTextLabel?.text = selectedItem.subtitle
        return cell
    }

}

extension LocationSearchTable {
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let selectedItem = matchingItems[indexPath.row]//.placemark
        handleMapSearchDelegate?.dropPinZoomIn(selectedItem)
        dismissViewControllerAnimated(true, completion: nil)
    }
}
</code>```

My question is how i can turn this to only search my annotations and not search all over the world with MKLocalSearch.

I'm a beginner coder using swift 3 and Xcode 8

Thanks you for helping.

答:
You should just leave the MKLocalSearch out altogether if you really don't want to search the entire map. You can choose to prioritize a given region with MKLocalSearchRequest.region, but you can't actually constrain the search. Instead of that, you should loop over the annotations variable of your MKMapView.

```<code>extension String {
  func caseInsensitiveSearch(_ string: String) -> Bool {
    if self.lowercased().range(of: string.lowercased()) != nil {
      return true;
    } else {
      return false;
    }
  }
}

extension MKMapView {
    func searchForCustomAnnotation(like query: String) -> [MyCustomAnnotationClass] {
      let allAnnotations = self.annotations;
      return allAnotations.filter { annotation in
        if let customAnnotation = annotation as? MyCustomAnnotationClass {
          return customAnnotation.title.caseInsensitiveSearch(query);
        }
      }
   }
}
</code>```

EDIT: I just noticed you said you were using Swift 2.3, my code is Swift 3. If you're using Swift 2.3, you should change the String.caseInsensitiveSearch method to:

```<code>extension String {
  func caseInsensitiveSearch(_ string: String) -> Bool {
    if self.lowercaseString.rangeOfString(string.lowercaseString) != nil {
      return true;
    } else {
      return false;
    }
  }
}
</code>```

You can then use searchForCustomAnnotation on your MKMapView to get a list of all annotations with a title containing your search query.

Your code would look like this:

```<code>extension LocationSearchTable: UISearchResultsUpdating {
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        guard let mapView = mapView,
              let searchBarText = searchController.searchBar.text else { return }
            self.matchingItems = mapView.searchForCustomAnnotation(like: searchBarText);
            self.tableView.reloadData()
        }
    }
}
</code>```

Title: Search specific annotations in mapView

Body:
In my project i have a mapView with a lot of annotations & i would like to add a search functionality to the map so i can search those annotations and quickly find the annotation i want.

I followed a tutorial i found on the web but it searches globally (MKLocalSearch) and not the annotations.

I tried looking for a tutorial \ Help for my problem but i couldn't get any help for a long time now.
Here is my search code :

I've made these annotations :

let LitzmanLocation = CLLocationCoordinate2DMake(32.100668,34.775192)
        // Drop a pin
        let Litzman = MKPointAnnotation()
        Litzman.coordinate = LitzmanLocation
        Litzman.title = "Litzman Bar"
        Litzman.subtitle = "נמל תל אביב 18,תל אביב"
        mapView.addAnnotation(Litzman)

        let ShalvataLocation = CLLocationCoordinate2DMake(32.101145,34.775163)
        // Drop a pin
        let Shalvata = MKPointAnnotation()
        Shalvata.coordinate = ShalvataLocation
        Shalvata.title = "Shalvata"
        Shalvata.subtitle = "האנגר 28,נמל תל אביב"
        mapView.addAnnotation(Shalvata)

        let MarkidLocation = CLLocationCoordinate2DMake(32.074961,34.781679)
        // Drop a pin
        let Markid = MKPointAnnotation()
        Markid.coordinate = MarkidLocation
        Markid.title = "Markid"
        Markid.subtitle = "אבן גבירול 30,תל אביב"
        mapView.addAnnotation(Markid)

Currently the search i have:

MapViewController:

    //All my Map code is here
    }
    }
    }
    extension MapViewController: HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark){
        // cache the pin
        selectedPin = placemark
        // clear existing pins
        let annotation = MKPointAnnotation()
        annotation.coordinate = placemark.coordinate
        annotation.title = placemark.name
        if let _ = placemark.locality,
            let _ = placemark.administrativeArea {
            annotation.subtitle = ""
        }
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.01, 0.01)
        let region = MKCoordinateRegionMake(placemark.coordinate, span)
        mapView.setRegion(region, animated: true)
    }
}

SearchTable:

import UIKit
import MapKit

class LocationSearchTable : UITableViewController {

    var matchingItems = [CustomAnnotations]()
    var mapView: MKMapView? = nil

    var handleMapSearchDelegate:HandleMapSearch? = nil

    func parseAddress(selectedItem:MKPlacemark) -> String {
        // put a space between "4" and "Melrose Place"
        let firstSpace = (selectedItem.subThoroughfare != nil && selectedItem.thoroughfare != nil) ? " " : ""
        // put a comma between street and city/state
        let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) && (selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : ""
        // put a space between "Washington" and "DC"
        let secondSpace = (selectedItem.subAdministrativeArea != nil && selectedItem.administrativeArea != nil) ? " " : ""
        let addressLine = String(
            format:"%@%@%@%@%@%@%@",
            // street number
            selectedItem.subThoroughfare ?? "",
            firstSpace,
            // street name
            selectedItem.thoroughfare ?? "",
            comma,
            // city
            selectedItem.locality ?? "",
            secondSpace,
            // state
            selectedItem.administrativeArea ?? ""
        )
        return addressLine
    }

    func search(keywords:String) {
        self.matchingItems.removeAll()
        for annotation in self.mapView!.annotations {
            if annotation.isKindOfClass(CustomAnnotations) {
                //Just an example here for searching annotation by title, you could add other filtering actions else.
                if (annotation.title??.rangeOfString(keywords) != nil) {
                    self.matchingItems.append(annotation as! CustomAnnotations)
                }
            }
        }
        self.tableView.reloadData()
    }

}

extension LocationSearchTable : UISearchResultsUpdating {
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        guard let mapView = mapView,
            let searchBarText = searchController.searchBar.text else { return }
        let request = MKLocalSearchRequest()
        request.naturalLanguageQuery = searchBarText
        request.region = mapView.region
        let search = MKLocalSearch(request: request)
        search.startWithCompletionHandler { response, _ in
            guard let response = response else {
                return
            }
            self.matchingItems = response.mapItems
            self.tableView.reloadData()
        }
    }

}

extension LocationSearchTable {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return matchingItems.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("MapSearchCell", forIndexPath: indexPath)
        let selectedItem = matchingItems[indexPath.row]
        cell.textLabel?.text = selectedItem.title
        cell.detailTextLabel?.text = selectedItem.subtitle
        return cell
    }

}

extension LocationSearchTable {
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let selectedItem = matchingItems[indexPath.row]//.placemark
        handleMapSearchDelegate?.dropPinZoomIn(selectedItem)
        dismissViewControllerAnimated(true, completion: nil)
    }
}

My question is how i can turn this to only search my annotations and not search all over the world with MKLocalSearch.

I'm a beginner coder using swift 3 and Xcode 8

Thanks you for helping.

Body:
You should just leave the MKLocalSearch out altogether if you really don't want to search the entire map. You can choose to prioritize a given region with MKLocalSearchRequest.region, but you can't actually constrain the search. Instead of that, you should loop over the annotations variable of your MKMapView.

extension String {
  func caseInsensitiveSearch(_ string: String) -> Bool {
    if self.lowercased().range(of: string.lowercased()) != nil {
      return true;
    } else {
      return false;
    }
  }
}

extension MKMapView {
    func searchForCustomAnnotation(like query: String) -> [MyCustomAnnotationClass] {
      let allAnnotations = self.annotations;
      return allAnotations.filter { annotation in
        if let customAnnotation = annotation as? MyCustomAnnotationClass {
          return customAnnotation.title.caseInsensitiveSearch(query);
        }
      }
   }
}

EDIT: I just noticed you said you were using Swift 2.3, my code is Swift 3. If you're using Swift 2.3, you should change the String.caseInsensitiveSearch method to:

extension String {
  func caseInsensitiveSearch(_ string: String) -> Bool {
    if self.lowercaseString.rangeOfString(string.lowercaseString) != nil {
      return true;
    } else {
      return false;
    }
  }
}

You can then use searchForCustomAnnotation on your MKMapView to get a list of all annotations with a title containing your search query.

Your code would look like this:

extension LocationSearchTable: UISearchResultsUpdating {
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        guard let mapView = mapView,
              let searchBarText = searchController.searchBar.text else { return }
            self.matchingItems = mapView.searchForCustomAnnotation(like: searchBarText);
            self.tableView.reloadData()
        }
    }
}


问:
How to solve Webpack 2 and Karma MemoryFileSystem error?
I am trying to set up karma to run with webpack in a very simple react app but since updating to webpack 2 all I get is errors when running my tests. Compiling the react app works perfectly tho. Anything in my webpack or karma config that might be causing this?

Here's my error:

```<code>> NODE_ENV=test karma start

START:
(node:1370) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
Error
    at MemoryFileSystem.mkdirpSync (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/memory-fs/lib/MemoryFileSystem.js:144:10)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/lib/Compiler.js:322:27)
    at /Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:3022:16
    at eachOfArrayLike (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:941:9)
    at eachOf (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:991:5)
    at Object.eachLimit (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:3086:3)
    at Compiler.emitFiles (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/lib/Compiler.js:312:20)
    at Immediate.<anonymous> (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/memory-fs/lib/MemoryFileSystem.js:288:4)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)
</code>```

dependencies:

```<code>"dependencies": {
    "axios": "^0.15.3",
    "express": "^4.15.2",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-router": "^3.0.2"
  },
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^6.4.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "babel-preset-stage-0": "^6.22.0",
    "css-loader": "^0.26.2",
    "expect": "^1.20.2",
    "foundation-sites": "^6.3.1",
    "jquery": "^3.1.1",
    "karma": "^1.5.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-mocha": "^1.3.0",
    "karma-mocha-reporter": "^2.2.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^2.0.2",
    "mocha": "^3.2.0",
    "node-sass": "^4.5.0",
    "react-addons-test-utils": "^15.4.2",
    "sass-loader": "^6.0.2",
    "script-loader": "^0.7.0",
    "style-loader": "^0.13.2",
    "webpack": "^2.2.1"
  }
</code>```

webpack config:

```<code>    const webpack = require('webpack');
    const path = require('path');

    //will be set to 'production on heroku'
    //process.env.NODE_ENV = process.env.NODE_ENV || 'development';

    module.exports = {
      //where to start the app
      entry: {
        app: path.resolve(__dirname, 'app/app.jsx'),
      },
      output: {
        path: path.resolve(__dirname, './public'),
        filename: '[name].bundle.js'
      },
      //setting up the babel loader to handle jsx files(es2015)
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            exclude: /(node_modules|bower_componets)/,
            use: [{
              loader: 'babel-loader',
              options: {presets:['react', 'es2015', 'stage-0']}
            }],
          },
        ],
      },//end of modules
      resolve: {
        //Tell webpack what directories should be searched when resolving modules.
        modules: [
          path.join(__dirname, 'app/components'),
          path.join(__dirname, 'app/api'),
          'node_modules',
        ],
        //Automatically resolve certain extensions.
        extensions: ['.js', '.jsx', '.json'],
      }, //end of resolve
      //This option controls if and how Source Maps are generated.
      devtool:'cheap-module-eval-source-map'
    };//end of module.exports
</code>```

karma config:

```<code>var webpackConfig = require('./webpack.config.js');

module.exports = function (config) {
  config.set({
    browsers: ['Chrome'],
    singleRun: true,
    frameworks: ['mocha'],
    files: [
      './app/tests/**/*.test.jsx'
    ],
    preprocessors: {
      './app/tests/**/*.test.jsx': ['webpack', 'sourcemap']
    },
    reporters: ['mocha'],
    client: {
      mocha: {
        timeout: '5000'
      }
    },
    webpack: webpackConfig,
    webpackServer: {
      noInfo: true
    }
  })
</code>```

答:
My problem was that I needed to remove the "entry" property from my webpack.config. I did this by adding the following piece of code:

```<code>webpackConfig.entry = null;
</code>```

Thanks to this post of the enlightenment:
Error: not a directory at MemoryFileSystem.mkdirpSync

Body:
I am trying to set up karma to run with webpack in a very simple react app but since updating to webpack 2 all I get is errors when running my tests. Compiling the react app works perfectly tho. Anything in my webpack or karma config that might be causing this?

Here's my error:

> NODE_ENV=test karma start

START:
(node:1370) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
Error
    at MemoryFileSystem.mkdirpSync (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/memory-fs/lib/MemoryFileSystem.js:144:10)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/lib/Compiler.js:322:27)
    at /Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:3022:16
    at eachOfArrayLike (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:941:9)
    at eachOf (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:991:5)
    at Object.eachLimit (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/node_modules/async/dist/async.js:3086:3)
    at Compiler.emitFiles (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/webpack/lib/Compiler.js:312:20)
    at Immediate.<anonymous> (/Users/rperez/devProjects/CamperLeaderBoard/node_modules/memory-fs/lib/MemoryFileSystem.js:288:4)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)

dependencies:

"dependencies": {
    "axios": "^0.15.3",
    "express": "^4.15.2",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-router": "^3.0.2"
  },
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-loader": "^6.4.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "babel-preset-stage-0": "^6.22.0",
    "css-loader": "^0.26.2",
    "expect": "^1.20.2",
    "foundation-sites": "^6.3.1",
    "jquery": "^3.1.1",
    "karma": "^1.5.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-mocha": "^1.3.0",
    "karma-mocha-reporter": "^2.2.2",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^2.0.2",
    "mocha": "^3.2.0",
    "node-sass": "^4.5.0",
    "react-addons-test-utils": "^15.4.2",
    "sass-loader": "^6.0.2",
    "script-loader": "^0.7.0",
    "style-loader": "^0.13.2",
    "webpack": "^2.2.1"
  }

webpack config:

    const webpack = require('webpack');
    const path = require('path');

    //will be set to 'production on heroku'
    //process.env.NODE_ENV = process.env.NODE_ENV || 'development';

    module.exports = {
      //where to start the app
      entry: {
        app: path.resolve(__dirname, 'app/app.jsx'),
      },
      output: {
        path: path.resolve(__dirname, './public'),
        filename: '[name].bundle.js'
      },
      //setting up the babel loader to handle jsx files(es2015)
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            exclude: /(node_modules|bower_componets)/,
            use: [{
              loader: 'babel-loader',
              options: {presets:['react', 'es2015', 'stage-0']}
            }],
          },
        ],
      },//end of modules
      resolve: {
        //Tell webpack what directories should be searched when resolving modules.
        modules: [
          path.join(__dirname, 'app/components'),
          path.join(__dirname, 'app/api'),
          'node_modules',
        ],
        //Automatically resolve certain extensions.
        extensions: ['.js', '.jsx', '.json'],
      }, //end of resolve
      //This option controls if and how Source Maps are generated.
      devtool:'cheap-module-eval-source-map'
    };//end of module.exports

karma config:

var webpackConfig = require('./webpack.config.js');

module.exports = function (config) {
  config.set({
    browsers: ['Chrome'],
    singleRun: true,
    frameworks: ['mocha'],
    files: [
      './app/tests/**/*.test.jsx'
    ],
    preprocessors: {
      './app/tests/**/*.test.jsx': ['webpack', 'sourcemap']
    },
    reporters: ['mocha'],
    client: {
      mocha: {
        timeout: '5000'
      }
    },
    webpack: webpackConfig,
    webpackServer: {
      noInfo: true
    }
  })

Body:
My problem was that I needed to remove the "entry" property from my webpack.config. I did this by adding the following piece of code:

webpackConfig.entry = null;

Thanks to this post of the enlightenment:
Error: not a directory at MemoryFileSystem.mkdirpSync