问:
Elegant way to convert python datetime.timedelta to dateutil.relativedelta
Is there an elegant was to convert between relativedelta and timedelta?

The use case is getting user input ISO date. Python's isodate will return either isodate.duration.Duration or datetime.timedelta.

We need the features of relativedelta (per What is the difference between "datetime.timedelta" and "dateutil.relativedelta.relativedelta" when working only with days? -- it does more) so need to convert both these types to a relativedata.

答:
Using seconds directly with relativedelta does not populate the months and years fields and there is a reason of course that we wouldn't know if it's a leap year or a month with 31 days.

So something like this:

```<code>[In]:  tdelta = datetime.now() - datetime(1971, 1, 1)
[In]:  relativedelta(seconds=tdelta.total_seconds())
[Out]: relativedelta(days=+16958, hours=+13, minutes=+19, seconds=+49)
</code>```

gives relative delta with lots of days and no months. While this can be okay in certain cases, in some we might need the years and months. Therefore:

```<code>def timedelta_to_relativedelta(tdelta):
    assert isinstance(tdelta, timedelta)

    seconds_in = {
        'year'  : 365 * 24 * 60 * 60,
        'month' : 30 * 24 * 60 * 60,
        'day'   : 24 * 60 * 60,
        'hour'  : 60 * 60,
        'minute': 60
    }

    years, rem = divmod(tdelta.total_seconds(), seconds_in['year'])
    months, rem = divmod(rem, seconds_in['month'])
    days, rem = divmod(rem, seconds_in['day'])
    hours, rem = divmod(rem, seconds_in['hour'])
    minutes, rem = divmod(rem, seconds_in['minute'])
    seconds = rem

    return relativedelta(years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds)
</code>```

This might not be a very Pythonic solution but it works.

Note: This assumes that a year has 365 days (ignores leap non leap years) and months have 30 days.

Body:
Using seconds directly with relativedelta does not populate the months and years fields and there is a reason of course that we wouldn't know if it's a leap year or a month with 31 days.

So something like this:

[In]:  tdelta = datetime.now() - datetime(1971, 1, 1)
[In]:  relativedelta(seconds=tdelta.total_seconds())
[Out]: relativedelta(days=+16958, hours=+13, minutes=+19, seconds=+49)

gives relative delta with lots of days and no months. While this can be okay in certain cases, in some we might need the years and months. Therefore:

def timedelta_to_relativedelta(tdelta):
    assert isinstance(tdelta, timedelta)

    seconds_in = {
        'year'  : 365 * 24 * 60 * 60,
        'month' : 30 * 24 * 60 * 60,
        'day'   : 24 * 60 * 60,
        'hour'  : 60 * 60,
        'minute': 60
    }

    years, rem = divmod(tdelta.total_seconds(), seconds_in['year'])
    months, rem = divmod(rem, seconds_in['month'])
    days, rem = divmod(rem, seconds_in['day'])
    hours, rem = divmod(rem, seconds_in['hour'])
    minutes, rem = divmod(rem, seconds_in['minute'])
    seconds = rem

    return relativedelta(years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds)

This might not be a very Pythonic solution but it works.

Note: This assumes that a year has 365 days (ignores leap non leap years) and months have 30 days.


来源: stackexchange

问:
Citrix Get-Brokerapplication from specific server
On XenApp 6.x servers, there was a cmdlet like this:

```<code>GET-XAApplication -ServerName servername
</code>```

I used to open a PSSession on the adminserver, then got all servers with GET-XAServer and then I simply did the Application command in a foreach loop, where the ServerName parameter was the servername from XAServer. Now I want to do the same on Version 7, but I can't figure out how it works.

I installed all new cmdlets for the newer Version. I found out I can get the Applications with GET-Brokerapplication - but I can't pass a parameter to tell the command from which server I want to grab them, so I can only grab them from my admin server.

Maybe someone can help me? I've already looked at the documentation (https://docs.citrix.com/de-de/xenapp-and-xendesktop/7-6/cds-sdk-wrapper-rho/xad-commands/citrix-broker-admin-v2-wrapper-xd76/get-brokerapplication-xd76.html) but I can't find a parameter who allows me to do what I want. MaybeI'm looking at the wrong cmdlet?

I would be really happy if someone has a advise for me.

答:
In XenApp 6.x there were Worker Groups and you should have been publishing applications for Worker Groups instead of individual servers. Then you can enumerate Worker Groups and Applications:

```<code>$wgs = Get-XAWorkerGroup
foreach ($group  in $wgs) {
    $apps = Get-XAApplication -WorkerGroupName $group
}
</code>```

In XenApp 7.x WorkerGroups are replaced by Delivery Groups and you can enumerate them and associated applications:

```<code>$groups = Get-BrokerDesktopGroup
foreach ($group in $groups) {
    $apps = Get-BrokerApplication -AssociatedDesktopGroupUid $group.UID
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
On XenApp 6.x servers, there was a cmdlet like this:

GET-XAApplication -ServerName servername

I used to open a PSSession on the adminserver, then got all servers with GET-XAServer and then I simply did the Application command in a foreach loop, where the ServerName parameter was the servername from XAServer. Now I want to do the same on Version 7, but I can't figure out how it works.

I installed all new cmdlets for the newer Version. I found out I can get the Applications with GET-Brokerapplication - but I can't pass a parameter to tell the command from which server I want to grab them, so I can only grab them from my admin server.

Maybe someone can help me? I've already looked at the documentation (https://docs.citrix.com/de-de/xenapp-and-xendesktop/7-6/cds-sdk-wrapper-rho/xad-commands/citrix-broker-admin-v2-wrapper-xd76/get-brokerapplication-xd76.html) but I can't find a parameter who allows me to do what I want. MaybeI'm looking at the wrong cmdlet?

I would be really happy if someone has a advise for me.

Body:
In XenApp 6.x there were Worker Groups and you should have been publishing applications for Worker Groups instead of individual servers. Then you can enumerate Worker Groups and Applications:

$wgs = Get-XAWorkerGroup
foreach ($group  in $wgs) {
    $apps = Get-XAApplication -WorkerGroupName $group
}

In XenApp 7.x WorkerGroups are replaced by Delivery Groups and you can enumerate them and associated applications:

$groups = Get-BrokerDesktopGroup
foreach ($group in $groups) {
    $apps = Get-BrokerApplication -AssociatedDesktopGroupUid $group.UID
}

ContentLicense: CC BY-SA 4.0


问:
Displaying custom error page at startup
Is there a way to display a custom error page when an exception occurs during the startup phase of an ASP.NET Core application? For example, if an exception occurs (db is down etc.) in any of the methods of the Startup class i.e. Configure, ConfigureServices, Startup.Ctor etc.?

I think that using the following code isn't going to help me

```<code>if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseBrowserLink();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}
</code>```

as the middleware pipline isn't constructed yet. So the line

```<code>app.UseExceptionHandler("/Home/Error");
</code>```

isn't executed as a consequence.

Is there a way to display a custom error page if an error occurs at this stage?

thanks

ashilon

答:
In the Configure method you're configuring the HTTP pipeline to handle requests. Since there is no request when your application starts, the pipeline is never executed. In fact, as you mentioned the exception might occur when you're actually configuring the pipeline.

The hosting layer provides a way to capture startup errors and show a decent error page. You can use the CaptureStartupErrors(true) on the IWebHostBuilder interface. This is where you configure the hosting layer of your application and is typically located in Pogram.cs. For example:

```<code>public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .CaptureStartupErrors(captureStartupErrors: true) // Add this line
        .Build();

    host.Run();
}
</code>```

Title: Displaying custom error page at startup

Body:
Is there a way to display a custom error page when an exception occurs during the startup phase of an ASP.NET Core application? For example, if an exception occurs (db is down etc.) in any of the methods of the Startup class i.e. Configure, ConfigureServices, Startup.Ctor etc.?

I think that using the following code isn't going to help me

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseBrowserLink();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

as the middleware pipline isn't constructed yet. So the line

app.UseExceptionHandler("/Home/Error");

isn't executed as a consequence.

Is there a way to display a custom error page if an error occurs at this stage?

thanks

ashilon

Body:
In the Configure method you're configuring the HTTP pipeline to handle requests. Since there is no request when your application starts, the pipeline is never executed. In fact, as you mentioned the exception might occur when you're actually configuring the pipeline.

The hosting layer provides a way to capture startup errors and show a decent error page. You can use the CaptureStartupErrors(true) on the IWebHostBuilder interface. This is where you configure the hosting layer of your application and is typically located in Pogram.cs. For example:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .CaptureStartupErrors(captureStartupErrors: true) // Add this line
        .Build();

    host.Run();
}


问:
trim down the error details logged by ELMAH
I am using Elmah for error logging and it is logging lot more info than what I need, especially all the server variables for the form in the form of Xml in database. I would like to exclude these server variables (and may be some more stuff), I am not interested in them. is it possible to configure this somewhere in web.config or do it programmatically at least?</p>

答:
Just keep them - you might not need them now, but at some point they may save your bacon.

If you're worried about space, then you're probably throwing too many exceptions...

ContentLicense: CC BY-SA 2.5


问:
WordPress excerpt character count not working
My loop looks like this:

```<code><!-- loop for the posts here -->
<?php
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'category_name' => 'news'
    );
    $query = new WP_Query($args);
    while($query->have_posts()) : $query->the_post();
?>
    <div class="news_box_content">
        <h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
        <figure><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure>
        <?php if($post->post_excerpt) { ?>
            <p><?php echo get_the_excerpt(); ?></p>
            <a href="<?php the_permalink(); ?>">Read more...</a>
        <?php } else {
            the_content('Read More');
        } ?>
    </div>
