答:
In my experience the backend tools do a good job of inferring clock gate enables (i.e. 95%+ of my registers in my Chisel SoC are clock gated).

Therefore I do not find myself needing to do what you ask, but if all you need is to specify the enable to a register this is easy with RegEnable.

Title: Chisel -- clock gating

Body:
Clock gating is important for power reduction.  How do we specify clock gating in Chisel?

Clock gating is where a logic signal determines whether or not the clock to a particular register is toggled.  When the logic signal is inactive, then the clock remains steady, unchanging.  Only when the enable is active does the clock signal toggle, which in turn latches inputs into the flip flop.

The backend tools handle inserting the implementation of this, but they need the RTL to indicate the enable signal.


来源: stackexchange

问:
Bootstrap 4 makes outline not work
How does Bootstrap disable the HTML outline property?
When I add the form control class to my input, "outline: none;" no longer works.

```<code><input class="form-control" style="outline:none;">
</code>```

codepen: https://codepen.io/Eli92/pen/WXXbRa

I can just use my own css class for this input, but I want to know what's happening here, and I'm too much of a beginner to submit a bug report.

The reason I want to remove the outline is to add my own to an outer element, like Youtube and most popular sites do for their search bar.

答:
Actually, a border and box-shadow are applied to every form-control when focused, so setting

```<code>.form-control:focus {
  border: none;
  box-shadow: none;
}
</code>```

should remove the styling

ContentLicense: CC BY-SA 3.0

Title: Bootstrap 4 makes outline not work

Body:
How does Bootstrap disable the HTML outline property?
When I add the form control class to my input, "outline: none;" no longer works.

<input class="form-control" style="outline:none;">

codepen: https://codepen.io/Eli92/pen/WXXbRa

I can just use my own css class for this input, but I want to know what's happening here, and I'm too much of a beginner to submit a bug report.

The reason I want to remove the outline is to add my own to an outer element, like Youtube and most popular sites do for their search bar.

Body:
Actually, a border and box-shadow are applied to every form-control when focused, so setting

.form-control:focus {
  border: none;
  box-shadow: none;
}

should remove the styling


问:
codeigniter validate numbers and decimals
Is it possible to validate both numbers and decimal values using codeigniter validations class?

Coz i need to give the user to enter either a number or a decimal value. Eg: 10 or 1.5 or 30.45

In codeigniter validation class it allows to either validate a number or decimal separately.

Can someone tell me how can this validation be done in codeigniter?

答:
You can try building your own callback or use the regex_match rule to do it like this:

```<code>$this->form_validation->set_rules('cost', 'Cost', array('trim','required','min_length[1]','regex_match[/(^\d+|^\d+[.]\d+)+$/]'));
</code>```

You have to use the array way to set the rules because the regex rule uses a pipe ( | ).

Body:
You can try building your own callback or use the regex_match rule to do it like this:

$this->form_validation->set_rules('cost', 'Cost', array('trim','required','min_length[1]','regex_match[/(^\d+|^\d+[.]\d+)+$/]'));

You have to use the array way to set the rules because the regex rule uses a pipe ( | ).


问:
In a multithreaded (Java or .Net) program, can I assume that copying a variable is atomic?
I was worrying about race conditions in an application I'm designing, when I was wondering about this question.

Let's say I have a large array or collection of some sort that is managed by one component of my program, let's call that component Monitor. Its job is to regularly check if the collection is "dirty", i. e. has changed recently, and if so, write a snapshot to disk (this is to checkpoint the application in case a crash occurs) and mark it as clean again.

Other components of the same program, running in a different thread, call the Monitor's methods to add data to or modify data in the array/collection. Those methods mark the collection as dirty.

Now, the altering methods run in the other components' threads, right? And if I'm not so lucky, they might be called while the snapshot is written to disk, change data that has already been written, set the dirty flag and the Monitor's thread unsets it just after that, without having saved the changes (it was already past the element when it changed). So I have a dirty collection that's marked as clean.

For a while, I thought that I could maybe solve the problem by making a temporary copy of the collection, mark it clean and then go and serialize the copy. But would the copying be atomic, i. e. can I be sure that the collection will not change while I'm copying it?

Meanwhile, I think I have found better solutions, like

setting a lock flag before beginning the write to disk and make the data altering methods wait until the flag is unset

have the data altering methods write to a "change queue" instead of directly to the collection and have the thread that does the disk writing process that queue

and I think the lock flag might be the best way to go. But I'm still curious: Is copying a variable atomic?

Follow-up: Maybe this should go in a question of its own, but actually it's very much the same. According to the answers below, my "lock flag" approach might also not work, right? Because the data altering method might check the lock flag while it is being set to the "locked" value and decide it's not locked. So I need a special construction like a mutex if I really want to do this right, correct?

Kudos to erickson for his very helpful answer on my follow-up. I really should have made this two questions so I could have accepted two answers. Please, vote him up, too.

答:
You need to be concerned about the visibility of changes to other threads when working on the JVM. In general, you should make your assignments within a synchronized block, or the variable should be volatile, or you should use a variable wrapper from the java.util.concurrent.atomic package.

However, in your case, it sounds like you have just one thread that ever clears the "dirty" flag—the thread that persists the data. If that's the case, clear the flag before writing the data. If other threads set it while you are writing the data, it will stay set until the next scheduled write. I'd use an AtomicBoolean, to give your persistence thread atomicity between checking the flag and clearing it, like this:

```<code>private final AtomicBoolean dirty = new AtomicBoolean();

/**
 * Any method that modifies the data structure should set the dirty flag.
 */
public void modify() {
  /* Modify the data first. */
  ...
  /* Set the flag afterward. */
  dirty.set(true);
}

private class Persister extends Thread {
  public void run() {
    while (!Thread.interrupted()) {
      if (dirty.getAndSet(false)) {
        /* The dirty flag was set; this thread cleared it
         * and should now persist the data. */
         ...
      }
    }
  }
}
</code>```

OwnerDisplayName: Hanno

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Hanno

Body:
You need to be concerned about the visibility of changes to other threads when working on the JVM. In general, you should make your assignments within a synchronized block, or the variable should be volatile, or you should use a variable wrapper from the java.util.concurrent.atomic package.

However, in your case, it sounds like you have just one thread that ever clears the "dirty" flag—the thread that persists the data. If that's the case, clear the flag before writing the data. If other threads set it while you are writing the data, it will stay set until the next scheduled write. I'd use an AtomicBoolean, to give your persistence thread atomicity between checking the flag and clearing it, like this:

private final AtomicBoolean dirty = new AtomicBoolean();

/**
 * Any method that modifies the data structure should set the dirty flag.
 */
public void modify() {
  /* Modify the data first. */
  ...
  /* Set the flag afterward. */
  dirty.set(true);
}

private class Persister extends Thread {
  public void run() {
    while (!Thread.interrupted()) {
      if (dirty.getAndSet(false)) {
        /* The dirty flag was set; this thread cleared it
         * and should now persist the data. */
         ...
      }
    }
  }
}

OwnerDisplayName: erickson


问:
DebugBreak() equivalent in C#
In C# is there any statement equivalent to DebugBreak()? I want to invoke the debugger when ever a particular condition is met.

答:
```<code>System.Diagnostics.Debugger.Break();

//Lauches the JIT debug window
System.Diagnostics.Debugger.Launch();
</code>```

This is particularly useful when debugging a service as you get the Just In Time debugger window and can then select the visual studio window to debug the service in.

ContentLicense: CC BY-SA 4.0

Title: DebugBreak() equivalent in C#

Body:
System.Diagnostics.Debugger.Break();

//Lauches the JIT debug window
System.Diagnostics.Debugger.Launch();

This is particularly useful when debugging a service as you get the Just In Time debugger window and can then select the visual studio window to debug the service in.


问:
Subclassing UIBarButtonItem with touchesBegan action
I'm trying to create a sub class of UIBarButtonItem that I can use in Storyboards/Xibs where for the touchesBegan action can be listened (to play a button sound right on touching the buttons). Here's what I got:

```<code>class UIAudibleBarButtonItem : UIBarButtonItem {
    override init()     {
        super.init()
        target = self
        action = "touchesBegan:"
    }

    required init(coder aDecoder:NSCoder) {
        super.init(coder: aDecoder)
    }

    func touchesBegan(touches:NSSet, withEvent event:UIEvent) {
        AudioManager.instance.playButtonSound()
    }
}
</code>```

However it doesn't work, i.e. touchesBegan isn't called. What do I need to change to make this work?

UPDATE:

```<code>class UIAudibleBarButtonItem : UIBarButtonItem {
    override init() {
        super.init();
        setup();
    }

    override init(barButtonSystemItem systemItem: UIBarButtonSystemItem, target: AnyObject?, action: Selector) {
        super.init(barButtonSystemItem: systemItem, target: target, action: action);
        setup();
    }

    override init(image: UIImage?, landscapeImagePhone: UIImage?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) {
        super.init(image: image, landscapeImagePhone: landscapeImagePhone, style: style, target: target, action: action);
        setup();
    }

    override init(image: UIImage?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) {
        super.init(image: image, style: style, target: target, action: action);
        setup();
    }

    override init(title: String?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) {
        super.init(title: title, style: style, target: target, action: action);
        setup();
    }

    override init(customView:UIView) {
        super.init(customView: customView);
        setup();
    }

    required init(coder aDecoder:NSCoder) {
        super.init(coder: aDecoder);
        setup();
    }

    private func setup()
    {
        target = self;
        action = "buttonPressed:";
        println("setup()");
    }

    func buttonPressed(sender:AnyObject)
    {
        AudioManager.instance.playButtonSound();
        println("buttonPressed()");
    }
}
</code>```

答:
If your using swift here's an easy way to detect actions below. All you have to do is hook up that class in your storyboard click on your bar button item you will see the action fire.

Thank me later!!!

```<code>class MVBarbuttonItem: UIBarButtonItem {

    override func awakeFromNib() {
        self.action = #selector(MVBarbuttonItem.didTapButton)
    }

    @objc func didTapButton() {

    }

}
</code>```

Body:
I'm trying to create a sub class of UIBarButtonItem that I can use in Storyboards/Xibs where for the touchesBegan action can be listened (to play a button sound right on touching the buttons). Here's what I got:

