问:
Is this a good/preferable pattern to Azure Queue construction for a T4 template?
I'm building a T4 template that will help people construct Azure queues in a consistent and simple manner.  I'd like to make this self-documenting, and somewhat consistent.

First I made the queue name at the top of the file, the queue names have to be in lowercase so I added ToLower()

The public constructor uses the built-in StorageClient API's to access the connection strings.  I've seen many different approaches to this, and would like to get something that works in almost all situations.  (ideas? do share)

I dislike the unneeded HTTP requests to check if the queues have been created so I made is a static bool .  I didn't implement a Lock(monitorObject) since I don't think one is needed.

Instead of using a string and parsing it with commas (like most MSDN documentation) I'm serializing the object when passing it into the queue.

For further optimization I'm using a JSON serializer extension method to get the most out of the 8k limit.  Not sure if an encoding will help optimize this any more

Added retry logic to handle certain scenarios that occur with the queue (see html link)

Q: Is "DataContext" appropriate name for this class?

Q: Is it a poor practice to name the Queue Action Name in the manner I have done?

What additional changes do you think I should make?

```<code>public class AgentQueueDataContext
{
    // Queue names must always be in lowercase
    // Is named like a const, but isn't one because .ToLower won't compile...
    static string AGENT_QUEUE_ACTION_NAME = "AgentQueueActions".ToLower();

  static bool QueuesWereCreated { get; set; }

    DataModel.SecretDataSource secDataSource = null;

    CloudStorageAccount cloudStorageAccount = null;
    CloudQueueClient cloudQueueClient = null;
    CloudQueue queueAgentQueueActions = null;

    static AgentQueueDataContext()
    {
        QueuesWereCreated = false;
    }

    public AgentQueueDataContext() : this(false)
    {
    }
    public AgentQueueDataContext(bool CreateQueues)
    {
        // This pattern of setting up queues is from:
        // ttp://convective.wordpress.com/2009/11/15/queues-azure-storage-client-v1-0/
        //
        this.cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        this.cloudQueueClient = cloudStorageAccount.CreateCloudQueueClient();
        this.secDataSource = new DataModel.SecretDataSource();

        queueAgentQueueActions = cloudQueueClient.GetQueueReference(AGENT_QUEUE_ACTION_NAME);

        if (QueuesWereCreated == false || CreateQueues)
        {
            queueAgentQueueActions.CreateIfNotExist();
            QueuesWereCreated = true;
        }
    }

  // This is the method that will be spawned using ThreadStart
   public void CheckQueue()
    {
        while (true)
        {
            try
            {
                CloudQueueMessage msg = queueAgentQueueActions.GetMessage();

                bool DoRetryDelayLogic = false;

                if (msg != null)
                {
                    // Deserialize using JSON (allows more data to be stored)
                    AgentQueueEntry actionableMessage = msg.AsString.FromJSONString<AgentQueueEntry>();

                    switch (actionableMessage.ActionType)
                    {
                        case AgentQueueActionEnum.EnrollNew:
                            {
                                // Add to
                                break;
                            }
                        case AgentQueueActionEnum.LinkToSite:
                            {
                                // Link within Agent itself

                                // Link within Site

                                break;
                            }
                        case AgentQueueActionEnum.DisableKey:
                            {
                                // Disable key in site

                                // Disable key in AgentTable (update modification time)

                                break;
                            }
                        default:
                            {
                                break;
                            }
                    }

                    //
                    // Only delete the message if the requested agent has been missing for
                    // at least 10 minutes
                    //
                    if (DoRetryDelayLogic)
                    {
                        if (msg.InsertionTime != null)
                            if (msg.InsertionTime < DateTime.UtcNow + new TimeSpan(0, 10, 10))
                                continue;

                        // ToDo: Log error: AgentID xxx has not been found in table for xxx minutes.
                        //                  It is likely the result of a the registratoin host crashing.
                        //                  Data is still consistent.  Deleting queued message.
                    }

                    //
                    // If execution made it to this point, then we are either fully processed, or
                    // there is sufficent reason to discard the message.
                    //
                    try
                    {
                        queueAgentQueueActions.DeleteMessage(msg);
                    }
                    catch (StorageClientException ex)
                    {
                        // As of July 2010, this is the best way to detect this class of exception
                        // Description: ttp://blog.smarx.com/posts/deleting-windows-azure-queue-messages-handling-exceptions
                        if (ex.ExtendedErrorInformation.ErrorCode == "MessageNotFound")
                        {
                            // pop receipt must be invalid
                            // ignore or log (so we can tune the visibility timeout)
                        }
                        else
                        {
                            // not the error we were expecting
                            throw;
                        }
                    }
                }
                else
                {
                   // allow control to fall to the bottom, where the sleep timer is...
                }
            }
            catch (Exception e)
            {
                // Justification: Thread must not fail.
                //Todo: Log this exception

                // allow control to fall to the bottom, where the sleep timer is...
                // Rationale: not doing so may cause queue thrashing on a specific corrupt entry
            }

            // todo: Thread.Sleep() is bad
            //       Replace with something better...
            Thread.Sleep(9000);
        }
</code>```

答:
Q: Is "DataContext" appropriate name for this class?

In .NET we have a lot of DataContext classes, so in the sense that you want names to appropriately communicate what the class does, I think XyzQueueDataContext properly communicates what the class does - although you can't query from it.

If you want to stay more aligned to accepted pattern languages, Patterns of Enterprise Application Architecture calls any class that encapsulates access to an external system for a Gateway, while more specifically you may want to use the term Channel in the language of Enterprise Integration Patterns - that's what I would do.

Q: Is it a poor practice to name the Queue Action Name in the manner I have done?

Well, it certainly tightly couples the queue name to the class. This means that if you later decide that you want to decouple those, you can't.

As a general comment I think this class might benefit from trying to do less. Using the queue is not the same thing as managing it, so instead of having all of that queue management code there, I'd suggest injecting a CloudQueue into the instance. Here's how I implement my AzureChannel constructor:

```<code>private readonly CloudQueue queue;

public AzureChannel(CloudQueue queue)
{
    if (queue == null)
    {
        throw new ArgumentNullException("queue");
    }

    this.queue = queue;
}
</code>```

This better fits the Single Responsibility Principle and you can now implement queue management in its own (reusable) class.

Body:
I'm building a T4 template that will help people construct Azure queues in a consistent and simple manner.  I'd like to make this self-documenting, and somewhat consistent.

First I made the queue name at the top of the file, the queue names have to be in lowercase so I added ToLower()

The public constructor uses the built-in StorageClient API's to access the connection strings.  I've seen many different approaches to this, and would like to get something that works in almost all situations.  (ideas? do share)

I dislike the unneeded HTTP requests to check if the queues have been created so I made is a static bool .  I didn't implement a Lock(monitorObject) since I don't think one is needed.

Instead of using a string and parsing it with commas (like most MSDN documentation) I'm serializing the object when passing it into the queue.

For further optimization I'm using a JSON serializer extension method to get the most out of the 8k limit.  Not sure if an encoding will help optimize this any more

Added retry logic to handle certain scenarios that occur with the queue (see html link)

Q: Is "DataContext" appropriate name for this class?

Q: Is it a poor practice to name the Queue Action Name in the manner I have done?

What additional changes do you think I should make?

public class AgentQueueDataContext
{
    // Queue names must always be in lowercase
    // Is named like a const, but isn't one because .ToLower won't compile...
    static string AGENT_QUEUE_ACTION_NAME = "AgentQueueActions".ToLower();

  static bool QueuesWereCreated { get; set; }

    DataModel.SecretDataSource secDataSource = null;

    CloudStorageAccount cloudStorageAccount = null;
    CloudQueueClient cloudQueueClient = null;
    CloudQueue queueAgentQueueActions = null;

    static AgentQueueDataContext()
    {
        QueuesWereCreated = false;
    }

    public AgentQueueDataContext() : this(false)
    {
    }
    public AgentQueueDataContext(bool CreateQueues)
    {
        // This pattern of setting up queues is from:
        // ttp://convective.wordpress.com/2009/11/15/queues-azure-storage-client-v1-0/
        //
        this.cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        this.cloudQueueClient = cloudStorageAccount.CreateCloudQueueClient();
        this.secDataSource = new DataModel.SecretDataSource();

        queueAgentQueueActions = cloudQueueClient.GetQueueReference(AGENT_QUEUE_ACTION_NAME);

        if (QueuesWereCreated == false || CreateQueues)
        {
            queueAgentQueueActions.CreateIfNotExist();
            QueuesWereCreated = true;
        }
    }