<?php endwhile; wp_reset_postdata(); ?>
</code>```

I used a function to count the excerpt length but it is not working.

```<code>function custom_excerpt_length(){
   return 10;
}
add_filter('excerpt_length', 'custom_excerpt_length');
</code>```

How can I limit the number of characters on any excerpt?

答:
No need for an extra filter</p>

```<code>echo substr(get_the_excerpt(), 0,10);
</code>```

Body:
My loop looks like this:

<?php
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'category_name' => 'news'
    );
    $query = new WP_Query($args);
    while($query->have_posts()) : $query->the_post();
?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?>

        <?php if($post->post_excerpt) { ?>

<?php echo get_the_excerpt(); ?>

            <a href="<?php the_permalink(); ?>">Read more...
        <?php } else {
            the_content('Read More');
        } ?>

<?php endwhile; wp_reset_postdata(); ?>

I used a function to count the excerpt length but it is not working.

function custom_excerpt_length(){
   return 10;
}
add_filter('excerpt_length', 'custom_excerpt_length');

How can I limit the number of characters on any excerpt?

Body:
No need for an extra filter

echo substr(get_the_excerpt(), 0,10);


问:
MSPL Script in Skype for Business 2015
I have a MSPL script running as a Server Application in a Lync Server 2013 system. The development of this application was done in c# referencing the library 'C:\Program Files\Microsoft Lync Server 2013\SDK\Bin\ServerAgent.dll' which was installed with the MS Lync Server 2013 SDK.

I need to migrate this application to a Skype for Business 2015 system but I can't find the SfB equivalent of the Lync Server 2013 SDK.

Does anyone know how to compile a MSPL application in SfB 2015 ? I've read in various places that it should 'just work' in SfB but that would only be if I dropped the ServerAgent.dll in the same folder as the application on the SfB Front End Server and that seems like a hack.

Any suggestions would be welcome.

Thanks

Ed James

答:
I ran into the same issue. In my case, using the old versions of "ServerAgent.dll" resulted in a strange behavior, as this typical piece of code to proxy the request was doing nothing:

```<code>ClientTransation ct = e.ServerTransaction.CreateBranch();

ct.SendRequest(e.Request);
</code>```

In Skype for Business / Lync client, when establishing a new conversation (while my MSPL script was triggered on INVITE) the error "your message could not be transmitted" was appearing.

After investigation, and after trying to recompile my code on a Windows Server 2012 R2 with Skype for Business Server 2015 installed on it, it appeared that the new version of "ServerAgent.dll" (version 6.0.9319 located in Windows's GAC folder) had a dependency against another DLL which was in .NET Framework 4.5, while all my solution was built on .NET Framework 4.0.
To solve this issue, I recompiled in 4.5, but as I wanted to keep using Visual Studio 2010, I had to apply this solution (look for the second solution):

Targeting .NET Framework 4.5 via Visual Studio 2010

After that I finally managed to have it working correctly on Skype for Business 2015.

Title: MSPL Script in Skype for Business 2015

Body:
I ran into the same issue. In my case, using the old versions of "ServerAgent.dll" resulted in a strange behavior, as this typical piece of code to proxy the request was doing nothing:

ClientTransation ct = e.ServerTransaction.CreateBranch();

ct.SendRequest(e.Request);

In Skype for Business / Lync client, when establishing a new conversation (while my MSPL script was triggered on INVITE) the error "your message could not be transmitted" was appearing.

After investigation, and after trying to recompile my code on a Windows Server 2012 R2 with Skype for Business Server 2015 installed on it, it appeared that the new version of "ServerAgent.dll" (version 6.0.9319 located in Windows's GAC folder) had a dependency against another DLL which was in .NET Framework 4.5, while all my solution was built on .NET Framework 4.0.
To solve this issue, I recompiled in 4.5, but as I wanted to keep using Visual Studio 2010, I had to apply this solution (look for the second solution):

Targeting .NET Framework 4.5 via Visual Studio 2010

After that I finally managed to have it working correctly on Skype for Business 2015.


问:
Shapeless find instance of Some among Nones in an Hlist of Options
lets say I have the following class hierarchy:

```<code>sealed trait Animal

case class Cat(isFriendly: Boolean) extends Animal
case class Dog(color: String) extends Animal
case class Fish(isFreshWater: Boolean) extends Animal
</code>```

Now I have an instance of type

```<code>Option[Cat] :: Option[Dog] :: Option[Fish] :: HNil
</code>```

But there is a restriction on the instance. It can only be of one of the following forms

```<code>Some(Cat(???)) :: None :: None :: HNil
</code>```

or

```<code>None :: Some(Dog(???)) :: None :: HNil
</code>```

or

```<code>None :: None :: Some(Fish(???)) :: HNil
</code>```

First, excuse any incoherence - it is part of a larger problem that I am trying to solve that is not yet well articulated

Second, the ??? is just my contrived place holder for real instance such as:

```<code>None :: Some(Dog(brown)) :: None :: HNil
</code>```

Thing is, I am rather new to shapeless and I don't exactly know if the value of the ??? makes a difference.

Onwards to the question

Is there a way to "iterate" over the HList and extract the Some?

I understand that when speaking generically it is not possible as shown in the following two questions. But I wonder whether adding the restrictions I set above would make a difference

https://stackoverflow.com/a/28598157/101715

https://stackoverflow.com/a/29572541/101715

答:
As explained in the link you gave, such an operation is only possible on HList if your values are statically typed as Some and None, so that the compiler can do anything about it.

If you have additional information that what the type gives (here, the fact that exactly one of the options can be a Some), it means that you're using the wrong type, since types are the information you have on values at compile time. In this case, the type you should use is Coproduct:

```<code>type AnimalCoproduct = Cat :+: Dog :+: Fish :+: CNil

val dog = Coproduct[AnimalCoproduct](Dog("brown"))
</code>```

Now, back to your question, assuming you know which are None and which are Some at compile time.

First, you need to check which HList have the property that they are a list of None.

```<code>trait IsNoneList[L <: HList]

object IsNoneList {
  //all values in an HNil are None, since there aren't any
  implicit val hnil: IsNoneList[HNil] = new IsNoneList[HNil] {}

  //if all the values in the tail are None, and the head is None, then all the values are None
  implicit def hcons[T <: HList: IsNoneList]: IsNoneList[None.type :: T] = new IsNoneList[None.type :: T] {}
}
</code>```

So now, if there is an implicit IsNoneList[L] in scope, it means that L is an HList of None.type. Let's do the same with the property we're looking for:

```<code>trait IsOneSomeHList[L <: HList] {
  type OneSome
  def get(l: L): OneSome
}

object IsOneSomeHList {
  type Aux[L <: HList, O] = IsOneSomeHList[L] { type OneSome =  O }

  def apply[L <: HList](implicit L: IsOneSomeHList[L]) = L

  // if the tail is full of None, and the head is a Some, then the property is true
  implicit def someHead[A, T <: HList: IsNoneList]: Aux[Some[A] :: T, A] = new IsOneSomeHList[Some[A] :: T] {
    type OneSome = A
    def get(l: Some[A] :: T) = l.head.get
  }

  //if the head is None, and the tail has the property, then the HCons also has the property, with the same extraction function
  implicit def noneHead[T <: HList](implicit T: IsOneSomeHList[T]): Aux[None.type :: T, T.OneSome] = new IsOneSomeHList[None.type :: T] {
    type OneSome = T.OneSome
    override def get(l: ::[None.type, T]): T.OneSome = T.get(l.tail)
  }
}
</code>```

Notice that if we have an implicit IsOneSomeHList[L] in scope, we know that L has the property we want, but we can also use this implicit to get the type and the value of the only Some in the list.

EDIT

Let's give an example:

```<code>val cat = Some(Cat(isFriendly = true)) :: None :: None :: HNil

IsOneSomeHList[Some[Cat] :: None.type :: None.type :: HNil].get(cat) == Cat(true)
</code>```

Body:
lets say I have the following class hierarchy:

sealed trait Animal

case class Cat(isFriendly: Boolean) extends Animal
case class Dog(color: String) extends Animal
case class Fish(isFreshWater: Boolean) extends Animal

Now I have an instance of type

Option[Cat] :: Option[Dog] :: Option[Fish] :: HNil

But there is a restriction on the instance. It can only be of one of the following forms

Some(Cat(???)) :: None :: None :: HNil

or

None :: Some(Dog(???)) :: None :: HNil

or

None :: None :: Some(Fish(???)) :: HNil

First, excuse any incoherence - it is part of a larger problem that I am trying to solve that is not yet well articulated

Second, the ??? is just my contrived place holder for real instance such as:

None :: Some(Dog(brown)) :: None :: HNil

Thing is, I am rather new to shapeless and I don't exactly know if the value of the ??? makes a difference.

Onwards to the question

Is there a way to "iterate" over the HList and extract the Some?

I understand that when speaking generically it is not possible as shown in the following two questions. But I wonder whether adding the restrictions I set above would make a difference

https://stackoverflow.com/a/28598157/101715

https://stackoverflow.com/a/29572541/101715

Body:
As explained in the link you gave, such an operation is only possible on HList if your values are statically typed as Some and None, so that the compiler can do anything about it.

If you have additional information that what the type gives (here, the fact that exactly one of the options can be a Some), it means that you're using the wrong type, since types are the information you have on values at compile time. In this case, the type you should use is Coproduct:

type AnimalCoproduct = Cat :+: Dog :+: Fish :+: CNil

val dog = Coproduct[AnimalCoproduct](Dog("brown"))

Now, back to your question, assuming you know which are None and which are Some at compile time.

First, you need to check which HList have the property that they are a list of None.

trait IsNoneList[L <: HList]

object IsNoneList {
  //all values in an HNil are None, since there aren't any
  implicit val hnil: IsNoneList[HNil] = new IsNoneList[HNil] {}

  //if all the values in the tail are None, and the head is None, then all the values are None
  implicit def hcons[T <: HList: IsNoneList]: IsNoneList[None.type :: T] = new IsNoneList[None.type :: T] {}
}

So now, if there is an implicit IsNoneList[L] in scope, it means that L is an HList of None.type. Let's do the same with the property we're looking for:

trait IsOneSomeHList[L <: HList] {
  type OneSome
  def get(l: L): OneSome
}

object IsOneSomeHList {
  type Aux[L <: HList, O] = IsOneSomeHList[L] { type OneSome =  O }

  def apply[L <: HList](implicit L: IsOneSomeHList[L]) = L

  // if the tail is full of None, and the head is a Some, then the property is true
  implicit def someHead[A, T <: HList: IsNoneList]: Aux[Some[A] :: T, A] = new IsOneSomeHList[Some[A] :: T] {
    type OneSome = A
    def get(l: Some[A] :: T) = l.head.get
  }

  //if the head is None, and the tail has the property, then the HCons also has the property, with the same extraction function
  implicit def noneHead[T <: HList](implicit T: IsOneSomeHList[T]): Aux[None.type :: T, T.OneSome] = new IsOneSomeHList[None.type :: T] {
    type OneSome = T.OneSome
    override def get(l: ::[None.type, T]): T.OneSome = T.get(l.tail)
  }
}

Notice that if we have an implicit IsOneSomeHList[L] in scope, we know that L has the property we want, but we can also use this implicit to get the type and the value of the only Some in the list.

EDIT

Let's give an example:

val cat = Some(Cat(isFriendly = true)) :: None :: None :: HNil

IsOneSomeHList[Some[Cat] :: None.type :: None.type :: HNil].get(cat) == Cat(true)


问:
Toggle and animate height of a ul within a li
I have a list inside a li which needs to slide into view when the parent li is clicked.

My code works nicely but if i click any li all of the sub lists show where as i want it only to apply to the one that was clicked...

```<code>$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });

<ul id="offering">
     <li class="t current"><a href="#solutions"><span>sage solutions</span></a>
                    <ul>
                        <li><a href="#">50</a></li>
                        <li><a href="#">200</a></li>
                        <li><a href="#">CRM</a></li>
                    </ul>
                </li>
     <li class="m"><a href="#management"><span>solutions</span></a>
                  <ul>
                      <li><a href="#">50</a></li>
                      <li><a href="#">200</a></li>
                      <li><a href="#">CRM</a></li>
                  </ul>
              </li>
     <li class="b"><a href="#thirdparty"><span>third party additions</span></a></li>
            </ul>
</code>```

Body:
I have a list inside a li which needs to slide into view when the parent li is clicked.

My code works nicely but if i click any li all of the sub lists show where as i want it only to apply to the one that was clicked...

$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });

sage solutions

50

200

CRM

solutions

50

200

CRM

third party additions

Body: $(this).find("ul").animate({height: "toggle"}, 1000);


问:
How do i fix my spawning script from randomly stopping the spawning of enemies?
I have a simple script that is supposed to spawn zombies with time delays that can be inputted. The script seems to work fine however, after I move my character for a while, the gameobject which is running the script stops spawning zombies.If my character stands still, the zombies will continue to spawn. The red arrow is pointing to the gameObject that is spawning the zombies.

```<code>using UnityEngine;
using System.Collections;

public class spawn : MonoBehaviour
{
    public GameObject zombie;
    public float delayTime = 4f;

    IEnumerator Start()
    {
        var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
        yield return new WaitForSeconds(delayTime);
        StartCoroutine(Start());
    }
}
</code>```

Scene setup is as follows:

答:
You don't really need to use coroutine for that, InvokeRepeating should be good enough. Also make sure your zombie prefab is private so it doesn't get replaced by other scripts</p>

```<code>[SerializeField] private GameObject zombie;
float waitBeforeFirstSpawn = 0f;
float delayTime = 4f;

void Start()
{
    InvokeRepeating("SpawnZombie", waitBeforeFirstSpawn, delayTime);
}

void SpawnZombie()
{
    GameObject zombieGO = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
}
</code>```

Body:
I have a simple script that is supposed to spawn zombies with time delays that can be inputted. The script seems to work fine however, after I move my character for a while, the gameobject which is running the script stops spawning zombies.If my character stands still, the zombies will continue to spawn. The red arrow is pointing to the gameObject that is spawning the zombies.

using UnityEngine;
using System.Collections;

public class spawn : MonoBehaviour
{
    public GameObject zombie;
    public float delayTime = 4f;

    IEnumerator Start()
    {
        var obj = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
        yield return new WaitForSeconds(delayTime);
        StartCoroutine(Start());
    }
}

Scene setup is as follows:

Body:
You don't really need to use coroutine for that, InvokeRepeating should be good enough. Also make sure your zombie prefab is private so it doesn't get replaced by other scripts

[SerializeField] private GameObject zombie;
float waitBeforeFirstSpawn = 0f;
float delayTime = 4f;

void Start()
{
    InvokeRepeating("SpawnZombie", waitBeforeFirstSpawn, delayTime);
}

void SpawnZombie()
{
    GameObject zombieGO = Instantiate(zombie, transform.position, transform.rotation) as GameObject;
}


问:
Why can't I move an element into vector of non-copyables?
The compiler tells me I'm trying to access a deleted function (i.e. the copy constructor of a lambda expression).  But I don't see where.

```<code>std::vector<std::function<void()>> tasks;
std::packaged_task<int()> task{ [] { return 1; } };
tasks.emplace_back(
    [ t = std::move(task) ] () mutable { t(); });
</code>```

(code is also here)

(I'm trying to find out why they use shared_ptr<task> in https://www.slideshare.net/GlobalLogicUkraine/c11-multithreading-futures).

On Gcc and MSVC I get the same error - I fear I'm doing something wrong...

```<code>error: use of deleted function
'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
</code>```

Why can't I emplace this std::function onto the vector?

答:
Short answer: Lambdas and std::packaged_task are not std::functions.

Long answer, you cannot move a std::packaged_task  into a std::function

Here's what I'm offering as a solution:

```<code>std::vector<std::packaged_task<int()>> tasks;
std::packaged_task<int()> task{ [] () mutable { return 1; } };
tasks.emplace_back( std::move(task) );
</code>```

If you actually need a std::function, and not just any callable, you'll have to bind a lambda into a std::function

Body:
The compiler tells me I'm trying to access a deleted function (i.e. the copy constructor of a lambda expression).  But I don't see where.

std::vector<std::function<void()>> tasks;
std::packaged_task<int()> task{ [] { return 1; } };
tasks.emplace_back(
    [ t = std::move(task) ] () mutable { t(); });

(code is also here)

(I'm trying to find out why they use shared_ptr<task> in https://www.slideshare.net/GlobalLogicUkraine/c11-multithreading-futures).

On Gcc and MSVC I get the same error - I fear I'm doing something wrong...

error: use of deleted function
'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'

Why can't I emplace this std::function onto the vector?

Body:
Short answer: Lambdas and std::packaged_task are not std::functions.

Long answer, you cannot move a std::packaged_task  into a std::function

Here's what I'm offering as a solution:

std::vector<std::packaged_task<int()>> tasks;
std::packaged_task<int()> task{ [] () mutable { return 1; } };
tasks.emplace_back( std::move(task) );

If you actually need a std::function, and not just any callable, you'll have to bind a lambda into a std::function


问:
Reading a string from and to a certain character
I would like to know if it is possible to read a certain string of n-length, from x character to y character without having to split it into smaller pieces.

I have the following string, for a path in AD CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com, and I would like to be able to just read the someName part of it, without splitting by = or , first. How do I achieve that?

Reason is, that I do not have to do group comparison as I am doing it right now:

```<code>SearchResult t1 = search.FindOne();
foreach (string s in t1.Properties["memberof"])
{
    foreach (string g in groups)
    {
        if (s.ToLower().Contains(g.ToLower()))
        {
            // do something
        }
    }
}
</code>```

I would rather make the if clause to equals, but I do not want to always split the above path/groups into an array twice. How do I do that?

答:
With Split you can check if any of the given keys equals to the search value.

```<code>var val = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
var prefix = "CN";
var searchValue = "someName";
var contains = val.Split(',').Any(value => value.Split('=')[0] == prefix && value.Split('=')[1] == searchValue);
</code>```

Insead of checking if the value is equal to the search value you can also just return the value.

```<code>var val = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
var prefix = "CN";
var foundValue = val.Split(',').FirstOrDefault(value => value.Split('=')[0] == prefix)?.Split('=')[1];
</code>```

I still used Split despite you said you don't want to use it as I think it makes a nice one liner.

Body:
I would like to know if it is possible to read a certain string of n-length, from x character to y character without having to split it into smaller pieces.

I have the following string, for a path in AD CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com, and I would like to be able to just read the someName part of it, without splitting by = or , first. How do I achieve that?

Reason is, that I do not have to do group comparison as I am doing it right now:

SearchResult t1 = search.FindOne();
foreach (string s in t1.Properties["memberof"])
{
    foreach (string g in groups)
    {
        if (s.ToLower().Contains(g.ToLower()))
        {
            // do something
        }
    }
}

I would rather make the if clause to equals, but I do not want to always split the above path/groups into an array twice. How do I do that?

Body:
With Split you can check if any of the given keys equals to the search value.

var val = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
var prefix = "CN";
var searchValue = "someName";
var contains = val.Split(',').Any(value => value.Split('=')[0] == prefix && value.Split('=')[1] == searchValue);

Insead of checking if the value is equal to the search value you can also just return the value.

var val = "CN=someName,OU=someGroup,OU=groups,DC=some,DC=domain,DC=com";
var prefix = "CN";
var foundValue = val.Split(',').FirstOrDefault(value => value.Split('=')[0] == prefix)?.Split('=')[1];

I still used Split despite you said you don't want to use it as I think it makes a nice one liner.


问:
How yield identify that its iteration done once.?
I have read about yield at What does the "yield" keyword do in Python? keyword in python but i have one question that how system identity that yield iterated once.

```<code>def test_yield():
    name = 'Hello World!'
    for i in name:
        yield i

y= test_yield()

print "first yield",y
for c in y:
    print c

print "second yield",y
for c in y:
    print c
</code>```

Output

```<code>first yield <generator object test_yield at 0x7f4c2bc10be0>
H
e
l
l
o