class UIAudibleBarButtonItem : UIBarButtonItem {
    override init()     {
        super.init()
        target = self
        action = "touchesBegan:"
    }

    required init(coder aDecoder:NSCoder) {
        super.init(coder: aDecoder)
    }

    func touchesBegan(touches:NSSet, withEvent event:UIEvent) {
        AudioManager.instance.playButtonSound()
    }
}

However it doesn't work, i.e. touchesBegan isn't called. What do I need to change to make this work?

UPDATE:

class UIAudibleBarButtonItem : UIBarButtonItem {
    override init() {
        super.init();
        setup();
    }

    override init(barButtonSystemItem systemItem: UIBarButtonSystemItem, target: AnyObject?, action: Selector) {
        super.init(barButtonSystemItem: systemItem, target: target, action: action);
        setup();
    }

    override init(image: UIImage?, landscapeImagePhone: UIImage?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) {
        super.init(image: image, landscapeImagePhone: landscapeImagePhone, style: style, target: target, action: action);
        setup();
    }

    override init(image: UIImage?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) {
        super.init(image: image, style: style, target: target, action: action);
        setup();
    }

    override init(title: String?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) {
        super.init(title: title, style: style, target: target, action: action);
        setup();
    }

    override init(customView:UIView) {
        super.init(customView: customView);
        setup();
    }

    required init(coder aDecoder:NSCoder) {
        super.init(coder: aDecoder);
        setup();
    }

    private func setup()
    {
        target = self;
        action = "buttonPressed:";
        println("setup()");
    }

    func buttonPressed(sender:AnyObject)
    {
        AudioManager.instance.playButtonSound();
        println("buttonPressed()");
    }
}

Body:
If your using swift here's an easy way to detect actions below. All you have to do is hook up that class in your storyboard click on your bar button item you will see the action fire.

Thank me later!!!

class MVBarbuttonItem: UIBarButtonItem {

    override func awakeFromNib() {
        self.action = #selector(MVBarbuttonItem.didTapButton)
    }

    @objc func didTapButton() {

    }

}


问:
Create a column based on other columns value
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

```<code>WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |
</code>```

To this:

```<code>WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |
</code>```

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?

答:
You can use 'data.table' packages and merge function:</p>

```<code>    library(data.table)
    df2 <- setDT(df)[, .SD[which.max(SCORE)], Cluster]
    result <- merge(df, df2[, c('Cluster', 'WORD')], by='Cluster')
</code>```

Body:
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |

To this:

WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?

Body:
You can use 'data.table' packages and merge function:

    library(data.table)
    df2 <- setDT(df)[, .SD[which.max(SCORE)], Cluster]
    result <- merge(df, df2[, c('Cluster', 'WORD')], by='Cluster')


问:
Canon SDK (EDSDK) capture region of specified size for video stream
I am very new to the EDSDK so sorry for maybe weird question in some places.

Is it possible to access a video stream and perform some operations on it using the SDK? I need this to capture very thin region (ROI) of a specified size (for example 3840x10 px) for each frame in the stream. Don`t understand this as compression of a frame, aspect ratios are not needed to follow. These changes in theory should increase fps, because the  region will be very thin (Should they?).

I found the code snippet below from the official documentation, although it seems this causes only to send a signal for starting and stopping video rec, without accessing the stream.

```<code>EdsUInt32 record_start = 4; // Begin movie shooting
err = EdsSetPropertyData(cameraRef, kEdsPropID_Record, 0, sizeof(record_start), &record_start);
EdsUInt32 record_stop = 0; // End movie shooting
err = EdsSetPropertyData(cameraRef, kEdsPropID_Record, 0, sizeof(record_stop), &record_stop);
</code>```

I would be very thanksful for any suggestions and help. Please feel free to ask any additional information!

答: This sdk doesnt allow you to directly get access to hi res streams like industrial cams would. You can access over USB ~960x640 liveview images in sequential JPGs. Movie recording can only be done to internal card, and after stopping transfering the result. Outside of this SDk, use of an external HDMI recorder gives access to a near realtime feed at max FullHD1080p, depending on model and not always “clean”.</p>

Body:
I am very new to the EDSDK so sorry for maybe weird question in some places.

Is it possible to access a video stream and perform some operations on it using the SDK? I need this to capture very thin region (ROI) of a specified size (for example 3840x10 px) for each frame in the stream. Don`t understand this as compression of a frame, aspect ratios are not needed to follow. These changes in theory should increase fps, because the  region will be very thin (Should they?).

I found the code snippet below from the official documentation, although it seems this causes only to send a signal for starting and stopping video rec, without accessing the stream.

EdsUInt32 record_start = 4; // Begin movie shooting
err = EdsSetPropertyData(cameraRef, kEdsPropID_Record, 0, sizeof(record_start), &record_start);
EdsUInt32 record_stop = 0; // End movie shooting
err = EdsSetPropertyData(cameraRef, kEdsPropID_Record, 0, sizeof(record_stop), &record_stop);

I would be very thanksful for any suggestions and help. Please feel free to ask any additional information!


问:
Why does python __file__ variable returns errorneous path when used in DJango?

I was trying to retrieve the file path using python __file__ variable under django though i am getting correct path. It's behavior is little weird. Here is my attached sample code please let me know why is the behavior so.

```<code>from django.shortcuts import render_to_response
import datetime

class WebServer():

    def __init__(self):
        pass

    def display_first_page(self, request):

        print "File Path: ", __file__
        return render_to_response('Hello')
</code>```

I have stored this code at the given location : C:\Django_example\MySample. Ideally it should have returned something like C:\Django_example\MySample\webserver.py, but instead i am getting C:\Django_example\MySample\..\MySample\webserver.py . Can someone please point me to the right direction.

Thanks in advance,

Rupesh

答:
As far as I can see, C:\Django_example\MySample\webserver.py and C:\Django_example\MySample\..\MySample\webserver.py points to the same file, so it isn't errorneous.

If you want a more succinct representation of the path, try:

```<code>import os
print "File Path: ", os.path.realpath(__file__)
</code>```

update (an attempt to understand the output of __file__)

The only way I can reproduce that behaviour is if I update sys.path. Example:

```<code>[me@home]$ cd /project/django/xyz
[me@home]$ ./manage.py shell
(InteractiveConsole)
>>> from app import models as M
>>> M.__file__
'/project/django/xyz/app/models.pyc'
>>> import sys
>>> sys.path.append('../')
>>> from xyz.app import models as N
>>> N.__file__
'/project/django/xyz/../xyz/app/models.pyc'
</code>```

Since the absolute path is formed by appending the relative path to the base path, I suspect you might have a /../ somewhere in your python path.

What do you get when you print sys.path from your view?

Body:
I was trying to retrieve the file path using python __file__ variable under django though i am getting correct path. It's behavior is little weird. Here is my attached sample code please let me know why is the behavior so.

from django.shortcuts import render_to_response
import datetime

class WebServer():

    def __init__(self):
        pass

    def display_first_page(self, request):

        print "File Path: ", __file__
        return render_to_response('Hello')

I have stored this code at the given location : C:\Django_example\MySample. Ideally it should have returned something like C:\Django_example\MySample\webserver.py, but instead i am getting C:\Django_example\MySample\..\MySample\webserver.py . Can someone please point me to the right direction.

Thanks in advance,

Rupesh

Body:
As far as I can see, C:\Django_example\MySample\webserver.py and C:\Django_example\MySample\..\MySample\webserver.py points to the same file, so it isn't errorneous.

If you want a more succinct representation of the path, try:

import os
print "File Path: ", os.path.realpath(__file__)

update (an attempt to understand the output of __file__)

The only way I can reproduce that behaviour is if I update sys.path. Example:

[me@home]$ cd /project/django/xyz
[me@home]$ ./manage.py shell
(InteractiveConsole)
>>> from app import models as M
>>> M.__file__
'/project/django/xyz/app/models.pyc'
>>> import sys
>>> sys.path.append('../')
>>> from xyz.app import models as N
>>> N.__file__
'/project/django/xyz/../xyz/app/models.pyc'

Since the absolute path is formed by appending the relative path to the base path, I suspect you might have a /../ somewhere in your python path.

What do you get when you print sys.path from your view?


问:
Why is password authentication failing when md5 hashing passwords in AWS Redshift?
I'm trying to create a new user on my AWS Redshift cluster. I followed the documentation when creating the user and hashing the password, but I keep getting authentication failures when trying to sign in using the real password.

Some example details of what I did:

To create the hash from the bash shell on a mac:

```<code>echo -n "my_userMyPassword1" | md5
1ce2ff3ac550ebd14b9fbf01e91d84cd
</code>```

And then on the redshift cluster as the superuser:

```<code>CREATE USER my_user PASSWORD 'md51ce2ff3ac550ebd14b9fbf01e91d84cd' CONNECTION LIMIT 20;
</code>```

When I try logging in as the user from the command line, I get the following error message:

```<code>psql -h mycluster.myregion.redshift.amazonaws.com -p 1234 -U my_user myredshiftdb
Password for user my_user:
psql: FATAL:  password authentication failed for user "my_user"
FATAL:  password authentication failed for user "my_user"
</code>```

I verified that the hash is correct using the redshift md5 function. I also created the account when not hashing the password, and I could successfully login. I've tried variants of the password (making it super simple and short) to no avail.

Here's the redshift version I'm using:

```<code>SELECT VERSION();
                                                         version
--------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 8.0.2 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3), Redshift 1.0.1499
(1 row)
</code>```

答:
You are creating the user / password hash reversed. The password goes first followed by the user.

echo -n "MyPassword1my_user" | md5

Body:
I'm trying to create a new user on my AWS Redshift cluster. I followed the documentation when creating the user and hashing the password, but I keep getting authentication failures when trying to sign in using the real password.

Some example details of what I did:

To create the hash from the bash shell on a mac:

echo -n "my_userMyPassword1" | md5
1ce2ff3ac550ebd14b9fbf01e91d84cd

And then on the redshift cluster as the superuser:

CREATE USER my_user PASSWORD 'md51ce2ff3ac550ebd14b9fbf01e91d84cd' CONNECTION LIMIT 20;

When I try logging in as the user from the command line, I get the following error message:

