问:
LinkedList Queue to List of Integers Method C#
I have two classes that represent a linked list implementation of a queue. Ultimately, I want to be able to bind an object of the queue to a list (to be able to bind it to a gird view).

However, trying to use foreach in methods will not work as 'Queue does not have a public definition for GetEnumerator'.

I need a method in the base class (queue) that will return all the node's data items in their order in the form of an array/list.

Any help would be much appreciated.

```<code>public class Queue
{
    private Node Head;
    private Node Tail;
    private int Count = 0;
    public Queue() { }
    public void Enqueue(int OrderID)
    {
        Node newNode = new Node(OrderID);
        if (Head == null)
        {
            Head = newNode;
            Tail = Head;
        }
        else
        {
            Tail.Next = newNode;
            Tail = Tail.Next;
        }
        Count++;
    }
    public int Dequeue()
    {
        if (Head == null)
        {
            throw new Exception("Nothing in queue.");
        }
        int Result = Head.OrderID;
        Head = Head.Next;
        return Result;
    }

    public int getCount()
    {
        return Count;
    }

}

public class Node
{
    public int OrderID { get; set; }
    public Node Next { get; set; }
    public Node(int ID)
    {
        this.OrderID = ID;
    }
}
</code>```

答:
You can just implement IEnumerable interface:

```<code>public class Queue<T> : IEnumerable<T>
{
    private Node _head;
    private Node _tail;
    private int _count = 0;
    public void Enqueue(T value)
    {
        Node newNode = new Node(value);
        if (_head == null)
        {
            _head = newNode;
            _tail = _head;
        }
        else
        {
            _tail.Next = newNode;
            _tail = _tail.Next;
        }
        _count++;
    }
    public T Dequeue()
    {
        if (_head == null)
        {
            throw new Exception("Nothing in queue.");
        }
        var result = _head.Value;
        _head = _head.Next;
        _count--;
        return result;
    }

    public int GetCount()
    {
        return _count;
    }

    private class Node
    {
        public readonly T Value;
        public Node Next { get; set; }
        public Node(T value)
        {
            Value = value;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        var iter = _head;
        while (iter != null)
        {
            yield return iter.Value;
            iter = _head.Next;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
</code>```

Then in code:

```<code>var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(100);

foreach(var item in queue)
{
   Console.WriteLine(item);
}
</code>```

PS: Also, fixed you error with GetCount() method on Dequeue.

Body:
I have two classes that represent a linked list implementation of a queue. Ultimately, I want to be able to bind an object of the queue to a list (to be able to bind it to a gird view).

However, trying to use foreach in methods will not work as 'Queue does not have a public definition for GetEnumerator'.

I need a method in the base class (queue) that will return all the node's data items in their order in the form of an array/list.

Any help would be much appreciated.

public class Queue
{
    private Node Head;
    private Node Tail;
    private int Count = 0;
    public Queue() { }
    public void Enqueue(int OrderID)
    {
        Node newNode = new Node(OrderID);
        if (Head == null)
        {
            Head = newNode;
            Tail = Head;
        }
        else
        {
            Tail.Next = newNode;
            Tail = Tail.Next;
        }
        Count++;
    }
    public int Dequeue()
    {
        if (Head == null)
        {
            throw new Exception("Nothing in queue.");
        }
        int Result = Head.OrderID;
        Head = Head.Next;
        return Result;
    }

    public int getCount()
    {
        return Count;
    }

}

public class Node
{
    public int OrderID { get; set; }
    public Node Next { get; set; }
    public Node(int ID)
    {
        this.OrderID = ID;
    }
}

Body:
You can just implement IEnumerable interface:

public class Queue<T> : IEnumerable<T>
{
    private Node _head;
    private Node _tail;
    private int _count = 0;
    public void Enqueue(T value)
    {
        Node newNode = new Node(value);
        if (_head == null)
        {
            _head = newNode;
            _tail = _head;
        }
        else
        {
            _tail.Next = newNode;
            _tail = _tail.Next;
        }
        _count++;
    }
    public T Dequeue()
    {
        if (_head == null)
        {
            throw new Exception("Nothing in queue.");
        }
        var result = _head.Value;
        _head = _head.Next;
        _count--;
        return result;
    }

    public int GetCount()
    {
        return _count;
    }

    private class Node
    {
        public readonly T Value;
        public Node Next { get; set; }
        public Node(T value)
        {
            Value = value;
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        var iter = _head;
        while (iter != null)
        {
            yield return iter.Value;
            iter = _head.Next;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Then in code:

var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(100);

foreach(var item in queue)
{
   Console.WriteLine(item);
}

PS: Also, fixed you error with GetCount() method on Dequeue.


来源: stackexchange

问:
Can I get Siesta to look at my persistent cache before making a network request?
I've started using Siesta while running in the background, using Apple's background fetch capabilities.  One of the (many) difficult things to work with while running this way is that on some devices, the OS tends to kill my process frequently.  I am trying to get my processing to be fast and as battery efficient as possible, so that the OS will choose to run it regularly.

As I understand it, if Siesta has no data in its in-memory cache (which is the case if the app is newly launched), then it makes both a network request and a persistent cache request.  I often have perfectly good, non-stale data in the persistent cache in this scenario.  Can I get Siesta to pre-load that data into the in-memory cache, before it makes the network request?  Then my code uses less battery, it gets run regularly, every thing is great!

答:
As it happens, I just hit this issue myself working on a prepackaged FileCache implementation for Siesta. I think it’s fair to call it a bug.

When you first bring a Resource into memory, Siesta fires off the cache check asynchronously. That’s as it should be — we don’t want expensive data loading to hold up the UI thread — but loadIfNeeded() doesn’t wait for the cache check to complete.

An improved design would have loadIfNeeded() still return a Request if there’s no data yet, but have that request be a chained one that first checks the cache and then checks the network.

In the meantime, a (very ugly) workaround for this is to delay your loadIfNeeded() call:

```<code>let resource = service.resource("whatever")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
  resource.loadIfNeeded()
}
</code>```

Update: I’ve filed an issue for this.

ContentLicense: CC BY-SA 3.0

Body:
As it happens, I just hit this issue myself working on a prepackaged FileCache implementation for Siesta. I think it’s fair to call it a bug.

When you first bring a Resource into memory, Siesta fires off the cache check asynchronously. That’s as it should be — we don’t want expensive data loading to hold up the UI thread — but loadIfNeeded() doesn’t wait for the cache check to complete.

An improved design would have loadIfNeeded() still return a Request if there’s no data yet, but have that request be a chained one that first checks the cache and then checks the network.

In the meantime, a (very ugly) workaround for this is to delay your loadIfNeeded() call:

let resource = service.resource("whatever")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
  resource.loadIfNeeded()
}

Update: I’ve filed an issue for this.


问:
Clean Way to Force Use of a Derived Interface
In my application, some of the entities implement interface A, others implement interface B, and some implement both A and B.  How can I force code that looks at these entities that implement both A and B to use the derived interface for A and B?

Here's some examples:

Interface A

```<code>public interface IActive
{
   DateTime? StartEffDT { get; set; }
   DateTime? EndEffDT { get; set; }
}
</code>```

Interface B

```<code>public interface ISecured
{
    object SecurityToCheck { get; set; }
}
</code>```

Interface A and B

```<code>public interface IActiveSecured : IActive, ISecured
{
}
</code>```

Method Example

```<code>public void ExampleMethod1(IActive x) { }
public void ExampleMethod2(ISecured y) { }
public void ExampleMethod3(IActiveSecured z) { }
</code>```

Is there a way to force ExampleMethod1 to only take IActive, but not IActiveSecured?

```<code>public void UpdateItem(IActive item) {
    //update the item, if it is currently active
}
</code>```

If I tried to call UpdateItem with an IActiveSecured item, it would work. No surprise, that's how inheritance works.  But what if I want to ensure that you can't call UpdateItem with an IActiveSecured, because the security needs to be checked to make sure that the user is authorized to update the item?

Thanks for the help!

答:
You may use this code, but it has bad smell.
If there are new interfaces that inherit from IActive - will inevitably complement the code.</p>

```<code>public void UpdateItem(IActive item) {
    if(item is IActiveSecured)
        return;
    //do some code
}
</code>```

Body:
In my application, some of the entities implement interface A, others implement interface B, and some implement both A and B.  How can I force code that looks at these entities that implement both A and B to use the derived interface for A and B?

Here's some examples:

Interface A

public interface IActive
{
   DateTime? StartEffDT { get; set; }
   DateTime? EndEffDT { get; set; }
}

Interface B

public interface ISecured
{
    object SecurityToCheck { get; set; }
}

Interface A and B

public interface IActiveSecured : IActive, ISecured
{
}

Method Example

public void ExampleMethod1(IActive x) { }
public void ExampleMethod2(ISecured y) { }
public void ExampleMethod3(IActiveSecured z) { }

Is there a way to force ExampleMethod1 to only take IActive, but not IActiveSecured?

public void UpdateItem(IActive item) {
    //update the item, if it is currently active
}

If I tried to call UpdateItem with an IActiveSecured item, it would work. No surprise, that's how inheritance works.  But what if I want to ensure that you can't call UpdateItem with an IActiveSecured, because the security needs to be checked to make sure that the user is authorized to update the item?

Thanks for the help!

Body:
You may use this code, but it has bad smell.
If there are new interfaces that inherit from IActive - will inevitably complement the code.

public void UpdateItem(IActive item) {
    if(item is IActiveSecured)
        return;
    //do some code
}


问:
React input onChange only registers one keypress
Here is the relevant code:

```<code>onAnswerChange = (e) => {
    e.preventDefault();
    const answerID = e.target.id
    const answerVal = e.target.value
    this.setState( (prevState) => {
      let allAnswers = prevState.answers
      allAnswers[answerID] = answerVal
      return {answers: allAnswers}
    })
  }
  generateAnswerInput = () => {
    const id = this.state.nAnswers
    const answerInput = (
      <div key={id}>
        <input
          type='text'
          placeholder={`Answer #${id+1}`}
          id={id}
          value={this.state.answers[id]}
          onChange={this.onAnswerChange}
          disabled={this.state.disabled}
        />
        <i
          id='delete-button'
          className="fa fa-window-close-o"
          aria-hidden="true"
          onClick={this.deleteAnswer}
        ></i>
      </div>
    )
    this.setState( (prevState) => ({inputToRender: [...prevState.inputToRender, answerInput]}))
  }
</code>```

Please excuse the spaghetti code. Right now the corresponding value in state does change (the answers array), but it only registers one character. Additionally, the input doesn't update to show the character in the input field. Any help would be greatly appreciated, thanks!

答: I changed the way I generated the inputs and fixed the problem. For anyone else who may have a similar set up, I am fairly certain that the input did not update when typing because the input itself was stored in state. </p>

Body:
Here is the relevant code:

onAnswerChange = (e) => {
    e.preventDefault();
    const answerID = e.target.id
    const answerVal = e.target.value
    this.setState( (prevState) => {
      let allAnswers = prevState.answers
      allAnswers[answerID] = answerVal
      return {answers: allAnswers}
    })
  }
  generateAnswerInput = () => {
    const id = this.state.nAnswers
    const answerInput = (

        <input
          type='text'
          placeholder={`Answer #${id+1}`}
          id={id}
          value={this.state.answers[id]}
          onChange={this.onAnswerChange}
          disabled={this.state.disabled}
        />

    )
    this.setState( (prevState) => ({inputToRender: [...prevState.inputToRender, answerInput]}))
  }