W
o
r
l
d
!
second yield <generator object test_yield at 0x7f4c2bc10be0>
</code>```

In output second time yield object printed but not iterate.so how program identity that its executed once?

答:
When a generator function calls yield, the "state" of the generator function is frozen; the values of all variables are saved and the next line of code to be executed is recorded until next() is called again. Once it is, the generator function simply resumes where it left off. If next() is never called again, the state recorded during the yield call is (eventually) discarded.

Given that when the generator function reaches it's end, a StopIteration Exception is raised, making it exhausted hence you have to reload it, that is the reason it didn't iterate any values during the second call.

Note : for gets values by calling next() implicitly

Body:
I have read about yield at What does the "yield" keyword do in Python? keyword in python but i have one question that how system identity that yield iterated once.

def test_yield():
    name = 'Hello World!'
    for i in name:
        yield i

y= test_yield()

print "first yield",y
for c in y:
    print c

print "second yield",y
for c in y:
    print c

Output

first yield <generator object test_yield at 0x7f4c2bc10be0>
H
e
l
l
o

W
o
r
l
d
!
second yield <generator object test_yield at 0x7f4c2bc10be0>

In output second time yield object printed but not iterate.so how program identity that its executed once?


问:
Swift Spritekit I detect a collison but it reads the collision mulitple times
AppImage I have a wall of 4 rectangles that are different colors, to pass through the wall the color of the ball has to match that of the rectangle on the wall. The ball will pass through the wall, and a new wall will appear. However, when I detect this collision I get multiple collision readings. I have tested this by printing dead or alive, and it prints both or more many times.

```<code>func didBegin(_ contact: SKPhysicsContact) {

    if let nodeA = contact.bodyA.node as? SKShapeNode, let nodeB = contact.bodyB.node as? SKShapeNode {
        if nodeA.fillColor != nodeB.fillColor {
            print("DEAD")
        }
        else {
            print("Alive")
        }
    }
}
</code>```

please help!!!

答:
Yep - this happens. The way to handle it (you can't get sprite-kit to NOT call didBegin multiple times in some circumstances) is to make sure that your contact code accommodates this and that handling the contract multiple times does not cause a problem (such as adding to the score multiple times, removing multiple lives, trying to access a node or physicsBody that has been removed etc).

There is a discussion here: Sprite-Kit registering multiple collisions for single contact

Some things you can do include:

If you remove a node that is contacted, check for it being nil before
you remove it (for the duplicate contacts)

Add the node to a set and then remove all the nodes in the set in
didFinishUpdate

Add an 'inactive' flag' to the node's userData

Make the node a subclass of SKSpriteNode and add an inactive property

Etc etc.

Body:
AppImage I have a wall of 4 rectangles that are different colors, to pass through the wall the color of the ball has to match that of the rectangle on the wall. The ball will pass through the wall, and a new wall will appear. However, when I detect this collision I get multiple collision readings. I have tested this by printing dead or alive, and it prints both or more many times.

func didBegin(_ contact: SKPhysicsContact) {

    if let nodeA = contact.bodyA.node as? SKShapeNode, let nodeB = contact.bodyB.node as? SKShapeNode {
        if nodeA.fillColor != nodeB.fillColor {
            print("DEAD")
        }
        else {
            print("Alive")
        }
    }
}

please help!!!


问:
laravel jquery select2 multiselect - initialize selected elements
Good morning everybody, I'm stuck while trying to set initial selected options (got through an ajax requests) to a jquery select2 (multi-select). If I use the control, multi selection works just fine. The problem arise when I have to edit a previously saved model, as none of the options I previously selected are shown.

This is my view:

```<code><div class="form-group {{ $errors->has('pubblicazione_giuridica_id') ? 'has-error' : ''}}">
    {!! Form::label('pubblicazione_giuridica_id', 'Law Pubs', ['class' => 'col-sm-3 control-label']) !!}
    <div class="col-sm-6">
        {!! Form::select('pubblicazione_giuridica_id[]', [$pubGiurList], null, ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']) !!}
        {!! $errors->first('pubblicazione_giuridica_id', '<p class="help-block">:message</p>') !!}
    </div>
</code>```

The javascript:

```<code>$('#select-pgiur').select2({
    ajax: {
        url: "{!! URL::to('/gare/proc-getpubgiur') !!}",
        dataType: 'json',
        delay: 150,
        data: function (params) {
            return { q: params.term, };
        },
        processResults: function (data, params) {
            return { results: data.items, };
        },
        cache: true
    },
    language: 'it',
    theme: "bootstrap",
    placeholder: "Choose an option."
});
</code>```

The Controller:

```<code>public function edit($id, Request $request) {
    $procedure = $this->getProcedure($id, $request, true);
    if (!$procedure) {
        return redirect('gare/procedure')->with('alert-warning', 'Gara non trovata - Operazione non consentita');
    }
    return view('gare.procedures.edit', [ 'procedure'=>$procedure, 'opChoiceList'=>$this->getOpChoiceList(), 'pubGiurList'=>json_encode(GaraPubblicazioneGiuridica::GetPubByGaraId($procedure->id)) ]);
}
</code>```

Model:

```<code>public static function GetPubByGaraId($id){
    //TODO: visualizzare le selected publications
    $procagg = GaraPubblicazioneGiuridica::where('gara_id','=',$id)->select('id')->get();
    if($procagg){
        $plucked = $procagg->pluck('nome');
        $toReturn = array();
        foreach($plucked as $key=>$value){
            $toReturn[$key]=$value;
        }
        return $toReturn;
    }
    return "";
}
</code>```

Could you shed some light on this?
Thank you in advance.

答:
You can create an ajax call on J-query Event and Bind the data through id.

$("#select-pgiur").val(data.items).trigger("change");

Maybe it helps you.....

Body:
Good morning everybody, I'm stuck while trying to set initial selected options (got through an ajax requests) to a jquery select2 (multi-select). If I use the control, multi selection works just fine. The problem arise when I have to edit a previously saved model, as none of the options I previously selected are shown.

This is my view:

has('pubblicazione_giuridica_id') ? 'has-error' : ''}}">
    {!! Form::label('pubblicazione_giuridica_id', 'Law Pubs', ['class' => 'col-sm-3 control-label']) !!}

        {!! Form::select('pubblicazione_giuridica_id[]', [$pubGiurList], null, ['class' => 'form-control', 'id'=>'select-pgiur', 'multiple'=>'multiple']) !!}
        {!! $errors->first('pubblicazione_giuridica_id', '
:message
') !!}

The javascript:

$('#select-pgiur').select2({
    ajax: {
        url: "{!! URL::to('/gare/proc-getpubgiur') !!}",
        dataType: 'json',
        delay: 150,
        data: function (params) {
            return { q: params.term, };
        },
        processResults: function (data, params) {
            return { results: data.items, };
        },
        cache: true
    },
    language: 'it',
    theme: "bootstrap",
    placeholder: "Choose an option."
});

The Controller:

public function edit($id, Request $request) {
    $procedure = $this->getProcedure($id, $request, true);
    if (!$procedure) {
        return redirect('gare/procedure')->with('alert-warning', 'Gara non trovata - Operazione non consentita');
    }
    return view('gare.procedures.edit', [ 'procedure'=>$procedure, 'opChoiceList'=>$this->getOpChoiceList(), 'pubGiurList'=>json_encode(GaraPubblicazioneGiuridica::GetPubByGaraId($procedure->id)) ]);
}

Model:

public static function GetPubByGaraId($id){
    //TODO: visualizzare le selected publications
    $procagg = GaraPubblicazioneGiuridica::where('gara_id','=',$id)->select('id')->get();
    if($procagg){
        $plucked = $procagg->pluck('nome');
        $toReturn = array();
        foreach($plucked as $key=>$value){
            $toReturn[$key]=$value;
        }
        return $toReturn;
    }
    return "";
}

Could you shed some light on this?
Thank you in advance.


问:
How to take backup of a firebase database from Google Cloud Engine using cURL?
I was taking backup of my firebase db using cURL on Google Compute engine. The backups were successful last week. Two days before I changed the security of my db to allow only authenticated users to read or write.
Something like this

```<code>{
  "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
  }
}
</code>```

Now my backup started failing. So, how do I add or grant the user in compute engine to successfully take backup of my firebase database? Thanks.

答:
As you mentioned in your other answer, you are now using the Firebase Admin SDK, so I'll include a very simple app that does what you are looking for (downloads your database and saves it as a JSON file).

For this script, I am going to assume that what you were trying to do is something like:

```<code>curl https://YOUR-PROJECT.firebaseio.com/.json?format=export -o backup-20170606.json
</code>```

In case someone needs them, setup instructions for the Firebase Admin SDK can be found here.

The Script

```<code>var fs = require('fs'); // Node.js Internal Module
var path = require('path'); // Node.js Internal Module
var moment = require('moment'); // External module

var admin = require("firebase-admin");
admin.initializeApp(/* Service account details go here */);

// Change these as desired
var outFileName = 'backup_' + moment().format('YYYYMMDD_HH-mm-ss');
var outFileDir = '/tmp';
var outFilePath = path.join(outFileDir, outFileName);

var rootRef = admin.database().ref(); // Ref to database root
rootRef.once("value", function(snapshot){
  var outText = JSON.stringify(snapshot.val());
  fs.writeFile(outFilePath, outText, function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved as '" + outFilePath + "'!");
  });
});
</code>```

Note: moment.js isn't explicitly required, it's just a really useful module I use often.

Things to Consider

You should download the database in pieces (see orderByKey()) and save each entry into a buffer and then to disk upon completed download. The current code will struggle with big databases.

The download will be slow depending on the database size. Consider parallelizing it.

Alternatives

You can also use the Firebase Tools to access/download/manipulate your database.

Body:
I was taking backup of my firebase db using cURL on Google Compute engine. The backups were successful last week. Two days before I changed the security of my db to allow only authenticated users to read or write.
Something like this

{
  "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
  }
}

Now my backup started failing. So, how do I add or grant the user in compute engine to successfully take backup of my firebase database? Thanks.

Body:
As you mentioned in your other answer, you are now using the Firebase Admin SDK, so I'll include a very simple app that does what you are looking for (downloads your database and saves it as a JSON file).

For this script, I am going to assume that what you were trying to do is something like:

curl https://YOUR-PROJECT.firebaseio.com/.json?format=export -o backup-20170606.json

In case someone needs them, setup instructions for the Firebase Admin SDK can be found here.

The Script

var fs = require('fs'); // Node.js Internal Module
var path = require('path'); // Node.js Internal Module
var moment = require('moment'); // External module

var admin = require("firebase-admin");
admin.initializeApp(/* Service account details go here */);

// Change these as desired
var outFileName = 'backup_' + moment().format('YYYYMMDD_HH-mm-ss');
var outFileDir = '/tmp';
var outFilePath = path.join(outFileDir, outFileName);

var rootRef = admin.database().ref(); // Ref to database root
rootRef.once("value", function(snapshot){
  var outText = JSON.stringify(snapshot.val());
  fs.writeFile(outFilePath, outText, function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved as '" + outFilePath + "'!");
  });
});

Note: moment.js isn't explicitly required, it's just a really useful module I use often.

Things to Consider

You should download the database in pieces (see orderByKey()) and save each entry into a buffer and then to disk upon completed download. The current code will struggle with big databases.

The download will be slow depending on the database size. Consider parallelizing it.

Alternatives

You can also use the Firebase Tools to access/download/manipulate your database.


问:
How to prevent element from exceeding his container borders
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}</code>```

```

答:
If you set the containing element to position: relative; and the inner element with position: absolute; the inner elements top left right and bottom properties will calculate from the borders of the containing element.

Here is a good source of css positioning.

In your case additional validation should be set to positionTop and positionLeft.

positionTop should be in the interval [( shapeHeight/2 ) - (100 - shapeHeight/2 ) ]

positionLeft should be in the interval [( shapeWidth/2 ) - (100 - shapeWeight/2 ) ]

Body:
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}

#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}


问:
Pyspark: Add the average as a new column to DataFrame
I am computing mean of a column in data-frame but it resulted in all the values zeros. Can someone help me in why this is happening? Following is the code and table before and after the transformation of a column.

Before computing mean and adding "mean" column

```<code>result.select("dis_price_released").show(10)
 +------------------+
 |dis_price_released|
 +------------------+
 |               0.0|
 |               4.0|
 |               4.0|
 |               4.0|
 |               1.0|
 |               4.0|
 |               4.0|
 |               0.0|
 |               4.0|
 |               0.0|
 +------------------+