psql -h mycluster.myregion.redshift.amazonaws.com -p 1234 -U my_user myredshiftdb
Password for user my_user:
psql: FATAL:  password authentication failed for user "my_user"
FATAL:  password authentication failed for user "my_user"

I verified that the hash is correct using the redshift md5 function. I also created the account when not hashing the password, and I could successfully login. I've tried variants of the password (making it super simple and short) to no avail.

Here's the redshift version I'm using:

SELECT VERSION();
                                                         version
--------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 8.0.2 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3), Redshift 1.0.1499
(1 row)


问:
Understanding FoldLeft in ScalaZ
I'm reading some articles about ScalaZ and have a question about understanding it. In this article, we generalize the sum function, to abstract away the type to be summed.

```<code>def sum[T](xs: List[T])(implicit m: Monoid[T]) = //...
</code>```

Where

trait Monoid[A] is defined as follows:

```<code>trait Monoid[A] {
  def mappend(a1: A, a2: A): A
  def mzero: A
}
</code>```

Yes, this is pretty clear. Monoid here corresponds to the algebraic monoid structure. Now in this article it abstracts over lists. To do this we define the following trait:

```<code>trait FoldLeft[F[_]] {
  def foldLeft[A, B](xs: F[A], b: B, f: (B, A) => B): B
}
object FoldLeft {
  implicit val FoldLeftList: FoldLeft[List] = new FoldLeft[List] {
    def foldLeft[A, B](xs: List[A], b: B, f: (B, A) => B) = xs.foldLeft(b)(f)
  }
}
</code>```

So now we can define the sum function as follows:

```<code>def sum[M[_]: FoldLeft, A: Monoid](xs: M[A]): A = {
  val m = implicitly[Monoid[A]]
  val fl = implicitly[FoldLeft[M]]
  fl.foldLeft(xs, m.mzero, m.mappend)
}
</code>```

I'm not a theory category expert, but it looks like Applicative functor to me. Is that correct? Can we provide such similarity to category theory.

答:
Applicative functor is a type class with two operations: A => F[A] and F[A => B] => F[A] => F[B]. None of operations you mentioned has such signature. FoldLeft is more like Foldable. It's a different type class, a parent of Traversable (aka Traverse). And Traversable is connected with Applicative.

```<code>trait Functor[F[_]] {
  def fmap[A, B](f: A => B)(fa: F[A]): F[B]
}

trait Applicative[F[_]] extends Functor[F] {
  def pure[A](a: A): F[A]
  def ap[A, B](ff: F[A => B])(fa: F[A]): F[B]
  override def fmap[A, B](f: A => B)(fa: F[A]): F[B] = ap(pure(f))(fa)
}

trait Foldable[T[_]] {
  def foldr[A, B](op: A => B => B)(seed: B)(ta: T[A]): B =
    (foldMap(op)(ta) _)(seed)
  def foldMap[A, M](f: A => M)(ta: T[A])(implicit monoid: Monoid[M]): M =
    foldr[A, M](a => m => monoid.append(f(a), m))(monoid.empty)(ta)
}

trait Traversable[T[_]] extends Functor[T] with Foldable[T] {
  def traverse[F[_]: Applicative, A, B](k: A => F[B])(ta: T[A]): F[T[B]] =
    sequence[F, B](fmap[A, F[B]](k)(ta))
  def sequence[F[_]: Applicative, A](tfa: T[F[A]]): F[T[A]] =
    traverse[F, F[A], A](fa => fa)(tfa)
  override def fmap[A, B](f: A => B)(ta: T[A]): T[B] = traverse[Id, A, B](f)(ta)
  override def foldr[A, B](op: A => B => B)(seed: B)(ta: T[A]): B =
    (traverse[Const[B => B]#λ, A, B](op)(ta) _)(seed)
  override def foldMap[A, M: Monoid](f: A => M)(ta: T[A]): M =
    traverse[Const[M]#λ, A, M](f)(ta)
}

type Id[A] = A

trait Const[C] {
  type λ[A] = C
}
</code>```

Type class Functor means you have a "container" F[_] and you know how to apply function f: A => B inside this container. Type class Applicative means you know how to pack a value a: A inside this container and how to apply a "function" F[A => B] to a "value" F[A]. Foldable means you know how to fold your container using binary operation A => B => B and starting value B and receiving result B. Traversable means you know how to traverse your container executing applicative effect A => F[B] in every "node".

Title: Understanding FoldLeft in ScalaZ

Body:
I'm reading some articles about ScalaZ and have a question about understanding it. In this article, we generalize the sum function, to abstract away the type to be summed.

def sum[T](xs: List[T])(implicit m: Monoid[T]) = //...

Where

trait Monoid[A] is defined as follows:

trait Monoid[A] {
  def mappend(a1: A, a2: A): A
  def mzero: A
}

Yes, this is pretty clear. Monoid here corresponds to the algebraic monoid structure. Now in this article it abstracts over lists. To do this we define the following trait:

trait FoldLeft[F[_]] {
  def foldLeft[A, B](xs: F[A], b: B, f: (B, A) => B): B
}
object FoldLeft {
  implicit val FoldLeftList: FoldLeft[List] = new FoldLeft[List] {
    def foldLeft[A, B](xs: List[A], b: B, f: (B, A) => B) = xs.foldLeft(b)(f)
  }
}

So now we can define the sum function as follows:

def sum[M[_]: FoldLeft, A: Monoid](xs: M[A]): A = {
  val m = implicitly[Monoid[A]]
  val fl = implicitly[FoldLeft[M]]
  fl.foldLeft(xs, m.mzero, m.mappend)
}

I'm not a theory category expert, but it looks like Applicative functor to me. Is that correct? Can we provide such similarity to category theory.

Body:
Applicative functor is a type class with two operations: A => F[A] and F[A => B] => F[A] => F[B]. None of operations you mentioned has such signature. FoldLeft is more like Foldable. It's a different type class, a parent of Traversable (aka Traverse). And Traversable is connected with Applicative.

trait Functor[F[_]] {
  def fmap[A, B](f: A => B)(fa: F[A]): F[B]
}

trait Applicative[F[_]] extends Functor[F] {
  def pure[A](a: A): F[A]
  def ap[A, B](ff: F[A => B])(fa: F[A]): F[B]
  override def fmap[A, B](f: A => B)(fa: F[A]): F[B] = ap(pure(f))(fa)
}

trait Foldable[T[_]] {
  def foldr[A, B](op: A => B => B)(seed: B)(ta: T[A]): B =
    (foldMap(op)(ta) _)(seed)
  def foldMap[A, M](f: A => M)(ta: T[A])(implicit monoid: Monoid[M]): M =
    foldr[A, M](a => m => monoid.append(f(a), m))(monoid.empty)(ta)
}