Please excuse the spaghetti code. Right now the corresponding value in state does change (the answers array), but it only registers one character. Additionally, the input doesn't update to show the character in the input field. Any help would be greatly appreciated, thanks!


问:
Lua obfuscation issue
I have tried to decompile one of Lua script just for learning purposes, and I got the original code however the code was obfuscated like below:

```<code>local L0_0, L1_1, L2_2, L3_3, L4_4, L5_5, L6_6, L7_7, L8_8, L9_9, L10_10, L11_11, L12_12, L13_13, L14_14, L15_15, L16_16, L17_17, L18_18, L19_19, L20_20, L21_21, L22_22, L23_23, L24_24, L25_25, L26_26, L27_27, L28_28, L29_29
L0_0 = require
L1_1 = "comm.NetworkClock"
L0_0 = L0_0(L1_1)
L1_1 = require
L2_2 = "comm_ads.fullscreenAds"
L1_1 = L1_1(L2_2)
L2_2 = require
L15_15 = L14_14.init
L15_15()
L15_15 = L4_4.log
L16_16 = "IN main"
L15_15(L16_16)
function L15_15()
  local L0_30, L1_31
end
print = L15_15
</code>```

Is there any way to recover these code to reach the original one?

答:
Can you get back to the original source? No, not likely.

Source code is optimized to be read by humans, byte code is optimized to be read by machines. Compiling usually results in a one-way conversion where information required to restore the original source is lost.

Best bet at this point is to simplify it by hand and a bunch of find & replace once you identify what a variable or function actually does.

If you did find (or build) a tool to simplify the decompiled source code to be more human-readable, it still would not really be reproducing the original source code.

Title: Lua obfuscation issue

Body:
I have tried to decompile one of Lua script just for learning purposes, and I got the original code however the code was obfuscated like below:

local L0_0, L1_1, L2_2, L3_3, L4_4, L5_5, L6_6, L7_7, L8_8, L9_9, L10_10, L11_11, L12_12, L13_13, L14_14, L15_15, L16_16, L17_17, L18_18, L19_19, L20_20, L21_21, L22_22, L23_23, L24_24, L25_25, L26_26, L27_27, L28_28, L29_29
L0_0 = require
L1_1 = "comm.NetworkClock"
L0_0 = L0_0(L1_1)
L1_1 = require
L2_2 = "comm_ads.fullscreenAds"
L1_1 = L1_1(L2_2)
L2_2 = require
L15_15 = L14_14.init
L15_15()
L15_15 = L4_4.log
L16_16 = "IN main"
L15_15(L16_16)
function L15_15()
  local L0_30, L1_31
end
print = L15_15

Is there any way to recover these code to reach the original one?


问:
How can I tell Gradle to use my testng.xml file for Test Classes and Ordering?
I am attempting to have Gradle execute some tests defined using a testng.xml file.  My testng.xml file looks like this:

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="mySuite" verbose="1">

  <listeners>
    <listener class-name="mypackage.MyListener" />
    <listener class-name="mypackage.TestOrderer" />
  </listeners>

  <test name="Tests">
    <classes>
      <class name="mytestpackage.CrazyTest1"/>
      <class name="mytestpackage.CrazyTest2"/>
      <class name="mytestpackage.CrazyTest3"/>
    </classes>
  </test>
</suite>
</code>```

So why do I need this?  I want to ensure that my tests are organized in a way that's defined by annotations similar to that which was listed here.  As you might guess, TestOrderer is an IMethodInterceptor.

Here's the problem, Gradle seems to be taking over my testng.xml file and scraping the test directory to find the tests it wants to execute.  Even if I disable this, it fails to execute the methods appropriately.  Here's what I think should work, but just, doesn't.

```<code>test {
  useTestNG()
  options.suites("src/test/resources/crazyTestNG.xml")
  # Adding
  # scanForTestClasses = false
  # causes zero tests to be executed, since the class names don't end in Test
}
</code>```

It seems like it should be a no-brainer...fork the TestNG process and let it run, but I can't figure out how to tell Gradle to get out of the way and just execute my tests.

答:
The Gradle TestNG runner assumes that if no test classes are specified, either by scanning for them, or pattern matching on the name, then it should skip test execution entirely.

Instead, it should consider whether a suite xml has been provided or not as well. Could you add a jira issue for this problem?

One possible work around is to use options.listener to specify the listeners, and not use a suite xml file at all:

```<code>test {
   options.listeners << 'mypackage.MyListener'
   options.listeners << 'mypackage.TestOrderer'
}
</code>```

This way you don't need to specify the test classes, and you can just let the scanning find them for you.

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to have Gradle execute some tests defined using a testng.xml file.  My testng.xml file looks like this:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="mySuite" verbose="1">

  <listeners>
    <listener class-name="mypackage.MyListener" />
    <listener class-name="mypackage.TestOrderer" />
  </listeners>

  <test name="Tests">
    <classes>
      <class name="mytestpackage.CrazyTest1"/>
      <class name="mytestpackage.CrazyTest2"/>
      <class name="mytestpackage.CrazyTest3"/>
    </classes>
  </test>
</suite>

So why do I need this?  I want to ensure that my tests are organized in a way that's defined by annotations similar to that which was listed here.  As you might guess, TestOrderer is an IMethodInterceptor.

Here's the problem, Gradle seems to be taking over my testng.xml file and scraping the test directory to find the tests it wants to execute.  Even if I disable this, it fails to execute the methods appropriately.  Here's what I think should work, but just, doesn't.

test {
  useTestNG()
  options.suites("src/test/resources/crazyTestNG.xml")
  # Adding
  # scanForTestClasses = false
  # causes zero tests to be executed, since the class names don't end in Test
}

It seems like it should be a no-brainer...fork the TestNG process and let it run, but I can't figure out how to tell Gradle to get out of the way and just execute my tests.

Body:
The Gradle TestNG runner assumes that if no test classes are specified, either by scanning for them, or pattern matching on the name, then it should skip test execution entirely.

Instead, it should consider whether a suite xml has been provided or not as well. Could you add a jira issue for this problem?

One possible work around is to use options.listener to specify the listeners, and not use a suite xml file at all:

test {
   options.listeners << 'mypackage.MyListener'
   options.listeners << 'mypackage.TestOrderer'
}

This way you don't need to specify the test classes, and you can just let the scanning find them for you.


问:
Is it possible to restrict third party app access on iOS
There's an app i want to get built but not sure if one of the main features is even possible. I want to be able to use an iOS app to restrict access to other third party apps (mostly games) on a device.

The app would detect which apps are on the device & then user could choose which apps would be blocked.

I'm assuming this requires some operating system level access which is why I think it cannot be done but would be very happy to be proven otherwise.

Thanks in advance for any insight.

答:
iOS Parental Control Restrictions, built into iOS, may be able to do some of what you're looking for.

https://support.apple.com/en-us/HT201304


问:
Owl inference : How to get the class of Individuals after loading ontology
I have an ontology witch is created in protege, insid it :

I have 2 classes ( teenager and adult ).

I have the individual John with a dataProperty hasAge.

In protege i get the class of john according to his age. ( so my ontology work well)

Now i have loaded my ontology in java and i try to get all the individuals that are in the class adult ( Like John in protege ). so i did

```<code>        //manager
        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

        //IRI
        String x = "file:/D:/Studies/tpOwl.owl";
        IRI ontologyIRI = IRI.create(x);

        //ontology
        OWLOntology ont = manager.createOntology(ontologyIRI);

        //factory
        OWLDataFactory factory = manager.getOWLDataFactory();

        OWLReasonerFactory reasonerFactory = new StructuralReasonerFactory();
        OWLReasoner reasoner = reasonerFactory.createReasoner(ont);

        OWLClass adult = factory.getOWLClass(IRI.create(ontologyIRI + "#Adult"));
        NodeSet<OWLNamedIndividual> instancess = reasoner.getInstances(adult, true);
        for (Node<OWLNamedIndividual> i : instancess)
        {
         System.out.println(""+i);
        }
</code>```

but i got nothing.

So how can i get the individuals of a specific class after loading my ontology in java ?

答:
There are a couple of errors in your code:

You need 2 IRIs: One for loading your ontology which is prepended with file:, the other the IRI used in your ontology for uniquely identifying constructs in your ontology.

You have to load your ontology, not create it.

You have to use a different reasoner. So instead of using StructuralReasonerFactory use say Hermit. See Hermit. JFact also does not work.

Here are the working code using Hermit:

```<code>        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

        //IRI
        Path path = Paths.get(".").toAbsolutePath().normalize();
        IRI loadDocumentIRI = IRI.create("file:/D:/Studies/tpOwl.owl");

        IRI ontologyIRI = IRI.create("http://www.semanticweb.org/akkou/ontologies/2017/10/tp-ontology");

        //ontology
        OWLOntology ont = manager.loadOntologyFromOntologyDocument(loadDocumentIRI);

        //factory
        OWLDataFactory factory = manager.getOWLDataFactory();

        OWLReasonerFactory reasonerFactory = new ReasonerFactory();
        OWLReasoner reasoner = reasonerFactory.createReasoner(ont);

        OWLClass adult = factory.getOWLClass(IRI.create(ontologyIRI + "#Adult"));
        NodeSet<OWLNamedIndividual> instancess = reasoner.getInstances(adult, true);
        for (Node<OWLNamedIndividual> i : instancess)  {
         System.out.println(""+i);
        }