</code>```

After computing mean and adding mean column

```<code>w = Window().partitionBy("dis_price_released").rowsBetween(-sys.maxsize, sys.maxsize)
df2 = result.withColumn("mean", avg("dis_price_released").over(w))
df2.select("dis_price_released", "mean").show(10)

+------------------+----+
|dis_price_released|mean|
+------------------+----+
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
+------------------+----+
</code>```

答:
You can compute the avg first for the whole column, then use lit() to add it as a variable to your DataFrame, there is no need for window functions:

```<code>from pyspark.sql.functions import lit

mean = df.groupBy().avg("dis_price_released").take(1)[0][0]
df.withColumn("test", lit(mean)).show()
 +------------------+----+
|dis_price_released|test|
+------------------+----+
|               0.0| 2.5|
|               4.0| 2.5|
|               4.0| 2.5|
|               4.0| 2.5|
|               1.0| 2.5|
|               4.0| 2.5|
|               4.0| 2.5|
|               0.0| 2.5|
|               4.0| 2.5|
|               0.0| 2.5|
+------------------+----+
</code>```

Body:
I am computing mean of a column in data-frame but it resulted in all the values zeros. Can someone help me in why this is happening? Following is the code and table before and after the transformation of a column.

Before computing mean and adding "mean" column

result.select("dis_price_released").show(10)
 +------------------+
 |dis_price_released|
 +------------------+
 |               0.0|
 |               4.0|
 |               4.0|
 |               4.0|
 |               1.0|
 |               4.0|
 |               4.0|
 |               0.0|
 |               4.0|
 |               0.0|
 +------------------+

After computing mean and adding mean column

w = Window().partitionBy("dis_price_released").rowsBetween(-sys.maxsize, sys.maxsize)
df2 = result.withColumn("mean", avg("dis_price_released").over(w))
df2.select("dis_price_released", "mean").show(10)

+------------------+----+
|dis_price_released|mean|
+------------------+----+
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
|               0.0| 0.0|
+------------------+----+

Body:
You can compute the avg first for the whole column, then use lit() to add it as a variable to your DataFrame, there is no need for window functions:

from pyspark.sql.functions import lit

mean = df.groupBy().avg("dis_price_released").take(1)[0][0]
df.withColumn("test", lit(mean)).show()
 +------------------+----+
|dis_price_released|test|
+------------------+----+
|               0.0| 2.5|
|               4.0| 2.5|
|               4.0| 2.5|
|               4.0| 2.5|
|               1.0| 2.5|
|               4.0| 2.5|
|               4.0| 2.5|
|               0.0| 2.5|
|               4.0| 2.5|
|               0.0| 2.5|
+------------------+----+


问:
Using jQuery to know when @font-face fonts are loaded?
I am using @font-face and I hate that Firefox shows the default font, waits to load the @font-face font, then replaces it.  So the whole page flashes with the new font.

Webkit browsers just don't display the text until the font is loaded and it is a much cleaner look.

So, I am wondering if jQuery could help me to know when all data on the page is loaded, including the @font-face file, so that I can then show my text? Is there a jQuery method that tells me when everything is loaded?

答:
I got the same problem. And somehow i can't get Google webfont loader to work with ttf font (especially chinese fonts) or send a jquery response when font is loaded.

So I came up with this a more basic solution, useful when changing font dynamically after page is loaded. it shows when the font face is properly loaded.

First i create a dummy div and then fill it with 'abcd' and then give it a font size 40, record the width of the div. When the 'change font' event is invoked via a button or anything, it should track the dummy div width changes. Width changes would represent that the font has change.

HTML CODE

```<code><style>
    @font-face {
     font-family: 'font1';
     src:url('somefont.ttf')  format('truetype');
     }
</style>
<div id="dummy" style="border:1px solid #000; display:inline-block">abdc</div>

<!--simple button to invoke the fontchange-->
<input type="button" onclick="javascript:changefont('font1')" value="change the font"/>
</code>```

JQuery

```<code>//create a variable to track initial width of default font
var trackwidth

//when change font is invoke
function changefont(newfont)
{
   //reset dummy font style
    $('#dummy').css('font-family','initial !important;');
    $('#dummy').css({'font-size':'40px'});
    $('#dummy').html('abcd');

    //ensure that trackwidth is only recorded once of the default font
    if(trackwidth==null)
    {
       trackwidth=( $('#dummy').width());
    }

    //apply new font
    $('#dummy').css('font-family',newfont);
    checkwidth()
}