trait Traversable[T[_]] extends Functor[T] with Foldable[T] {
  def traverse[F[_]: Applicative, A, B](k: A => F[B])(ta: T[A]): F[T[B]] =
    sequence[F, B](fmap[A, F[B]](k)(ta))
  def sequence[F[_]: Applicative, A](tfa: T[F[A]]): F[T[A]] =
    traverse[F, F[A], A](fa => fa)(tfa)
  override def fmap[A, B](f: A => B)(ta: T[A]): T[B] = traverse[Id, A, B](f)(ta)
  override def foldr[A, B](op: A => B => B)(seed: B)(ta: T[A]): B =
    (traverse[Const[B => B]#λ, A, B](op)(ta) _)(seed)
  override def foldMap[A, M: Monoid](f: A => M)(ta: T[A]): M =
    traverse[Const[M]#λ, A, M](f)(ta)
}

type Id[A] = A

trait Const[C] {
  type λ[A] = C
}

Type class Functor means you have a "container" F[_] and you know how to apply function f: A => B inside this container. Type class Applicative means you know how to pack a value a: A inside this container and how to apply a "function" F[A => B] to a "value" F[A]. Foldable means you know how to fold your container using binary operation A => B => B and starting value B and receiving result B. Traversable means you know how to traverse your container executing applicative effect A => F[B] in every "node".


问:
error docker: invalid reference format. when execute docker run
Complete command is

docker run --name mynginx2 -v /var/www:/usr/share/nginx/html:ro \ -v /var/nginx/conf:/etc/nginx:ro -P -d nginx

Why its not working?

I found it here https://blog.docker.com/2015/04/tips-for-deploying-nginx-official-image-with-docker/

Thanks

答:
\ is breaking up the command

Run the whole thing without the '\'

docker run --name mynginx2 -v /var/www:/usr/share/nginx/html:ro -v /var/nginx
/conf:/etc/nginx:ro -P -d nginx


问:
For Integer type variable, does '=' operator equate the value or the reference?
CODE 1 :

```<code>Car car1 = new Car();
Car car2 = new Car();
car2.setColor("Green");
car2.setModel("I20");
car1 = car2;
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());
car1.setColor("Red");
car1.setModel("I10");
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());
</code>```

Output :

```<code>Green , I20
Green , I20
Red , I10
Red , I10
</code>```

Here the car1 = car2; make the car1 object refer to car2 object thus any further change to car1 is equivalent to changing the car2 object as both are referencing to same value.

CODE 2 :

```<code>Integer c = 5;
Integer d = 10;
System.out.println(c + ", " + d);
c = d;
System.out.println(c + ", " + d);
c = 7;
System.out.println(c + ", " + d);
</code>```

Output :

```<code>5, 10
10, 10
7, 10
</code>```

Here also after c = d; both c and d refer to the same value then why changing the value of c does not change the value of d?

答:
Integer is immutable. This means it cannot be changed that way. You are not allowed to change its internal fields. You are not allowed to change to what place in the memory it points to, but you are able to change the value that is assigned to the reference of given Integer. In example, when you write

```<code>Integer i = 5;
Integer j = 10;
i = j;
</code>```

this doesn't mean that from now i is pointing to the same place in the memory where j points. It just assigns the value stored in j to i, because only that is allowed for immutable types.

Body:
CODE 1 :

Car car1 = new Car();
Car car2 = new Car();
car2.setColor("Green");
car2.setModel("I20");
car1 = car2;
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());
car1.setColor("Red");
car1.setModel("I10");
System.out.println(car1.getColor() + " , " + car1.getModel());
System.out.println(car2.getColor() + " , " + car2.getModel());

Output :

Green , I20
Green , I20
Red , I10
Red , I10

Here the car1 = car2; make the car1 object refer to car2 object thus any further change to car1 is equivalent to changing the car2 object as both are referencing to same value.

CODE 2 :

Integer c = 5;
Integer d = 10;
System.out.println(c + ", " + d);
c = d;
System.out.println(c + ", " + d);
c = 7;
System.out.println(c + ", " + d);

Output :

5, 10
10, 10
7, 10

Here also after c = d; both c and d refer to the same value then why changing the value of c does not change the value of d?

Body:
Integer is immutable. This means it cannot be changed that way. You are not allowed to change its internal fields. You are not allowed to change to what place in the memory it points to, but you are able to change the value that is assigned to the reference of given Integer. In example, when you write

Integer i = 5;
Integer j = 10;
i = j;

this doesn't mean that from now i is pointing to the same place in the memory where j points. It just assigns the value stored in j to i, because only that is allowed for immutable types.


问:
React Router v4 <NavLink> vs <Link> benefits
Besides the ability to set an "activeClassName" and "activeStyle" on NavLink, is there any reason to use NavLink over Link when creating links to other routes on non-navigational elements (ie. not main nav in header or footer) on your site that don't need an active state/class?

答:
The official documentation is clear:

<NavLink>

A special version of the <Link> that will add styling attributes to the  rendered element when it matches the current URL.

Thus, the answer is NO. There are no other reasons except the mentioned one.


问:
Data on axis is not in expected order
I'm trying to plot some data on a graph, but when I do if I use data_list, it's all wonky.

```<code>import numpy as np
from numpy import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

data_list = [('January', 1645480), ('February', 1608476), ('March', 1557113), ('April', 1391652), ('May', 1090298), ('July', 1150535), ('August', 1125931), ('September', 1158741), ('October', 1305849), ('November', 1407438), ('December', 1501733)]
working_list = [('April', 1391652), ('August', 1125931), ('December', 1501733), ('February', 1608476), ('January', 1645480), ('July', 1150535), ('March', 1557113), ('May', 1090298), ('November', 1407438), ('October', 1305849), ('September', 1158741)]

#### GRAPHING
def create_graph(data):
    x, y = zip(*data)
    plt.plot(x,y)
    axes = plt.gca() # Get the Current Axes
    axes.get_yaxis().get_major_formatter().set_scientific(False)  # Turn off scientific
    # Show data on Y axis points
    for i, j in zip(x,y):
        plt.annotate(str(j),xy=(i,j))
    plt.show()

def main():
## Graphing
    create_graph(working_list)

if __name__ == "__main__":
    main()
</code>```

But if I use working_list, it's correct! (It's in the order of the list. I'm simply trying to get the data to show from Jan - December on X-axis)

I've been staring at this for too long -- the data looks to be the exact same in each list, only data_list has "January" first, through December...I'm not sure why that would throw off the graph like it does.  I did notice that the X-Axis months and the data on the Y axis are correct -- but the line connector is all off, as is the order I expected...

答:
Matplotlib draws lines from point to point in the order that you provide them.

Ticks on the Axes are sorted according to the type of x-values passed (e.g., numerical for quantities, alphabetical for caetgories, chronologically for dates).

If you want to plot these values as dates, you need to pass actual dates to the plot method.

So reading between the lines and assuming you want your x-axis to go from January to December and the lines drawn accordingly, here's how I'd do it:

```<code>from datetime import datetime

from matplotlib import pyplot
from matplotlib import dates

raw_list = [('April', 1391652), ('August', 1125931), ('December', 1501733), ('February', 1608476), ('January', 1645480), ('July', 1150535), ('March', 1557113), ('May', 1090298), ('November', 1407438), ('October', 1305849), ('September', 1158741)]
sorted_list = sorted(working_list, key=lambda x: datetime.strptime(x[0], '%B'))

def create_graph(data):
    fig, ax = pyplot.subplots()
    _x, y = zip(*data)
    x = [datetime.strptime(month, '%B') for month in _x]
    ax.plot(x, y)

    ax.yaxis.get_major_formatter().set_scientific(False)  # Turn off scientific
    ax.xaxis.set_major_locator(dates.MonthLocator(interval=1))
    ax.xaxis.set_major_formatter(dates.DateFormatter('%B'))

    for tick in ax.xaxis.get_ticklabels():
        tick.set_rotation(45)
        tick.set_rotation_mode('anchor')
        tick.set_horizontalalignment('right')

    for i, j in zip(x,y):
        ax.annotate(str(j), xy=(i, j))
    return fig
</code>```

So create_graph(raw_list) does this:

And So create_graph(sorted_list) does this:

Title: Data on axis is not in expected order

Body:
I'm trying to plot some data on a graph, but when I do if I use data_list, it's all wonky.

import numpy as np
from numpy import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker

data_list = [('January', 1645480), ('February', 1608476), ('March', 1557113), ('April', 1391652), ('May', 1090298), ('July', 1150535), ('August', 1125931), ('September', 1158741), ('October', 1305849), ('November', 1407438), ('December', 1501733)]
working_list = [('April', 1391652), ('August', 1125931), ('December', 1501733), ('February', 1608476), ('January', 1645480), ('July', 1150535), ('March', 1557113), ('May', 1090298), ('November', 1407438), ('October', 1305849), ('September', 1158741)]

#### GRAPHING
def create_graph(data):
    x, y = zip(*data)
    plt.plot(x,y)
    axes = plt.gca() # Get the Current Axes
    axes.get_yaxis().get_major_formatter().set_scientific(False)  # Turn off scientific
    # Show data on Y axis points
    for i, j in zip(x,y):
        plt.annotate(str(j),xy=(i,j))
    plt.show()

def main():
## Graphing
    create_graph(working_list)

if __name__ == "__main__":
    main()

But if I use working_list, it's correct! (It's in the order of the list. I'm simply trying to get the data to show from Jan - December on X-axis)

I've been staring at this for too long -- the data looks to be the exact same in each list, only data_list has "January" first, through December...I'm not sure why that would throw off the graph like it does.  I did notice that the X-Axis months and the data on the Y axis are correct -- but the line connector is all off, as is the order I expected...

Body:
Matplotlib draws lines from point to point in the order that you provide them.

Ticks on the Axes are sorted according to the type of x-values passed (e.g., numerical for quantities, alphabetical for caetgories, chronologically for dates).

If you want to plot these values as dates, you need to pass actual dates to the plot method.

So reading between the lines and assuming you want your x-axis to go from January to December and the lines drawn accordingly, here's how I'd do it:

from datetime import datetime

from matplotlib import pyplot
from matplotlib import dates

raw_list = [('April', 1391652), ('August', 1125931), ('December', 1501733), ('February', 1608476), ('January', 1645480), ('July', 1150535), ('March', 1557113), ('May', 1090298), ('November', 1407438), ('October', 1305849), ('September', 1158741)]
sorted_list = sorted(working_list, key=lambda x: datetime.strptime(x[0], '%B'))

def create_graph(data):
    fig, ax = pyplot.subplots()
    _x, y = zip(*data)
    x = [datetime.strptime(month, '%B') for month in _x]
    ax.plot(x, y)

    ax.yaxis.get_major_formatter().set_scientific(False)  # Turn off scientific
    ax.xaxis.set_major_locator(dates.MonthLocator(interval=1))
    ax.xaxis.set_major_formatter(dates.DateFormatter('%B'))

    for tick in ax.xaxis.get_ticklabels():
        tick.set_rotation(45)
        tick.set_rotation_mode('anchor')
        tick.set_horizontalalignment('right')

    for i, j in zip(x,y):
        ax.annotate(str(j), xy=(i, j))
    return fig

So create_graph(raw_list) does this:

And So create_graph(sorted_list) does this:


问:
How should I pass a variable to another class?
I have declared a variable  named public static  String parameterForURL which I need to pass SendRequest class so that total URL would be together like
URL=http://www.eurekabd.com/shakil/home.php/?+shaki,123.
But Server is receiving  /shakil/shakil.php/?[Ljava.lang.String;@ce6cdf7

```<code>public static  String parameterForURL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
    parameterForURL ="shakil,123";

    doorOpenButtonActionClass.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new SendRequest().execute();
            resultContainer="";
        }
    });
}

public class SendRequest extends AsyncTask<String, Void, String> {

    protected String doInBackground(String[] paramparameterForURL) {

        Log.v("Passed=",paramparameterForURL.toString());

        try{
            Log.v("Passed=",paramparameterForURL.toString());
            //String serv_url="http://www.eurekabd.com/shakil/home.php"+paramparameterForURL.toString();

            serv_url="http://192.168.0.109/shakil/shakil.php/?"+paramparameterForURL;
            //serv_url += paramparameterForURL;
            Log.e("Server Url",serv_url.toString());
            URL url = new URL(serv_url);
        }
    }
}
</code>```

**How to make can i pass this paramparameterForURL variable so that i can get my desired out put **

答:
The problem is that you are doing paramparameterForURL.toString(). Since paramparameterForURL is a String array, it's toString method will not return it's contents but an identifier like [Ljava.lang.String;@ce6cdf7. That's the class name, an @ sign and then the hash code of the object. Therefore the server will receive

/shakil/shakil.php/?[Ljava.lang.String;@ce6cdf7

What you want to do is something like the following

```<code>public static  String parameterForURL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    parameterForURL ="shakil,123";

    doorOpenButtonActionClass.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new SendRequest().execute(parameterForURL);
            resultContainer="";
        }
    });
}

public class SendRequest extends AsyncTask<String, Void, String> {

    protected String doInBackground(String[] paramparameterForURL) {

        Log.v("Passed=",paramparameterForURL[0].toString());

        try{
            Log.v("Passed=",paramparameterForURL[0].toString());
            //String serv_url="http://www.eurekabd.com/shakil/home.php"+paramparameterForURL[0].toString();

            serv_url="http://192.168.0.109/shakil/shakil.php/?"+paramparameterForURL[0];
            //serv_url += paramparameterForURL;
            Log.e("Server Url",serv_url.toString());
            URL url = new URL(serv_url);
</code>```

You pass the parameterForURL as an argument to your AsyncTask and then in the async task you get the first item of the array, since you only specified one parameter.

Body:
I have declared a variable  named public static  String parameterForURL which I need to pass SendRequest class so that total URL would be together like
URL=http://www.eurekabd.com/shakil/home.php/?+shaki,123.
But Server is receiving  /shakil/shakil.php/?[Ljava.lang.String;@ce6cdf7

public static  String parameterForURL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
    parameterForURL ="shakil,123";

    doorOpenButtonActionClass.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new SendRequest().execute();
            resultContainer="";
        }
    });
}

public class SendRequest extends AsyncTask<String, Void, String> {

    protected String doInBackground(String[] paramparameterForURL) {

        Log.v("Passed=",paramparameterForURL.toString());

        try{
            Log.v("Passed=",paramparameterForURL.toString());
            //String serv_url="http://www.eurekabd.com/shakil/home.php"+paramparameterForURL.toString();

            serv_url="http://192.168.0.109/shakil/shakil.php/?"+paramparameterForURL;
            //serv_url += paramparameterForURL;
            Log.e("Server Url",serv_url.toString());
            URL url = new URL(serv_url);
        }
    }
}

**How to make can i pass this paramparameterForURL variable so that i can get my desired out put **

Body:
The problem is that you are doing paramparameterForURL.toString(). Since paramparameterForURL is a String array, it's toString method will not return it's contents but an identifier like [Ljava.lang.String;@ce6cdf7. That's the class name, an @ sign and then the hash code of the object. Therefore the server will receive

/shakil/shakil.php/?[Ljava.lang.String;@ce6cdf7

What you want to do is something like the following

public static  String parameterForURL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    parameterForURL ="shakil,123";

    doorOpenButtonActionClass.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new SendRequest().execute(parameterForURL);
            resultContainer="";
        }
    });
}