</code>```

Body:
I have an ontology witch is created in protege, insid it :

I have 2 classes ( teenager and adult ).

I have the individual John with a dataProperty hasAge.

In protege i get the class of john according to his age. ( so my ontology work well)

Now i have loaded my ontology in java and i try to get all the individuals that are in the class adult ( Like John in protege ). so i did

        //manager
        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

        //IRI
        String x = "file:/D:/Studies/tpOwl.owl";
        IRI ontologyIRI = IRI.create(x);

        //ontology
        OWLOntology ont = manager.createOntology(ontologyIRI);

        //factory
        OWLDataFactory factory = manager.getOWLDataFactory();

        OWLReasonerFactory reasonerFactory = new StructuralReasonerFactory();
        OWLReasoner reasoner = reasonerFactory.createReasoner(ont);

        OWLClass adult = factory.getOWLClass(IRI.create(ontologyIRI + "#Adult"));
        NodeSet<OWLNamedIndividual> instancess = reasoner.getInstances(adult, true);
        for (Node<OWLNamedIndividual> i : instancess)
        {
         System.out.println(""+i);
        }

but i got nothing.

So how can i get the individuals of a specific class after loading my ontology in java ?

Body:
There are a couple of errors in your code:

You need 2 IRIs: One for loading your ontology which is prepended with file:, the other the IRI used in your ontology for uniquely identifying constructs in your ontology.

You have to load your ontology, not create it.

You have to use a different reasoner. So instead of using StructuralReasonerFactory use say Hermit. See Hermit. JFact also does not work.

Here are the working code using Hermit:

        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

        //IRI
        Path path = Paths.get(".").toAbsolutePath().normalize();
        IRI loadDocumentIRI = IRI.create("file:/D:/Studies/tpOwl.owl");

        IRI ontologyIRI = IRI.create("http://www.semanticweb.org/akkou/ontologies/2017/10/tp-ontology");

        //ontology
        OWLOntology ont = manager.loadOntologyFromOntologyDocument(loadDocumentIRI);

        //factory
        OWLDataFactory factory = manager.getOWLDataFactory();

        OWLReasonerFactory reasonerFactory = new ReasonerFactory();
        OWLReasoner reasoner = reasonerFactory.createReasoner(ont);

        OWLClass adult = factory.getOWLClass(IRI.create(ontologyIRI + "#Adult"));
        NodeSet<OWLNamedIndividual> instancess = reasoner.getInstances(adult, true);
        for (Node<OWLNamedIndividual> i : instancess)  {
         System.out.println(""+i);
        }


问:
Converting Geometry to Longitude/Latitude coordinates in R
https://data.sfgov.org/Transportation/Bike-Share-Stations/gtyg-jpkj

I am working with this dataset, and am wondering if I could convert geometry (Geom in the table) to two columns: longitude and latitude in R.

Thank you!

Body:
RSocrata::read.socrata and tidyr::extract make this concise:

library(tidyverse)

df <- RSocrata::read.socrata('https://data.sfgov.org/Transportation/Bike-Share-Stations/gtyg-jpkj')

df <- df %>% extract(Geom, c('lat', 'lon'), '\\((.*), (.*)\\)', convert = TRUE)

# print nicely
df %>% select(UID, Site.ID, lat, lon) %>% as_data_frame()
#> # A tibble: 107 x 4
#>      UID    Site.ID      lat       lon
#>  * <int>      <chr>    <dbl>     <dbl>
#>  1     1  SF-T24 S1 37.75182 -122.4266
#>  2     2  SF-G33 S1 37.79350 -122.3928
#>  3     3   SOMA-06A 37.78974 -122.3947
#>  4     4  SF-T22 S5 37.75128 -122.4318
#>  5     5  SF-R25 S4 37.75671 -122.4210
#>  6     6    NOMA-2E 37.79861 -122.4008
#>  7     7  SF-L33 S4 37.77590 -122.3932
#>  8     8  SF-O24 S4 37.76623 -122.4269
#>  9     9 Market-03B 37.78099 -122.4117
#> 10    10  SF-O28 S2 37.76723 -122.4108
#> # ... with 97 more rows


问:
Why do so many Android games ask for full file access instead of using Internal Storage?
Many major games start out by asking for full file read permissions:  Allow APPNAME to access photos, media, and files on your device

I'm assuming that is android.permission.READ_EXTERNAL_STORAGE

This seems dangerous to grant arbitrary apps to read any files on your phone.  Why wouldn't the games use Internal Storage?

I'm not the only one with this question, there are unanswered posts like this with the same concern.  An example game that request it.

答:
It’s actually recommended in the Android docs:

If you are handling files that are not intended for other apps to use
  (such as graphic textures or sound effects used by only your app), you
  should use a private storage directory on the external storage by
  calling getExternalFilesDir()

https://developer.android.com/guide/topics/data/data-storage.html#filesExternal


问:
Angular CLI looking for router module in wrong place? "router_module not found"
I have an issue:

Based on the trace, my code is looking for the router module in the wrong place, it should be looking in my node modules\@angular folder but its looking in my src\app\ folder, how can i fix this?

How I got here

I've installed angular 2 using angular cli, when I go to use the router module to create my routes, I import it like so:

```<code>import { RouterModule } '@angular/router/src/router_module';
</code>```

and then use it passing in my routes like so:

```<code>export const routing = RouterModule.forRoot(APP_ROUTES, {enableTracing: true});
</code>```

now when it goes to compile i get the following error:

Failed to compile.

./src/app/app.routing.ts Module not found: Error: Can't resolve

'@angular/router/src/router_module' in 'C:\path\to\src\app' <== important part ?

@ ./src/app/app.routing.ts 3:0-84

@ ./src/app/app.module.ts

@ ./src/main.ts

@ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts

I've checked that  node module/@angular/router/src/router_module exists, and it does... I'm really stumped

angluar cli v1.0.1

angular v 4.4.6

答:
Use this as your import:

```<code>import { RouterModule } from '@angular/router';
</code>```

Get rid of the /src/router_module on the end of the path, and don't forgot the from.

I don't know what IDE you are using, but I use VS Code. Sometimes, when I use the Ctrl+. (control period) to get the IDE to add a reference for me, I get some extra stuff in the path like what you had.

Something to watch out for!

Body:
I have an issue:

Based on the trace, my code is looking for the router module in the wrong place, it should be looking in my node modules\@angular folder but its looking in my src\app\ folder, how can i fix this?

How I got here

I've installed angular 2 using angular cli, when I go to use the router module to create my routes, I import it like so:

import { RouterModule } '@angular/router/src/router_module';

and then use it passing in my routes like so:

export const routing = RouterModule.forRoot(APP_ROUTES, {enableTracing: true});

now when it goes to compile i get the following error:

Failed to compile.

./src/app/app.routing.ts Module not found: Error: Can't resolve

'@angular/router/src/router_module' in 'C:\path\to\src\app' <== important part ?

@ ./src/app/app.routing.ts 3:0-84

@ ./src/app/app.module.ts

@ ./src/main.ts

@ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts

I've checked that  node module/@angular/router/src/router_module exists, and it does... I'm really stumped

angluar cli v1.0.1

angular v 4.4.6

Body:
Use this as your import:

import { RouterModule } from '@angular/router';

Get rid of the /src/router_module on the end of the path, and don't forgot the from.

I don't know what IDE you are using, but I use VS Code. Sometimes, when I use the Ctrl+. (control period) to get the IDE to add a reference for me, I get some extra stuff in the path like what you had.

Something to watch out for!


问:
In Java, do methods that don't use static or class variables need to be synchronized?
Do methods that only use local variables inside suffer any threading issues ?. Somewhere it was mentioned that the method with local variables are copied to each thread stack frame to work with and do not need to synchronized for multithreaded implementation unless it uses class level or static references/variables ?</p>

答: You do not need to worry about local variables.   Instance variables however are something to care about.</p>


问:
[Python3x]: How to extract two values separately (beautifulsoup)?
This is the value (coordinates) that I would like to have separately (latitude, longitude).

```<code><input id="dokad" value="51.819544, 19.30441" type="hidden">
</code>```

When I do like that:

```<code>lat_lon = soup.find('input', attrs={'id':'dokad'}).get('value')
</code>```

Result:

```<code>lat_lon
Out[1012]: '51.186147, 19.199997'
type(lat_lon)
Out[1013]: str
</code>```

How can I extract these two values separately?

答:
Another attempt can be something like below to get them separately:

```<code>content='''
<input id="dokad" value="51.819544, 19.30441" type="hidden">
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(content,"lxml")

item = soup.select("#dokad")[0]['value']
lat = item.split(", ")[0]
lon = item.split(", ")[1]

print("Lat: {}\nLong: {}".format(lat,lon))
</code>```

Result:

```<code>Lat: 51.819544
Long: 19.30441
</code>```

Body:
This is the value (coordinates) that I would like to have separately (latitude, longitude).

<input id="dokad" value="51.819544, 19.30441" type="hidden">

When I do like that:

lat_lon = soup.find('input', attrs={'id':'dokad'}).get('value')

Result:

lat_lon
Out[1012]: '51.186147, 19.199997'
type(lat_lon)
Out[1013]: str

How can I extract these two values separately?

Body:
Another attempt can be something like below to get them separately:

content='''
<input id="dokad" value="51.819544, 19.30441" type="hidden">
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(content,"lxml")

item = soup.select("#dokad")[0]['value']
lat = item.split(", ")[0]
lon = item.split(", ")[1]

print("Lat: {}\nLong: {}".format(lat,lon))

Result:

Lat: 51.819544
Long: 19.30441


问:
Can't create multiple private BLE services on RN4020 Bluetooth module
I'm trying to use Microchip's RN4020 Bluetooth Low Energy module to create my own custom services so I could control them from my phone.

When I try to create only one private service everything works just fine. The problem starts if I try to create more than 1 using the following commands

From all the AOK messages looks like there are no problems but when
i actually list all the available services with LS command

both characteristics are put under the 2nd service and 1st one don't even exist anymore. I tried to set one service at 1st, than reboot and than add another one but it made no difference.

Is there even a way to create more than 1 private service on this RN4020 BLE module?

答:
Hi etrusks I guess by now you might have the answer for this issue. But for those who have the same issue.

It looks like RN4020 module has this issue and its not solved yet (firmware V1.23). microchip has addressed this issue in the "RN4020 Bluetooth® Low Energy Module User’s Guide" They have a work around for this and you can read more about it in the same document.

Thank you!


问:
How to Copy Messages backup of from one HornnetQ server to another Server?
I have Hornet Queue message backup containing around 60 million messages from one of the server and i am trying to copy that backup to another server's HornetQ, But after copying backup to another server when i check the queues in Jconsole it shows 0 messages in that queue.