function checkwidth()
{
   //check if div width changed
   if($('#dummy').width() == trackwidth)
    {
        //if div never change, detect again every 500 milisecs
        setTimeout(checkwidth, 500);
    }
    else
    {
      //do something, font is loaded!
    }
}
</code>```

Body:
I got the same problem. And somehow i can't get Google webfont loader to work with ttf font (especially chinese fonts) or send a jquery response when font is loaded.

So I came up with this a more basic solution, useful when changing font dynamically after page is loaded. it shows when the font face is properly loaded.

First i create a dummy div and then fill it with 'abcd' and then give it a font size 40, record the width of the div. When the 'change font' event is invoked via a button or anything, it should track the dummy div width changes. Width changes would represent that the font has change.

HTML CODE

<style>
    @font-face {
     font-family: 'font1';
     src:url('somefont.ttf')  format('truetype');
     }
</style>
<div id="dummy" style="border:1px solid #000; display:inline-block">abdc</div>

<!--simple button to invoke the fontchange-->
<input type="button" onclick="javascript:changefont('font1')" value="change the font"/>

JQuery

//create a variable to track initial width of default font
var trackwidth

//when change font is invoke
function changefont(newfont)
{
   //reset dummy font style
    $('#dummy').css('font-family','initial !important;');
    $('#dummy').css({'font-size':'40px'});
    $('#dummy').html('abcd');

    //ensure that trackwidth is only recorded once of the default font
    if(trackwidth==null)
    {
       trackwidth=( $('#dummy').width());
    }

    //apply new font
    $('#dummy').css('font-family',newfont);
    checkwidth()
}

function checkwidth()
{
   //check if div width changed
   if($('#dummy').width() == trackwidth)
    {
        //if div never change, detect again every 500 milisecs
        setTimeout(checkwidth, 500);
    }
    else
    {
      //do something, font is loaded!
    }
}


问:
UILabel rounding corners cuts-off text
I am using custom TableCell which has a label with numberofLines = 0

I wanted the label like this.

That is rounded only in three corners.For this to achieve i've written code like this in cell's swift file.I've extended the UIView basically.

```<code>extension UIView {
    func roundCorners(corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}
</code>```

And i've used this like this to round my corners.

```<code>self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
</code>```

But the problem is when label's content is bigger than the cell's row height it's not showing the content

Please just see the second cell's label in first picture .It's content is not showing.
But when i remove the rounded corner's code everything is working fine but lost my corner radius.

Any suggestion is highly appreciated.Thanks.

Edited:

My cell is like this.

And i am achieving chat UI using the code below.

```<code>var cellTypeToDraw:cellType {
        get {
            return self.cellTypeToDraw
        }
        set(newValue) {
            switch newValue {
            case .cellTypeReceiver:
                self.leftImage.isHidden = true
                 self.rightImage.isHidden = false
                self.chatLabel.textAlignment = .right
                self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
            case .cellTypeSender:
                self.rightImage.isHidden = true
                self.leftImage.isHidden = false
                self.chatLabel.textAlignment = .left
                self.chatLabel.roundCorners(corners: [.topRight,.bottomLeft,.bottomRight], radius: 7.0)
            }
            self.leftImage.layer.cornerRadius = self.leftImage.bounds.size.width/2
            self.rightImage.layer.cornerRadius = self.rightImage.bounds.size.width/2
           // self.chatLabel.sizeToFit()
           // self.chatLabel.autoresizingMask = .flexibleHeight
        }
    }
</code>```

and accessing this variable in cellForRowAtIndexPath like this.

```<code> if indexPath.row % 2 != 0 {
            cell.cellTypeToDraw = .cellTypeReceiver
        }
        else {
            cell.cellTypeToDraw = .cellTypeSender
        }
</code>```

答:
You're doing it too early.

You set the cellTypeToDraw and thus call your roundCorners(corners:, radius:) method at a point in time when the layout isn't done yet. In cellForRow(at:) you get a recycled cell whose chatLabel still has the frame that matched the text it displayed previously.

A quick fix would be to move this corner-rounding to the cell's layoutSubviews() method. Something like:

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
}
</code>```

(You can check the cellTypeToDraw there as well if you only want to have rounded corners for some cell types.)

By the way:

Tip 1:

You should never do something like that:

```<code>var cellTypeToDraw:cellType {
    get {
        return self.cellTypeToDraw
    }
    // ...
}
</code>```

This will result in an endless recursion when you ever try to call cellTypeToDraw and eventually crash your app. By implementing the getter and the setter you define a computed property that is not backed by an instance variable. self.cellTypeToDraw doesn't have a value. It simply calls the getter again which returns self.cellTypeToDraw again and so on.

Solution: Don't use a computed property but a "regular" one which is backed by an instance variable and do all your cell setup in the property's observer:

```<code>var cellTypeToDraw:cellType {
    didSet {
        // configure your cell here
    }
}
</code>```

Tip 2:

You can (and should) omit all the self. prefixes in Swift for better readability and less work.

Title: UILabel rounding corners cuts-off text

Body:
I am using custom TableCell which has a label with numberofLines = 0

I wanted the label like this.

That is rounded only in three corners.For this to achieve i've written code like this in cell's swift file.I've extended the UIView basically.

extension UIView {
    func roundCorners(corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

And i've used this like this to round my corners.

self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)

But the problem is when label's content is bigger than the cell's row height it's not showing the content

Please just see the second cell's label in first picture .It's content is not showing.
But when i remove the rounded corner's code everything is working fine but lost my corner radius.

Any suggestion is highly appreciated.Thanks.

Edited:

My cell is like this.

And i am achieving chat UI using the code below.

var cellTypeToDraw:cellType {
        get {
            return self.cellTypeToDraw
        }
        set(newValue) {
            switch newValue {
            case .cellTypeReceiver:
                self.leftImage.isHidden = true
                 self.rightImage.isHidden = false
                self.chatLabel.textAlignment = .right
                self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
            case .cellTypeSender:
                self.rightImage.isHidden = true
                self.leftImage.isHidden = false
                self.chatLabel.textAlignment = .left
                self.chatLabel.roundCorners(corners: [.topRight,.bottomLeft,.bottomRight], radius: 7.0)
            }
            self.leftImage.layer.cornerRadius = self.leftImage.bounds.size.width/2
            self.rightImage.layer.cornerRadius = self.rightImage.bounds.size.width/2
           // self.chatLabel.sizeToFit()
           // self.chatLabel.autoresizingMask = .flexibleHeight
        }
    }

and accessing this variable in cellForRowAtIndexPath like this.

 if indexPath.row % 2 != 0 {
            cell.cellTypeToDraw = .cellTypeReceiver
        }
        else {
            cell.cellTypeToDraw = .cellTypeSender
        }

Body:
You're doing it too early.

You set the cellTypeToDraw and thus call your roundCorners(corners:, radius:) method at a point in time when the layout isn't done yet. In cellForRow(at:) you get a recycled cell whose chatLabel still has the frame that matched the text it displayed previously.

A quick fix would be to move this corner-rounding to the cell's layoutSubviews() method. Something like:

override func layoutSubviews() {
    super.layoutSubviews()
    chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
}

(You can check the cellTypeToDraw there as well if you only want to have rounded corners for some cell types.)

By the way:

Tip 1:

You should never do something like that:

var cellTypeToDraw:cellType {
    get {
        return self.cellTypeToDraw
    }
    // ...
}

This will result in an endless recursion when you ever try to call cellTypeToDraw and eventually crash your app. By implementing the getter and the setter you define a computed property that is not backed by an instance variable. self.cellTypeToDraw doesn't have a value. It simply calls the getter again which returns self.cellTypeToDraw again and so on.

Solution: Don't use a computed property but a "regular" one which is backed by an instance variable and do all your cell setup in the property's observer:

var cellTypeToDraw:cellType {
    didSet {
        // configure your cell here
    }
}

Tip 2:

You can (and should) omit all the self. prefixes in Swift for better readability and less work.


问:
Why does C# disallow readonly local variables?
Having a friendly debate with a co-worker about this.  We have some thoughts about this, but wondering what the SO crowd thinks about this?</p>

答:
One reason is there is no CLR support for a readonly local.  Readonly is translated into the CLR/CLI initonly opcode.  This flag can only be applied to fields and has no meaning for a local.  In fact, applying it to a local will likely produce unverifiable code.

This doesn't mean that C# couldn't do this.  But it would give two different meanings to the same language construct.  The version for locals would have no CLR equivalent mapping.

OwnerDisplayName: Brian Genisio

OwnerDisplayName: JaredPar


问:
JSON root key configuration
{
 "name:Sagar": {
  "Subject1": "Maths",
  "Subject2": "science",
  "Subject3": "English",
  "Subject4": "French"
 }
}

how to parse this json payload ?  Normally we use "name":"Sagar" but know my query is "name:sagar" . Please help me to solve this type of JSON payload .

答:
in JSON, objects are written like :

{ "objectName" : { "first member" , "second member " , ... } }

here your object name is "name:Sagar"

perhaps you wanted to make "name:Sagar" a single value then you write :

{ "name" : "Sagar" ,
"newObjectName" : { "Subject1": "Maths", "Subject2": "science", "Subject3": "English", "Subject4": "French" } }

other solution with your own JSON, you parse and then split the "name:Sagar" with the ":" separator.

Hope that help you.

Title: JSON root key configuration


问:
Parsing key values pairs from text as dictionary
I'm still quite new to Python and I was wondering how would I convert something that is already in key:value form in a text file into a Python dictionary?

Eg.

```<code>2:red
3:orange
5:yellow
6:green
</code>```

(each key:value on a separate line)

I've looked at other posts but none of them seem to work and I know I'm doing something wrong. So far, I have:

```<code>def create_colours_dictionary(filename):
    colours_dict = {}
    file = open(filename,'r')
    contents = file.read()

    for key in contents:
        #???
    return colours_dict
</code>```

答:
Iterate over your file and build a dictionary.

```<code>def create_colours_dictionary(filename):
    colours_dict = {}
    with open(filename) as file:
        for line in file:
            k, v = line.rstrip().split(':')
            colours_dict[k] = v

    return colours_dict

dct = create_colours_dictionary('file.txt')
</code>```

Or, if you're looking for something compact, you can use a dict comprehension with a lambda to split on colons.

```<code>colours_dict = {k : v for k, v in (
    line.rstrip().split(':') for line in open(filename)
}
</code>```

This approach will need some modification if the colon is surrounded by spaces—perhaps regex?

Body:
I'm still quite new to Python and I was wondering how would I convert something that is already in key:value form in a text file into a Python dictionary?

Eg.

2:red
3:orange
5:yellow
6:green

(each key:value on a separate line)

I've looked at other posts but none of them seem to work and I know I'm doing something wrong. So far, I have:

def create_colours_dictionary(filename):
    colours_dict = {}
    file = open(filename,'r')
    contents = file.read()

    for key in contents:
        #???
    return colours_dict

Body:
Iterate over your file and build a dictionary.

def create_colours_dictionary(filename):
    colours_dict = {}
    with open(filename) as file:
        for line in file:
            k, v = line.rstrip().split(':')
            colours_dict[k] = v

    return colours_dict

dct = create_colours_dictionary('file.txt')

Or, if you're looking for something compact, you can use a dict comprehension with a lambda to split on colons.

colours_dict = {k : v for k, v in (
    line.rstrip().split(':') for line in open(filename)
}

This approach will need some modification if the colon is surrounded by spaces—perhaps regex?


问:
GetUserMedia iOS issue?
I'm using the following code in an HTML5 page. When I run my page on Android and PC (chrome), the code works fine and I get the correct JavaScript alert(); but when I run the same page on an iOS device like iPhone or iPad, I don't get anything (no alert() at all).

This is my code:

```<code>navigator.getUserMedia = ( navigator.getUserMedia || // use the proper vendor prefix
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

navigator.getUserMedia({video: true}, function() {
   alert('camera is supported in your browser');
}, function() {
   alert('camera is not supported in your browser!');
});
</code>```

Is there something that I'm missing?

Any help would be appreciated.

答: It will work in fall 2017, once iOS11 is released.

Title: GetUserMedia iOS issue?

Body:
I'm using the following code in an HTML5 page. When I run my page on Android and PC (chrome), the code works fine and I get the correct JavaScript alert(); but when I run the same page on an iOS device like iPhone or iPad, I don't get anything (no alert() at all).

This is my code:

navigator.getUserMedia = ( navigator.getUserMedia || // use the proper vendor prefix
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

navigator.getUserMedia({video: true}, function() {
   alert('camera is supported in your browser');
}, function() {
   alert('camera is not supported in your browser!');
});

Is there something that I'm missing?

Any help would be appreciated.


问:
How to ssr to replace all string in kdb?
table dd

```<code>dd:([]a:("account=abcde;cash=123";"account=abc;cash=345");1 2)
</code>```

result:

```<code>"account=abcde;cash=123"    1
"account=abc;cash=345"      2
</code>```

I want to replace everything in account:
so the result should be

```<code>"replace;cash=123"  1
"replace;cash=345"  2
</code>```

I tried this

```<code>update ssr[;"account=* ;";""] each a from dd
</code>```

but it didn't work.

答:
And just to throw one more answer on the pile!  If you can assume the account part you want to replace is always the first member of the ; separated list you can use the slightly simpler:</p>

```<code>update ";"sv'@[;0;:;"replace"]each";"vs'a from dd
</code>```

Body:
table dd

dd:([]a:("account=abcde;cash=123";"account=abc;cash=345");1 2)

result:

"account=abcde;cash=123"    1
"account=abc;cash=345"      2

I want to replace everything in account:
so the result should be

"replace;cash=123"  1
"replace;cash=345"  2

I tried this

update ssr[;"account=* ;";""] each a from dd

but it didn't work.

Body:
And just to throw one more answer on the pile!  If you can assume the account part you want to replace is always the first member of the ; separated list you can use the slightly simpler:

update ";"sv'@[;0;:;"replace"]each";"vs'a from dd


问:
Uncaught Error: React.PropTypes type checking code is stripped in production
I'm on React 15.4.0, all of a sudden started seeing this error on production builds. I'm not using any of the bable plugins mentioned here

Also, below are all my babel-preset packages I use.

```<code>"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "6.5.0",
"babel-preset-react-hmre": "1.1.1",
"babel-preset-stage-2": "^6.18.0",
</code>```

Wondering why I started getting this error since last night..

答:
I encountered the same error as you. And I found it is external lib's issue.

import { PropTypes } from 'react'; is deprecated, we should use import PropTypes from 'prop-types'; instead.

You can find more info here: https://github.com/facebook/prop-types

After upgrading react-router form v2 to v4, problem solved. Hope this helps.

Update@2017/10/31:

The following config works fine:

```<code>"immutable": "^3.8.2",
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^4.0.0",
"react-router-dom": "^4.1.1",
"redux": "^3.0.2",
"redux-thunk": "^1.0.0",

"babel-cli": "^6.7.5",
"babel-core": "^6.3.17",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
</code>```

Body:
I'm on React 15.4.0, all of a sudden started seeing this error on production builds. I'm not using any of the bable plugins mentioned here

Also, below are all my babel-preset packages I use.

"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "6.5.0",
"babel-preset-react-hmre": "1.1.1",
"babel-preset-stage-2": "^6.18.0",

Wondering why I started getting this error since last night..

Body:
I encountered the same error as you. And I found it is external lib's issue.

import { PropTypes } from 'react'; is deprecated, we should use import PropTypes from 'prop-types'; instead.

You can find more info here: https://github.com/facebook/prop-types

After upgrading react-router form v2 to v4, problem solved. Hope this helps.

Update@2017/10/31:

The following config works fine:

"immutable": "^3.8.2",
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^4.0.0",
"react-router-dom": "^4.1.1",
"redux": "^3.0.2",
"redux-thunk": "^1.0.0",

"babel-cli": "^6.7.5",
"babel-core": "^6.3.17",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",


问:
How to get the value of geolocation in a javascript function
I have the following function which takes two values: latitude and longitude:

```<code>    getgps(latitude , longitude);
</code>```

and I need for this to get the data from the geolocation function:

```<code> <script>

function getLocation() {
   if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
   }
}
function showPosition(position) {
  var x = position.coords.latitude;
  var y = position.coords.longitude;
 getgps(x , y);

}
  </script>
</code>```

but it is not working

The good script

```<code>navigator.geolocation.getCurrentPosition(function(position) {
 findGps(position.coords.latitude, position.coords.longitude); });
</code>```

答:
NOTE: when you start your code, in browser top left corner it showing popup for asking for allow access your location. allow it. if you allow, it will show you location otherwise it wont able to find your location.

if i understand your problem correct. this is working code what you want to achieve. refer https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

```<code>Working fiddle: `https://jsfiddle.net/api/mdn/`

Hope it will help you.
</code>```

Body:
I have the following function which takes two values: latitude and longitude:

    getgps(latitude , longitude);

and I need for this to get the data from the geolocation function:

but it is not working

The good script

navigator.geolocation.getCurrentPosition(function(position) {
 findGps(position.coords.latitude, position.coords.longitude); });

Body:
NOTE: when you start your code, in browser top left corner it showing popup for asking for allow access your location. allow it. if you allow, it will show you location otherwise it wont able to find your location.

if i understand your problem correct. this is working code what you want to achieve. refer https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

Working fiddle: `https://jsfiddle.net/api/mdn/`

Hope it will help you.


问:
Checking the CustomItem in j2me support traversal or not
Checking the CustomItem in j2me support traversal or not?

How should I check the CustomItem in j2me support traversal or not?

答:
I find the solution. It's working for me.

The correct solution Finding the CustomItem traversal is supported by the device calling the method "getInteractionModes()" of the class "javax.microedition.lcdui.CustomItem".

Code snippet is given below

```<code>int supported_interaction_modes=this.getInteractionModes();
boolean horizontal__interaction,vertical_interaction;
if((supported_interaction_modes&CustomItem.TRAVERSE_HORIZONTAL)!=0)        //Horizontal traverse support
  horizontal_interaction=true;
else
  horizontal_interaction=false;
if((supported_interaction_modes&CustomItem.TRAVERSE_VERTICAL)!=0)
  vertical_interaction=true;
else
  vertical_interaction=false;
</code>```

in the above code snippet the "this" refers to the object of the class which is derived from "javax.microedition.lcdui.CustomItem"

Body:
I find the solution. It's working for me.

The correct solution Finding the CustomItem traversal is supported by the device calling the method "getInteractionModes()" of the class "javax.microedition.lcdui.CustomItem".

Code snippet is given below

int supported_interaction_modes=this.getInteractionModes();
boolean horizontal__interaction,vertical_interaction;
if((supported_interaction_modes&CustomItem.TRAVERSE_HORIZONTAL)!=0)        //Horizontal traverse support
  horizontal_interaction=true;
else
  horizontal_interaction=false;
if((supported_interaction_modes&CustomItem.TRAVERSE_VERTICAL)!=0)
  vertical_interaction=true;
else
  vertical_interaction=false;

in the above code snippet the "this" refers to the object of the class which is derived from "javax.microedition.lcdui.CustomItem"


答:
You can get the parent element size, so that in your scirpt, use a condition to prevent the square to exceed.

```<code>function position() {

var maxWidth = document.getElementById("playSpace").offsetWidth;
var maxTop = document.getElementById("playSpace").offsetHeight;

var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;

if (positionTop > maxTop) { positionTop = maxTop;)
if (positionLeft > maxWidth) { positionLeft = maxWidth;)
var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
return position;

}
</code>```

I'm not sure if .offsetWidth and .offsetHeight works well, but you got the idea :)

Title: How to prevent element from exceeding his container borders

Body:
You can get the parent element size, so that in your scirpt, use a condition to prevent the square to exceed.

function position() {

var maxWidth = document.getElementById("playSpace").offsetWidth;
var maxTop = document.getElementById("playSpace").offsetHeight;

var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;

if (positionTop > maxTop) { positionTop = maxTop;)
if (positionLeft > maxWidth) { positionLeft = maxWidth;)
var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
return position;

}

I'm not sure if .offsetWidth and .offsetHeight works well, but you got the idea :)


问:
Android : why does defining the widgets in this part (i.e MainActivity ) Cause an error
If I define the following lines

```<code>myText =(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);
</code>```

in onCreate the program runs smoothly but if I do that in Main Activity then it causes an error.

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(myText.getVisibility()==View.VISIBLE){

                    myText.setVisibility(View.INVISIBLE);
                }else
                {
                    myText.setVisibility(View.VISIBLE);
                }

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

答:
Write this code</p>

```<code>public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       if(myText.getVisibility()==View.VISIBLE){
             myText.setVisibility(View.INVISIBLE);
         }else
         {
             myText.setVisibility(View.VISIBLE);
         }
        }
    });
}
}
</code>```

Body:
If I define the following lines

myText =(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);

in onCreate the program runs smoothly but if I do that in Main Activity then it causes an error.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(myText.getVisibility()==View.VISIBLE){

                    myText.setVisibility(View.INVISIBLE);
                }else
                {
                    myText.setVisibility(View.VISIBLE);
                }

            }
        });
    }
}