public class SendRequest extends AsyncTask<String, Void, String> {

    protected String doInBackground(String[] paramparameterForURL) {

        Log.v("Passed=",paramparameterForURL[0].toString());

        try{
            Log.v("Passed=",paramparameterForURL[0].toString());
            //String serv_url="http://www.eurekabd.com/shakil/home.php"+paramparameterForURL[0].toString();

            serv_url="http://192.168.0.109/shakil/shakil.php/?"+paramparameterForURL[0];
            //serv_url += paramparameterForURL;
            Log.e("Server Url",serv_url.toString());
            URL url = new URL(serv_url);

You pass the parameterForURL as an argument to your AsyncTask and then in the async task you get the first item of the array, since you only specified one parameter.


问:
How to perform TDD when developing a Django API
When doing TDD on a Django app API, I write tests demonstrating that when proper constraints are provided, expected results are achieved. How do I write tests for the infinite permutations of cases where inputs are 'wrong'.

Two things come to mind:

1) I shouldn't break the dynamic aspect of python by type-checking every input, and

2) I should be testing "interesting" functions or methods (not getters and setters), though I'm not sure how this applies to an API

答:
With TDD, a good way to stay sane is to write tests that cover the required number of valid inputs, have the tests fail because there's no code yet, write as little code as possible to make them pass, then refactor that code into something production-ready, while ensuring your tests still pass. Sounds like you've done that bit.

Then, in terms in invalid input-testing, I doubt that the choices really need to be infinite, and will fall into several cases that you can test reasonably well with just a few alternative inputs/arguments (eg: for an integer input, test passing a zero, negative integers, masssive/overflowing integers, characters).

Of course, that still takes time to work out and code up (even if you automate it by looping over a lists of variables and call the same test repeatedly with different inputs), and while it's definitely worth doing, if you want more, you can always look at something like fuzz testing for extra piece of mind.

PS. In terms of testing the API, I would focus on creating test queries against the API's exposed collections/resources (easy to do as unit tests with the Django test Client), and also directly unit test any non-trivial methods that the API uses under the covers. Getters and setters, etc, should then be implicitly tested by higher-level functions. In theory :o)


问:
Jenkins does not send emails to cell phone emails xxxxxxxxxx@tmomail.net and @vnet.com
We are using Jenkins 2.16, Email Extension Plugin 2.47, and Status Monitor Plugin in order to check our site to make sure it is up. The goal is to send an email to our cell phones to alert us that the check failed.

Everything works, but no one is getting texts!

Emails sent to name@ourcompany.com work. Emails sent to @gmail.com work! Emails going to 1234567899@tmomail.net do not work. I have a powershell on that server that sends an email to 1234567899@tmomail.net and I do get a text.

I tried the sms Jenkins plugin but it requires a paid membership and my company does not approve.

I will next try a hack where Jenkins calls the PS1 to run using the Powershell plugin ... but this is totally dumb and harder to manage. Impossible to manage on the Jenkins front end.

What gives?!? Any Ideas on how to make JUST Jenkins work ??
I see no errors on the console output: https://i.stack.imgur.com/1AT9M.png

This question is similar to
Integrating SMS service in Jenkins
... but no one has answered.

答:
Problem solved.

I had an email address for the Jenkins administrative address in my global settings that was bogus (no@reply.com). I changed it to a legit company email and texts are now being sent.

I got this solution by posting a bug on the Jenkins forum and they gave me some possible solutions there.


问:
How do I add csv file data into a dictionary
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

```<code>ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30
</code>```

For example if I called the ID: "12345" it would display - Italy, 100, 80

答:
```<code>csv = """ID     |   Tour   | Start | End
12345  |  Italy   |  100  | 80
13579  |  China   |  50   | 30
24680  |  France  |  50   | 30"""

d = [[v.strip() for v in row.split('|')] for row in csv.split('\n')]
d = dict((row[0], row[1:]) for row in d)

print(d["12345"])
</code>```

Body:
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30

For example if I called the ID: "12345" it would display - Italy, 100, 80


问:
unexpected value in my feet to meters converter with pure javascript
//I'm trying to get a result in meters out of an input in feet.

```<code>            <div id="inner-wrapper">
                <label for="feet-input">Enter feet
                </label>
                <input type="number" id="feet-input" placeholder="Feet">

                <label for="result">Result
                </label>
                <div id="result"></div>

                <button id="calculate" onclick="calculate()">Calculate</button>
                <button id="clear" onclick="clear()">Clear</button>
            </div>
</code>```

//For any number I type I get 0 as answer.

```<code>        var feetInput = document.getElementById("feet-input").value;
        var result = document.getElementById("result");
        var total;

        function calculate(){
            total = feetInput * 0.3048;
            result.innerHTML = total;
            return total;

        }

            function clear(){
                feetInput.value = "";
                result.value = "";

            }

    //For any number I type get 0 as result.
</code>```

For any number I type get 0 as answer.

答:
Because your  var feetInput = document.getElementById("feet-input").value; is only executed once you need to fetch always latest value on function call as below

 //var feetInput = document.getElementById("feet-input").value;//only executed once
        var result = document.getElementById("result");
        var total;

        function calculate(){
        var feetInput = document.getElementById("feet-input").value;
            total = feetInput * 0.3048;
            result.innerHTML = total;
            return total;

        }

            function clear(){
                feetInput.value = "";
                result.value = "";

            }

    //For any number I type get 0 as result.```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="inner-wrapper">
                <label for="feet-input">Enter feet
                </label>
                <input type="number" id="feet-input" placeholder="Feet">

                <label for="result">Result
                </label>
                <div id="result"></div>

                <button id="calculate" onclick="calculate()">Calculate</button>
                <button id="clear" onclick="clear()">Clear</button>
            </div></code>```

Body:
//I'm trying to get a result in meters out of an input in feet.

                Enter feet

                <input type="number" id="feet-input" placeholder="Feet">

                Result

                <button id="calculate" onclick="calculate()">Calculate</button>
                <button id="clear" onclick="clear()">Clear</button>

//For any number I type I get 0 as answer.

        var feetInput = document.getElementById("feet-input").value;
        var result = document.getElementById("result");
        var total;

        function calculate(){
            total = feetInput * 0.3048;
            result.innerHTML = total;
            return total;

        }

            function clear(){
                feetInput.value = "";
                result.value = "";

            }

    //For any number I type get 0 as result.

For any number I type get 0 as answer.

Body:
Because your  var feetInput = document.getElementById("feet-input").value; is only executed once you need to fetch always latest value on function call as below

 //var feetInput = document.getElementById("feet-input").value;//only executed once
        var result = document.getElementById("result");
        var total;

        function calculate(){
        var feetInput = document.getElementById("feet-input").value;
            total = feetInput * 0.3048;
            result.innerHTML = total;
            return total;

        }

            function clear(){
                feetInput.value = "";
                result.value = "";

            }

    //For any number I type get 0 as result.

<div id="inner-wrapper">
                <label for="feet-input">Enter feet
                </label>
                <input type="number" id="feet-input" placeholder="Feet">

                <label for="result">Result
                </label>
                <div id="result"></div>

                <button id="calculate" onclick="calculate()">Calculate</button>
                <button id="clear" onclick="clear()">Clear</button>
            </div>


问:
How can I continue to play my GIF during JavaScript processing (as it freezes)?
My GIF image freezes after 5 seconds while my JavaScript code is doing some work. It unfreezes when procesing is finished.

Is there a solution to animate my GIF while the code is executing?

Here's my JavaScript code:

```<code>var play = function() {
    var image = document.getElementById('img');
    image.style.display="block";

    window.setTimeout(function(){
        for ( var i =0; i < 2000000000; i++ )
        {
            //Do nothing, in example
        }
    }, 5000);
};

var stop = function() {
    var image = document.getElementById('img');
    image.style.display="none";
};
</code>```

HTML code:

```<code><img id="img" src="loader.gif" style="display: none;"/>
<button id="Start" onclick="play()">Play</button>
<button id="Stop" onclick="stop()">Stop</button>
</code>```

答:
Use yield as in this working example with minor mod's to your own code...

var play = function() {
//'-----------------------------------Insert Handler..
      var obj = myfuncGen.next(); //'start it
      if (obj.done == false) {
          setTimeout(play, 150); //'adjust for the amount of time you wish to yield (depends how much screen drawing is required or etc)
      }
  }
  var myfuncGen = myfuncSurrogate(); //'creates a "Generator" out of next.
  function* myfuncSurrogate() { //'This the original function repackaged! Note asterisk.
//'-------------------------------------End Insert
  var image = document.getElementById('img');
    image.style.display="block";

    //window.setTimeout(function(){
        console.log("start");
        for ( var i =0; i < 20000000; i++ )
        {
          if ((i % 1000000) == 0) { //a yield set to go off every 1,000,000 loops (if the yield is called too often it will needlessly slowe down yor loop)
            console.log("yielding ", i / 1000000);
            yield;
          }
        }
        console.log("done");
    //}, 500);
};

play()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id='img' src='http://bestanimations.com/Earth&Space/Earth/earth-spinning-rotating-animation-52.gif' /></code>```

..I had to edit out window.setTimeout() as it created a detached function which causes an error with Yield. To restore your original intent, I would call play() from such a timeout.

If the link becomes broken to the random gif I chose, I am sure you could substitute another :-).