I copied paging and bindings folder from server1 to server 2.

Is there any special way to do that or i am missing something?

Regards,
Simer

答: You must copy each of the 4 folders from one broker to another (i.e. large-messages, journal, bindings, & paging).  Aside from that you can start both brokers and use a bridge to move messages between them.</p>


问:
Understanding Egg Drop Algorithm for more than two eggs.
http://datagenetics.com/blog/july22012/index.html

I am using the mentioned link to understand the eggdrop problem. I have also looked at code online which I understand to decent extent (the recursion is a bit confusing) but I can't seem to understand a few main things about this egg drop problem.

Suppose we have 100 floors

For 2 eggs we say we start at 14 and then go to 14 + (14-1). I understand why we do this to keep the worse case time uniform and all. However, where will we start for three eggs? The formula shows that 3 eggs will have a max of 9 tries in the worst case. Obviously we don't start from 9 because going 9 + ( 9 - 1 )  doesn't give us a consisten 9 trials across 100 so where do we start for 3? Not only that but how do we figure this out?

It seems like for 3 eggs, we run a few trials until the problem degenerates into 2 eggs and x amount of floors. Conceptually this makes sense but I don't understand how to visualize or implement this

I have to find the sequence of tries in a worst case scenario and implement it which is why I want to visualize the tries.

I hope this is clear. It is the first bullet of mine that is my main issue. Please let me know if I'm missing out any info and I'll edit it.

答:
Here is the algorithm which have implemented in swift(This includes concept of all previous algorithm):-</p>

```<code>//Here n is number of eggs and k is number of floors
func eggDrop(_ n: Int, _ k: Int) -> Int {
        var eggFloor: [[Int]] = Array(repeating:Array(repeating: 0, count: k+1),count: n+1)
        if k == 1 {
            return k
        }
        for i in 1...n {
            eggFloor[i][1] = 1
            eggFloor[i][0] = 0
        }
        for j in 1...k {
            eggFloor[1][j] = j
        }
        for i in 2...n {
            for j in 2...k {
                eggFloor[i][j] = Int(INT_MAX)
                for x in 1...j {
                    let attempts = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x])
                    if attempts < eggFloor[i][j] {
                        eggFloor[i][j] = attempts
                    }
                }
            }
        }
        return eggFloor[n][k]
    }
</code>```

Body:
Here is the algorithm which have implemented in swift(This includes concept of all previous algorithm):-

//Here n is number of eggs and k is number of floors
func eggDrop(_ n: Int, _ k: Int) -> Int {
        var eggFloor: [[Int]] = Array(repeating:Array(repeating: 0, count: k+1),count: n+1)
        if k == 1 {
            return k
        }
        for i in 1...n {
            eggFloor[i][1] = 1
            eggFloor[i][0] = 0
        }
        for j in 1...k {
            eggFloor[1][j] = j
        }
        for i in 2...n {
            for j in 2...k {
                eggFloor[i][j] = Int(INT_MAX)
                for x in 1...j {
                    let attempts = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x])
                    if attempts < eggFloor[i][j] {
                        eggFloor[i][j] = attempts
                    }
                }
            }
        }
        return eggFloor[n][k]
    }


问:
Passing variables through Selenium send.keys instead of strings
I'm trying to use Selenium for some app testing, and I need it to plug a variable in when filling a form instead of a hardcoded string. IE:

this works
name_element.send_keys("John Doe")

but this doesnt
name_element.send_keys(username)

Does anyone know how I can accomplish this? Pretty big Python noob, but used Google extensively to try and find out.

答:
Try this.  </p>

```
username = r'John Doe'

name_element.send_keys(username)
```

<p>I was able to pass the string without casting it just fine in my test. </p>

Body:
Try this.

username = r'John Doe'

name_element.send_keys(username)

I was able to pass the string without casting it just fine in my test.


问:
How would I make my buttons scrollable?
I have 3 buttons that I would like to make possible for it to scroll.

I've tried adding <ScrollView's to encapsulate each <LinearLayout that contains <Button's but that didn't work and just gave me more problems.

How can I use <ScrollView the correct way so that my buttons scroll?

Here's activity-maps.xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.mancj.example.MapsActivity">
    </fragment>

    <LinearLayout
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <EditText
            android:hint="Search"
            android:id="@+id/searchBar"
            android:layout_width="289dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/searchButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:onClick="onSearch"
            android:text="SEARCH" />

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="something1"
        android:id="@+id/button2"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="480dp"
            android:text="something2"
            android:id="@+id/button3"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="440dp"
            android:text="something3"
            android:id="@+id/button4"/>
    </LinearLayout>

</RelativeLayout>
</code>```

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="co.sovf.example.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:id="@+id/button5"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Button" />

            <Button
                android:id="@+id/button3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Button" />

            <Button
                android:id="@+id/button4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Button" />
        </LinearLayout>
    </ScrollView>

</android.support.constraint.ConstraintLayout>
</code>```

Title: How would I make my buttons scrollable?

Body:
I have 3 buttons that I would like to make possible for it to scroll.

I've tried adding <ScrollView's to encapsulate each <LinearLayout that contains <Button's but that didn't work and just gave me more problems.

How can I use <ScrollView the correct way so that my buttons scroll?

Here's activity-maps.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.mancj.example.MapsActivity">
    </fragment>

    <LinearLayout
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <EditText
            android:hint="Search"
            android:id="@+id/searchBar"
            android:layout_width="289dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/searchButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:onClick="onSearch"
            android:text="SEARCH" />

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="something1"
        android:id="@+id/button2"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="480dp"
            android:text="something2"
            android:id="@+id/button3"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="440dp"
            android:text="something3"
            android:id="@+id/button4"/>
    </LinearLayout>

</RelativeLayout>


问:
If statement is not branching correctly
I am a novice at python.  The program was to pass any list into a function and print a string with the words separated with a ',' with the last word separated by a ', and'.  But the If statement does not branch for the last word.  I don't know if putting it in a for loop is breaking it.

```<code>spam = ['apples', 'oranges', 'pears', 'strawberries', 'watermelon']

def comma(x):
    newSpam = x[0]
    del x[0]
    for i in range(len(x)):
        print(type(len(x)))
        if i == (len(x)):
            newSpam = newSpam + ', and ' + [x(i)]
        else:
            newSpam = newSpam + ', '+ x[i]
    print(newSpam)
comma(spam)
</code>```

The output I get is:

```<code>apples, oranges, pears, strawberries, watermelon
</code>```

答:
length does not indicate the last item of a list.You need to use length-1 to indicate the last item.</p>

```<code>def comma(a_list):
   x=len(a_list)
   y=""
   for i in range (x):
     if i==(x-1):
        y=y+"and "
        y=y+spam[i]
        break
     y=y+spam[i]
     y=y+", "

    print (y)
</code>```

Title: If statement is not branching correctly

Body:
I am a novice at python.  The program was to pass any list into a function and print a string with the words separated with a ',' with the last word separated by a ', and'.  But the If statement does not branch for the last word.  I don't know if putting it in a for loop is breaking it.

spam = ['apples', 'oranges', 'pears', 'strawberries', 'watermelon']

def comma(x):
    newSpam = x[0]
    del x[0]
    for i in range(len(x)):
        print(type(len(x)))
        if i == (len(x)):
            newSpam = newSpam + ', and ' + [x(i)]
        else:
            newSpam = newSpam + ', '+ x[i]
    print(newSpam)
comma(spam)

The output I get is:

apples, oranges, pears, strawberries, watermelon

Body:
length does not indicate the last item of a list.You need to use length-1 to indicate the last item.

def comma(a_list):
   x=len(a_list)
   y=""
   for i in range (x):
     if i==(x-1):
        y=y+"and "
        y=y+spam[i]
        break
     y=y+spam[i]
     y=y+", "

    print (y)


问:
QGraphicsItem line width / transformation changes from PyQt4 to PyQt5
I have some small utility GUIs that I have made with PyQt, which use a QGraphicsScene with some items in it, and a view that response to user clicks (for making boxes, selecting points, etc).

On the (offline) machine I use, the software was just upgraded from Anaconda 2.5 to Anaconda 4.3, including the switch from PyQt4 to PyQt5.  Everything still works, except somehow the transformations for my various QGraphicsItem objects are messed up if the scene rect is defined in anything but pixel coordinates.

Upfront question: What changed as far as item transformations from PyQt4 to PyQt5?

Here is an example of what I'm talking about: The top row is a box selector containing a dummy grayscale in a scene with a bounding rect of (0, 0, 2pi, 4pi).  The green box is a QGraphicsRectItem drawn by the user from which I get the LL and UR points (in scene coordinates) after "Done" is clicked. The bottom row is a point layout with a user-clicked ellipse, on a small dummy image that has been zoomed in by 20.

The left and right were made with identical code. The version on the left is the result using PyQt4 under Anaconda 2.5 Python 3.5, whereas the result on the right is using PyQt5 under Anaconda 4.3 Python 3.6.

Clearly there is some sort of item transformation that is handled differently but I haven't been able to find it in any of the PyQt4->PyQt5 documentation (it's all about the API changes).

How do I go about making the line width of the QGraphicsItems be one in device coordinates while still maintaining the correct positions in scene coordinates?  More generally, how do I scale a general QGraphicsItem so that it doesn't blow up or get fat based on scene size?

The code is below. SimpleDialog is the primary base class I use for various picker utilities, and it includes MouseView and ImageScene which automatically build in a vertical flip and a background image. The two utilities I used here are BoxSelector and PointLayout.

# Imports
import numpy as np
try:
    from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot, QPointF
    from PyQt5.QtGui import QImage, QPixmap, QFont, QBrush, QPen, QTransform
    from PyQt5.QtWidgets import (QGraphicsView, QGraphicsScene, QDialog, QSizePolicy,
                                 QVBoxLayout, QPushButton, QMainWindow, QApplication)
except ImportError:
    from PyQt4.QtCore import Qt, pyqtSignal, pyqtSlot, QPointF
    from PyQt4.QtGui import (QImage, QPixmap, QFont, QBrush, QPen, QTransform,
                             QGraphicsView, QGraphicsScene, QDialog, QSizePolicy,
                             QVBoxLayout, QPushButton, QMainWindow, QApplication)