Body:
Write this code

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myText =(TextView)findViewById(R.id.textView); //error
    button=(Button)findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       if(myText.getVisibility()==View.VISIBLE){
             myText.setVisibility(View.INVISIBLE);
         }else
         {
             myText.setVisibility(View.VISIBLE);
         }
        }
    });
}
}


问:
YouTube Video Signature
I have been working on a YouTube downloader and I have most of the parts working.

Certain videos (ie Vevo videos) have ciphered signatures such as:

https://www.youtube.com/watch?v=v2AC41dglnM

So I find the video's player and get the javascript for it:

https://youtube.com/yts/jsbin/player-en_US-vflchU0AK/base.js

With that I grab the Signature function and Object:

```<code>var BE={
    lW:function(a,b){
        var c=a[0];
        a[0]=a[b%a.length];
        a[b]=c
    },
    e9:function(a){
        a.reverse()
    },
    TM:function(a,b){
        a.splice(0,b)
    }
};

CE=function(a){
    a=a.split("");
    BE.lW(a,58);BE.TM(a,1);
    BE.e9(a,63);BE.TM(a,2);
    BE.lW(a,8);
    BE.lW(a,21);
    return a.join("")
};
</code>```

I take the s= from the YouTube video and run it through the CE function:

```<code>CE("02753A38F9C9290D0778202DC28B1DFA0F291DF67.A9DECBE95FE5A74123D0FC22527374E2F2501FBCBC")
</code>```

then I try to replace the s= in the url:

```<code>https://r15---sn-5uaeznls.googlevideo.com/videoplayback?key=yt6&itag=43&mm=31&ratebypass=yes&requiressl=yes&sparams=clen%2Cdur%2Cei%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&source=youtube&mime=video%2Fwebm&expire=1493019580&dur=0.000&lmt=1365515278685092&ip=173.48.112.179&gcr=us&ms=au&mv=m&mt=1492997904&id=o-ACO6aSSDctHIeB2fsnvl0R4IpaSTeVBeBYxVwHiVSJg5&mn=sn-5uaeznls&gir=yes&clen=32929005&initcwndbps=887500&ipbits=0&upn=ywp8mm27sXc&pl=16&ei=XFf9WPWhNYmC8gSk3wU&s=66482ABA143BFD4DF419B22142266495EF11A26D.81873834D2C06DEAFFC33A22127DE1841BAD4676
</code>```

But I'm still getting "Access Denied" from YouTube.
Am I using the deciphered signature correctly? Am I doing something else wrong?

答:
You 're doing it right, except that you have to add  the word "signature" and not "s" in the url.

An example would be:

```<code>https://r15---sn-5uaeznls.googlevideo.com/videoplayback?key=yt6&itag=43&mm=31&ratebypass=yes&requiressl=yes&sparams=clen%2Cdur%2Cei%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&source=youtube&mime=video%2Fwebm&expire=1493019580&dur=0.000&lmt=1365515278685092&ip=173.48.112.179&gcr=us&ms=au&mv=m&mt=1492997904&id=o-ACO6aSSDctHIeB2fsnvl0R4IpaSTeVBeBYxVwHiVSJg5&mn=sn-5uaeznls&gir=yes&clen=32929005&initcwndbps=887500&ipbits=0&upn=ywp8mm27sXc&pl=16&ei=XFf9WPWhNYmC8gSk3wU&signature=66482ABA143BFD4DF419B22142266495EF11A26D.81873834D2C06DEAFFC33A22127DE1841BAD4676
</code>```

Title: YouTube Video Signature

Body:
I have been working on a YouTube downloader and I have most of the parts working.

Certain videos (ie Vevo videos) have ciphered signatures such as:

https://www.youtube.com/watch?v=v2AC41dglnM

So I find the video's player and get the javascript for it:

https://youtube.com/yts/jsbin/player-en_US-vflchU0AK/base.js

With that I grab the Signature function and Object:

var BE={
    lW:function(a,b){
        var c=a[0];
        a[0]=a[b%a.length];
        a[b]=c
    },
    e9:function(a){
        a.reverse()
    },
    TM:function(a,b){
        a.splice(0,b)
    }
};

CE=function(a){
    a=a.split("");
    BE.lW(a,58);BE.TM(a,1);
    BE.e9(a,63);BE.TM(a,2);
    BE.lW(a,8);
    BE.lW(a,21);
    return a.join("")
};

I take the s= from the YouTube video and run it through the CE function:

CE("02753A38F9C9290D0778202DC28B1DFA0F291DF67.A9DECBE95FE5A74123D0FC22527374E2F2501FBCBC")

then I try to replace the s= in the url:

https://r15---sn-5uaeznls.googlevideo.com/videoplayback?key=yt6&itag=43&mm=31&ratebypass=yes&requiressl=yes&sparams=clen%2Cdur%2Cei%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&source=youtube&mime=video%2Fwebm&expire=1493019580&dur=0.000&lmt=1365515278685092&ip=173.48.112.179&gcr=us&ms=au&mv=m&mt=1492997904&id=o-ACO6aSSDctHIeB2fsnvl0R4IpaSTeVBeBYxVwHiVSJg5&mn=sn-5uaeznls&gir=yes&clen=32929005&initcwndbps=887500&ipbits=0&upn=ywp8mm27sXc&pl=16&ei=XFf9WPWhNYmC8gSk3wU&s=66482ABA143BFD4DF419B22142266495EF11A26D.81873834D2C06DEAFFC33A22127DE1841BAD4676