Body:
My GIF image freezes after 5 seconds while my JavaScript code is doing some work. It unfreezes when procesing is finished.

Is there a solution to animate my GIF while the code is executing?

Here's my JavaScript code:

var play = function() {
    var image = document.getElementById('img');
    image.style.display="block";

    window.setTimeout(function(){
        for ( var i =0; i < 2000000000; i++ )
        {
            //Do nothing, in example
        }
    }, 5000);
};

var stop = function() {
    var image = document.getElementById('img');
    image.style.display="none";
};

HTML code:

<button id="Start" onclick="play()">Play</button>
<button id="Stop" onclick="stop()">Stop</button>

Body:
Use yield as in this working example with minor mod's to your own code...

var play = function() {
//'-----------------------------------Insert Handler..
      var obj = myfuncGen.next(); //'start it
      if (obj.done == false) {
          setTimeout(play, 150); //'adjust for the amount of time you wish to yield (depends how much screen drawing is required or etc)
      }
  }
  var myfuncGen = myfuncSurrogate(); //'creates a "Generator" out of next.
  function* myfuncSurrogate() { //'This the original function repackaged! Note asterisk.
//'-------------------------------------End Insert
  var image = document.getElementById('img');
    image.style.display="block";

    //window.setTimeout(function(){
        console.log("start");
        for ( var i =0; i < 20000000; i++ )
        {
          if ((i % 1000000) == 0) { //a yield set to go off every 1,000,000 loops (if the yield is called too often it will needlessly slowe down yor loop)
            console.log("yielding ", i / 1000000);
            yield;
          }
        }
        console.log("done");
    //}, 500);
};

play()

<img id='img' src='http://bestanimations.com/Earth&Space/Earth/earth-spinning-rotating-animation-52.gif' />

..I had to edit out window.setTimeout() as it created a detached function which causes an error with Yield. To restore your original intent, I would call play() from such a timeout.

If the link becomes broken to the random gif I chose, I am sure you could substitute another :-).


问:
Excel COUNTIF returns ambiguous results
I'm trying to use Excel's COUNTIF formula on a large range of values to basically create a unique and sorted list of those values. However, several values don't seem to be considered in this operation, so I went to debugging it.

Could you explain to me why the values in column B of the snipet table below are all '0'? What is the catch to obtain a value of '1' when comparing values like the ones below?

I understand I'm probably missing some silly detail...

Thanks in advance

```<code>   -----------------
   |   A   |   B   |
   -----------------
1  | 10 B  |   0   |  <-- B1 formula is =COUNTIF(A1;"<52")
   -----------------
2  |  52   |   0   |  <-- B2 formula is =COUNTIF(A2;"<10 B")
   -----------------
3  |  52   |   0   |  <-- B3 formula is =COUNTIF(A3;"=10 B")
   -----------------
</code>```

EDIT:
Let me put this into perspective. Consider the table below.

What I'm trying to achieve exactly is, on column B, construct a list of unique values from column A. I'm doing this by using the following formula on B2, with CTRL+SHIFT+ENTER, and dragging it through cells in B column, B3, B4, etc:

```<code>=INDEX($A$2:$A$100;MATCH(0;COUNTIF($A$2:$A$100;"<"&$A$2:$A$100)-SUM(COUNTIF($A$2:$A$100;B$1:B1));0))
</code>```

However, several values from column A are "skipped", hence why I've tried debuging the COUNTIF formula like I explained above, but still no idea why certain values are skipped, perhaps an error with the formula?

```<code>    -----------------------
    |     A    |     B    |
    -----------------------
 1  |          |          |
    -----------------------
 2  |    52    |    52    |
    -----------------------
 3  |   16277  |  16277   |
    -----------------------
 4  |   16277  |  21785   |
    -----------------------
 5  |   16277  | 5411828  |
    -----------------------
 6  |   21785  | 54112528 |
    -----------------------
 7  |  5411828 |   37-50  |
    -----------------------
 8  | 54112528 |   42-B   |
    -----------------------
 9  |   10 B   |  ABC-01  |
    -----------------------
10  |   10-M   |          |
    -----------------------
11  |   15-94  |          |
    -----------------------
12  |  15-971/ |          |
    -----------------------
13  |   16.    |          |
    -----------------------
14  |   16..   |          |
    -----------------------
15  |   22-23  |          |
    -----------------------
16  |   37-50  |          |
    -----------------------
17  |   42-B   |          |
    -----------------------
18  |  ABC-01  |          |
    -----------------------
</code>```

答:
For the first row, "10 B" is not a numerical value, so it cannot fit the COUNTIF criteria of being less than 52. If that field will always have a number and letter then you could parse out the number with LEFT(A1,2) to get the two digits on the left, and then see if they're less than 52.

For the second and third rows your COUNTIF is looking for criteria that is less than a non-numerical value, so the function won't work. You could COUNTIF if the cell value was equal to that criteria, looking for a match. Or you could change the formula to COUNTIF(A3,"<10") which would then return a count of any cells that are less than 10.

Your primary issue seems to be differentiating between numbers, and numbers with letters. In excel, when you have a cell with letters and/or spaces in addition to numbers, it will typically format to a text field and so mathematical formulas will not use it with out some tweaking.

Title: Excel COUNTIF returns ambiguous results

Body:
I'm trying to use Excel's COUNTIF formula on a large range of values to basically create a unique and sorted list of those values. However, several values don't seem to be considered in this operation, so I went to debugging it.

Could you explain to me why the values in column B of the snipet table below are all '0'? What is the catch to obtain a value of '1' when comparing values like the ones below?

I understand I'm probably missing some silly detail...

Thanks in advance

   -----------------
   |   A   |   B   |
   -----------------
1  | 10 B  |   0   |  <-- B1 formula is =COUNTIF(A1;"<52")
   -----------------
2  |  52   |   0   |  <-- B2 formula is =COUNTIF(A2;"<10 B")
   -----------------
3  |  52   |   0   |  <-- B3 formula is =COUNTIF(A3;"=10 B")
   -----------------

EDIT:
Let me put this into perspective. Consider the table below.

What I'm trying to achieve exactly is, on column B, construct a list of unique values from column A. I'm doing this by using the following formula on B2, with CTRL+SHIFT+ENTER, and dragging it through cells in B column, B3, B4, etc:

=INDEX($A$2:$A$100;MATCH(0;COUNTIF($A$2:$A$100;"<"&$A$2:$A$100)-SUM(COUNTIF($A$2:$A$100;B$1:B1));0))

However, several values from column A are "skipped", hence why I've tried debuging the COUNTIF formula like I explained above, but still no idea why certain values are skipped, perhaps an error with the formula?

    -----------------------
    |     A    |     B    |
    -----------------------
 1  |          |          |
    -----------------------
 2  |    52    |    52    |
    -----------------------
 3  |   16277  |  16277   |
    -----------------------
 4  |   16277  |  21785   |
    -----------------------
 5  |   16277  | 5411828  |
    -----------------------
 6  |   21785  | 54112528 |
    -----------------------
 7  |  5411828 |   37-50  |
    -----------------------
 8  | 54112528 |   42-B   |
    -----------------------
 9  |   10 B   |  ABC-01  |
    -----------------------
10  |   10-M   |          |
    -----------------------
11  |   15-94  |          |
    -----------------------
12  |  15-971/ |          |
    -----------------------
13  |   16.    |          |
    -----------------------
14  |   16..   |          |
    -----------------------
15  |   22-23  |          |
    -----------------------
16  |   37-50  |          |
    -----------------------
17  |   42-B   |          |
    -----------------------
18  |  ABC-01  |          |
    -----------------------


问:
How to correctly unquote url which is supposed to contain Japanese symbols
I have the following string for example (which was built as I realized from incorrectly encoded string)

https://ja-jp.facebook.com/%C3%A5%C2%90%C2%8D%C3%A5%C2%8F%C2%A4%C3%A5%C2%B1%E2%80%B9%C3%AF%C2%BD%C5%A0%C3%AF%C2%BD%E2%80%99%C3%A3%E2%80%9A%C2%B2%C3%A3%C6%92%C2%BC%C3%A3%C6%92%CB%86%C3%A3%E2%80%9A%C2%BF%C3%A3%C6%92%C2%AF%C3%A3%C6%92%C2%BC%C3%A3%C6%92%E2%80%BA%C3%A3%C6%92%E2%80%A0%C3%A3%C6%92%C2%AB-219123305237478

This url could be properly decoded by browser showing  the following:

https://ja-jp.facebook.com/名古屋ｊｒゲートタワーホテル-219123305237478/

Is there a way to unquote/decode the string so it's not presented like this:

https://ja-jp.facebook.com/åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478

Browser shows url with same rubbish initially for a short time, but then without redirect it adjustst the string so it looks fine.

I'm trying to fix encoding with this simple code:

```<code>def fix_encoding(s):
    for a in aliases:
        for b in aliases:
            try:
                fixed = s.encode(a).decode(b)
            except:
                pass
            else:
                print (a, b)
                print(fixed)

fix_encoding(u'åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478')
</code>```

The best results I've got are pretty close to what it should look like, but 2 first symbols are wrong for all same results. For ex.:

```<code>��屋ｊｒゲートタワーホテル-219123305237478
('1252', 'l8')
</code>```

答:
The first URL is broken. What happend is, that some software considered the correct UTF-8 URL being CP1252 even though there were some bytes invalid in CP1252. Thus it translated the bytes of the correct URL from the supposed CP1252 to UTF8, but if and only if the bytes were valid in CP1252. The invalid bytes were left as they were. This is the reason, why all the URL is not restorable by one encode-decode combination.