class MouseView(QGraphicsView):
    """A subclass of QGraphicsView that returns mouse click events."""

    mousedown = pyqtSignal(QPointF)
    mouseup = pyqtSignal(QPointF)
    mousemove = pyqtSignal(QPointF)

    def __init__(self, scene, parent=None):
        super(MouseView, self).__init__(scene, parent=parent)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setSizePolicy(QSizePolicy.Fixed,
                           QSizePolicy.Fixed)
        self.scale(1, -1)

        self.moving = False

    def mousePressEvent(self, event):
        """Emit a mouse click signal."""
        self.mousedown.emit(self.mapToScene(event.pos()))

    def mouseReleaseEvent(self, event):
        """Emit a mouse release signal."""
        self.mouseup.emit(self.mapToScene(event.pos()))

    def mouseMoveEvent(self, event):
        """Emit a mouse move signal."""
        if self.moving:
            self.mousemove.emit(self.mapToScene(event.pos()))

class ImageScene(QGraphicsScene):
    """A subclass of QGraphicsScene that includes a background pixmap."""

    def __init__(self, data, scene_rect, parent=None):
        super(ImageScene, self).__init__(parent=parent)

        bdata = ((data - np.min(data)) / (np.max(data) - np.min(data)) * 255).astype(np.uint8)
        wid, hgt = data.shape

        img = QImage(bdata.T.copy(), wid, hgt, wid, QImage.Format_Indexed8)

        self.setSceneRect(*scene_rect)

        px = QPixmap.fromImage(img)

        self.px = self.addPixmap(px)

        px_trans = QTransform.fromTranslate(scene_rect[0], scene_rect[1])
        px_trans = px_trans.scale(scene_rect[2]/wid, scene_rect[3]/hgt)
        self.px.setTransform(px_trans)

class SimpleDialog(QDialog):
    """A base class for utility dialogs using a background image in scene."""

    def __init__(self, data, bounds=None, grow=[1.0, 1.0], wsize=None, parent=None):
        super(SimpleDialog, self).__init__(parent=parent)

        self.grow = grow

        wid, hgt = data.shape
        if bounds is None:
            bounds = [0, 0, wid, hgt]

        if wsize is None:
            wsize = [wid, hgt]

        vscale = [grow[0]*wsize[0]/bounds[2], grow[1]*wsize[1]/bounds[3]]

        self.scene = ImageScene(data, bounds, parent=self)

        self.view = MouseView(self.scene, parent=self)
        self.view.scale(vscale[0], vscale[1])

        quitb = QPushButton("Done")
        quitb.clicked.connect(self.close)

        lay = QVBoxLayout()
        lay.addWidget(self.view)
        lay.addWidget(quitb)

        self.setLayout(lay)

    def close(self):
        self.accept()

class BoxSelector(SimpleDialog):
    """Simple box selector."""

    def __init__(self, *args, **kwargs):
        super(BoxSelector, self).__init__(*args, **kwargs)

        self.rpen = QPen(Qt.green)
        self.rect = self.scene.addRect(0, 0, 0, 0, pen=self.rpen)

        self.view.mousedown.connect(self.start_box)
        self.view.mouseup.connect(self.end_box)
        self.view.mousemove.connect(self.draw_box)

        self.start_point = []
        self.points = []

        self.setWindowTitle('Box Selector')

    @pyqtSlot(QPointF)
    def start_box(self, xy):
        self.start_point = [xy.x(), xy.y()]
        self.view.moving = True

    @pyqtSlot(QPointF)
    def end_box(self, xy):
        lx = np.minimum(xy.x(), self.start_point[0])
        ly = np.minimum(xy.y(), self.start_point[1])
        rx = np.maximum(xy.x(), self.start_point[0])
        ry = np.maximum(xy.y(), self.start_point[1])
        self.points = [[lx, ly], [rx, ry]]
        self.view.moving = False

    @pyqtSlot(QPointF)
    def draw_box(self, xy):
        newpoint = [xy.x(), xy.y()]
        minx = np.minimum(self.start_point[0], newpoint[0])
        miny = np.minimum(self.start_point[1], newpoint[1])
        size = [np.abs(i - j) for i, j in zip(self.start_point, newpoint)]
        self.rect.setRect(minx, miny, size[0], size[1])

class PointLayout(SimpleDialog):
    """Simple point display."""

    def __init__(self, *args, **kwargs):
        super(PointLayout, self).__init__(*args, **kwargs)

        self.pen = QPen(Qt.green)

        self.view.mousedown.connect(self.mouse_click)

        self.circles = []
        self.points = []

        self.setWindowTitle('Point Layout')

    @pyqtSlot(QPointF)
    def mouse_click(self, xy):
        self.points.append((xy.x(), xy.y()))
        pt = self.scene.addEllipse(xy.x()-0.5, xy.y()-0.5, 1, 1, pen=self.pen)
        self.circles.append(pt)
```

<p>And here is the code I used to do the tests:</p>

<pre class="lang-python prettyprint-override"><code>def test_box():

    x, y = np.mgrid[0:175, 0:100]
    img = x * y

    app = QApplication.instance()
    if app is None:
        app = QApplication(['python'])

    picker = BoxSelector(img, bounds=[0, 0, 2*np.pi, 4*np.pi])
    picker.show()
    app.exec_()

    return picker

def test_point():

    np.random.seed(159753)
    img = np.random.randn(10, 5)

    app = QApplication.instance()
    if app is None:
        app = QApplication(['python'])

    pointer = PointLayout(img, bounds=[0, 0, 10, 5], grow=[20, 20])
    pointer.show()

    app.exec_()

    return pointer

if __name__ == "__main__":
    pick = test_box()
    point = test_point()
</code>```

答:
I found that explicitly setting the pen width to zero restores the previous behaviour:

```<code>class BoxSelector(SimpleDialog):
    def __init__(self, *args, **kwargs):
        ...
        self.rpen = QPen(Qt.green)
        self.rpen.setWidth(0)
        ...

class PointLayout(SimpleDialog):
    def __init__(self, *args, **kwargs):
        ...
        self.pen = QPen(Qt.green)
        self.pen.setWidth(0)
        ...
</code>```

It seems that the default was 0 in Qt4, but it is 1 in Qt5.

From the Qt Docs for QPen.setWidth:

A line width of zero indicates a cosmetic pen. This means that the pen
  width is always drawn one pixel wide, independent of the
  transformation set on the painter.

Body:
I have some small utility GUIs that I have made with PyQt, which use a QGraphicsScene with some items in it, and a view that response to user clicks (for making boxes, selecting points, etc).

On the (offline) machine I use, the software was just upgraded from Anaconda 2.5 to Anaconda 4.3, including the switch from PyQt4 to PyQt5.  Everything still works, except somehow the transformations for my various QGraphicsItem objects are messed up if the scene rect is defined in anything but pixel coordinates.

Upfront question: What changed as far as item transformations from PyQt4 to PyQt5?

Here is an example of what I'm talking about: The top row is a box selector containing a dummy grayscale in a scene with a bounding rect of (0, 0, 2pi, 4pi).  The green box is a QGraphicsRectItem drawn by the user from which I get the LL and UR points (in scene coordinates) after "Done" is clicked. The bottom row is a point layout with a user-clicked ellipse, on a small dummy image that has been zoomed in by 20.

The left and right were made with identical code. The version on the left is the result using PyQt4 under Anaconda 2.5 Python 3.5, whereas the result on the right is using PyQt5 under Anaconda 4.3 Python 3.6.

Clearly there is some sort of item transformation that is handled differently but I haven't been able to find it in any of the PyQt4->PyQt5 documentation (it's all about the API changes).

How do I go about making the line width of the QGraphicsItems be one in device coordinates while still maintaining the correct positions in scene coordinates?  More generally, how do I scale a general QGraphicsItem so that it doesn't blow up or get fat based on scene size?

The code is below. SimpleDialog is the primary base class I use for various picker utilities, and it includes MouseView and ImageScene which automatically build in a vertical flip and a background image. The two utilities I used here are BoxSelector and PointLayout.

# Imports
import numpy as np
try:
    from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot, QPointF
    from PyQt5.QtGui import QImage, QPixmap, QFont, QBrush, QPen, QTransform
    from PyQt5.QtWidgets import (QGraphicsView, QGraphicsScene, QDialog, QSizePolicy,
                                 QVBoxLayout, QPushButton, QMainWindow, QApplication)
except ImportError:
    from PyQt4.QtCore import Qt, pyqtSignal, pyqtSlot, QPointF
    from PyQt4.QtGui import (QImage, QPixmap, QFont, QBrush, QPen, QTransform,
                             QGraphicsView, QGraphicsScene, QDialog, QSizePolicy,
                             QVBoxLayout, QPushButton, QMainWindow, QApplication)

class MouseView(QGraphicsView):
    """A subclass of QGraphicsView that returns mouse click events."""

    mousedown = pyqtSignal(QPointF)
    mouseup = pyqtSignal(QPointF)
    mousemove = pyqtSignal(QPointF)

    def __init__(self, scene, parent=None):
        super(MouseView, self).__init__(scene, parent=parent)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setSizePolicy(QSizePolicy.Fixed,
                           QSizePolicy.Fixed)
        self.scale(1, -1)

        self.moving = False

    def mousePressEvent(self, event):
        """Emit a mouse click signal."""
        self.mousedown.emit(self.mapToScene(event.pos()))

    def mouseReleaseEvent(self, event):
        """Emit a mouse release signal."""
        self.mouseup.emit(self.mapToScene(event.pos()))

    def mouseMoveEvent(self, event):
        """Emit a mouse move signal."""
        if self.moving:
            self.mousemove.emit(self.mapToScene(event.pos()))

class ImageScene(QGraphicsScene):
    """A subclass of QGraphicsScene that includes a background pixmap."""

    def __init__(self, data, scene_rect, parent=None):
        super(ImageScene, self).__init__(parent=parent)

        bdata = ((data - np.min(data)) / (np.max(data) - np.min(data)) * 255).astype(np.uint8)
        wid, hgt = data.shape

        img = QImage(bdata.T.copy(), wid, hgt, wid, QImage.Format_Indexed8)

        self.setSceneRect(*scene_rect)

        px = QPixmap.fromImage(img)

        self.px = self.addPixmap(px)

        px_trans = QTransform.fromTranslate(scene_rect[0], scene_rect[1])
        px_trans = px_trans.scale(scene_rect[2]/wid, scene_rect[3]/hgt)
        self.px.setTransform(px_trans)