  // This is the method that will be spawned using ThreadStart
   public void CheckQueue()
    {
        while (true)
        {
            try
            {
                CloudQueueMessage msg = queueAgentQueueActions.GetMessage();

                bool DoRetryDelayLogic = false;

                if (msg != null)
                {
                    // Deserialize using JSON (allows more data to be stored)
                    AgentQueueEntry actionableMessage = msg.AsString.FromJSONString<AgentQueueEntry>();

                    switch (actionableMessage.ActionType)
                    {
                        case AgentQueueActionEnum.EnrollNew:
                            {
                                // Add to
                                break;
                            }
                        case AgentQueueActionEnum.LinkToSite:
                            {
                                // Link within Agent itself

                                // Link within Site

                                break;
                            }
                        case AgentQueueActionEnum.DisableKey:
                            {
                                // Disable key in site

                                // Disable key in AgentTable (update modification time)

                                break;
                            }
                        default:
                            {
                                break;
                            }
                    }

                    //
                    // Only delete the message if the requested agent has been missing for
                    // at least 10 minutes
                    //
                    if (DoRetryDelayLogic)
                    {
                        if (msg.InsertionTime != null)
                            if (msg.InsertionTime < DateTime.UtcNow + new TimeSpan(0, 10, 10))
                                continue;

                        // ToDo: Log error: AgentID xxx has not been found in table for xxx minutes.
                        //                  It is likely the result of a the registratoin host crashing.
                        //                  Data is still consistent.  Deleting queued message.
                    }

                    //
                    // If execution made it to this point, then we are either fully processed, or
                    // there is sufficent reason to discard the message.
                    //
                    try
                    {
                        queueAgentQueueActions.DeleteMessage(msg);
                    }
                    catch (StorageClientException ex)
                    {
                        // As of July 2010, this is the best way to detect this class of exception
                        // Description: ttp://blog.smarx.com/posts/deleting-windows-azure-queue-messages-handling-exceptions
                        if (ex.ExtendedErrorInformation.ErrorCode == "MessageNotFound")
                        {
                            // pop receipt must be invalid
                            // ignore or log (so we can tune the visibility timeout)
                        }
                        else
                        {
                            // not the error we were expecting
                            throw;
                        }
                    }
                }
                else
                {
                   // allow control to fall to the bottom, where the sleep timer is...
                }
            }
            catch (Exception e)
            {
                // Justification: Thread must not fail.
                //Todo: Log this exception

                // allow control to fall to the bottom, where the sleep timer is...
                // Rationale: not doing so may cause queue thrashing on a specific corrupt entry
            }

            // todo: Thread.Sleep() is bad
            //       Replace with something better...
            Thread.Sleep(9000);
        }

Body:
Q: Is "DataContext" appropriate name for this class?

In .NET we have a lot of DataContext classes, so in the sense that you want names to appropriately communicate what the class does, I think XyzQueueDataContext properly communicates what the class does - although you can't query from it.

If you want to stay more aligned to accepted pattern languages, Patterns of Enterprise Application Architecture calls any class that encapsulates access to an external system for a Gateway, while more specifically you may want to use the term Channel in the language of Enterprise Integration Patterns - that's what I would do.

Q: Is it a poor practice to name the Queue Action Name in the manner I have done?

Well, it certainly tightly couples the queue name to the class. This means that if you later decide that you want to decouple those, you can't.

As a general comment I think this class might benefit from trying to do less. Using the queue is not the same thing as managing it, so instead of having all of that queue management code there, I'd suggest injecting a CloudQueue into the instance. Here's how I implement my AzureChannel constructor:

private readonly CloudQueue queue;

public AzureChannel(CloudQueue queue)
{
    if (queue == null)
    {
        throw new ArgumentNullException("queue");
    }

    this.queue = queue;
}

This better fits the Single Responsibility Principle and you can now implement queue management in its own (reusable) class.


来源: stackexchange

问:
Undefined symbols for architecture arm64: "_OBJC_CLASS_$_RadioUIButton"
I am trying to create a custom UIButton. Here is my .h class:

```<code>@interface RadioUIButton : UIButton

@property (strong) NSString* stringTag;

@end
</code>```

When I try to access the class from FeedbackViewController.m I get this error:

Undefined symbols for architecture arm64:

  "_OBJC_CLASS_$_RadioUIButton", referenced from:
        objc-class-ref in FeedbackViewController.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with
  exit code 1 (use -v to see invocation)

What I have tried so far:

Enable Bitcode: set to NO

Build Active Architecture only: set to NO

None of the above worked. What else can I try?

答: Check Compile Bundle resources this phase must contain RadioUIButton.m for compile it.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a custom UIButton. Here is my .h class:

@interface RadioUIButton : UIButton

@property (strong) NSString* stringTag;

@end

When I try to access the class from FeedbackViewController.m I get this error:

Undefined symbols for architecture arm64:

  "_OBJC_CLASS_$_RadioUIButton", referenced from:
        objc-class-ref in FeedbackViewController.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with
  exit code 1 (use -v to see invocation)

What I have tried so far:

Enable Bitcode: set to NO

Build Active Architecture only: set to NO

None of the above worked. What else can I try?


问:
How can I concisely modify a record's field?
```<code>data Person = Person
  {
    name :: String
  , counter :: Int
  }

incrementPersonCounter :: Person -> Person
incrementPersonCounter p@(Person _ c) = p { counter = c + 1 }
</code>```

Is there a more concise way of doing the above? Is there a function I could use, where I specify the record, one of its fields (name / counter in this case) and a function to apply to the return value?

I was thinking something along the lines of:

```<code>applyRecord r f f' = r
  { f = f' (f r) }
</code>```

Though this won't work because:

```<code>error: Not in scope: ‘f’
   |
13 |   { f = f' (f r) }
</code>```

答:
One way of generalizing incrementPersonCounter is to abstract over the modification function:

```<code>modifyPersonCounter :: (Int -> Int) -> Person -> Person
modifyPersonCounter f p = (\c -> p { counter = c}) $ f (counter p)
</code>```

In fact, a common pattern is to abstract as well over the effect we want to perform in the field:

```<code>counterLens :: forall f. Functor f => (Int -> f Int) -> (Person -> f Person)
counterLens f p = (\c -> p { counter = c }) <$> f (counter p)
</code>```

For example, we might want to read the counter increase from console, or from a database (both IO effects).

We can give a synonym to the type of functions that, given a (possibly effectful) way of changing a field, return a function that transforms the whole record:

```<code>type Lens' a b = forall f. Functor f => (b -> f b) -> (a -> f a)
</code>```

To modify a record purely, now we need an auxiliary function we can call over, which only needs to be defined once:

```<code>over :: Lens' a b -> (b -> b) -> a -> a
over l f p = runIdentity $ l (Identity . f) p
</code>```

For example:

```<code>*Main> over counterLens (+1) (Person "foo" 40)
Person {name = "foo", counter = 41}
</code>```

We have abstracted over the modification function and its possible effects, but we still need to define these "lenses" for each field, which is annoying. In practice, people use Template Haskell to define them automatically and avoid boilerplate.

But what if we wanted a single function that let us specify the name of the field? That is, sadly, more complex. You need a way to pass type-level strings as arguments, and a multi-parameter type class that encodes the relationship between a field's name, the type of the record, and the type of the field. There are some packages which do that (again, with Template Haskell help for the boilerplate) but to my knowledge they are not widely used.

The main library for lenses is called lens, and there is also microlens, an alternative with a lighter dependency footprint. They are interoperable: lenses defined using one library work with the other.

Body:
data Person = Person
  {
    name :: String
  , counter :: Int
  }

incrementPersonCounter :: Person -> Person
incrementPersonCounter p@(Person _ c) = p { counter = c + 1 }

Is there a more concise way of doing the above? Is there a function I could use, where I specify the record, one of its fields (name / counter in this case) and a function to apply to the return value?

I was thinking something along the lines of:

applyRecord r f f' = r
  { f = f' (f r) }

Though this won't work because:

error: Not in scope: ‘f’
   |
13 |   { f = f' (f r) }

Body:
One way of generalizing incrementPersonCounter is to abstract over the modification function:

modifyPersonCounter :: (Int -> Int) -> Person -> Person
modifyPersonCounter f p = (\c -> p { counter = c}) $ f (counter p)

In fact, a common pattern is to abstract as well over the effect we want to perform in the field:

counterLens :: forall f. Functor f => (Int -> f Int) -> (Person -> f Person)
counterLens f p = (\c -> p { counter = c }) <$> f (counter p)

For example, we might want to read the counter increase from console, or from a database (both IO effects).

We can give a synonym to the type of functions that, given a (possibly effectful) way of changing a field, return a function that transforms the whole record:

type Lens' a b = forall f. Functor f => (b -> f b) -> (a -> f a)

To modify a record purely, now we need an auxiliary function we can call over, which only needs to be defined once:

over :: Lens' a b -> (b -> b) -> a -> a
over l f p = runIdentity $ l (Identity . f) p

For example:

*Main> over counterLens (+1) (Person "foo" 40)
Person {name = "foo", counter = 41}

We have abstracted over the modification function and its possible effects, but we still need to define these "lenses" for each field, which is annoying. In practice, people use Template Haskell to define them automatically and avoid boilerplate.

But what if we wanted a single function that let us specify the name of the field? That is, sadly, more complex. You need a way to pass type-level strings as arguments, and a multi-parameter type class that encodes the relationship between a field's name, the type of the record, and the type of the field. There are some packages which do that (again, with Template Haskell help for the boilerplate) but to my knowledge they are not widely used.

The main library for lenses is called lens, and there is also microlens, an alternative with a lighter dependency footprint. They are interoperable: lenses defined using one library work with the other.


问:
What sort of time complexity would be required to solve the RSA Factoring Challenge?
Although the challenge ended a long time ago, I'm kinda bored so I decided to try to factorise some of the numbers.

I initially had an O(n) algorithm, but then, I decided to research big O notation.

Apparently (I could be wrong), O(n) algorithms and O(2n) algorithms basically have the same running time. So do O(n) and O(4n) algorithms. In fact, O(n) and O(cn) algorithms (where c is an integer) essentially have the same running time.

So now, I have an O(8n) algorithm, but it isn't quick enough for 77-bit numbers.

What sort of time complexity would be required to factorise the first few RSA numbers (in under 5-ish minutes)?

My O(8n) algorithm:

```<code>import math

num = int(input())

sq = math.sqrt(num)

if num % 2 == 0:
  print(2, int(num / 2))

elif sq % 1 == sq:
  print(int(sq), int(sq))

else:

  sq = round(sq)

  a = 3
  b = sq + (1 - (sq % 2))

  c = ((b + 1) / 2)
  d = ((b + 1) / 2)
  c -= (1 - (c % 2))
  d += (1 - (d % 2))

  e = ((c + 1) / 2)
  f = ((c + 1) / 2)
  e -= (1 - (e % 2))
  f += (1 - (f % 2))
  g = ((d + 1) / 2) + d
  h = ((d + 1) / 2) + d
  g -= (1 - (g % 2))
  h += (1 - (h % 2))

  while a <= sq and num % a != 0 and b > 2 and num % b != 0 and c <= sq and num % c != 0 and d > 2 and num % d != 0 and e <= sq and num % e != 0 and f > 2 and num % f != 0 and g <= sq and num % g != 0 and h > 2 and num % h != 0:

    a += 2
    b -= 2
    c += 2
    d -= 2
    e += 2
    f -= 2
    g += 2
    h -= 2

  if num % a == 0:
    print(a, int(num / a))
  elif num % b == 0:
    print(b, int(num / b))
  elif num % c == 0:
    print(c, int(num / c))
  elif num % d == 0:
    print(d, int(num / d))
  elif num % e == 0:
    print(e, int(num / e))
  elif num % f == 0:
    print(f, int(num / f))
  elif num % g == 0:
    print(g, int(num / g))
  elif num % h == 0:
    print(h, int(num / h))
</code>```

答:
Your algorithm is poorly-implemented trial division. Throw it away.

Here is my basic prime-number library, using the Sieve of Eratosthenes to enumerate prime numbers, the Miller-Rabin algorithm to recognize primes, and wheel factorization followed by Pollard's rho algorithm to factor composites, which I leave to you to translate to Python:

```<code>function primes(n)
    i, p, ps, m := 0, 3, [2], n // 2
    sieve := makeArray(0..m-1, True)
    while i < m
        if sieve[i]
            ps := p :: ps # insert at head of list
            for j from (p*p-3)/2 to m step p
                sieve[i] := False
        i, p := i+1, p+2
    return reverse(ps)

function isPrime(n, k=5)
    if n < 2 then return False
    for p in [2,3,5,7,11,13,17,19,23,29]
        if n % p == 0 then return n == p
    s, d = 0, n-1
    while d % 2 == 0
        s, d = s+1, d/2
    for i from 0 to k
        x = powerMod(randint(2, n-1), d, n)
        if x == 1 or x == n-1 then next i
        for r from 1 to s
            x = (x * x) % n
            if x == 1 then return False
            if x == n-1 then next i
        return False
    return True

function factors(n, limit=10000)
    wheel := [1,2,2,4,2,4,2,4,6,2,6]
    w, f, fs := 0, 2, []
    while f*f <= n and f < limit
        while n % f == 0
            fs, n := f :: fs, n / f
        f, w := f + wheel[w], w+1
        if w = 11 then w = 3
    if n == 1 return fs
    h, t, g, c := 1, 1, 1, 1
    while not isPrime(n)
        repeat
            h := (h*h+c) % n # the hare runs
            h := (h*h+c) % n # twice as fast
            t := (t*t+c) % n # as the tortoise
            g := gcd(t-h, n)
        while g == 1
        if isPrime(g)
            while n % g == 0
                fs, n := g :: fs, n / g
        h, t, g, c := 1, 1, 1, c+1
    return sort(n :: fs)

function powerMod(b, e, m)
    x := 1
    while e > 0
        if e%2 == 1
            x, e := (x*b)%m, e-1
        else b, e := (b*b)%m, e//2
    return x

function gcd(a, b)
    if b == 0 then return a
    return gcd(b, a % b)
</code>```

Properly implemented, that algorithm should factor your 79-bit number nearly instantly.

To factor larger numbers, you will have to work harder. Look up "elliptic curve factorization" and "self-initializing quadratic sieve" to find factoring algorithms that you can implement yourself.

Body:
Although the challenge ended a long time ago, I'm kinda bored so I decided to try to factorise some of the numbers.

I initially had an O(n) algorithm, but then, I decided to research big O notation.

Apparently (I could be wrong), O(n) algorithms and O(2n) algorithms basically have the same running time. So do O(n) and O(4n) algorithms. In fact, O(n) and O(cn) algorithms (where c is an integer) essentially have the same running time.

So now, I have an O(8n) algorithm, but it isn't quick enough for 77-bit numbers.

What sort of time complexity would be required to factorise the first few RSA numbers (in under 5-ish minutes)?

My O(8n) algorithm:

import math

num = int(input())

sq = math.sqrt(num)

if num % 2 == 0:
  print(2, int(num / 2))

elif sq % 1 == sq:
  print(int(sq), int(sq))

else:

  sq = round(sq)

  a = 3
  b = sq + (1 - (sq % 2))

  c = ((b + 1) / 2)
  d = ((b + 1) / 2)
  c -= (1 - (c % 2))
  d += (1 - (d % 2))

  e = ((c + 1) / 2)
  f = ((c + 1) / 2)
  e -= (1 - (e % 2))
  f += (1 - (f % 2))
  g = ((d + 1) / 2) + d
  h = ((d + 1) / 2) + d
  g -= (1 - (g % 2))
  h += (1 - (h % 2))

  while a <= sq and num % a != 0 and b > 2 and num % b != 0 and c <= sq and num % c != 0 and d > 2 and num % d != 0 and e <= sq and num % e != 0 and f > 2 and num % f != 0 and g <= sq and num % g != 0 and h > 2 and num % h != 0:

    a += 2
    b -= 2
    c += 2
    d -= 2
    e += 2
    f -= 2
    g += 2
    h -= 2

  if num % a == 0:
    print(a, int(num / a))
  elif num % b == 0:
    print(b, int(num / b))
  elif num % c == 0:
    print(c, int(num / c))
  elif num % d == 0:
    print(d, int(num / d))
  elif num % e == 0:
    print(e, int(num / e))
  elif num % f == 0:
    print(f, int(num / f))
  elif num % g == 0:
    print(g, int(num / g))
  elif num % h == 0:
    print(h, int(num / h))

Body:
Your algorithm is poorly-implemented trial division. Throw it away.

Here is my basic prime-number library, using the Sieve of Eratosthenes to enumerate prime numbers, the Miller-Rabin algorithm to recognize primes, and wheel factorization followed by Pollard's rho algorithm to factor composites, which I leave to you to translate to Python:

function primes(n)
    i, p, ps, m := 0, 3, [2], n // 2
    sieve := makeArray(0..m-1, True)
    while i < m
        if sieve[i]
            ps := p :: ps # insert at head of list
            for j from (p*p-3)/2 to m step p
                sieve[i] := False
        i, p := i+1, p+2
    return reverse(ps)

function isPrime(n, k=5)
    if n < 2 then return False
    for p in [2,3,5,7,11,13,17,19,23,29]
        if n % p == 0 then return n == p
    s, d = 0, n-1
    while d % 2 == 0
        s, d = s+1, d/2
    for i from 0 to k
        x = powerMod(randint(2, n-1), d, n)
        if x == 1 or x == n-1 then next i
        for r from 1 to s
            x = (x * x) % n
            if x == 1 then return False
            if x == n-1 then next i
        return False
    return True

function factors(n, limit=10000)
    wheel := [1,2,2,4,2,4,2,4,6,2,6]
    w, f, fs := 0, 2, []
    while f*f <= n and f < limit
        while n % f == 0
            fs, n := f :: fs, n / f
        f, w := f + wheel[w], w+1
        if w = 11 then w = 3
    if n == 1 return fs
    h, t, g, c := 1, 1, 1, 1
    while not isPrime(n)
        repeat
            h := (h*h+c) % n # the hare runs
            h := (h*h+c) % n # twice as fast
            t := (t*t+c) % n # as the tortoise
            g := gcd(t-h, n)
        while g == 1
        if isPrime(g)
            while n % g == 0
                fs, n := g :: fs, n / g
        h, t, g, c := 1, 1, 1, c+1
    return sort(n :: fs)

function powerMod(b, e, m)
    x := 1
    while e > 0
        if e%2 == 1
            x, e := (x*b)%m, e-1
        else b, e := (b*b)%m, e//2
    return x

function gcd(a, b)
    if b == 0 then return a
    return gcd(b, a % b)

Properly implemented, that algorithm should factor your 79-bit number nearly instantly.

To factor larger numbers, you will have to work harder. Look up "elliptic curve factorization" and "self-initializing quadratic sieve" to find factoring algorithms that you can implement yourself.


问:
Generation of pdf file using java
I am developing a standalone application in Java. I want to generate a pdf file using Java code. I have a display form in which all the details are fetched from database and displayed in the window. Details are Customer Name, Order Details etc.

Now I want to have a button there which says Convert to pdf.
I want to convert this to pdf file with proper alignment and formatting like tables, font etc.

What can be an ideal way to go about it?

答:
I'd suggest you to use reporting tool like a jasperreports.

JasperReports is entirely written in
  Java and it is able to use data coming
  from any kind of data source and
  produce pixel-perfect documents that
  can be viewed, printed or exported in
  a variety of document formats
  including HTML, PDF, Excel, OpenOffice
  and Word.

Have a look at other open source projects (pdf api):

Apache PDFBox

Apache Tika (Toolkit for detecting and extracting metadata and structured text content from various documents using POI and PDFBOX parser libs.)

PDFjet

Title: Generation of pdf file using java

ContentLicense: CC BY-SA 2.5


问:
Ruby coinflip simulation (head or number)
Hey guys i need to do a program that simulates a coinflip and give out head or number.I did that

```<code>a = rand(1..2)
if a == 1 then
  puts "HEAD!"
else
  puts "NUMBER!"
end

enter = gets
if enter == "\n"
  a = rand(1..2)
  if a == 1 then
    puts "HEAD!"
  else
    puts "NUMBER!"
  end
end
</code>```

but how can i include everytime you press enter it should continue and continue simulating coinflip like ... HEAD (enter) HEAD (enter) NUMBER (enter) and so on.

答:
You need some kind of loop, not just an if. Here's a short way to do it:

```<code>loop do
  puts ['HEAD', 'NUMBER'].sample
  break if gets != "\n"
end
</code>```

Or if you're ok with stopping by pressing CTRL-C:

```<code>loop do
  puts ['HEAD', 'NUMBER'].sample
  gets
end
</code>```

Using a post-loop test (i.e., do the gets and possibly break after printing the flip result) is more appropriate here, as it avoids the code duplication. Also see this popular Ruby style guide:

https://github.com/bbatsov/ruby-style-guide#loop-with-break

https://github.com/bbatsov/ruby-style-guide#infinite-loop

Body:
Hey guys i need to do a program that simulates a coinflip and give out head or number.I did that

a = rand(1..2)
if a == 1 then
  puts "HEAD!"
else
  puts "NUMBER!"
end

enter = gets
if enter == "\n"
  a = rand(1..2)
  if a == 1 then
    puts "HEAD!"
  else
    puts "NUMBER!"
  end
end

but how can i include everytime you press enter it should continue and continue simulating coinflip like ... HEAD (enter) HEAD (enter) NUMBER (enter) and so on.

Body:
You need some kind of loop, not just an if. Here's a short way to do it:

loop do
  puts ['HEAD', 'NUMBER'].sample
  break if gets != "\n"
end

Or if you're ok with stopping by pressing CTRL-C:

loop do
  puts ['HEAD', 'NUMBER'].sample
  gets
end

Using a post-loop test (i.e., do the gets and possibly break after printing the flip result) is more appropriate here, as it avoids the code duplication. Also see this popular Ruby style guide:

https://github.com/bbatsov/ruby-style-guide#loop-with-break

https://github.com/bbatsov/ruby-style-guide#infinite-loop


问:
In XSD, when optional parent element occurs, are its children mandatory?
I have been wondering about a simple but very important question.

I have a parent element that is optional because of minOccurs="0" but its child elements do not have any minOccurs or maxOccures attributes defined.

Am I right that in case the parent element occurs, all its child elements are mandatory?

My example code looks like this:

```<code>name="FiscalRepresentativeInfo" minOccurs="0">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="FiscalRepresentativeTaxRegistrations" type="MandatoryTaxNumbersType"></xs:element>
            <xs:element name="FiscalRepresentativeName" type="LongStringType"></xs:element>
            <xs:element name="FiscalRepresentativeAddress" type="AddressType"></xs:element>
            <xs:element name="FiscalRepresentativeBankAccountNumber" type="BankAccountNumberType"></xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</code>```

Now, my question in practical terms is this:

The fiscal representative info is optional, the XML instance may or may not contain it.

Here comes the point: in case there is a fiscal representative info in the XML, it MUST have all 4 elements. For example, it is not possible to miss the bank account number.

Please let me know whether my understanding above is correct.

答: Your understanding is correct: The optionality of children is independent of the optionality of present parents.  That is, the mandatory children of an optional parent must be present if the parent is present.

Body:
I have been wondering about a simple but very important question.

I have a parent element that is optional because of minOccurs="0" but its child elements do not have any minOccurs or maxOccures attributes defined.

Am I right that in case the parent element occurs, all its child elements are mandatory?

My example code looks like this:

name="FiscalRepresentativeInfo" minOccurs="0">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="FiscalRepresentativeTaxRegistrations" type="MandatoryTaxNumbersType"></xs:element>
            <xs:element name="FiscalRepresentativeName" type="LongStringType"></xs:element>
            <xs:element name="FiscalRepresentativeAddress" type="AddressType"></xs:element>
            <xs:element name="FiscalRepresentativeBankAccountNumber" type="BankAccountNumberType"></xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

Now, my question in practical terms is this:

The fiscal representative info is optional, the XML instance may or may not contain it.

Here comes the point: in case there is a fiscal representative info in the XML, it MUST have all 4 elements. For example, it is not possible to miss the bank account number.

Please let me know whether my understanding above is correct.


问:
Get details of a currently logged in user
I have am trying to get the admin rights of a user which is either true or false. I do not think i am getting the current logged in users details, the below code is what i have but when i debug it, it seems that it loops through all the users in the firebase table and if any are true it sets the buttons to visible</p>

```<code> databaseUsers = FirebaseDatabase.getInstance().getReference("users");
    //  buttonAddProducts.setVisibility(View.GONE);
    //   buttonAddBeverages.setVisibility(View.GONE);

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference currentUserReference = databaseUsers.child(uid);
    currentUserReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot userSnapshot) {
            if (userSnapshot.exists()) {
                User user = userSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }
            else{
                Log.i("myInfoTag", "Connection problem");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore exceptions
        }
    });
</code>```

答:
First of all, when we are referring to Firebase, we cannot speak about tables. In a NoSQL database there are no tables. There are only pairs of key and value.

To solve your problem, i recomand you change your database a little bit, by adding a new node in your Firebase database named userAdmins. When you add a user into your database and is also an admin, add him in this new section. Your new node should look like this:

```<code>Firebase-root
    |
    --- userAdmins
            |
            --- userId1: true
            |
            --- userId2: true
</code>```

This practice is named denormalization and for that i recomand you see this video, Denormalization is normal with the Firebase Database. If you'll see this video, you'll have a better understanding about this practice.

To verify if a user is admin, just use exists() method on the DataSnapshot object like this:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("userAdmins").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()) {
            //do something
        } else {
            //do something else
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
</code>```

In which uid is the id of the user you want to verify if is an admin.

Body:
I have am trying to get the admin rights of a user which is either true or false. I do not think i am getting the current logged in users details, the below code is what i have but when i debug it, it seems that it loops through all the users in the firebase table and if any are true it sets the buttons to visible

 databaseUsers = FirebaseDatabase.getInstance().getReference("users");
    //  buttonAddProducts.setVisibility(View.GONE);
    //   buttonAddBeverages.setVisibility(View.GONE);

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference currentUserReference = databaseUsers.child(uid);
    currentUserReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot userSnapshot) {
            if (userSnapshot.exists()) {
                User user = userSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }
            else{
                Log.i("myInfoTag", "Connection problem");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore exceptions
        }
    });

Body:
First of all, when we are referring to Firebase, we cannot speak about tables. In a NoSQL database there are no tables. There are only pairs of key and value.

To solve your problem, i recomand you change your database a little bit, by adding a new node in your Firebase database named userAdmins. When you add a user into your database and is also an admin, add him in this new section. Your new node should look like this:

Firebase-root
    |
    --- userAdmins
            |
            --- userId1: true
            |
            --- userId2: true

This practice is named denormalization and for that i recomand you see this video, Denormalization is normal with the Firebase Database. If you'll see this video, you'll have a better understanding about this practice.

To verify if a user is admin, just use exists() method on the DataSnapshot object like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("userAdmins").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()) {
            //do something
        } else {
            //do something else
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);

In which uid is the id of the user you want to verify if is an admin.


问:
Display date only and no time in Android
I am attempting to display a date in android with year, month, and day chosen using a DatePicker. What I'm having trouble with is taking the year, month, and day chosen and displaying them on the screen in the correct format for the locale of the phone without also displaying the time.

The code as it stands now will display the date correctly but it also displays the time.

```<code>StringBuilder string = new StringBuilder()
    // Month is 0 based so add 1
    .append(mYear).append("-")
    .append(mMonth + 1).append("-")
    .append(mDay);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    try {
        Date date = format.parse(string.toString());
        mDateDisplay.setText(date.toLocaleString());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

mDateDisplay is a TextView.

I can't figure out how to get rid of the time that is also displayed. I've done a fair amount of searching and reading documentation and I couldn't figure it out. Any help would be appreciated.

答:
try this code </p>

```<code>long date = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat timeonly = new SimpleDateFormat("hh:mm");
        String dateString = sdf.format(date);
        String timeString = timeonly.format(date);
        //show present date
        textView.setText(dateString);

        //show present time
        TextView.setText(timeString);
</code>```

Body:
I am attempting to display a date in android with year, month, and day chosen using a DatePicker. What I'm having trouble with is taking the year, month, and day chosen and displaying them on the screen in the correct format for the locale of the phone without also displaying the time.

The code as it stands now will display the date correctly but it also displays the time.

StringBuilder string = new StringBuilder()
    // Month is 0 based so add 1
    .append(mYear).append("-")
    .append(mMonth + 1).append("-")
    .append(mDay);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    try {
        Date date = format.parse(string.toString());
        mDateDisplay.setText(date.toLocaleString());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

mDateDisplay is a TextView.

I can't figure out how to get rid of the time that is also displayed. I've done a fair amount of searching and reading documentation and I couldn't figure it out. Any help would be appreciated.

Body:
try this code

long date = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat timeonly = new SimpleDateFormat("hh:mm");
        String dateString = sdf.format(date);
        String timeString = timeonly.format(date);
        //show present date
        textView.setText(dateString);

        //show present time
        TextView.setText(timeString);


问:
If statement inside a for loop prints all values as true if any are - bash

I want to find a git project containing the project name inputed and auto cd into it. It should be a simple bash function but it behaves strangely.

```<code>project() {
    target=$1"/.git"
    for string in "$(find ~ -name .git -type d -prune)"
    do
        if [[ $string == *"${target}" ]]
        then
            echo $string
        else
            echo 2
        fi
    done
    # cd "$HOME/Work/$1/src"
}
</code>```

If I were to echo all the projects found (the string values), it properly prints out all of the projects. Also, target is also a valid string. The expected result should be echoing of the correct path once, and all other values to be 2.

The problem appears when the code matches target as being part of the string. In that case it prints out ALL projects, instead of the wanted one. If the pattern doesn't match any projects, the code will print the value 2 ONCE. Maybe it has something to do with the fact that I'm using zsh but I really don't know.

答:
You can do much of what this function does using the CDPATH variable. For example,

```<code>$ CDPATH=$HOME/Work
$ cd project/src
$ pwd
/home/jyslar/Work/project/src
</code>```

Incorporating this into your function,

```<code>project () {
    local CDPATH="$HOME/Work"
    cd "$1/src"
}
</code>```

There is no explicit check for a .git directory, but it seems reasonable to assume that the contents of $HOME/Work are all Git repositories, or that at least it's not worth complicating the definition of project to avoid false positives (e.g., if $HOME/Work/$1/src is a directory without $1 actually being a Git repository).

Wait, you ask: why do I need CDPATH? Couldn't I just define

```<code>project () { cd "$HOME/Work/$1/src"; }
</code>```

Yes, you could. I suppose my point was that you don't even need a function. Just add

```<code>CDPATH=$HOME/Work
</code>```

to your .bashrc; then cd project-omega/src will automatically take you to $HOME/Work/project-omega/src if project-omega doesn't happen to exist in the current working directory.

Like PATH, CDPATH can contain a colon-separated list of directories, for example:

```<code>CDPATH=$HOME/Work:$HOME/Fun:$HOME/Experimental
</code>```

Body:
I want to find a git project containing the project name inputed and auto cd into it. It should be a simple bash function but it behaves strangely.

project() {
    target=$1"/.git"
    for string in "$(find ~ -name .git -type d -prune)"
    do
        if [[ $string == *"${target}" ]]
        then
            echo $string
        else
            echo 2
        fi
    done
    # cd "$HOME/Work/$1/src"
}

If I were to echo all the projects found (the string values), it properly prints out all of the projects. Also, target is also a valid string. The expected result should be echoing of the correct path once, and all other values to be 2.

The problem appears when the code matches target as being part of the string. In that case it prints out ALL projects, instead of the wanted one. If the pattern doesn't match any projects, the code will print the value 2 ONCE. Maybe it has something to do with the fact that I'm using zsh but I really don't know.

Body:
You can do much of what this function does using the CDPATH variable. For example,

$ CDPATH=$HOME/Work
$ cd project/src
$ pwd
/home/jyslar/Work/project/src

Incorporating this into your function,

project () {
    local CDPATH="$HOME/Work"
    cd "$1/src"
}

There is no explicit check for a .git directory, but it seems reasonable to assume that the contents of $HOME/Work are all Git repositories, or that at least it's not worth complicating the definition of project to avoid false positives (e.g., if $HOME/Work/$1/src is a directory without $1 actually being a Git repository).

Wait, you ask: why do I need CDPATH? Couldn't I just define

project () { cd "$HOME/Work/$1/src"; }

Yes, you could. I suppose my point was that you don't even need a function. Just add

CDPATH=$HOME/Work

to your .bashrc; then cd project-omega/src will automatically take you to $HOME/Work/project-omega/src if project-omega doesn't happen to exist in the current working directory.

Like PATH, CDPATH can contain a colon-separated list of directories, for example:

CDPATH=$HOME/Work:$HOME/Fun:$HOME/Experimental


问:
Why both subclass and superclass are true while using instanceof?
Sorry that I had a mistake while posting. The class that implements I should be B rather than A in this case. And here it is where I find confusing.
Also, if it is class C that implements I rather than A or B, the results are still the same.

```<code>interface I{}

public class A{
    A() {
        System.out.print("A: " + (this instanceof I) + " ");
    }
    public static void main(String[] args) {
        new C();
    }
}

class B extends A implements I {
    B() {
        System.out.print("B: " + (this instanceof I) + " ");
    }
}

class C extends B {
    C() {
        System.out.print("C: " + (this instanceof I) + " ");
    }
}
</code>```

Why both subclass and superclass are true while using instanceof?

The result of this code is:

```<code>A: true
B: true
C: true
</code>```

答:
This is a fundamental of object oriented programming. Let me give you an example which might help you to feel why subclasses get the behavior of interfaces implemented by parent class. Let me know if this helps.</p>

```<code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

interface Flyable {
    /* Guys, Don't worry about what kind of flyable object you are talking to.
     * just call me if you want to request someone to fly. */
    public void fly();

}

/*
 * Bird is abstract since there is nothing called 'Bird' existing in the world.
 * It should be either a Crow, Pegion, Sparrow and so on.
 */

abstract class Bird implements Flyable {

    public void fly() {
    /*  All birds follow same sequence of actions to fly.
     This method contains set of instructions to fly. */
    }

    // call this method to know where the bird was born
    public abstract String getCountry();
}

class Sparrow extends Bird {

    private String country;

    // I am responsible to give birth to a new sparrow.
    Sparrow(String beakColor, int weight, String bodyColor, String countryToLive) {
        this.country = countryToLive;

        // code to give birth to a new sparrow.
    }

    // Call me to know where i'm born
    public String getCountry() {
        return this.country;
    }

}

class Helicopter implements Flyable {

    private Date manufacturDate;
    private int engineCapacity;

    Helicopter() {
        /* sequence of instruction on how to assemble a new helicopter with default specifications */
    }

    @Override
    public void fly() {
        /* sequence of instruction on how helicopter should fly
         * Of course it will be different from how birds fly
         *  */

    }

    public Date getManufacturDate() {
        return this.manufacturDate;
    }

    public int getEngineCapacity() {
        return this.engineCapacity;
    }

}

class RandomSkyObjectsHandler {

    public static List<Flyable> getFewFlyableObjectsOfAnyType() {
        List<Flyable> randomList = new ArrayList<Flyable>();
        Sparrow sp1 = new Sparrow("black", 50, "brown", "India");
        Helicopter h1 = new Helicopter();
        Helicopter h2 = new Helicopter();
        Sparrow sp2 =  new Sparrow("Brown", 60, "white", "Kenya");
        Helicopter h3 = new Helicopter();
        Sparrow sp3 = new Sparrow("white", 70, "black", "USA");

        Flyable[] f = {sp1, sp2, h1, sp3, h2, h3};
        randomList = Arrays.asList(f);
        return randomList;

    }
}

public class TestProgramExecutor {
    public static void main(String... commandLineArguments) {

        List<Flyable> mixOfFlyingStuff = RandomSkyObjectsHandler.getFewFlyableObjectsOfAnyType();

        /* here is the beauty of OOPS. I don't need the knowledge of whether i'm telling a helicopter to fly or a sparrow to fly.
         * I'm just pretty sure that I'm talking to a flyable object and it understand if i say fly();
         * */

        for(Flyable f: mixOfFlyingStuff) {

            f.fly();
        }
    }
}
</code>```

Body:
Sorry that I had a mistake while posting. The class that implements I should be B rather than A in this case. And here it is where I find confusing.
Also, if it is class C that implements I rather than A or B, the results are still the same.

interface I{}

public class A{
    A() {
        System.out.print("A: " + (this instanceof I) + " ");
    }
    public static void main(String[] args) {
        new C();
    }
}

class B extends A implements I {
    B() {
        System.out.print("B: " + (this instanceof I) + " ");
    }
}

class C extends B {
    C() {
        System.out.print("C: " + (this instanceof I) + " ");
    }
}

Why both subclass and superclass are true while using instanceof?

The result of this code is:

A: true
B: true
C: true

Body:
This is a fundamental of object oriented programming. Let me give you an example which might help you to feel why subclasses get the behavior of interfaces implemented by parent class. Let me know if this helps.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

interface Flyable {
    /* Guys, Don't worry about what kind of flyable object you are talking to.
     * just call me if you want to request someone to fly. */
    public void fly();

}

/*
 * Bird is abstract since there is nothing called 'Bird' existing in the world.
 * It should be either a Crow, Pegion, Sparrow and so on.
 */

abstract class Bird implements Flyable {

    public void fly() {
    /*  All birds follow same sequence of actions to fly.
     This method contains set of instructions to fly. */
    }

    // call this method to know where the bird was born
    public abstract String getCountry();
}

class Sparrow extends Bird {

    private String country;

    // I am responsible to give birth to a new sparrow.
    Sparrow(String beakColor, int weight, String bodyColor, String countryToLive) {
        this.country = countryToLive;

        // code to give birth to a new sparrow.
    }

    // Call me to know where i'm born
    public String getCountry() {
        return this.country;
    }

}

class Helicopter implements Flyable {

    private Date manufacturDate;
    private int engineCapacity;

    Helicopter() {
        /* sequence of instruction on how to assemble a new helicopter with default specifications */
    }

    @Override
    public void fly() {
        /* sequence of instruction on how helicopter should fly
         * Of course it will be different from how birds fly
         *  */

    }

    public Date getManufacturDate() {
        return this.manufacturDate;
    }

    public int getEngineCapacity() {
        return this.engineCapacity;
    }

}

class RandomSkyObjectsHandler {

    public static List<Flyable> getFewFlyableObjectsOfAnyType() {
        List<Flyable> randomList = new ArrayList<Flyable>();
        Sparrow sp1 = new Sparrow("black", 50, "brown", "India");
        Helicopter h1 = new Helicopter();
        Helicopter h2 = new Helicopter();
        Sparrow sp2 =  new Sparrow("Brown", 60, "white", "Kenya");
        Helicopter h3 = new Helicopter();
        Sparrow sp3 = new Sparrow("white", 70, "black", "USA");

        Flyable[] f = {sp1, sp2, h1, sp3, h2, h3};
        randomList = Arrays.asList(f);
        return randomList;

    }
}

public class TestProgramExecutor {
    public static void main(String... commandLineArguments) {

        List<Flyable> mixOfFlyingStuff = RandomSkyObjectsHandler.getFewFlyableObjectsOfAnyType();

        /* here is the beauty of OOPS. I don't need the knowledge of whether i'm telling a helicopter to fly or a sparrow to fly.
         * I'm just pretty sure that I'm talking to a flyable object and it understand if i say fly();
         * */

        for(Flyable f: mixOfFlyingStuff) {

            f.fly();
        }
    }
}


问:
How do I solve TypeError: '>' not supported between instances of 'int' and 'list'?
Here's the code, I just don't know why the error keeps showing up even after reading the past answers about it.   </p>

```<code>import random
rand = random.sample(range(10), 1)
print(rand)

guess = input('Try guessing a number between 0-10! ')

for num in str(guess):
    if rand > guess:
        print('The number is too low! Try again!')
    elif rand < guess:
        print('The number is too high! Try again!')
    else:
        print("You got it!")
</code>```

答:
for this problem, simply replace random.sample(range(10), 1) with random.randint(1,11) or random.choice(range(10)). random.sample returns a list. You want to return a integer, so you can do a comparison.

Besides, your error description does not seem correct. It seems you should get:

```<code>Traceback (most recent call last):
File "<pyshell#11>", line 2, in <module>
    if rand>guess:
TypeError: unorderable types: list() > str()
</code>```

And to avoid this, use the int() function to convert your input to a number and make the other change from above.

Body:
Here's the code, I just don't know why the error keeps showing up even after reading the past answers about it.

import random
rand = random.sample(range(10), 1)
print(rand)

guess = input('Try guessing a number between 0-10! ')

for num in str(guess):
    if rand > guess:
        print('The number is too low! Try again!')
    elif rand < guess:
        print('The number is too high! Try again!')
    else:
        print("You got it!")

Body:
for this problem, simply replace random.sample(range(10), 1) with random.randint(1,11) or random.choice(range(10)). random.sample returns a list. You want to return a integer, so you can do a comparison.

Besides, your error description does not seem correct. It seems you should get:

Traceback (most recent call last):
File "<pyshell#11>", line 2, in <module>
    if rand>guess:
TypeError: unorderable types: list() > str()

And to avoid this, use the int() function to convert your input to a number and make the other change from above.


问:
Can I convert a View to Layout?
In android, one can Inflate a Layout file and will get a View in return.
For Example:

```<code>LayoutInflater layoutInflater = LayoutInflater.from(context);
View myView = layoutInflater.inflate(R.layout.example_layout, null);
</code>```

But I'm trying if I can get a Layout back from that inflated layout which is now a View?
Something by which I can retrieve back the original Layout from the Inflated View.

答:
Consider the layout below. It has a text view only.

```<code> <TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="@dimen/mediumTextSize"
    android:textColor="@color/black_text_color"
    />
</code>```

After inflation you can directly get the textView as its the only view contain in layout.

```<code> LayoutInflater inflater=LayoutInflater.from(this);
    TextView view=(TextView)inflater.inflate(R.layout.temp,null);
</code>```

Now consider the layout below .

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

    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textColor="@color/black_text_color"
        android:textSize="@dimen/largeTExtSize" />

    <TextView
        android:id="@+id/csvName"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textColor="@color/black_text_color"
        android:textSize="@dimen/largeTExtSize" />

</LinearLayout>
</code>```

On inflation.

```<code> LayoutInflater inflater=LayoutInflater.from(this);
    View view=inflater.inflate(R.layout.temp,null);
    //Or you can do
    // LinearLayout view=(LinearLayout)inflater.inflate(R.layout.temp,null);
    TextView txt=view.findViewById(R.id.txtId);
</code>```

Title: Can I convert a View to Layout?

Body:
In android, one can Inflate a Layout file and will get a View in return.
For Example:

LayoutInflater layoutInflater = LayoutInflater.from(context);
View myView = layoutInflater.inflate(R.layout.example_layout, null);

But I'm trying if I can get a Layout back from that inflated layout which is now a View?
Something by which I can retrieve back the original Layout from the Inflated View.

Body:
Consider the layout below. It has a text view only.

 <TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="@dimen/mediumTextSize"
    android:textColor="@color/black_text_color"
    />

After inflation you can directly get the textView as its the only view contain in layout.

 LayoutInflater inflater=LayoutInflater.from(this);
    TextView view=(TextView)inflater.inflate(R.layout.temp,null);

Now consider the layout below .

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

    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textColor="@color/black_text_color"
        android:textSize="@dimen/largeTExtSize" />

    <TextView
        android:id="@+id/csvName"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textColor="@color/black_text_color"
        android:textSize="@dimen/largeTExtSize" />

</LinearLayout>

On inflation.

 LayoutInflater inflater=LayoutInflater.from(this);
    View view=inflater.inflate(R.layout.temp,null);
    //Or you can do
    // LinearLayout view=(LinearLayout)inflater.inflate(R.layout.temp,null);
    TextView txt=view.findViewById(R.id.txtId);


问:
Invalid token in member declaration
I'm trying to declare this item for use in a list.

```<code>class Item
{
    Public int Resource{ get;set; }
    Public long Offset{ get;set; }
    Public int Value{ get;set; }
}
</code>```

I thought this would be ok, I copied it off someone else, but I don't understand what get and set do. I'm completely new to C#, but the tutorial I watched put their class declaration in a different file - do you have to do that?

I get this error:

Line: 15 Column: 11 (CS1519) Invalid token 'int' in class, struct, or interface member declaration

答:
C# case sensitive, write public in lower case:

```<code>class Item
{
    public int Resource { get; set; }
    public long Offset { get; set; }
    public int Value { get; set; }
}
</code>```

Get and sen in this example do nothing (almost) more info about them:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties

Title: Invalid token in member declaration

Body:
I'm trying to declare this item for use in a list.

class Item
{
    Public int Resource{ get;set; }
    Public long Offset{ get;set; }
    Public int Value{ get;set; }
}

I thought this would be ok, I copied it off someone else, but I don't understand what get and set do. I'm completely new to C#, but the tutorial I watched put their class declaration in a different file - do you have to do that?

I get this error:

Line: 15 Column: 11 (CS1519) Invalid token 'int' in class, struct, or interface member declaration

Body:
C# case sensitive, write public in lower case:

class Item
{
    public int Resource { get; set; }
    public long Offset { get; set; }
    public int Value { get; set; }
}

Get and sen in this example do nothing (almost) more info about them:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties


问:
Any way faster than pow() to compute an integer power of 10 in C++?
I know power of 2 can be implemented using << operator.
What about power of 10? Like 10^5? Is there any way faster than pow(10,5) in C++? It is a pretty straight-forward computation by hand. But seems not easy for computers due to binary representation of the numbers... Let us assume I am only interested in integer powers, 10^n, where n is an integer. </p>

答:
This function will calculate x ^ y much faster then pow. In case of integer values.

```<code>int pot(int x, int y){
int solution = 1;
while(y){
    if(y&1)
        solution*= x;
    x *= x;
    y >>= 1;
}
return solution;
</code>```

}

Body:
This function will calculate x ^ y much faster then pow. In case of integer values.

int pot(int x, int y){
int solution = 1;
while(y){
    if(y&1)
        solution*= x;
    x *= x;
    y >>= 1;
}
return solution;

}


问:
call javascript function on div with same class
I have a javascript function i would like to call on multiple div with same class but when i call the function and hover over the first div the function is called on the other div with same class

```<code>function flip() {
    $('.front').css("display", "none");
    $('.back').fadeIn();
}
function flipBack() {
    $('.front').fadeIn();
    $('.back').css("display", "none");
}
</code>```

html

```<code><div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-globe"></i>
                    <h3>Nigeriaeexport</h3>
                    <p>Your one stop export solution platform for everything export.</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div>
            <div class="subMainSlates" onmouseenter="flip(this)" onmouseleave="flipBack(this)">
                <div class="front">
                    <i class="typcn typcn-location-arrow"></i>
                    <h3>XPT Logistics</h3>
                    <p>The top Company in terms of Export Logistics in Nigeria</p>
                </div>
                <div class="back">
                    Want to work
                </div>
            </div>
</code>```

What I want is when mouseenter the .subMainSlate the .front fadeOut() and .back fadeIn().

Thanks.

答:
You're passing this as the argument to the handler, but you're not using it. All you need to do is define a parameter on your function and use that.

```<code>function flip(elem) {
    // 'elem' is the element that received the event
    $(elem).find('.front').css("display", "none");
    $(elem).find('.back').fadeIn();
}
function flipBack(elem) {
    // 'elem' is the element that received the event
    $(elem).find('.front').fadeIn();
    $(elem).find('.back').css("display", "none");
}
</code>```

Body:
I have a javascript function i would like to call on multiple div with same class but when i call the function and hover over the first div the function is called on the other div with same class

function flip() {
    $('.front').css("display", "none");
    $('.back').fadeIn();
}
function flipBack() {
    $('.front').fadeIn();
    $('.back').css("display", "none");
}

html

Nigeriaeexport

Your one stop export solution platform for everything export.

                    Want to work

XPT Logistics

The top Company in terms of Export Logistics in Nigeria

                    Want to work

What I want is when mouseenter the .subMainSlate the .front fadeOut() and .back fadeIn().

Thanks.

Body:
You're passing this as the argument to the handler, but you're not using it. All you need to do is define a parameter on your function and use that.

function flip(elem) {
    // 'elem' is the element that received the event
    $(elem).find('.front').css("display", "none");
    $(elem).find('.back').fadeIn();
}
function flipBack(elem) {
    // 'elem' is the element that received the event
    $(elem).find('.front').fadeIn();
    $(elem).find('.back').css("display", "none");
}


问:
How to optimize transmission of Mongo query result set from server to client; perhaps by compression?
I'm writing some Mongo queries for pieces of data that are about 12 KB each in raw JSON. I expect to grab anywhere from 5000 to 150000 of these objects for our users at the startup of a program I'm writing. Over our 100Mbps LAN, this takes a while--about 55 seconds for 50000 objects, or 6 seconds for 5000 objects. The objects don't change, so I'm fine caching them after they're in memory. But the initial query time is unacceptable. I've verified using Wireshark that the network is actually causing the bottleneck. It takes nearly a minute to get the packets of all 50000 objects, unfortunately. Converting objects, deserializing, indices, etc. are not causing an issue for me.

I suspect it would be faster if Mongo did something like compressing the data first, sending it to me, and letting me decompress it client-side. Is this a realistic suspicion, and if so, does Mongo have any facility to do this? Or, is there any other way to speed up the transmission of large query result sets? I've tried setting the batch_size higher, and it didn't help.

My environment is PyMongo on Python 3.6 on Windows. The client computer and server hardware specs are more than adequate to handle the (de)compression. I'm trying to avoid a solution that would have me write a program to put on the server to locally query and compress the data before sending it over the network to the client.

答:
Your observations certainly seem to make sense. Let's do the Maths:

```<code>  5'000 * 12kb =  60MB
150'000 * 12kb = 1.8GB
</code>```

A 100Mbps network transmits max. 750MB/min so that'd result in something between 4.8s (for 5'000 documents) and 2m:24s (for 150'000) assuming an otherwise empty wire. That's quite a bit.

If it's not an option for you to upgrade to e.g. Gigabit ethernet then there's still hope:

MongoDB v3.6 comes with protocol compression: https://emptysqua.re/blog/driver-features-for-mongodb-3-6/. It has been released a few days ago. You may need to wait for your driver to become available, though.

Also, some e.g. Cisco routers support compression which should help but obviously requires hardware and know-how again: https://www.cisco.com/c/en/us/support/docs/wan/data-compression/14156-compress-overview.html

Body:
Your observations certainly seem to make sense. Let's do the Maths:

  5'000 * 12kb =  60MB
150'000 * 12kb = 1.8GB

A 100Mbps network transmits max. 750MB/min so that'd result in something between 4.8s (for 5'000 documents) and 2m:24s (for 150'000) assuming an otherwise empty wire. That's quite a bit.

If it's not an option for you to upgrade to e.g. Gigabit ethernet then there's still hope:

MongoDB v3.6 comes with protocol compression: https://emptysqua.re/blog/driver-features-for-mongodb-3-6/. It has been released a few days ago. You may need to wait for your driver to become available, though.

Also, some e.g. Cisco routers support compression which should help but obviously requires hardware and know-how again: https://www.cisco.com/c/en/us/support/docs/wan/data-compression/14156-compress-overview.html


答:
Using lens you can write it like this:

```<code>incrementPersonCounter :: Person -> Person
incrementPersonCounter = counter +~ 1
</code>```

Example:

```<code>λ> incrementPersonCounter $ Person "foo" 42
Person {_name = "foo", _counter = 43}
</code>```

Full code:

```<code>{-# LANGUAGE TemplateHaskell #-}

module Lib where

import Control.Lens

data Person = Person
  {
    _name :: String
  , _counter :: Int
  } deriving (Show, Eq)
makeLenses ''Person

incrementPersonCounter :: Person -> Person
incrementPersonCounter = counter +~ 1
</code>```

Title: How can I concisely modify a record's field?

Body:
data Person = Person
  {
    name :: String
  , counter :: Int
  }

incrementPersonCounter :: Person -> Person
incrementPersonCounter p@(Person _ c) = p { counter = c + 1 }

Is there a more concise way of doing the above? Is there a function I could use, where I specify the record, one of its fields (name / counter in this case) and a function to apply to the return value?

I was thinking something along the lines of:

applyRecord r f f' = r
  { f = f' (f r) }

Though this won't work because:

error: Not in scope: ‘f’
   |
13 |   { f = f' (f r) }

Body:
Using lens you can write it like this:

incrementPersonCounter :: Person -> Person
incrementPersonCounter = counter +~ 1

Example:

λ> incrementPersonCounter $ Person "foo" 42
Person {_name = "foo", _counter = 43}

Full code:

{-# LANGUAGE TemplateHaskell #-}

module Lib where

import Control.Lens

data Person = Person
  {
    _name :: String
  , _counter :: Int
  } deriving (Show, Eq)
makeLenses ''Person

incrementPersonCounter :: Person -> Person
incrementPersonCounter = counter +~ 1


问:
javascript - Remove in Array closest values
i try remove neighborhood values in array. The items are moved from one array to another, after which if the two neighboring elements are similar, they must be removed. And so on the chain.
Experience is not enough to understand what I'm doing wrong.

let arr = ["w", "w", "s", "n", "d", "a", "a", "d", "o", "w", "f", "f", "d", "e", "n", "n", "n"];

var unique = arr.filter(function(elem, index, self) {
  return index === self.indexOf(elem);

});

console.log('unique', unique);```

in OUTPUT: After the second filtering, we get the name of the person!

wrong answers:

unique (12) ["w", "s", "n", "d", "a", "d", "o", "w", "f", "d", "e", "n"]

unique (5) ["w", "a", "f", "n", "n"]

答:
You can use array#reduce. Inside the loop compare last value inserted with the current value, if same remove the last value otherwise push the new value. The name is Snowden.

let arr = ["w", "w", "s", "n", "d", "a", "a", "d", "o", "w", "f", "f", "d", "e", "n", "n", "n"];

var unique = arr.reduce(function(result, elem) {
  if(result[result.length - 1] == elem)
    result.pop();
  else
    result.push(elem);
  return result;
}, []);

console.log('unique', unique);```

Body:
i try remove neighborhood values in array. The items are moved from one array to another, after which if the two neighboring elements are similar, they must be removed. And so on the chain.
Experience is not enough to understand what I'm doing wrong.

let arr = ["w", "w", "s", "n", "d", "a", "a", "d", "o", "w", "f", "f", "d", "e", "n", "n", "n"];

var unique = arr.filter(function(elem, index, self) {
  return index === self.indexOf(elem);

});

console.log('unique', unique);

in OUTPUT: After the second filtering, we get the name of the person!

wrong answers:

unique (12) ["w", "s", "n", "d", "a", "d", "o", "w", "f", "d", "e", "n"]

unique (5) ["w", "a", "f", "n", "n"]


问:
np.where to search whole column
I have a dataframe in this format

```<code>Date       D1
12/8/2017  12/7/2017
12/7/2017  12/2/2017
12/6/2017  12/1/2017
12/5/2017
12/4/2017

df['Exist'] = np.where(df['Date'] == df['D1'], 1, 0)
</code>```

The above code does not work as it only looks at the same row, how do I make it such that it will search the whole D1 to produce:

```<code>Date       D1         Exist
12/8/2017  12/7/2017  0
12/7/2017  12/2/2017  1
12/6/2017  12/1/2017  0
12/5/2017             0
12/4/2017             0
</code>```

Thank you!

答:
If both columns are of the same dtype:</p>

```<code>df['Exist'] = df['Date'].isin(df['D1']).astype(np.int8)
</code>```

Title: np.where to search whole column

Body:
I have a dataframe in this format

Date       D1
12/8/2017  12/7/2017
12/7/2017  12/2/2017
12/6/2017  12/1/2017
12/5/2017
12/4/2017

df['Exist'] = np.where(df['Date'] == df['D1'], 1, 0)

The above code does not work as it only looks at the same row, how do I make it such that it will search the whole D1 to produce:

Date       D1         Exist
12/8/2017  12/7/2017  0
12/7/2017  12/2/2017  1
12/6/2017  12/1/2017  0
12/5/2017             0
12/4/2017             0

Thank you!

Body:
If both columns are of the same dtype:

df['Exist'] = df['Date'].isin(df['D1']).astype(np.int8)


问:
Is there like python monthcalendar method in c#?
I want to convert a python code to c# code,in python code there is a method that name is calendar.monthcalendar(year,month) I don't know how can i convert it c# code.

monthcalendar() method

The monthrange() method is used to get a matrix representing a month’s
  calendar.  Each row represents a week; days outside of the month a
  represented by zeros.  Each week begins with Monday unless set by
  setfirstweekday().

答:
```<code>static int[,] MonthCalendar(int year, int month, DayOfWeek firstWeekDay)
{
    int daysInMonth = DateTime.DaysInMonth(year, month);
    DayOfWeek first = new DateTime(year, month, 1).DayOfWeek;
    int left = ((int)first - (int)firstWeekDay + 7) % 7;
    int[,] arr = new int[7, (left + daysInMonth + 6) / 7];
    for (int i = 0; i < daysInMonth; i++)
    {
        int a = left + i;
        arr[a % 7, a / 7] = i + 1;
    }
    return arr;
}

static void Test(int year, int month, DayOfWeek firstWeekDay)
{
    string[] week = new string[]{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    Console.WriteLine(year + "-" + month);
    for (int i = (int)firstWeekDay; i < ((int)firstWeekDay + 7); i++)
    {
        Console.Write(" " + week[i % 7]);
    }
    Console.WriteLine();
    var arr = MonthCalendar(year, month, firstWeekDay);
    for (int y = 0; y < arr.GetLength(1); y++)
    {
        for (int x = 0; x < 7; x++)
        {
            Console.Write(arr[x, y].ToString().PadLeft(4));
        }
        Console.WriteLine();
    }
}
</code>```

Test(2017, 12, DayOfWeek.Monday); output:

```<code>2017-12
 Mon Tue Wed Thu Fri Sat Sun
   0   0   0   0   1   2   3
   4   5   6   7   8   9  10
  11  12  13  14  15  16  17
  18  19  20  21  22  23  24
  25  26  27  28  29  30  31
</code>```

Body:
static int[,] MonthCalendar(int year, int month, DayOfWeek firstWeekDay)
{
    int daysInMonth = DateTime.DaysInMonth(year, month);
    DayOfWeek first = new DateTime(year, month, 1).DayOfWeek;
    int left = ((int)first - (int)firstWeekDay + 7) % 7;
    int[,] arr = new int[7, (left + daysInMonth + 6) / 7];
    for (int i = 0; i < daysInMonth; i++)
    {
        int a = left + i;
        arr[a % 7, a / 7] = i + 1;
    }
    return arr;
}

static void Test(int year, int month, DayOfWeek firstWeekDay)
{
    string[] week = new string[]{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
    Console.WriteLine(year + "-" + month);
    for (int i = (int)firstWeekDay; i < ((int)firstWeekDay + 7); i++)
    {
        Console.Write(" " + week[i % 7]);
    }
    Console.WriteLine();
    var arr = MonthCalendar(year, month, firstWeekDay);
    for (int y = 0; y < arr.GetLength(1); y++)
    {
        for (int x = 0; x < 7; x++)
        {
            Console.Write(arr[x, y].ToString().PadLeft(4));
        }
        Console.WriteLine();
    }
}

Test(2017, 12, DayOfWeek.Monday); output:

2017-12
 Mon Tue Wed Thu Fri Sat Sun
   0   0   0   0   1   2   3
   4   5   6   7   8   9  10
  11  12  13  14  15  16  17
  18  19  20  21  22  23  24
  25  26  27  28  29  30  31


答:
Try replacing

```<code>rand = random.sample(range(10), 1)
</code>```

With

```<code>rand = random.randint(0, 10)
</code>```

Your code is trying to compare a list with a string. You need to compare two of the same. Also try making guess an integer first:

```<code>guess = int(input('Try guessing a number between 0-10! '))
</code>```

and removing the str(guess) - leave just guess as it is now an integer

Title: How do I solve TypeError: '>' not supported between instances of 'int' and 'list'?

Body:
Try replacing

rand = random.sample(range(10), 1)

With

rand = random.randint(0, 10)

Your code is trying to compare a list with a string. You need to compare two of the same. Also try making guess an integer first:

guess = int(input('Try guessing a number between 0-10! '))

and removing the str(guess) - leave just guess as it is now an integer


问:
Windows mobile Windows Messages tracing utility
I'm looking for small utility to run on windows mobile phone and trace all windows messages it receive. Not message codes, but names if it could figure them out.

I could probably write on for my own, but don't know where I could get a dictionary of WM. Parsing .H files perspective drives me mad.

答:
There is a version of "Spy" installed as part of most windows mobile SDK's under the remote tools.  So if you have MSVC with either the builtin Windows Mobile SDK or you have installed a windows mobile SDK then you should be able to find it: (at least for vc2008 install)

\Program Files\CE Remote Tools\5.01\bin\ccspy.exe

Run it under windows and connect it to a windows mobile device.  It works similar to the standard spy++ but more limited.

OwnerDisplayName: Artem Tikhomirov

OwnerDisplayName: Shane Powell


问:
How to correctly override literal operators?
Ok, so I made my own class and I've overloaded an operator ""s so I can use it for my string formation.

BUT, I get an error when compiling and I have no idea what it means.
Could someone explain the meaning of it and how to fix it?

my code:

```<code>PString operator"" s(const char* text, std::size_t len) {
    return PString(std::string(text, len));
}
</code>```

my error:

```<code>error: ‘PString PString::operator""s(const char*, std::size_t)’ must be a non-member function
 PString operator"" s(const char* text, std::size_t len) {
</code>```

答:
Ok, so prior to asking this question I've been confused about something. Because I've added other operator overrides inside of the class, I thought that I was supposed to add that operator"" s inside of the class as well. But apparently, that is not so.

I'm keeping this just as a reference to the answer @user0042 gave to me.

This is what solved the problem for me.

Body:
Ok, so I made my own class and I've overloaded an operator ""s so I can use it for my string formation.

BUT, I get an error when compiling and I have no idea what it means.
Could someone explain the meaning of it and how to fix it?

my code:

PString operator"" s(const char* text, std::size_t len) {
    return PString(std::string(text, len));
}

my error:

error: ‘PString PString::operator""s(const char*, std::size_t)’ must be a non-member function
 PString operator"" s(const char* text, std::size_t len) {


问:
SQL Server vs. MySQL
I am confused about the database I should choose, since the application I am doing will store and handle large amounts of data, I think SQL Server will be better than MySQL. Any recommendations?</p>

答:
Both platforms SQL Server and MySQL can handle small and large software projects, so you should anticipate similar performance from both, provided the database designer and programmer are familiar with the right way to optimize queries and code.

Structured query language (SQL) is the language of relational databases. Several database platforms use SQL, but a slight variation on it—each tend to have a slightly different syntax. Microsoft SQL and MySQL are two of the most common database platforms on the web. Once you go with one, it can be very difficult to switch to the other. That’s because the database platform you choose will end up being the core of your dynamic content moving forward. It stores, secures, and retrieves all the data for your applications.

It’s an important decision to make, and will likely hinge on a few things. If you’re having a hard time deciding which one is right for your project, here’s a look at some similarities and differences between the two, SQL and MySQL.

THE BASICS

Whether you want to store, retrieve or edit your data—the way dynamic websites and applications perform nearly every request a user makes—SQL is the language of choice for relational databases. On the surface, both Microsoft and MySQL look similar:

They both give you the ability to host several databases on one
server.

They use tables to store data.

They have primary and foreign    key constraints.

They use indexes to sort data and speed up performance, and they both support desktop and web applications.

SQL Server is slightly older than MySQL. Microsoft SQL Server was introduced in 1989 and MySQL was introduced in 1995 as an open-source project. Since both of them have been in production for years, they both have a firm foothold in the market. MySQL runs on either Windows or Linux, typically as a part of a LAMP environment. SQL Server runs on Windows, and is usually a part of a Windows environment.

Both platforms handle small and large software projects, so you should anticipate similar performance from both, provided the database designer and programmer are familiar with the right way to optimize queries and code.

Microsoft SQL Server vs. MySQL: Similarities

Both Microsoft and MySQL are relational database platforms, so they have several similarities. Most developers specialize in either one or the other, because although they appear similar, the way they work in the underlying architecture is very different. Here are some similarities, which make it somewhat easy for a database developer to work on both platforms efficiently, even if they specialize in only one.

Scalability: Both platforms allow you to scale as your business grows. You can use both for small projects, however should these projects take off to an enterprise-level, they can still support millions of transactions a day.
High-performance: A database is your application’s backbone. It stores your all of data, so you need a database that can return data in less than a second. Both platforms can handle this type of high-performance speed.

Tables: Both platforms use the standard relational database table model to store data in rows and columns.
Keys: Both platforms use primary and foreign keys to establish relationships between tables.

Syntax: Syntax between the two database platforms are similar, although there are some minor differences across different CRUD (create, read, update, delete) statements.

Web-based popularity: Aside from Oracle, Microsoft SQL Server and MySQL are the most common databases used for web applications. When you sign up for hosting, you typically get a choice between MySQL databases or SQL Server.
Drivers: You can find connection drivers for almost any popular language on the web, so you can easily connect to both platforms without writing complex code.

MICROSOFT SQL SERVER VS. MYSQL: DIFFERENCES

While the two platforms are similar in the interface and basic relational database standards, they are two very different programs and operate differently. Most of the differences are in the way they operate in the background, and these differences are not seen by the average user. As long as the database performs well, it can be used with your project. However, it’s still important to know these differences because they’ll play a huge role in your developer’s choice platform.

Native compatibility: You can use either database with both Windows and Linux projects, but MySQL works natively with PHP and MSSQL is mainly used with .NET. It makes integration simpler if you stick with MySQL for PHP and MSSQL for Windows projects.

MyISAM and InnoDB: Both of these engines are configurations for MySQL and allow the developer to perform very different design and programming. With MSSQL, you create a database and don’t specify different engines.

Cost: SQL Server is generally expensive to run, because you need licenses for the server running the software. MySQL is free and open-source, but you’ll pay for support if you need it.

LINQ: With MSSQL, you can set up your entity framework classes in .NET and get started with LINQ queries. With MySQL and .NET, you need to download third-party provider tools.

IDE tools: Both platforms have IDE tools, but you need the right tool with the right server. MSSQL uses Management Studio and MySQL has Enterprise Manager. These tools let you connect to the server and manage settings and configurations for security, architecture, and table design.

WHICH ONE SHOULD YOU USE?

The database you use usually depends on the hosting environment you choose. Linux hosting providers usually offer MySQL. Since MySQL is open-source and free, you can have as many databases as you need. You can have 10 of them to support 10 different projects if need be.

Because SQL Server costs money for licenses, Windows hosts will give you one MSSQL database and you must pay for additional ones. Overall, this makes SQL Server more costly than MySQL. However, SQL Server works natively with .NET applications, so it’s the choice for software that runs on a Windows server or desktop. The development tools are free, but the production environment is not free.

The best way to determine the right platform is to first post your project in the marketplace and discuss your requirements with a few developers. You will get different opinions and preferences based on the developer’s area of expertise, but most Windows developers work with MSSQL and Linux developers work with MySQL. You should decide which environment you want to target, and then you can get a clearer idea of which platform is right for you.

Source
sql-vs-mysql-which-relational-database-is-right-for-you

ContentLicense: CC BY-SA 4.0

Title: SQL Server vs. MySQL


问:
Cannot get files when lazy loading a module
I'm trying to lazy load some modules on my angular 2 application but when I go to the route for a particular module the GET request seems to be messed up.

app-routing.module.ts

const routes = [
  {path: 'products', loadChildren: './products/products.module#ProductsModule'},
  {path: 'user', loadChildren: './user/user.module#UserModule'},
  {path: '**', redirectTo: '/products'}
]
```

<p>product-routing.module.ts</p>

<pre class="lang-js prettyprint-override"><code>const routes: Routes = [
  {path: '', component: ProductsComponent}
];
</code>```

user-routing.module.ts

const routes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent},
  {path: 'reset-password', component: ResetPasswordComponent},
  {path: 'profile', component: ProfileComponent}
];
```

The product route works perfectly but the user routes don't seem to work which I believe is due to the following console error:

GET http://localhost:4200/user/inline.bundle.js net::ERR_ABORTED

For some reason user is being added into the url to get all of my assets. I'm guessing I've done something wrong with the routing but I'm not entirely sure what?

答:
Do you have '' empty path in user module? You should create some redirect empty pass for your user module because your path is at /user/ when UserModule was lazy loaded and there isn't a route to it.

user-routing.module.ts

```<code>const routes: Routes = [
  {path: '', redirectTo: 'login', pathMatch: 'full'},
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent},
  {path: 'reset-password', component: ResetPasswordComponent},
  {path: 'profile', component: ProfileComponent}
];
</code>```

Body:
I'm trying to lazy load some modules on my angular 2 application but when I go to the route for a particular module the GET request seems to be messed up.

app-routing.module.ts

const routes = [
  {path: 'products', loadChildren: './products/products.module#ProductsModule'},
  {path: 'user', loadChildren: './user/user.module#UserModule'},
  {path: '**', redirectTo: '/products'}
]

product-routing.module.ts

const routes: Routes = [
  {path: '', component: ProductsComponent}
];

user-routing.module.ts

const routes: Routes = [
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent},
  {path: 'reset-password', component: ResetPasswordComponent},
  {path: 'profile', component: ProfileComponent}
];

The product route works perfectly but the user routes don't seem to work which I believe is due to the following console error:

GET http://localhost:4200/user/inline.bundle.js net::ERR_ABORTED

For some reason user is being added into the url to get all of my assets. I'm guessing I've done something wrong with the routing but I'm not entirely sure what?

Body:
Do you have '' empty path in user module? You should create some redirect empty pass for your user module because your path is at /user/ when UserModule was lazy loaded and there isn't a route to it.

user-routing.module.ts

const routes: Routes = [
  {path: '', redirectTo: 'login', pathMatch: 'full'},
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent},
  {path: 'reset-password', component: ResetPasswordComponent},
  {path: 'profile', component: ProfileComponent}
];


问:
Gibbon GEM: API wrapper for MailChimp's API - How to implement with a DELETE method
The Gibbon Gem seems quite versatile. I managed to use it and create GET requests. For example, I am able to do a GET request and get all information on an order on Mailchimp. But I somehow can't make a request with the method DELETE.

MailChimp Documentation on the API Order: Documentation

Gibbon Mailchimp API Wrapper Documentation

So here is my code:

```<code>gibbon.ecommerce.stores("YourStoreName")
                .orders("orderNumber")
                .retrieve(headers: {"method": "delete"})
</code>```

The result is a GET request and a huge JSON with all information on the order. If I run the exact same request again, I get the same information back (even though I wanted to delete it)

Anyone have a good idea?

答:
By writing this answer I just found the solution myself.

The correct solution would be to use the .delete method (and not trying to specify the method in the header)

```<code>gibbon.ecommerce.stores("YourStoreName")
                .orders("orderNumber")
                .delete
</code>```

Keeping the answer here, because maybe someone else will find this useful.

Body:
The Gibbon Gem seems quite versatile. I managed to use it and create GET requests. For example, I am able to do a GET request and get all information on an order on Mailchimp. But I somehow can't make a request with the method DELETE.

MailChimp Documentation on the API Order: Documentation

Gibbon Mailchimp API Wrapper Documentation

So here is my code:

gibbon.ecommerce.stores("YourStoreName")
                .orders("orderNumber")
                .retrieve(headers: {"method": "delete"})

The result is a GET request and a huge JSON with all information on the order. If I run the exact same request again, I get the same information back (even though I wanted to delete it)

Anyone have a good idea?

Body:
By writing this answer I just found the solution myself.

The correct solution would be to use the .delete method (and not trying to specify the method in the header)

gibbon.ecommerce.stores("YourStoreName")
                .orders("orderNumber")
                .delete

Keeping the answer here, because maybe someone else will find this useful.