To reverse the described process we need for example this code (in Python 2):

```<code>#-*-coding:utf8-*-
from six.moves.urllib import parse

correct = 'https://ja-jp.facebook.com/名古屋ｊｒゲートタワーホテル-219123305237478'
url = 'https://ja-jp.facebook.com/%C3%A5%C2%90%C2%8D%C3%A5%C2%8F%C2%A4%C3%A5%C2%B1%E2%80%B9%C3%AF%C2%BD%C5%A0%C3%AF%C2%BD%E2%80%99%C3%A3%E2%80%9A%C2%B2%C3%A3%C6%92%C2%BC%C3%A3%C6%92%CB%86%C3%A3%E2%80%9A%C2%BF%C3%A3%C6%92%C2%AF%C3%A3%C6%92%C2%BC%C3%A3%C6%92%E2%80%BA%C3%A3%C6%92%E2%80%A0%C3%A3%C6%92%C2%AB-219123305237478'
unq_url = parse.unquote(url.encode('ascii'))

res = ''
for c in unq_url.decode('utf8'):
    try:
        res += c.encode('cp1252')
    except:
        res += chr(ord(c))

print res == correct
</code>```

Body:
I have the following string for example (which was built as I realized from incorrectly encoded string)

https://ja-jp.facebook.com/%C3%A5%C2%90%C2%8D%C3%A5%C2%8F%C2%A4%C3%A5%C2%B1%E2%80%B9%C3%AF%C2%BD%C5%A0%C3%AF%C2%BD%E2%80%99%C3%A3%E2%80%9A%C2%B2%C3%A3%C6%92%C2%BC%C3%A3%C6%92%CB%86%C3%A3%E2%80%9A%C2%BF%C3%A3%C6%92%C2%AF%C3%A3%C6%92%C2%BC%C3%A3%C6%92%E2%80%BA%C3%A3%C6%92%E2%80%A0%C3%A3%C6%92%C2%AB-219123305237478

This url could be properly decoded by browser showing  the following:

https://ja-jp.facebook.com/名古屋ｊｒゲートタワーホテル-219123305237478/

Is there a way to unquote/decode the string so it's not presented like this:

https://ja-jp.facebook.com/åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478

Browser shows url with same rubbish initially for a short time, but then without redirect it adjustst the string so it looks fine.

I'm trying to fix encoding with this simple code:

def fix_encoding(s):
    for a in aliases:
        for b in aliases:
            try:
                fixed = s.encode(a).decode(b)
            except:
                pass
            else:
                print (a, b)
                print(fixed)

fix_encoding(u'åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478')

The best results I've got are pretty close to what it should look like, but 2 first symbols are wrong for all same results. For ex.:

��屋ｊｒゲートタワーホテル-219123305237478
('1252', 'l8')

Body:
The first URL is broken. What happend is, that some software considered the correct UTF-8 URL being CP1252 even though there were some bytes invalid in CP1252. Thus it translated the bytes of the correct URL from the supposed CP1252 to UTF8, but if and only if the bytes were valid in CP1252. The invalid bytes were left as they were. This is the reason, why all the URL is not restorable by one encode-decode combination.

To reverse the described process we need for example this code (in Python 2):

#-*-coding:utf8-*-
from six.moves.urllib import parse

correct = 'https://ja-jp.facebook.com/名古屋ｊｒゲートタワーホテル-219123305237478'
url = 'https://ja-jp.facebook.com/%C3%A5%C2%90%C2%8D%C3%A5%C2%8F%C2%A4%C3%A5%C2%B1%E2%80%B9%C3%AF%C2%BD%C5%A0%C3%AF%C2%BD%E2%80%99%C3%A3%E2%80%9A%C2%B2%C3%A3%C6%92%C2%BC%C3%A3%C6%92%CB%86%C3%A3%E2%80%9A%C2%BF%C3%A3%C6%92%C2%AF%C3%A3%C6%92%C2%BC%C3%A3%C6%92%E2%80%BA%C3%A3%C6%92%E2%80%A0%C3%A3%C6%92%C2%AB-219123305237478'
unq_url = parse.unquote(url.encode('ascii'))

res = ''
for c in unq_url.decode('utf8'):
    try:
        res += c.encode('cp1252')
    except:
        res += chr(ord(c))

print res == correct


问:
Dynamic Computation in Tableau based on User Input
I have a requirement to dynamically perform computations in Tableau based on User Input.

For this purpose my basic query looks something like this:

```<code>Select some_dimension,sum(some_measure)/count(some_measure) as
some_measure_average
from table
where date = User_Input
group by some_dimension
</code>```

The User_Input value should be passed based on what the user has selected and the corresponding computation should be performed based on the above query logic.Here , the Custom SQL should hit the connected Database that contains the data and display the computed data on Tableau.

Here the average is calculated based on the division of sum and count and should only be computed for the date value that has been selected.

The Custom SQL Query option in Tableau is not able to fulfill this requirement.
Not sure if we are doing it correctly.

答: You can create a date parameter in Tableau and pass that as your User_Input. Type your query and click "Insert Parameter". Set the parameter Data type to Date and provide a current value. Insert it where needed in your query.

Body:
I have a requirement to dynamically perform computations in Tableau based on User Input.

For this purpose my basic query looks something like this:

Select some_dimension,sum(some_measure)/count(some_measure) as
some_measure_average
from table
where date = User_Input
group by some_dimension

The User_Input value should be passed based on what the user has selected and the corresponding computation should be performed based on the above query logic.Here , the Custom SQL should hit the connected Database that contains the data and display the computed data on Tableau.

Here the average is calculated based on the division of sum and count and should only be computed for the date value that has been selected.

The Custom SQL Query option in Tableau is not able to fulfill this requirement.
Not sure if we are doing it correctly.


问:
C - How to get string from user when using typedef?
I have the following typedef in my code:

```<code>typedef char * string;
</code>```

And I need to have the user input a string so that I can then parse it and use the contents later. If I am just declaring a string with this definition it works, like this:

```<code>string bob = "My name is bob!;
printf("%s\n", bob);
</code>```

What should I use to get user input when using this, scanf() and fgets()
both give me Segmentation fault (core dumped) errors when I try to use them.

This is for school, which is why I need to use the typedef this way.

答:
How to get string from user when using typedef? (typedef char * string;)

string bob needs to be assigned a value, a memory location is which to store the data read.

```<code>#define N 80

// local array
char buf[N];
string bob = buf;
fgets(bob, N, stdin);

// or malloc
string bob = malloc(N);
if (bob == NULL) Handle_OutOfMemory();
fgets(bob, N, stdin);
</code>```

Now trim the potential '\n'

```<code>bob[strcspn(bob, "\n")] = '\0';
</code>```

Print result

```<code>printf("<%s>\n", bob);
</code>```

... and use the contents later.

This implies code should use a right-sized memory allocation for use well passed this input code.    strdup() is not in the standard C library, but very common.
 Sample code.

```<code> // local array approach
 bob = strdup(bob);
 // Now bob points to allocated memory

 // malloc approach
 // re-size to be efficient
 void *t = realloc(bob, strlen(bob) + 1);
 if (t) {
   bob = t;
 }
 // Detail: A realloc to a smaller amount of memory rarely ever fails.
 // If it did fail, just continue with old pointer.
</code>```

If bob points to allocated memory, clean up when done with bob.

```<code>free(bob);
</code>```

Only use scanf() if required and you can't drop the class or get employment elsewhere.

Body:
I have the following typedef in my code:

typedef char * string;

And I need to have the user input a string so that I can then parse it and use the contents later. If I am just declaring a string with this definition it works, like this:

string bob = "My name is bob!;
printf("%s\n", bob);

What should I use to get user input when using this, scanf() and fgets()
both give me Segmentation fault (core dumped) errors when I try to use them.

This is for school, which is why I need to use the typedef this way.

Body:
How to get string from user when using typedef? (typedef char * string;)

string bob needs to be assigned a value, a memory location is which to store the data read.

#define N 80

// local array
char buf[N];
string bob = buf;
fgets(bob, N, stdin);

// or malloc
string bob = malloc(N);
if (bob == NULL) Handle_OutOfMemory();
fgets(bob, N, stdin);

Now trim the potential '\n'

bob[strcspn(bob, "\n")] = '\0';

Print result

printf("<%s>\n", bob);

... and use the contents later.

This implies code should use a right-sized memory allocation for use well passed this input code.    strdup() is not in the standard C library, but very common.
 Sample code.

 // local array approach
 bob = strdup(bob);
 // Now bob points to allocated memory

 // malloc approach
 // re-size to be efficient
 void *t = realloc(bob, strlen(bob) + 1);
 if (t) {
   bob = t;
 }
 // Detail: A realloc to a smaller amount of memory rarely ever fails.
 // If it did fail, just continue with old pointer.

If bob points to allocated memory, clean up when done with bob.

free(bob);

Only use scanf() if required and you can't drop the class or get employment elsewhere.


答:
You should have a property inside your class and constructor to fill it

try putting this inside your class :

```<code>private String _myParam;

public SendRequest ( string myParam ){
    _myParam = myParam;
    }

// then continue with your try catch.
</code>```

then when you create the instance :

```<code>new SendRequest("My awesome param").execute();
</code>```

i hope this helps :)

Title: How should I pass a variable to another class?

Body:
You should have a property inside your class and constructor to fill it

try putting this inside your class :

private String _myParam;

public SendRequest ( string myParam ){
    _myParam = myParam;
    }

// then continue with your try catch.

then when you create the instance :

new SendRequest("My awesome param").execute();

i hope this helps :)


问:
Build Linq queries and concatenate dynamically based on a table
I'm summarizing data to build an alert system. This query counts how many points an employee has based on some criteria. The one below is working fine. However, the query can be longer depending on the User's location. For example, below I have only have 3 unions but  for other Employees' locations more unions may be needed. For example in Location B they may also want to add an alert if a ReasonTypeID == is 3 and any entries in the last 90 days.

So I was thinking on building a table that I can add parameters on a location by location basis. I've read about dynamic linq library and I can use that for the WHERE statements but how would I add another query concatenation on the fly?

Here is what I have now.