class SimpleDialog(QDialog):
    """A base class for utility dialogs using a background image in scene."""

    def __init__(self, data, bounds=None, grow=[1.0, 1.0], wsize=None, parent=None):
        super(SimpleDialog, self).__init__(parent=parent)

        self.grow = grow

        wid, hgt = data.shape
        if bounds is None:
            bounds = [0, 0, wid, hgt]

        if wsize is None:
            wsize = [wid, hgt]

        vscale = [grow[0]*wsize[0]/bounds[2], grow[1]*wsize[1]/bounds[3]]

        self.scene = ImageScene(data, bounds, parent=self)

        self.view = MouseView(self.scene, parent=self)
        self.view.scale(vscale[0], vscale[1])

        quitb = QPushButton("Done")
        quitb.clicked.connect(self.close)

        lay = QVBoxLayout()
        lay.addWidget(self.view)
        lay.addWidget(quitb)

        self.setLayout(lay)

    def close(self):
        self.accept()

class BoxSelector(SimpleDialog):
    """Simple box selector."""

    def __init__(self, *args, **kwargs):
        super(BoxSelector, self).__init__(*args, **kwargs)

        self.rpen = QPen(Qt.green)
        self.rect = self.scene.addRect(0, 0, 0, 0, pen=self.rpen)

        self.view.mousedown.connect(self.start_box)
        self.view.mouseup.connect(self.end_box)
        self.view.mousemove.connect(self.draw_box)

        self.start_point = []
        self.points = []

        self.setWindowTitle('Box Selector')

    @pyqtSlot(QPointF)
    def start_box(self, xy):
        self.start_point = [xy.x(), xy.y()]
        self.view.moving = True

    @pyqtSlot(QPointF)
    def end_box(self, xy):
        lx = np.minimum(xy.x(), self.start_point[0])
        ly = np.minimum(xy.y(), self.start_point[1])
        rx = np.maximum(xy.x(), self.start_point[0])
        ry = np.maximum(xy.y(), self.start_point[1])
        self.points = [[lx, ly], [rx, ry]]
        self.view.moving = False

    @pyqtSlot(QPointF)
    def draw_box(self, xy):
        newpoint = [xy.x(), xy.y()]
        minx = np.minimum(self.start_point[0], newpoint[0])
        miny = np.minimum(self.start_point[1], newpoint[1])
        size = [np.abs(i - j) for i, j in zip(self.start_point, newpoint)]
        self.rect.setRect(minx, miny, size[0], size[1])

class PointLayout(SimpleDialog):
    """Simple point display."""

    def __init__(self, *args, **kwargs):
        super(PointLayout, self).__init__(*args, **kwargs)

        self.pen = QPen(Qt.green)

        self.view.mousedown.connect(self.mouse_click)

        self.circles = []
        self.points = []

        self.setWindowTitle('Point Layout')

    @pyqtSlot(QPointF)
    def mouse_click(self, xy):
        self.points.append((xy.x(), xy.y()))
        pt = self.scene.addEllipse(xy.x()-0.5, xy.y()-0.5, 1, 1, pen=self.pen)
        self.circles.append(pt)

And here is the code I used to do the tests:

def test_box():

    x, y = np.mgrid[0:175, 0:100]
    img = x * y

    app = QApplication.instance()
    if app is None:
        app = QApplication(['python'])

    picker = BoxSelector(img, bounds=[0, 0, 2*np.pi, 4*np.pi])
    picker.show()
    app.exec_()

    return picker

def test_point():

    np.random.seed(159753)
    img = np.random.randn(10, 5)

    app = QApplication.instance()
    if app is None:
        app = QApplication(['python'])

    pointer = PointLayout(img, bounds=[0, 0, 10, 5], grow=[20, 20])
    pointer.show()

    app.exec_()

    return pointer

if __name__ == "__main__":
    pick = test_box()
    point = test_point()

Body:
I found that explicitly setting the pen width to zero restores the previous behaviour:

class BoxSelector(SimpleDialog):
    def __init__(self, *args, **kwargs):
        ...
        self.rpen = QPen(Qt.green)
        self.rpen.setWidth(0)
        ...

class PointLayout(SimpleDialog):
    def __init__(self, *args, **kwargs):
        ...
        self.pen = QPen(Qt.green)
        self.pen.setWidth(0)
        ...

It seems that the default was 0 in Qt4, but it is 1 in Qt5.

From the Qt Docs for QPen.setWidth:

A line width of zero indicates a cosmetic pen. This means that the pen
  width is always drawn one pixel wide, independent of the
  transformation set on the painter.


问:
How do I decrypt data encrypted by Ruby's `symmetric-encryption` gem in another language?
I want to access data in a database created by Rails for use by non-Ruby code. Some fields use attr_encrypted accessors, and the library in use is the symmetric-encryption gem. I consistently get a "wrong final block length" error if I try to decrypt the data with, e.g., the NodeJS crypto library.

I suspect this has to do either with character encoding or with padding, but I can't figure it out based on the docs.

As an experiment, I tried decrypting data from symmetric-encryption in Ruby's own OpenSSL library, and I get either a "bad decrypt" error or the same problem:

```<code>SymmetricEncryption.cipher = SymmetricEncryption::Cipher.new(
  key: "1234567890ABCDEF",
  iv:  "1234567890ABCDEF",
  cipher_name: "aes-128-cbc"
)

ciphertext = SymmetricEncryption.encrypt("Hello world")

c = OpenSSL::Cipher.new("aes-128-cbc")
c.iv = c.key = "1234567890ABCDEF"
c.update(ciphertext) + c.final
</code>```

That gives me a "bad decrypt" error.

Interestingly, the encrypted data in the database can be decrypted by the symmetric-encryption gem, but isn't the same as the output of SymmetricEncryption.encrypt (and OpenSSL doesn't successfully decrypt it, either).

Edit:

```<code>psql=# SELECT "encrypted_firstName" FROM people LIMIT 1;
                   encrypted_firstName
----------------------------------------------------------
 QEVuQwBAEAAuR5vRj/iFbaEsXKtpjubrWgyEhK5Pji2EWPDPoT4CyQ==
(1 row)
</code>```

Then

```<code>irb> SymmetricEncryption.decrypt "QEVuQwBAEAAuR5vRj/iFbaEsXKtpjubrWgyEhK5Pji2EWPDPoT4CyQ=="
=> "Lurline"
irb> SymmetricEncryption.encrypt "Lurline"
=> "QEVuQwAAlRBeYptjK0Fg76jFQkjLtA=="
</code>```

答:
Looking at the source for the symmetric-encryption gem, by default it adds a header to the output and base64 encodes it, although both of these are configurable.

To decrypt using Ruby’s OpenSSL directly, you will need to decode it and strip off this header, which is 6 bytes long in this simple case:

```<code>ciphertext = Base64.decode64(ciphertext)
ciphertext = ciphertext[6..-1]

c = OpenSSL::Cipher.new("aes-128-cbc")
c.decrypt
c.iv = "1234567890ABCDEF"
c.key = "1234567890ABCDEF"

result = c.update(ciphertext) + c.final
</code>```

Of course, you may need to alter this depending on what settings you are using in symmetric-encryption, e.g. the header length may vary. In order to decrypt the result from the database you will need to parse the header. Have a look at the source.

Body:
I want to access data in a database created by Rails for use by non-Ruby code. Some fields use attr_encrypted accessors, and the library in use is the symmetric-encryption gem. I consistently get a "wrong final block length" error if I try to decrypt the data with, e.g., the NodeJS crypto library.

I suspect this has to do either with character encoding or with padding, but I can't figure it out based on the docs.

As an experiment, I tried decrypting data from symmetric-encryption in Ruby's own OpenSSL library, and I get either a "bad decrypt" error or the same problem:

SymmetricEncryption.cipher = SymmetricEncryption::Cipher.new(
  key: "1234567890ABCDEF",
  iv:  "1234567890ABCDEF",
  cipher_name: "aes-128-cbc"
)

ciphertext = SymmetricEncryption.encrypt("Hello world")

c = OpenSSL::Cipher.new("aes-128-cbc")
c.iv = c.key = "1234567890ABCDEF"
c.update(ciphertext) + c.final

That gives me a "bad decrypt" error.

Interestingly, the encrypted data in the database can be decrypted by the symmetric-encryption gem, but isn't the same as the output of SymmetricEncryption.encrypt (and OpenSSL doesn't successfully decrypt it, either).

Edit:

psql=# SELECT "encrypted_firstName" FROM people LIMIT 1;
                   encrypted_firstName
----------------------------------------------------------
 QEVuQwBAEAAuR5vRj/iFbaEsXKtpjubrWgyEhK5Pji2EWPDPoT4CyQ==
(1 row)

Then

irb> SymmetricEncryption.decrypt "QEVuQwBAEAAuR5vRj/iFbaEsXKtpjubrWgyEhK5Pji2EWPDPoT4CyQ=="
=> "Lurline"
irb> SymmetricEncryption.encrypt "Lurline"
=> "QEVuQwAAlRBeYptjK0Fg76jFQkjLtA=="

Body:
Looking at the source for the symmetric-encryption gem, by default it adds a header to the output and base64 encodes it, although both of these are configurable.

To decrypt using Ruby’s OpenSSL directly, you will need to decode it and strip off this header, which is 6 bytes long in this simple case:

ciphertext = Base64.decode64(ciphertext)
ciphertext = ciphertext[6..-1]

c = OpenSSL::Cipher.new("aes-128-cbc")
c.decrypt
c.iv = "1234567890ABCDEF"
c.key = "1234567890ABCDEF"

result = c.update(ciphertext) + c.final

Of course, you may need to alter this depending on what settings you are using in symmetric-encryption, e.g. the header length may vary. In order to decrypt the result from the database you will need to parse the header. Have a look at the source.


问:
How to set the color of a UIButton inside (not background color)
I'm tweaking some visual changes and noticed that when I try to set the background color of a UIButton it only sets the color outside the actual button (not inside the button itself)

```<code>UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(6, 9, 50, 25);
[button setTitle:@"Select" forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
</code>```

Does another property exist that would allow me to set the color?

答:
Use setImage:forState:

```<code>- (void)setImage:(UIImage *)image forState:(UIControlState)state
</code>```

Also, don't forget to create your button with [UIButton buttonWithType:UIButtonTypeCustom]

Body:
I'm tweaking some visual changes and noticed that when I try to set the background color of a UIButton it only sets the color outside the actual button (not inside the button itself)

UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(6, 9, 50, 25);
[button setTitle:@"Select" forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];

Does another property exist that would allow me to set the color?

Body:
Use setImage:forState:

- (void)setImage:(UIImage *)image forState:(UIControlState)state

Also, don't forget to create your button with [UIButton buttonWithType:UIButtonTypeCustom]


问:
Copy object data to heap location