But I'm still getting "Access Denied" from YouTube.
Am I using the deciphered signature correctly? Am I doing something else wrong?

Body:
You 're doing it right, except that you have to add  the word "signature" and not "s" in the url.

An example would be:

https://r15---sn-5uaeznls.googlevideo.com/videoplayback?key=yt6&itag=43&mm=31&ratebypass=yes&requiressl=yes&sparams=clen%2Cdur%2Cei%2Cgcr%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&source=youtube&mime=video%2Fwebm&expire=1493019580&dur=0.000&lmt=1365515278685092&ip=173.48.112.179&gcr=us&ms=au&mv=m&mt=1492997904&id=o-ACO6aSSDctHIeB2fsnvl0R4IpaSTeVBeBYxVwHiVSJg5&mn=sn-5uaeznls&gir=yes&clen=32929005&initcwndbps=887500&ipbits=0&upn=ywp8mm27sXc&pl=16&ei=XFf9WPWhNYmC8gSk3wU&signature=66482ABA143BFD4DF419B22142266495EF11A26D.81873834D2C06DEAFFC33A22127DE1841BAD4676


问:
Android: Aligning Images using OpenCV
I am trying to align two images using OpenCV. I based this code off of a C++/Python tutorial I found: http://www.learnopencv.com/image-alignment-ecc-in-opencv-c-python/

The findTransformECC() function in android requires an extra parameter for inputMask. The C++ and Python functions don't have this.

My Code:

```<code>import android.graphics.Bitmap;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.TermCriteria;
import org.opencv.imgproc.Imgproc;

import static org.opencv.core.CvType.CV_32F;
import static org.opencv.video.Video.MOTION_EUCLIDEAN;
import static org.opencv.video.Video.findTransformECC;

public class ImageProcessor {

    public static Bitmap alignImages(Bitmap A, Bitmap B){
        final int warp_mode = MOTION_EUCLIDEAN;
        Mat matA = new Mat(A.getHeight(),A.getWidth(), CvType.CV_8UC3);
        Mat matAgray = new Mat(A.getHeight(),A.getWidth(), CvType.CV_8U);
        Mat matB = new Mat(B.getHeight(),B.getWidth(), CvType.CV_8UC3);
        Mat matBgray = new Mat(B.getHeight(),B.getWidth(), CvType.CV_8U);
        Mat matBaligned = new Mat(A.getHeight(),A.getWidth(), CvType.CV_8UC3);
        Mat warpMatrix = Mat.eye(3,3,CV_32F);

        Utils.bitmapToMat(A,matA);
        Utils.bitmapToMat(B,matB);

        Imgproc.cvtColor(matA,matAgray, Imgproc.COLOR_BGR2GRAY);
        Imgproc.cvtColor(matB,matBgray,Imgproc.COLOR_BGR2GRAY);

        int numIter = 5000;
        double terminationEps = 1e-10;
        TermCriteria criteria = new TermCriteria(TermCriteria.COUNT+TermCriteria.EPS,numIter,terminationEps);

        findTransformECC(matAgray,matBgray,warpMatrix,warp_mode,criteria,matBgray);
        Imgproc.warpPerspective(matA,matBaligned,warpMatrix,matA.size(),Imgproc.INTER_LINEAR+ Imgproc.WARP_INVERSE_MAP);
        Bitmap alignedBMP = Bitmap.createBitmap(A.getWidth(),A.getHeight(),null);
        Utils.matToBitmap(matBaligned,alignedBMP);
        return alignedBMP;
    }

}
</code>```

I get the following error

```<code>W/System.err: CvException [org.opencv.core.CvException: cv::Exception: /build/master_pack-android/opencv/modules/imgproc/src/imgwarp.cpp:5987: error: (-215) (M0.type() == CV_32F || M0.type() == CV_64F) && M0.rows == 2 && M0.cols == 3 in function void cv::warpAffine(cv::InputArray, cv::OutputArray, cv::InputArray, cv::Size, int, int, const Scalar&)
W/System.err: ]
W/System.err:     at org.opencv.video.Video.findTransformECC_0(Native Method)
W/System.err:     at org.opencv.video.Video.findTransformECC(Video.java:132)
W/System.err:     at com.test.imgptest.ImageProcessor.alignImages(ImageProcessor.java:42)
W/System.err:     at com.test.imgptest.MainActivity.onActivityResult(MainActivity.java:141)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:6937)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4122)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4169)
W/System.err:     at android.app.ActivityThread.-wrap20(ActivityThread.java)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:154)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6186)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

答:
You're inputting a full 3x3 homography matrix warpMatrix to findTransformECC but your selected warp_mode is MOTION_EUCLIDEAN.

If you want to use a 3x3 homography, then you should set warp_mode to MOTION_HOMOGRAPHY.

If you want a Euclidean transformation, you simply need to clip the last row off your input warpMatrix as Euclidean transformations are given by 2x3 matrices. According to the findTransformECC() documentation,

MOTION_EUCLIDEAN sets a Euclidean (rigid) transformation as motion model; three parameters are estimated; warpMatrix is 2x3.

Then since you'll be working with 2x3 warp matrices, use warpAffine() instead of warpPerspective() to align the images.

Title: Android: Aligning Images using OpenCV

Body:
I am trying to align two images using OpenCV. I based this code off of a C++/Python tutorial I found: http://www.learnopencv.com/image-alignment-ecc-in-opencv-c-python/

The findTransformECC() function in android requires an extra parameter for inputMask. The C++ and Python functions don't have this.

My Code:

import android.graphics.Bitmap;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.TermCriteria;
import org.opencv.imgproc.Imgproc;

import static org.opencv.core.CvType.CV_32F;
import static org.opencv.video.Video.MOTION_EUCLIDEAN;
import static org.opencv.video.Video.findTransformECC;

public class ImageProcessor {

    public static Bitmap alignImages(Bitmap A, Bitmap B){
        final int warp_mode = MOTION_EUCLIDEAN;
        Mat matA = new Mat(A.getHeight(),A.getWidth(), CvType.CV_8UC3);
        Mat matAgray = new Mat(A.getHeight(),A.getWidth(), CvType.CV_8U);
        Mat matB = new Mat(B.getHeight(),B.getWidth(), CvType.CV_8UC3);
        Mat matBgray = new Mat(B.getHeight(),B.getWidth(), CvType.CV_8U);
        Mat matBaligned = new Mat(A.getHeight(),A.getWidth(), CvType.CV_8UC3);
        Mat warpMatrix = Mat.eye(3,3,CV_32F);

        Utils.bitmapToMat(A,matA);
        Utils.bitmapToMat(B,matB);

        Imgproc.cvtColor(matA,matAgray, Imgproc.COLOR_BGR2GRAY);
        Imgproc.cvtColor(matB,matBgray,Imgproc.COLOR_BGR2GRAY);

        int numIter = 5000;
        double terminationEps = 1e-10;
        TermCriteria criteria = new TermCriteria(TermCriteria.COUNT+TermCriteria.EPS,numIter,terminationEps);

        findTransformECC(matAgray,matBgray,warpMatrix,warp_mode,criteria,matBgray);
        Imgproc.warpPerspective(matA,matBaligned,warpMatrix,matA.size(),Imgproc.INTER_LINEAR+ Imgproc.WARP_INVERSE_MAP);
        Bitmap alignedBMP = Bitmap.createBitmap(A.getWidth(),A.getHeight(),null);
        Utils.matToBitmap(matBaligned,alignedBMP);
        return alignedBMP;
    }

}

I get the following error

W/System.err: CvException [org.opencv.core.CvException: cv::Exception: /build/master_pack-android/opencv/modules/imgproc/src/imgwarp.cpp:5987: error: (-215) (M0.type() == CV_32F || M0.type() == CV_64F) && M0.rows == 2 && M0.cols == 3 in function void cv::warpAffine(cv::InputArray, cv::OutputArray, cv::InputArray, cv::Size, int, int, const Scalar&)
W/System.err: ]
W/System.err:     at org.opencv.video.Video.findTransformECC_0(Native Method)
W/System.err:     at org.opencv.video.Video.findTransformECC(Video.java:132)
W/System.err:     at com.test.imgptest.ImageProcessor.alignImages(ImageProcessor.java:42)
W/System.err:     at com.test.imgptest.MainActivity.onActivityResult(MainActivity.java:141)
W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:6937)
W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:4122)
W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4169)
W/System.err:     at android.app.ActivityThread.-wrap20(ActivityThread.java)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:154)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6186)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)


问:
Django - joining multiple tables (models) and filtering out based on their attribute
I'm new to django and ORM in general, and so have trouble coming up with query which would join multiple tables.

I have 4 Models that need joining - Category, SubCategory, Product and Packaging, example values would be:

Category: 'male'

SubCategory: 'shoes'

Product: 'nikeXYZ'

Packaging: 'size_36: 1'

Each of the Model have FK to the model above (ie. SubCategory has field category etc).

My question is - how can I filter Product given a Category (e.g. male) and only show products which have Packaging attribute available set to True? Obviously I want to minimise the hits on my database (ideally do it with 1 SQL query).

I could do something along these lines:

```<code>available = Product.objects.filter(packaging__available=True)
subcategories = SubCategory.objects.filter(category_id=<id_of_male>)
products = available.filter(subcategory_id__in=subcategories)
</code>```

but then that requires 2 hits on database at least (available, subcategories) I think. Is there a way to do it in one go?

答:
try this:</p>

```<code>lookup = {'packaging_available': True, 'subcategory__category_id__in': ['ids of males']}
product_objs = Product.objects.filter(**lookup)
</code>```

Body:
I'm new to django and ORM in general, and so have trouble coming up with query which would join multiple tables.

I have 4 Models that need joining - Category, SubCategory, Product and Packaging, example values would be:

Category: 'male'

SubCategory: 'shoes'

Product: 'nikeXYZ'

Packaging: 'size_36: 1'

Each of the Model have FK to the model above (ie. SubCategory has field category etc).

My question is - how can I filter Product given a Category (e.g. male) and only show products which have Packaging attribute available set to True? Obviously I want to minimise the hits on my database (ideally do it with 1 SQL query).

I could do something along these lines:

available = Product.objects.filter(packaging__available=True)
subcategories = SubCategory.objects.filter(category_id=<id_of_male>)
products = available.filter(subcategory_id__in=subcategories)

but then that requires 2 hits on database at least (available, subcategories) I think. Is there a way to do it in one go?

Body:
try this:

lookup = {'packaging_available': True, 'subcategory__category_id__in': ['ids of males']}
product_objs = Product.objects.filter(**lookup)