```<code>public class TMAlert
{
    public string EmpID { get; set; }
    public string FullName { get; set; }
    public decimal? PointSummary { get; set; }
    public string WarningLabel { get; set; }
    public bool AlertFlag { get; set; }
}

IEnumerable<TMAlert> tmAlert = (
    from a in allEntries
    where a.Date >= DateTime.Now.AddDays(-30) && a.ReasonTypeID == 1
    group a by new
    {
        a.EmpID,
        a.FullName,
        a.ReasonTypeID
    } into g
    select new TMAlert
    {
        EmpID = g.Key.EmpID,
        FullName = g.Key.FullName,
        WarningLabel = "Last 30 Days",
        PointSummary = g.Sum(a => a.Points),
        AlertFlag = (g.Sum(a => a.Points) >= 4) ? true : false
    }).Concat(from a in allEntries
              where a.Date >= DateTime.Now.AddDays(-90) && a.ReasonTypeID == 1
              group a by new
              {
                  a.EmpID,
                  a.FullName,
                  a.ReasonTypeID
              } into g
              select new TMAlert
              {
                  EmpID = g.Key.EmpID,
                  FullName = g.Key.FullName,
                  WarningLabel = "Last 90 Days",
                  PointSummary = g.Sum(a => a.Points),
                  AlertFlag = (g.Sum(a => a.Points) >= 9) ? true : false
              }).Concat(from a in allEntries
                        where a.Date >= (
                        from o in allEntries
                        where o.EmpID == a.EmpID && a.WarningTypeID == 2
                        select (DateTime?)o.Date).Max()
                        group a by new
                        {
                            a.EmpID,
                            a.FullName,
                            a.ReasonTypeID
                        } into g
                        select new TMAlert
                        {
                            EmpID = g.Key.EmpID,
                            FullName = g.Key.FullName,
                            WarningLabel = "60 Since Warning type 2 ",
                            PointSummary = g.Sum(a => a.Points),
                            AlertFlag = (g.Sum(a => a.Points) >= 4) ? true : false
                        });
</code>```

I was thinking to build a criteria table then build the queries on the fly based on the table.
for example

```<code>for each entry in criteriaTable

add dynamic linq entry.Param
.concat(....

next....
</code>```

is this possible or are there better ways to do this?

答:
There is a way to combine linq queries dynamically.  I use it to add conditional filters to my where statements when showing a filtered list of data.

I initialize the lambda expression like this

```<code>Expression<Func<CatalogItem, bool>> Filter = CatalogItem => true;
</code>```

then as I go I add to it.

```<code>if(!string.IsNullOrEmpty(searchVal)) {Filter = Filter.Compose(CatalogItem => CatalogItem.Title.ToLower().Contains(searchVal), Expression.And);}
</code>```

I may have different if conditions that cause me to add more and more to my filter then finally I want to apply that filter against my collection.

```<code>IQueryable<CatalogItem> FilteredList = Items.AsQueryable().Where(Filter);
</code>```

In this case Items is a list of CatalogItems that was pulled from the database earlier. I am using IQueryable instead of just List<> cause I need to act on the results afterwards.

```<code>List<CatalogItem> Items;//fill Items list here;
</code>```

I know this is in-line Linq as opposed to the structure you use but I really can't get into the other form of linq querying as this is so quick and dirty for me. If you have to use the other linq form these rules may still apply.

Body:
I'm summarizing data to build an alert system. This query counts how many points an employee has based on some criteria. The one below is working fine. However, the query can be longer depending on the User's location. For example, below I have only have 3 unions but  for other Employees' locations more unions may be needed. For example in Location B they may also want to add an alert if a ReasonTypeID == is 3 and any entries in the last 90 days.

So I was thinking on building a table that I can add parameters on a location by location basis. I've read about dynamic linq library and I can use that for the WHERE statements but how would I add another query concatenation on the fly?

Here is what I have now.

public class TMAlert
{
    public string EmpID { get; set; }
    public string FullName { get; set; }
    public decimal? PointSummary { get; set; }
    public string WarningLabel { get; set; }
    public bool AlertFlag { get; set; }
}

IEnumerable<TMAlert> tmAlert = (
    from a in allEntries
    where a.Date >= DateTime.Now.AddDays(-30) && a.ReasonTypeID == 1
    group a by new
    {
        a.EmpID,
        a.FullName,
        a.ReasonTypeID
    } into g
    select new TMAlert
    {
        EmpID = g.Key.EmpID,
        FullName = g.Key.FullName,
        WarningLabel = "Last 30 Days",
        PointSummary = g.Sum(a => a.Points),
        AlertFlag = (g.Sum(a => a.Points) >= 4) ? true : false
    }).Concat(from a in allEntries
              where a.Date >= DateTime.Now.AddDays(-90) && a.ReasonTypeID == 1
              group a by new
              {
                  a.EmpID,
                  a.FullName,
                  a.ReasonTypeID
              } into g
              select new TMAlert
              {
                  EmpID = g.Key.EmpID,
                  FullName = g.Key.FullName,
                  WarningLabel = "Last 90 Days",
                  PointSummary = g.Sum(a => a.Points),
                  AlertFlag = (g.Sum(a => a.Points) >= 9) ? true : false
              }).Concat(from a in allEntries
                        where a.Date >= (
                        from o in allEntries
                        where o.EmpID == a.EmpID && a.WarningTypeID == 2
                        select (DateTime?)o.Date).Max()
                        group a by new
                        {
                            a.EmpID,
                            a.FullName,
                            a.ReasonTypeID
                        } into g
                        select new TMAlert
                        {
                            EmpID = g.Key.EmpID,
                            FullName = g.Key.FullName,
                            WarningLabel = "60 Since Warning type 2 ",
                            PointSummary = g.Sum(a => a.Points),
                            AlertFlag = (g.Sum(a => a.Points) >= 4) ? true : false
                        });

I was thinking to build a criteria table then build the queries on the fly based on the table.
for example

for each entry in criteriaTable

add dynamic linq entry.Param
.concat(....

next....

is this possible or are there better ways to do this?

Body:
There is a way to combine linq queries dynamically.  I use it to add conditional filters to my where statements when showing a filtered list of data.

I initialize the lambda expression like this

Expression<Func<CatalogItem, bool>> Filter = CatalogItem => true;

then as I go I add to it.

if(!string.IsNullOrEmpty(searchVal)) {Filter = Filter.Compose(CatalogItem => CatalogItem.Title.ToLower().Contains(searchVal), Expression.And);}

I may have different if conditions that cause me to add more and more to my filter then finally I want to apply that filter against my collection.

IQueryable<CatalogItem> FilteredList = Items.AsQueryable().Where(Filter);

In this case Items is a list of CatalogItems that was pulled from the database earlier. I am using IQueryable instead of just List<> cause I need to act on the results afterwards.

List<CatalogItem> Items;//fill Items list here;

I know this is in-line Linq as opposed to the structure you use but I really can't get into the other form of linq querying as this is so quick and dirty for me. If you have to use the other linq form these rules may still apply.


问:
Script to execute chmod continuously
I am working on Solaris servers. I am using an ADMIN user which has all the accesses while other colleagues are using a different user with limited access.
When others want to access the logs I have to manually give chmod 755 on the log folders and when a new file is generated I have to do chmod again.

Is there a way to write a script to run chmod continuously every 2 mins on some folders?

答:
i think it's not a good idea to assign permissions for every 2 min

it's better to change umask of log file owner for create new log file with default 777 permissions

still if you want to use like your idea do like this

open crontab
crontab -e

add entry to execute command for every 2 min
*/2 * * * *  chmod -R /path_to_log_folder/

save and close
:wq if it's vi editor
press x and hit enter if it's nano editor

Title: Script to execute chmod continuously


问:
Tree Search using a SQL Query to find Common Cells
What I will like to do is to retrieve all the persons that contain two common columns (movie and year):

```<code>login_id | movie               | year
---------|---------------------|-----------
john     | the matrix          | 1999
john     | star wars           | 1977
bob      | titanic             | 1997
johnny   | the matrix          | 1999
tony     | lord of the rings   | 2001
tony     | lord of the rings   | 2002
tony     | lord of the rings   | 2003
james    | star wars           | 1977
robert   | star trek           | 1966
james    | titanic             | 1997
bob      | star trek           | 1966
...
</code>```

So if am interested in finding for login_id: bob what movies he watched plus who else watched the same movies expected output:

```<code>login_id | movie               | year
---------|---------------------|-----------
james    | titanic             | 1997
robert   | star trek           | 1966
...
</code>```

I want to do it efficiently as possible and if I need to restructure the table I will do it. First guess:

SELECT login_id, movie, year, count(*)
 FROM watchers
 GROUP BY login_id, movie, year
 HAVING count(*) > 1 **and login_id = 'bob'**

The 'and' is where I am confuse, because it is grouping by count instead of pulling out all the common data.

答:
I am thinking exists:

```<code>select w.*
from watchers w
where exists (select 1
              from watchers w2
              where w2.movie = w.movie and w2.year = w.year and w2.login_id = 'bob'
             );
</code>```

Body:
What I will like to do is to retrieve all the persons that contain two common columns (movie and year):

login_id | movie               | year
---------|---------------------|-----------
john     | the matrix          | 1999
john     | star wars           | 1977
bob      | titanic             | 1997
johnny   | the matrix          | 1999
tony     | lord of the rings   | 2001
tony     | lord of the rings   | 2002
tony     | lord of the rings   | 2003
james    | star wars           | 1977
robert   | star trek           | 1966
james    | titanic             | 1997
bob      | star trek           | 1966
...

So if am interested in finding for login_id: bob what movies he watched plus who else watched the same movies expected output:

login_id | movie               | year
---------|---------------------|-----------
james    | titanic             | 1997
robert   | star trek           | 1966
...

I want to do it efficiently as possible and if I need to restructure the table I will do it. First guess:

SELECT login_id, movie, year, count(*)
 FROM watchers
 GROUP BY login_id, movie, year
 HAVING count(*) > 1 **and login_id = 'bob'**

The 'and' is where I am confuse, because it is grouping by count instead of pulling out all the common data.

Body:
I am thinking exists:

select w.*
from watchers w
where exists (select 1
              from watchers w2
              where w2.movie = w.movie and w2.year = w.year and w2.login_id = 'bob'
             );