I have the following code:

```<code>public class Entity
{
    public int Number;
    public string Text;
}

System.Collections.Generic.List<Entity> list = new List<Entity>();
list.Add(new Entity() { Number = 100, Text = "hello1" });
list.Add(new Entity() { Number = 200, Text = "hello2" });

Entity sampleEntity = new Entity() { Number = 300, Text = "World" };

list[0] = sampleEntity // this does only replace the pointer in the list

list[0].Text = sampleEntity.Text; // this writes to the pointer in list
list[0].Number = sampleEntity.Number; // this writes to the pointer in list
</code>```

What I would like to know if there is any possible way of performing a memcopy of the whole object data to the heap-location the list[0] entry points to? I mean in c++ it is a simple dereference *list[0] = *entity;

答:
Not unless Entity implements ICloneable (see Creating a copy of an object in C#).

I would personally just instantiate a new Entity.

list[0] = new Entity { Number = sampleEntity.Number, Text = sampleEntity.Text };

Title: Copy object data to heap location

Body:
I have the following code:

public class Entity
{
    public int Number;
    public string Text;
}

System.Collections.Generic.List<Entity> list = new List<Entity>();
list.Add(new Entity() { Number = 100, Text = "hello1" });
list.Add(new Entity() { Number = 200, Text = "hello2" });

Entity sampleEntity = new Entity() { Number = 300, Text = "World" };

list[0] = sampleEntity // this does only replace the pointer in the list

list[0].Text = sampleEntity.Text; // this writes to the pointer in list
list[0].Number = sampleEntity.Number; // this writes to the pointer in list

What I would like to know if there is any possible way of performing a memcopy of the whole object data to the heap-location the list[0] entry points to? I mean in c++ it is a simple dereference *list[0] = *entity;


问:
Simple Postgres queries running slow on Heroku
I have a Movie model with around 15,000 items and a Dvd model with 3500.

The following queries are simple Rails associations using a Crane Postgres db running on Heroku. I'm wondering why the following queries are taking so long, and how could I eventually reduce the time of it.

```<code>2012-10-24T05:42:19+00:00 app[postgres]: [30-1] [BLACK] LOG:  duration: 57.914 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 37 ORDER BY scene LIMIT 1
2012-10-24T05:42:20+00:00 app[postgres]: [31-1] [BLACK] LOG:  duration: 77.086 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 915 ORDER BY scene LIMIT 1
2012-10-24T05:42:20+00:00 app[postgres]: [32-1] [BLACK] LOG:  duration: 85.602 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 108 ORDER BY scene LIMIT 1
2012-10-24T05:42:21+00:00 app[postgres]: [33-1] [BLACK] LOG:  duration: 70.147 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 11 ORDER BY scene LIMIT 1
2012-10-24T05:42:21+00:00 app[postgres]: [34-1] [BLACK] LOG:  duration: 144.204 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 6 ORDER BY scene LIMIT 1
2012-10-24T05:42:22+00:00 app[postgres]: [35-1] [BLACK] LOG:  duration: 56.623 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 1956 ORDER BY scene LIMIT 1
2012-10-24T05:42:23+00:00 app[postgres]: [36-1] [BLACK] LOG:  duration: 64.860 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 747 ORDER BY scene LIMIT 1
</code>```

答:
```<code>duration: 57.914 ms
duration: 77.086 ms
duration: 85.602 ms
duration: 70.147 ms
duration: 144.204 ms
duration: 56.623 ms
duration: 64.860 ms
</code>```

On average (~80ms) this is the usual duration needed for queries operating over different continents. Make sure both your Heroku app and DB are hosted in the same region (EU or US).

Body:
I have a Movie model with around 15,000 items and a Dvd model with 3500.

The following queries are simple Rails associations using a Crane Postgres db running on Heroku. I'm wondering why the following queries are taking so long, and how could I eventually reduce the time of it.

2012-10-24T05:42:19+00:00 app[postgres]: [30-1] [BLACK] LOG:  duration: 57.914 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 37 ORDER BY scene LIMIT 1
2012-10-24T05:42:20+00:00 app[postgres]: [31-1] [BLACK] LOG:  duration: 77.086 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 915 ORDER BY scene LIMIT 1
2012-10-24T05:42:20+00:00 app[postgres]: [32-1] [BLACK] LOG:  duration: 85.602 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 108 ORDER BY scene LIMIT 1
2012-10-24T05:42:21+00:00 app[postgres]: [33-1] [BLACK] LOG:  duration: 70.147 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 11 ORDER BY scene LIMIT 1
2012-10-24T05:42:21+00:00 app[postgres]: [34-1] [BLACK] LOG:  duration: 144.204 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 6 ORDER BY scene LIMIT 1
2012-10-24T05:42:22+00:00 app[postgres]: [35-1] [BLACK] LOG:  duration: 56.623 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 1956 ORDER BY scene LIMIT 1
2012-10-24T05:42:23+00:00 app[postgres]: [36-1] [BLACK] LOG:  duration: 64.860 ms  statement: SELECT  "movies".* FROM "movies"  WHERE "movies"."dvd_id" = 747 ORDER BY scene LIMIT 1

Body:
duration: 57.914 ms
duration: 77.086 ms
duration: 85.602 ms
duration: 70.147 ms
duration: 144.204 ms
duration: 56.623 ms
duration: 64.860 ms

On average (~80ms) this is the usual duration needed for queries operating over different continents. Make sure both your Heroku app and DB are hosted in the same region (EU or US).


问:
What is the purpose of ungetc (or ungetch from K&R)?
Can anyone explain to me the purpose of ungetch?
This is from K&R chapter 4 where you create a Reverse Polish Calculator.

I've ran the program without the call to ungetch and in my tests it still works the same.

```<code> int getch(void) /* get a (possibly pushed back) character */
    {
        if (bufp > 0)
        {
            return buf[--bufp];
        }
        else
        {
            return getchar();
        }
    }

    void ungetch(int c) /* push character back on input */
    {
        if (bufp >= BUFSIZE)
        {
            printf("ungetch: too many characters\n");
        }
        else
        {
            buf[bufp++] = c;
        }

}
</code>```

(I've removed the ternary operator in getch to make it clearer.)

答: I don't know about the specific example you're referring to (It's probaby 23 years since I read K&R, and that was the first edition.), but often when parsing it's convenient to 'peek' at the next character to see if it is part of what you're currently parsing.  For instance, if you're reading a number you want to keep reading digits until you come to a non-digit.  Ungetc lets the number reader look at the next character without consuming it so that someone else can read it.  In Greg Hewgill's example of "2 3+", the number reader would read the 3 digit, then read the plus sign and know the number is finished, then ungetc the plus sign so that it can be read later.</p>

OwnerDisplayName: Tyler

Body:
Can anyone explain to me the purpose of ungetch?
This is from K&R chapter 4 where you create a Reverse Polish Calculator.

I've ran the program without the call to ungetch and in my tests it still works the same.

 int getch(void) /* get a (possibly pushed back) character */
    {
        if (bufp > 0)
        {
            return buf[--bufp];
        }
        else
        {
            return getchar();
        }
    }

    void ungetch(int c) /* push character back on input */
    {
        if (bufp >= BUFSIZE)
        {
            printf("ungetch: too many characters\n");
        }
        else
        {
            buf[bufp++] = c;
        }

}

(I've removed the ternary operator in getch to make it clearer.)

OwnerDisplayName: David Norman


问:
IB Designables: Failed to update auto layout status: Failed to load designables from path (null)
I'm seeing this error for a XIB. But everything else compiles and there doesn't seem to be any harm done by this error. Is this something I need to worry about? What's the problem here and how would I go about fixing this?

UPDATE:
I've updated cocoapods to the latest version (0.36.3) and while that fixed the problem for a few compiles, the error has returned and I'm now seeing an additional error:

答:
I had the same issue as I was using custom view from POD on storyboard.

Doing the following things fixed the issue for me

Add the following line (To turn the POD in dynamic framework) on pod
use_frameworks!

Do pod update

Restart the Xcode


问:
Running into: Unexpectedly found nil while unwrapping an Optional value, when I try to make it optional, I get another error
I get this error when trying to make farmTile optional: Value of optional type Bool? not unwrapped; did you mean to use '!' or '?'?

It was working fine an hour ago.

```<code>var farmTile:SKSpriteNode!

func createFarmTile(){

    farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    farmTile?.size = CGSize(width: 185, height: 195)
    farmTile?.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile!)
    farmTile?.name = "farmTile"
    farmTile.zPosition = 1

   if farmTile?.contains(touchLocation){
       print("test")
   }
}
</code>```

答:
The reason you are getting this error: Unexpectedly found nil while unwrapping an Optional value is because you have a nil for something that should not be nil.  In your case, your farmtile is nil, but you are using SKSpriteNode! which in lay mans terms means at the time of using this variable, it better not be nil.

The only point you set farmtile is on this line farmTile = SKSpriteNode(imageNamed: "farmtile.png"), which means you have an issue with your image file because SKSpriteNode is coming back nil.  I would recommend that you check to make sure you have your image file correctly set up within your assets, it is named correctly, and that it is getting bundled into your binary.  If I knew how you were setting up your assets, I could further assist here.

After you solve this problem, you have another problem ahead of you. (I assume this is going to be in a different function)

```<code>if farmTile?.contains(touchLocation){
    print("test")
}
</code>```

This is where you get your second error: optional: Value of optional type Bool? not unwrapped; did you mean to use '!' or '?'?

You are getting this error at compile time instead of run time because you added a ? to your farmTile thinking it will fix your problem, when it doesn't.

Now at this point you may as well correctly be handling your optionals.

You can use a guard statement to verify that the sprite is being created, and pass on a more meaningful message to yourself so that you know where the problem is in the future.

```<code>var farmTile:SKSpriteNode!

func createFarmTile(){

    guard let farmTile = SKSpriteNode(imageNamed: "farmtile.png") else { //insert your error handling here}
    farmTile.size = CGSize(width: 185, height: 195)
    farmTile.position = CGPoint(x: -95, y: 150)
    farmTile.name = "farmTile"
    farmTile.zPosition = 1
    self.farmTile = farmTile
    self.addChild(farmTile)
}
</code>```

At this point we designed it so that farmTile has to exist (Basically by ensuring 100% that the createFarmTile function got called), so there is no reason to add an additional unwrap, so take out the question mark.

```<code>//Inside the touch begins function
if farmTile.contains(touchLocation){
    print("test")
}
</code>```

Body:
I get this error when trying to make farmTile optional: Value of optional type Bool? not unwrapped; did you mean to use '!' or '?'?

It was working fine an hour ago.

var farmTile:SKSpriteNode!

func createFarmTile(){

    farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    farmTile?.size = CGSize(width: 185, height: 195)
    farmTile?.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile!)
    farmTile?.name = "farmTile"
    farmTile.zPosition = 1

   if farmTile?.contains(touchLocation){
       print("test")
   }
}

Body:
The reason you are getting this error: Unexpectedly found nil while unwrapping an Optional value is because you have a nil for something that should not be nil.  In your case, your farmtile is nil, but you are using SKSpriteNode! which in lay mans terms means at the time of using this variable, it better not be nil.

The only point you set farmtile is on this line farmTile = SKSpriteNode(imageNamed: "farmtile.png"), which means you have an issue with your image file because SKSpriteNode is coming back nil.  I would recommend that you check to make sure you have your image file correctly set up within your assets, it is named correctly, and that it is getting bundled into your binary.  If I knew how you were setting up your assets, I could further assist here.

After you solve this problem, you have another problem ahead of you. (I assume this is going to be in a different function)

if farmTile?.contains(touchLocation){
    print("test")
}

This is where you get your second error: optional: Value of optional type Bool? not unwrapped; did you mean to use '!' or '?'?

You are getting this error at compile time instead of run time because you added a ? to your farmTile thinking it will fix your problem, when it doesn't.

Now at this point you may as well correctly be handling your optionals.

You can use a guard statement to verify that the sprite is being created, and pass on a more meaningful message to yourself so that you know where the problem is in the future.

var farmTile:SKSpriteNode!

func createFarmTile(){

    guard let farmTile = SKSpriteNode(imageNamed: "farmtile.png") else { //insert your error handling here}
    farmTile.size = CGSize(width: 185, height: 195)
    farmTile.position = CGPoint(x: -95, y: 150)
    farmTile.name = "farmTile"
    farmTile.zPosition = 1
    self.farmTile = farmTile
    self.addChild(farmTile)
}

At this point we designed it so that farmTile has to exist (Basically by ensuring 100% that the createFarmTile function got called), so there is no reason to add an additional unwrap, so take out the question mark.

//Inside the touch begins function
if farmTile.contains(touchLocation){
    print("test")
}


问:
Setting up root controller
I copied routes from Silverstripe 4 alpha 6 to 4.0 project, and root controller stopped working. All I've got is that "Welcome to SilverStripe" page, no matter what I type in routes. I use framework only, downloaded zip file.

If I try to add route other than '' (empty one), and other than that noted in root/core routes, it works, but it seems that I cannot override those that are in. Tried with before/after in routes.yml also.

I even tried copying whole routes file from documentation, but no luck. Tried with namespaced controller and plain PHP class. Again, nothing happened.

Any ideas?

答:
Found out solution - in related question for aliasing Security/login.

All I need to do is to set routes to be after everything:

```<code>After: '*'
</code>```

Title: Setting up root controller

Body:
Found out solution - in related question for aliasing Security/login.

All I need to do is to set routes to be after everything:

After: '*'


问:
Nested forms in JHipster
I am new to the JHipster stack (and Spring in general) and I want to create an app in which the "children" of OneToMany and ManyToOne relationships are created/edited in the same form (from the users perspective) as their parent.

It's a common pattern that we all are familiar with. Imagine a Person having multiple Addresses or an Invoice having multiple Items and the parent and child are so tightly coupled in the domain that it only makes sense to create them together.

```<code>entity Invoice
entity InvoiceItem

relationship ManyToOne {
    InvoiceItem{invoice} to Invoice
}
</code>```

With JHipster 4.11.1 using Angular(4) and a Postgres or MySQL database, what steps do I need to take to solve this in the best possible way?

I can imagine doing this with client-side code only by simply posting to the auto-generated endpoints like /invoice /invoice-items, but it seems to me that it would put too much business logic scripting on the client side.

Should I nest specific child endpoints on my InvoiceResource or make the existing create and update endpoints accept related data somehow?

答:
I would do it server-side by defining a DTO manually that combines parent and children, keep the same endpoint for parent and manage the relationship in service, delete the the child endpoint.
This is an aggregate in DDD.</p>

Title: Nested forms in JHipster

Body:
I am new to the JHipster stack (and Spring in general) and I want to create an app in which the "children" of OneToMany and ManyToOne relationships are created/edited in the same form (from the users perspective) as their parent.

It's a common pattern that we all are familiar with. Imagine a Person having multiple Addresses or an Invoice having multiple Items and the parent and child are so tightly coupled in the domain that it only makes sense to create them together.

entity Invoice
entity InvoiceItem

relationship ManyToOne {
    InvoiceItem{invoice} to Invoice
}

With JHipster 4.11.1 using Angular(4) and a Postgres or MySQL database, what steps do I need to take to solve this in the best possible way?

I can imagine doing this with client-side code only by simply posting to the auto-generated endpoints like /invoice /invoice-items, but it seems to me that it would put too much business logic scripting on the client side.

Should I nest specific child endpoints on my InvoiceResource or make the existing create and update endpoints accept related data somehow?


问:
Property for subclass UICollectionViewCell
Here is my class

```<code>class myCell: UICollectionViewCell {

     public var myProp:String = ""

     let myControl:UILabel = {

           let label = UILabel()
           label.translatesAutoresizingMaskIntoConstraints = false
           label.Text = myProp

        return label
    }()

}
</code>```

I want to use the myProp within the creation of my UI elements but the compiler is saying I cannot use myProp.

or why is this incorrect

```<code>class myCell: UICollectionViewCell {

     public var myLabel:UILabel = UILabel()

     let myControl:UIView = {
            let ui = UIView()

            myLabel = {

              let lbl = UILabel()

              lbl.translatesAutoresizingMaskIntoConstraints = false

              return lbl
            }()

               ui.AddSubView(myLabel)

            return ui
        }()

    }
</code>```

答:
This will work

```<code>class CollectionViewCell: UICollectionViewCell {
     public var myProp:String = ""

     override init(frame: CGRect) {
        super.init(frame: frame)

    }

     func setText() {
        let myControl:UILabel = {
            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.text = myProp

            return label
        }()
        self.addSubview(myControl)
    }
}
</code>```

During rendering, in cellForRowAtIndex need to implement this for adding subview with text.

```<code> override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
    cell.myProp = "text"
    cell.setText()

    return cell
}
</code>```

Body:
Here is my class

class myCell: UICollectionViewCell {

     public var myProp:String = ""

     let myControl:UILabel = {

           let label = UILabel()
           label.translatesAutoresizingMaskIntoConstraints = false
           label.Text = myProp

        return label
    }()

}

I want to use the myProp within the creation of my UI elements but the compiler is saying I cannot use myProp.

or why is this incorrect

class myCell: UICollectionViewCell {

     public var myLabel:UILabel = UILabel()

     let myControl:UIView = {
            let ui = UIView()

            myLabel = {

              let lbl = UILabel()

              lbl.translatesAutoresizingMaskIntoConstraints = false

              return lbl
            }()

               ui.AddSubView(myLabel)

            return ui
        }()

    }

Body:
This will work

class CollectionViewCell: UICollectionViewCell {
     public var myProp:String = ""

     override init(frame: CGRect) {
        super.init(frame: frame)

    }

     func setText() {
        let myControl:UILabel = {
            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.text = myProp

            return label
        }()
        self.addSubview(myControl)
    }
}

During rendering, in cellForRowAtIndex need to implement this for adding subview with text.

 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
    cell.myProp = "text"
    cell.setText()

    return cell
}


问:
Simulate a general positive lookbehind for VBA regex
There are a plethora of questions about lookbehinds in VBA. The problem is that, while there are positive and negative lookaheads, VBA doesn't support lookbehinds at all.

Most of the questions people have asked seek to solve a very specific problem of extracting strings from text and the Stack Overflow community has been very helpful in providing workarounds for these particular cases. My question is, could you write a function in VB that simulates positive lookbehind by accepting Regex patterns as arguments and doing some kind of find-replace in the resulting string to only return the desired match group while omitting a (required but not captured) prefix?

答:
The following function accepts three arguments in order to satisfy this problem: a string to be matched, the regex pattern of a non-capturable prefix, and the regex pattern of the subsequent capture group.

```<code>Function LookBehindRegex(ByVal inputText As String, nonCaptureRegex As String, _
   captureRegex As String)

    'Non capturing lookbehind to retrieve reference preceded by a regex group

    Dim regEx As New RegExp
    Dim intermediate As String
    Dim nonCaptureText As String

    regEx.IgnoreCase = True
    'First set the capture pattern to both regex groups, to capture the whole text
    regEx.Pattern = "(" & nonCaptureRegex & ")" & "(" & captureRegex & ")"
    'Store that
    intermediate = regEx.Execute(inputText)(0)
    'Next, set the pattern to only capture the non-capture regex
    regEx.Pattern = nonCaptureRegex
    'Store the non-capturable text from the intermediate result
    nonCaptureText = regEx.Execute(intermediate)(0)
    'Finally remove the non-capture text from the intermediate result
    LookBehindRegex = Replace(intermediate, nonCaptureText, "")

End Function
</code>```

Limitations: This will only simulate positive lookbehind. The relevant Regular Expressions module must be added as a reference to the VB project.

Body:
The following function accepts three arguments in order to satisfy this problem: a string to be matched, the regex pattern of a non-capturable prefix, and the regex pattern of the subsequent capture group.

Function LookBehindRegex(ByVal inputText As String, nonCaptureRegex As String, _
   captureRegex As String)

    'Non capturing lookbehind to retrieve reference preceded by a regex group

    Dim regEx As New RegExp
    Dim intermediate As String
    Dim nonCaptureText As String

    regEx.IgnoreCase = True
    'First set the capture pattern to both regex groups, to capture the whole text
    regEx.Pattern = "(" & nonCaptureRegex & ")" & "(" & captureRegex & ")"
    'Store that
    intermediate = regEx.Execute(inputText)(0)
    'Next, set the pattern to only capture the non-capture regex
    regEx.Pattern = nonCaptureRegex
    'Store the non-capturable text from the intermediate result
    nonCaptureText = regEx.Execute(intermediate)(0)
    'Finally remove the non-capture text from the intermediate result
    LookBehindRegex = Replace(intermediate, nonCaptureText, "")

End Function

Limitations: This will only simulate positive lookbehind. The relevant Regular Expressions module must be added as a reference to the VB project.

ContentLicense: CC BY-SA 4.0