text:
Q: MS-SQL permissions on stored Proc Can Stored Proc be given "Execute" Privileges without giving table privileges. Meaning just giving a user permission to execute stored Calls and nothing else.
This was my interview question today. And I said "Yes" but the person interviewing said I was wrong. I just want to be sure so I can email back with the correct Answer. Thanks for the help!

A: Yes. You can do that. you have to simply give EXECUTE permission on the stored procedure to the user.
GRANT EXECUTE ON schemaName.StoredProcedureName TO UserName


text:
Q: How do I list elements in the table with React? I am new to React. How can I list elements from two different arrays in two columns using "map" function?
state = {
  dates: ["2000", "2001", "2002"],
  cases: ["1", "2", "3"]
}

render() {
  return (

        Date
        Cases

      {this.state.dates.map(el =>

          {el}

      )} // I want to list elements from "cases" array like this but in the second column

  )
}

A: Quick and Easy Solution: Not recommended
If you're going to always assume that dates and cases will always be the same length then you could do this:
{this.state.dates.map((el, index) => (

    {this.state.dates[index]}
    {this.state.cases[index]}

))}

This method makes use of the index parameter of the map function. Then you can access the array at the specific index mentioned.

Recommended Solution:
The usual practice is to keep your data grouped per record.
Using your example, use a structure like this:
state  = {
  records: [
    { date: '2000', caseId: '1' },
    { date: '2001', caseId: '2' },
    { date: '2002', caseId: '3' }
  ],
}

Then implement it like this:
{this.state.records.map(({ date, caseId }) => (

    {date}
    {caseId}

))}

I'm using caseId instead of case because case is a reserved word in JavaScript for switch statements.

A: You can use index parameter from the map function and access the cases array

  {this.state.dates.map((el, index) => (

      {el}
      {this.state.cases[index]}

  ))}{" "}

;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android - Failure [INSTALL_FAILED_INTERNAL_ERROR] I'm having some problems trying to install APKs in a specific device. I have lots of devices and it hadn't happened so far (all of them, Radxa Rock Pro).
When I run pm install myApp I get
root@radxaPro:/ # pm install /sdcard/myApp.apk
pkg: /sdcard/myApp.apk
Failure [INSTALL_FAILED_INTERNAL_ERROR]

Logcat output:
06-02 13:02:33.032 I/AndroidRuntime( 4469): JNI options: '-Xjniopts:warnonly'
06-02 13:02:33.042 D/dalvikvm( 4469): Trying to load lib libjavacore.so 0x0
06-02 13:02:33.042 D/dalvikvm( 4469): Added shared lib libjavacore.so 0x0
06-02 13:02:33.052 D/dalvikvm( 4469): Trying to load lib libnativehelper.so 0x0
06-02 13:02:33.052 D/dalvikvm( 4469): Added shared lib libnativehelper.so 0x0
06-02 13:02:33.052 D/dalvikvm( 4469): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
06-02 13:02:33.082 D/dalvikvm( 4469): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
06-02 13:02:33.232 E/memtrack( 4469): Couldn't load memtrack module (No such file or directory)
06-02 13:02:33.232 E/android.os.Debug( 4469): failed to load memtrack module: -2
06-02 13:02:33.282 D/AndroidRuntime( 4469): Calling main entry com.android.commands.pm.Pm
06-02 13:02:33.292 W/ActivityManager( 474): Unable to start service Intent { cmp=com.android.defcontainer/.DefaultContainerService } U=0: not found
06-02 13:02:33.292 E/PackageManager( 474): Failed to bind to media container service

I think the most important line is Unable to start service Intent { cmp=com.android.defcontainer/.DefaultContainerService } U=0: not found because a successful installation shows this (another device):
06-02 13:04:35.747: I/AndroidRuntime(1005): JNI options: '-Xjniopts:warnonly'
06-02 13:04:35.757: D/dalvikvm(1005): Trying to load lib libjavacore.so 0x0
06-02 13:04:35.767: D/dalvikvm(1005): Added shared lib libjavacore.so 0x0
06-02 13:04:35.767: D/dalvikvm(1005): Trying to load lib libnativehelper.so 0x0
06-02 13:04:35.767: D/dalvikvm(1005): Added shared lib libnativehelper.so 0x0
06-02 13:04:35.767: D/dalvikvm(1005): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
06-02 13:04:35.797: D/dalvikvm(1005): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
06-02 13:04:35.927: E/memtrack(1005): Couldn't load memtrack module (No such file or directory)
06-02 13:04:35.927: E/android.os.Debug(1005): failed to load memtrack module: -2
06-02 13:04:35.977: D/AndroidRuntime(1005): Calling main entry com.android.commands.pm.Pm
06-02 13:04:35.987: I/ActivityManager(478): Start proc com.android.defcontainer for service com.android.defcontainer/.DefaultContainerService: pid=1016 uid=10001 gids={50001, 1028, 1015, 1023, 2001, 1035}

The DefaultContainerService.apk is located in /system/priv-app/ but I have been able to check that it is not actually installed in that device. If I try to install it, I get the same error.
Does anyone have an idea? Is the Android system corrupt?
Thanks in advance.


text:
Q: Kafka doesn't work with external NFS Volume I am trying to run Kafka with mounted NFS Volume, facing exception and can not start Kafka:
    [2020-03-15 09:36:11,580] ERROR There was an error in one of the threads during logs loading: org.apache.kafka.common.KafkaException: Found directory /var/lib/kafka/data/.snapshot, '.snapshot' is not in the form of topic-partition or topic-partition.uniqueId-delete (if marked for deletion).
Kafka's log directories (and children) should only contain Kafka topic data. (kafka.log.LogManager)
[2020-03-15 09:36:11,582] ERROR [KafkaServer id=1] Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
org.apache.kafka.common.KafkaException: Found directory /var/lib/kafka/data/.snapshot, '.snapshot' is not in the form of topic-partition or topic-partition.uniqueId-delete (if marked for deletion).
Kafka's log directories (and children) should only contain Kafka topic data.
        at kafka.log.Log$.exception$1(Log.scala:2150)
        at kafka.log.Log$.parseTopicPartitionName(Log.scala:2157)
        at kafka.log.LogManager.kafka$log$LogManager$$loadLog(LogManager.scala:260)
        at kafka.log.LogManager$$anonfun$loadLogs$2$$anonfun$11$$anonfun$apply$15$$anonfun$apply$2.apply$mcV$sp(LogManager.scala:345)
        at kafka.utils.CoreUtils$$anon$1.run(CoreUtils.scala:63)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

This is my docker-compose scripts:
  zookeeper:
    image: confluentinc/cp-zookeeper:5.3.2
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
    volumes:
      - zk-data:/var/lib/zookeeper/data:nocopy
      - zk-log:/var/lib/zookeeper/log:nocopy

  kafka:
    image: confluentinc/cp-kafka:5.3.2
    environment:
      KAFKA_ADVERTISED_HOST_NAME: kafka
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
    volumes:
      - kf-data:/var/lib/kafka/data:nocopy

volumes:
  zk-data:
    driver: local
    driver_opts:
      type: "nfs"
      o: addr=18.0.3.227 #IP of NFS
      device: ":/opt/data/zk-data"
  zk-log:
    driver: local
    driver_opts:
      type: "nfs"
      o: addr=18.0.3.227
      device: ":/opt/data/zk-log"
  kf-data:
    driver: local
    driver_opts:
      type: "nfs"
      o: addr=18.0.3.227
      device: ":/opt/data/kf-data"

If I go to my NFS server,
ls -la /opt/data/kf-data/.snapshot

total 80
drwxrwxrwx 33 root   root         12288 Mar 28 00:10 .
drwx------  2 root domain^users  4096 Feb 21 19:20 ..
drwx------  2 root domain^users  4096 Feb 13 11:06 daily.2020-02-14_0010
drwx------  2 root domain^users  4096 Feb 13 11:06 daily.2020-02-15_0010
drwx------  2 root domain^users  4096 Feb 13 11:06 daily.2020-02-16_0010
drwx------  2 root domain^users  4096 Feb 13 11:06 daily.2020-02-17_0010
drwx------  2 root domain^users  4096 Feb 21 19:20 snapmirror.ka938443-8ea1-22e8-6608-00a067d1a20a_2148891236.2020-02-27_180700

There is a hidden folder named .snapshot, this folder is generated by NFS automatically and can not be removed. This is the reason why Kafka complains:  Found directory /var/lib/kafka/data/.snapshot, '.snapshot' is not in the form of topic-partition or topic-partition.uniqueId-delete (if marked for deletion).
And this could be the general Kafka problem, is there any special configure or solution to let Kafka use the external NFS volume?
Any ideas will be grateful!

A: As advised above Kafka on NFS is a flawed solution due to the way NFS file system works. You will run into issues with repartitioning and expansion. This is to do with the way NFS handles deletion of open files - silly rename behaviour. You can read about it in this blog post (Kafka on NFS).

A:
There is a hidden folder named .snapshot, this folder is generated by NFS automatically and can not be removed

Well, if there is no way around that, then Kafka will not be able to start, period.

To my knowledge, nowhere in the docs does it say remote attached storage is supported.

A: If you are using NetApp as NFS platform, this info could help: disable
 .snapshot access in NetApp is a global vFilter function, which is not a function per folder or share.
If you can not turn off the access to .snapshot, there is no solution, unless you use other NFS platforms, which will not generate .snapshot folder in every folder.

A: Have you tried to not use the root of the volume? the .snapshot directory is only accessible on the root.


text:
Q: Devise send_reset_password_instructions does not work I'm adding a function in my controller, the only goal is to trigger the forgot password procedure through API Request.
Here is the reset_password method-
  def reset_password
    @user = User.find_by_email(params[:email])
    @user.send_reset_password_instructions
    respond_to do |format|
      format.xml  { render :xml => user_api_ressource(@user, :xml)}
      format.json  { render :json => user_api_ressource(@user, :json)}
    end
  end

I'm receiving the mail with the reset password link, it opens the page where I can set a new password but when I submit the form it says that the token is invalid.
I'm using sendgrid to send email. I think it's not a token truncate problem.
I'm running the rails application on Heroku cedar with the latest version of devise.
Any idea ?

A: I just faced the same issue. In my case, it was because the user was unscoped. It seems like it doesn't the user is not found in that case.
It is in the Devise sources in /lib/devise/models/authenticatable.rb at line 113
      recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token)

which do not search unscoped.
I'll fork the repo, let me know if you are interested too.


text:
Q: Wrapping multiple method calls into one if statement I have a validation method that I call to validate the fields on my form. I want to put these in an if statement check to see if they return true then in my else statement insert them into my database. i already have the method declared and the insert method declared. How can I write this if statement to check to see if all the validation methods return true?
My method validation calls:
formValidation(firstnameTextBox.Text);
formValidation(lastnameTextBox.Text);
formValidation(usernameTextBox.Text);
formValidation(passwordTextBox.Text);
formValidation(emailTextBox.Text);
formValidation(cellnumberTextBox.Text);

A: Just use the AND operator (&&)
if(formValidation(firstnameTextBox.Text) &&
formValidation(lastnameTextBox.Text) &&
formValidation(usernameTextBox.Text) &&
formValidation(passwordTextBox.Text) &&
formValidation(emailTextBox.Text) &&
formValidation(cellnumberTextBox.Text))
{
}

As mentioned in the comments, if you want all of the methods to be run (to display the relevant errors for each field) no matter what, and to not stop as soon as it hits the first error, you can use a non-short circuiting AND, which is the & operator.
Alternatively, you could put the textboxes into a collection and act on that collection:
var fieldsToValidate = new TextBox[]{firstnameTextBox, lastnameTextBox, ...}
if(fieldsToValidate.All(field => formValidation(field.Text));


text:
Q: Objective C method naming convention - usage of colon I'm new to Objective C.
While I am reading the tutorial here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF
It says:
Use keywords before all arguments.
Right way:
- (void)sendAction:(SEL)aSelector toObject:(id)anObject forAllCells:(BOOL)flag;

Wrong way:
- (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;

It confuses me about Objective-C's method names. Here is my question:
1.
The wrong way is not recommended. But it's perfectly legal, right?
2.
The name(signature?) of the method is sendAction:toObject:forAllCells: for the first one and sendAction::: for the second one. Right?
I noticed that people emphasize that the colon : is always counted as in the method name.
I assume that : indicates an argument will follow and it cannot be modified anyway. So what's the implication of including colon in the method name as it's not subject to my modification.
3.
To make an example,     - (void)sendAction :(SEL)aSelector;
So the name of the method should be sendAction :
Noticing the blank space before colon is part of the name, should I consider this as a different method from - (void)sendAction:(SEL)aSelector; ?
The answer should be NO as [anObject sendAction : anSel]; should be the same as [anObject sendAction:anSel];
How do you guys understand the scheme as a whole that make sense?
Thanks.
P.S. Appreciate your reading through this question. I am pretty sure I am gonna feel silly once some of you pointed out and cleared my confusion.

A: The wrong way is legal, yes, but bad style. Just don't do it. The colons are part of what make ObjC code nice to read (though verbose); all the arguments at the call site have labels that remind you what they are for and often what type they should be.
The space is not in fact part of the method name; it's ignored. This is one of those things about ObjC that's pretty much "compiler-specified".
@interface Jackson : NSObject

- (void)shootCannon :(double)range;

- (void)grillSandwichWithBread :(BreadType)bread cheese :(CheeseType)cheese;

@end

@implementation Jackson
@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSLog(@"%@", NSStringFromSelector(@selector(shootCannon:)));
        NSLog(@"%@", NSStringFromSelector(@selector(shootCannon :)));
        NSLog(@"%@", NSStringFromSelector(@selector(grillSandwichWithBread:cheese:)));
        NSLog(@"%@", NSStringFromSelector(@selector(grillSandwichWithBread :cheese :)));

        NSLog(@"%d", @selector(shootCannon:) == @selector(shootCannon :));
        NSLog(@"%d", @selector(grillSandwichWithBread:cheese:) == @selector(grillSandwichWithBread :cheese :));

    }
    return 0;
}

2014-04-05 23:59:29.548 MethodNameSpace[66948:303] shootCannon:
  2014-04-05 23:59:29.548 MethodNameSpace[66948:303] shootCannon:
  2014-04-05 23:59:29.549 MethodNameSpace[66948:303] grillSandwichWithBread:cheese:
  2014-04-05 23:59:29.550 MethodNameSpace[66948:303] grillSandwichWithBread:cheese:
  2014-04-05 23:59:29.550 MethodNameSpace[66948:303] 1
  2014-04-05 23:59:29.551 MethodNameSpace[66948:303] 1


text:
Q: Y86-64 Leading Zero in Start Position Address for Stack Setup I have a question about some Y86 code
If we're given that a stack starts at pos .200 I'm trying to understand this one line at the beginning of the yas output for the program (this is the sum program in the Bryant text, p. 368 Ch 4)
                            |       Execution begins at address 0
0x000:                      |       .pos 0
0x000: 30f40002000000000000 | irmovq stack, %rsp # set up stack pointer

I understand that for irmovq it's set up like
instruction encoding | 0 | F | rB | Value

So if we're setting the stack pointer to address 0x200 why is there a leading zero after the 4? Why isn't it 30f400200... ? I'm guessing it's for alignment but doesn't having that padding change the value of the address?


text:
Q: Change date format (12 hours) to elasticsearch time format (24 hours) with Python I'm working on an agent in python to send data toelasticsearch and I have a field that takes a date, and I need you not to read it as string but as time,
this is an example of the date I am getting 1/29/2019 3:59:06 PM the date that I should get should have the following format2019-01-29T03: 59: 06.142163-0500
Thanks for all :)

A: You should use datetime module, particularly strptime and isoformat methods.
For example:
from datetime import datetime

your_time = '1/29/2019 3:59:06 PM'
result = datetime.strptime(your_time, '%m/%d/%Y %I:%M:%S %p')
print(result, type(result))
# 2019-01-29 15:59:06 <class 'datetime.datetime'>

new_time = result.isoformat(timespec='microseconds')
print(new_time, type(new_time))
# 2019-01-29T15:59:06.000000 <class 'str'>

You can learn more here: https://docs.python.org/3/library/datetime.html


text:
Q: Getting NameError: name 'GL_POINT_SMOOTH' is not defined error while creating plot using Geoplotlib I am trying to create a Dot Map using geoplotlib and getting the following error:
Traceback (most recent call last):
  File "/Users/abc/opt/anaconda3/lib/python3.9/site-packages/geoplotlib/__init__.py", line 32, in _runapp
    app.start()
  File "/Users/abc/opt/anaconda3/lib/python3.9/site-packages/geoplotlib/core.py", line 367, in start
    l.invalidate(self.proj)
  File "/Users/abc/opt/anaconda3/lib/python3.9/site-packages/geoplotlib/layers.py", line 148, in invalidate
    self.painter.points(x, y, 2*self.point_size, False)
  File "/Users/abc/opt/anaconda3/lib/python3.9/site-packages/geoplotlib/core.py", line 517, in points
    glDisable(GL_POINT_SMOOTH)
NameError: name 'GL_POINT_SMOOTH' is not defined

This is the code that I am using:
import geoplotlib
from geoplotlib.utils import read_csv

data = read_csv("merged.csv")

geoplotlib.dot(data)

geoplotlib.show()

The file merged.csv looks like this:
lat,lon,val
24.0,54.0,1.67
33.0,65.0,3.9
17.05,-61.8,2.0
41.0,20.0,1.7
40.0,45.0,1.58
12.25,-68.75,1.82
-12.5,18.5,5.34
-34.0,-64.0,2.22

As per my understanding, this code should work after installing Geoplotlib.
How could I resolve this error?

A: The error message you are seeing suggests that the GL_POINT_SMOOTH constant is not defined in the OpenGL library. This error could be due to a version mismatch between the OpenGL library and geoplotlib.
One possible solution is to try updating OpenGL library to a compatible version. You can do this by running the following command in your terminal:
pip install pyopengl==3.1.5
After installing the new version of pyopengl, try running your code again and see if the error still persists.
If the above solution does not work, another option is to try downgrading the version of geoplotlib. You can try installing version 0.4.0 of geoplotlib using the following command:
pip install geoplotlib==0.4.0
This version of geoplotlib is known to work well with older versions of OpenGL.
Alternatively, you can also try updating geoplotlib to the latest version (0.4.5 as of this writing) and then installing a compatible version of pyopengl.


text:
Q: Did I prove and disprove the following statements correctly? Let $A = \left\{x \in \mathbb{Z} \mid \exists a\in\mathbb{Z}: x = 6a + 4\right\}$
and $B = \left\{y \in \mathbb{Z} \mid \exists b\in\mathbb{Z}:  y = 18b - 2\right\}$
and $C = \left\{z \in\mathbb{Z} \mid \exists c\in\mathbb{Z}:z = 18c + 16\right\}$
Prove or disprove each of the following statements:
a.  $A\subseteq B$
b.  $B\subseteq A$
c.  $A = B$
Did I Prove these correctly?
a. A ⊆ B.
Suppose x is a particular, but arbitrarily chosen element of A.
By definition of A, there is an integer a, such that 6a+4.
Suppose that a = 1 then 6(1)+4=10=x.
Suppose y is a particular, but arbitrarily chosen element of B.
By definition of B, there is an integer b, such that 18b-2.
If x, or 10 in this case is an element of A, then it must be an element of B for A⊆B.
However if 18b-2=10 then
18b=12
b=12/18
b=⅔
Therefore, b is not an integer thus 10 is an element of A, but not of B,
therefore  A ⊈ B.   [This is what needed to be shown.]

b. B  ⊆ A.
Suppose x is an arbitrarily chosen element of A.
By definition of A, there is an integer a, such that 6a+4.
Suppose y is a particular, but arbitrarily chosen element of B.
By definition of B, there is an integer b, such that 18b-2.
Suppose that y =1 then y= 18(1)-2 = 16.
If y, or 16 in this case is an element of B then it must be an element of A for B  ⊆ A.
If 6a+4=16 then,
6a=12
a=12/6
a=2.
Therefore, 16 is an element of both B and A, thus B  ⊆ A. [This is what needed to be shown.]

c.  B=C
Suppose y is an element of B and z is an element of C.  By definition of B, there is an integer b,
Such that 18b-2.  By definition of C, there is an integer c, such that 18c+16.  Suppose that b = 1
Then 18(1) -2 = 16.  If y, or in this case 16 ∈  B, then it must be an element of C for B  ⊆ C.
If 18c+ 16=16
c=0.
0 is an integer, thus y is an element of both B and C, thus B  ⊆ C.
For B=C, C must also be a subset of B.
We know that 0∈ C thus,
18b-2=0
b=1/9
B is not an integer, therefore C⊈B, thus B≠C.

A: In order to show that $A \nsubseteq B$ it is enough to find a single element $x \in A$ which is not an element of $B$. You don't need to write "If x, or 10 in this case is an element of A, then it must be an element of B for A⊆B." Although it's fine to show $a \subseteq B$ results in a contradiction, it's simpler to just show $10 \in A$ but $10 \notin B$
In order to prove that one set is a subset of another, e.g., $B \subseteq A$, you show that any element of $B$ must be an element of $A$. You have successfully shown that 16 is an element of both sets, but not that every $b \in B$ is also in $A$.
In step c you're making an error when you write that "we know that $0 \in C$." $0$ is not in $C$, it is the integer in $\mathbb{Z}$ which we use as $c$ in the definition of $C$ to see that $16 \in C$ as $16 = 18*0 + 16$ and $0 \in \mathbb{Z}$
Try parts b and c again with this information. And remember that your sets, $A, B, C$ contain those elements $x, y, z$ which satisfy the predicates in their definitions, not the $a$,$b$,$c \in \mathbb{Z}$


text:
Q: PHP hangs when run from CMD I have PHP added as an env variable - set to C:\Program Files\PHP\v7.3, but when I run php from CMD the window locks up and it just hangs indefinitely. When run "C:\Program Files\PHP\v7.3\php.exe" directly then the interactive shell starts normally.
No errors in the event log. Microsoft Visual C++ 2019 redistributable is installed. No other versions of PHP present (though there was an old version installed historically).

A: To run PHP in an interactive mode you need to pass the -a flag
example :
php -a  or C:\Program Files\PHP\v7.3\php.exe -a
Running both php or C:\Program Files\PHP\v7.3\php.exe will cause the terminal to hang and a CLI php process to start
You can quit the process by pressing Ctrl + C

A: Running only the php command will cause this problem.
php -r command can be used to run PHP code on CLI. Example: php -r 'echo "Hello world!";'


text:
Q: Cartesian product for multiple sets at compile time I am struggling with an implementation of the Cartesian product for
multiple indices with a given range 0,...,n-1.
The basic idea is to have a function:
cartesian_product<std::size_t range, std::size_t sets>()
with an output array that contains tuples that hold the different products
[(0,..,0), (0,...,1), (0,...,n-1),...., (n-1, ..., n-1)]

An simple example would be the following:
auto result = cartesian_product<3, 2>();

with the output type std::array<std::tuple<int, int>, (3^2)>:
[(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

My main problem is that my version of the Cartesian product is slow and creates a stack overflow if you choose to have more than 5 sets. I believe that my code has too many recursions and temporary variables.
My implementation (C++17) can be found here: cartesian_product
#include <stdio.h>
#include <iostream>

#include <tuple>

template<typename T, std::size_t ...is>
constexpr auto flatten_tuple_i(T tuple, std::index_sequence<is...>) {

    return std::tuple_cat(std::get<is>(tuple)...);

}

template<typename T>
constexpr auto flatten_tuple(T tuple) {
    return flatten_tuple_i(tuple, std::make_index_sequence<std::tuple_size<T>::value>{});
}

template<std::size_t depth, typename T>
constexpr auto recursive_flatten_tuple(T tuple){

    if constexpr(depth <= 1){
        return tuple;
    }else{
        return recursive_flatten_tuple<depth-1>(flatten_tuple(tuple));
    }
}

template<std::size_t depth, typename T, std::size_t ...is>
constexpr auto wdh(T&& tuple, std::index_sequence<is...>){

    if constexpr (depth == 0) {
        return tuple;
    }else{
        //return (wdh<depth-1>(std::tuple_cat(tuple, std::make_tuple(is)),std::make_index_sequence<sizeof...(is)>{})...);
        return std::make_tuple(wdh<depth-1>(std::tuple_cat(tuple, std::make_tuple(is)), std::make_index_sequence<sizeof...(is)>{})...);
    }
}

template<std::size_t sets, typename T, std::size_t ...is>
constexpr auto to_array(T tuple, std::index_sequence<is...>){

    if constexpr (sets == 0){
        auto t = (std::make_tuple(std::get<is>(tuple)),...);
        std::array<decltype(t), sizeof...(is)> arr = {std::make_tuple(std::get<is>(tuple))...};
        //decltype(arr)::foo = 1;
        return arr;
    }else{
        auto t = ((std::get<is>(tuple)),...);
        std::array<decltype(t), sizeof...(is)> arr = {std::get<is>(tuple)...};
        return arr;
    }
}

template<std::size_t sets, std::size_t ...is>
constexpr auto ct_i(std::index_sequence<is...>){

    if constexpr (sets == 0){

        auto u = std::tuple_cat(wdh<sets>(std::make_tuple(is), std::make_index_sequence<sizeof...(is)>{})...);
        auto arr = to_array<sets>(u, std::make_index_sequence<std::tuple_size<decltype(u)>::value>{});

        return arr;

    }else {

        auto u = std::tuple_cat(wdh<sets>(std::make_tuple(is), std::make_index_sequence<sizeof...(is)>{})...);

        auto r = recursive_flatten_tuple<sets>(u);

        auto d = to_array<sets>(r, std::make_index_sequence<std::tuple_size<decltype(r)>::value>{});

        return d;
    }

}

template<std::size_t range, std::size_t sets>
constexpr auto cartesian_product(){

    static_assert( (range > 0), "lowest input must be cartesian<1,1>" );
    static_assert( (sets > 0), "lowest input must be cartesian<1,1>" );
    return ct_i<sets-1>(std::make_index_sequence<range>{});
}

int main()
{
    constexpr auto crt = cartesian_product<3, 2>();

    for(auto&& ele : crt){

        std::cout << std::get<0>(ele) << " " << std::get<1>(ele) << std::endl;

    }

    return 0;
}

A: Since I was also working on a solution I thought I post it aswell (although very similar to Artyer's answer). Same premise, we replace the tuple with an array and just iterate over the elements, incrementing them one by one.
Note that the power function is broken, so if you need power values <0 or non-integer types you have to fix it.
template <typename It, typename T>
constexpr void setAll(It begin, It end, T value)
{
    for (; begin != end; ++begin)
        *begin = value;
}

template <typename T, std::size_t I>
constexpr void increment(std::array<T, I>& counter, T max)
{
    for (auto idx = I; idx > 0;)
    {
        --idx;
        if (++counter[idx] >= max)
        {
            setAll(counter.begin() + idx, counter.end(), 0); // because std::fill is not constexpr yet
        }
        else
        {
            break;
        }
    }
}

// std::pow is not constexpr
constexpr auto power = [](auto base, auto power)
{
    auto result = base;
    while (--power)
        result *= base;
    return result;
};

template<std::size_t range, std::size_t sets>
constexpr auto cartesian_product()
{
    std::array<std::array<int, sets>, power(range, sets)> products{};
    std::array<int, sets> currentSet{};

    for (auto& product : products)
    {
        product = currentSet;
        increment(currentSet, static_cast<int>(range));
    }

    return products;
}

int main()
{
    constexpr auto crt = cartesian_product<5, 3>();

    for (auto&& ele : crt)
    {
        for (auto val : ele)
            std::cout << val << " ";
        std::cout << "\n";
    }

    return 0;
}

Example

A: With Boost.Mp11, this is... alright, it's not a one-liner, but it's still not so bad:
template <typename... Lists>
using list_product = mp_product<mp_list, Lists...>;

template <typename... Ts>
constexpr auto list_to_tuple(mp_list<Ts...>) {
    return std::make_tuple(int(Ts::value)...);
}

template <typename... Ls>
constexpr auto list_to_array(mp_list<Ls...>) {
    return std::array{list_to_tuple(Ls{})...};
}

template <size_t R, size_t N>
constexpr auto cartesian_product()
{
    using L = mp_repeat_c<mp_list<mp_iota_c<R>>, N>;
    return list_to_array(mp_apply<list_product, L>{});
}

With C++20, you can declare the two helper function templates as lambdas inside of cartesian_product, which makes this read nicer (top to bottom instead of bottom to top).
Explanation of what's going on, based on the OP example of cartesian_product<3, 2>:

*

*mp_iota_c<R> gives us the list [0, 1, 2] (but as integral constant types)

*mp_repeat_c<mp_list<mp_iota_c<R>>, N> gives us [[0, 1, 2], [0, 1, 2]]. We just repeat the list, but we want a list of lists (hence the extra mp_list in the middle).

*mp_apply<list_product, L> does mp_product, which is a cartesian product of all the lists you pass in... sticking the result in an mp_list. This gives you [[0, 0], [0, 1], [0, 2], ..., [2, 2]], but as an mp_list of mp_list of integral constants.

*At this point the hard part is over, we just have to convert the result back to an array of tuples. list_to_tuple takes an mp_list of integral constants and turns that into a tuple<int...> with the right values. And list_to_array takes an mp_list of mp_lists of integral constants and turns that into an std::array of tuples.

A slightly different approach using just the single helper function:
template <template <typename...> class L,
    typename... Ts, typename F>
constexpr auto unpack(L<Ts...>, F f) {
    return f(Ts{}...);
}

template <size_t R, size_t N>
constexpr auto cartesian_product()
{
    using P = mp_apply_q<
        mp_bind_front<mp_product_q, mp_quote<mp_list>>,
        mp_repeat_c<mp_list<mp_iota_c<R>>, N>>;

    return unpack(P{},
        [](auto... lists){
            return std::array{
                unpack(lists, [](auto... values){
                    return std::make_tuple(int(values)...);
                })...
            };
        });
}

This approach is harder to read though, but it's the same algorithm.

A: You can do this without recursion easily. Notice that each tuple is the digits of numbers from 0 to range ** sets in base range, so you could increment a counter (Or apply to a std::index_sequence) and calculate each value one after the other.
Here's an implementation (That returns a std::array of std::arrays, which works mostly the same as std::tuples as you can get<N>, tuple_size and tuple_element<N> on a std::array, though if you really wanted you can convert them to std::tuples):
#include <cstddef>
#include <array>

namespace detail {
    constexpr std::size_t ipow(std::size_t base, std::size_t exponent) noexcept {
        std::size_t p = 1;
        while (exponent) {
            if (exponent % 2 != 0) {
                p *= base;
            }
            exponent /= 2;
            base *= base;
        }
        return p;
    }
}

template<std::size_t range, std::size_t sets>
constexpr std::array<std::array<std::size_t, sets>, detail::ipow(range, sets)>
cartesian_product() noexcept {
    constexpr std::size_t size = detail::ipow(range, sets);
    std::array<std::array<std::size_t, sets>, size> result{};
    for (std::size_t i = 0; i < size; ++i) {
        std::size_t place = size;
        for (std::size_t j = 0; j < sets; ++j) {
            place /= range;
            result[i][j] = (i / place) % range;
        }
    }
    return result;
}

Here's a test link: https://www.onlinegdb.com/By_X9wbrI
Note that (empty_set)^0 is defined as a set containing an empty set here, but that can be changed by making ipow(0, 0) == 0 instead of 1

A: I was trying it out just for fun and I ended with pretty much the same idea as @Timo, just with a different format/style.
#include <iostream>
#include <array>
using namespace std;

template<size_t range, size_t sets>
constexpr auto cartesian_product() {
    // how many elements = range^sets
    constexpr auto size = []() {
        size_t x = range;
        size_t n = sets;
        while(--n != 0) x *= range;
        return x;
    }();

    auto products = array<array<size_t, sets>, size>();
    auto counter = array<size_t, sets>{}; // array of zeroes

    for (auto &product : products) {
        product = counter;

        // counter increment and wrapping/carry over
        counter.back()++;
        for (size_t i = counter.size()-1; i != 0; i--) {
            if (counter[i] == range) {
                counter[i] = 0;
                counter[i-1]++;
            }
            else break;
        }
    }
    return products;
}

int main() {
    auto prods = cartesian_product<3, 6>();
}

I basically have a counter array which I increment manually, like so:
// given cartesian_product<3, 4>
[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 0, 2]
[0, 0, 1, 0] // carry over
...
...
[2, 2, 2, 2]

Pretty much just how you would do it by hand.
Example

A: If you want it in compile-time, you should only employ compile-time evaluations over compile-time data structures. As @Barry pointed above, using Boost.Mp11 greatly facilitates it. Of course you can do reimplement the relevant fundamental functions in plain C++17 on your own:
#include <iostream>

template<class T> struct Box {
        using type = T;
};

template<class... Types> struct List {};

template<class Car, class Cdr> struct Cons;
template<class Car, class Cdr> using ConsT = typename Cons<Car, Cdr>::type;

template<class Car, class... Cdr> struct Cons<Car, List<Cdr...>>: Box<List<Car, Cdr...>> {};

using Nil = List<>;

template<std::size_t i, class L> struct Nth;
template<std::size_t i, class L> using NthT = typename Nth<i, L>::type;

template<std::size_t i, class... Ts> struct Nth<i, List<Ts...>>: std::tuple_element<i, std::tuple<Ts...>> {};

template<class L> struct Head;
template<class L> using HeadT = typename Head<L>::type;

template<class Car, class... Cdr> struct Head<List<Car, Cdr...>>: Box<Car> {};

template<class L> struct Tail;
template<class L> using TailT = typename Tail<L>::type;

template<class Car, class... Cdr> struct Tail<List<Car, Cdr...>>: Box<List<Cdr...>> {};

template<class... Lists> struct Concat;
template<class... Lists> using ConcatT = typename Concat<Lists...>::type;

template<class T, class... Rest> struct Concat<T, Rest...>: Cons<T, ConcatT<Rest...>> {};

template<class Head, class... Tail, class... Rest> struct Concat<List<Head, Tail...>, Rest...>: Cons<Head, ConcatT<List<Tail...>, Rest...>> {};

template<class... Rest> struct Concat<Nil, Rest...>: Concat<Rest...> {};

template<> struct Concat<>: Box<Nil> {};

template<class T, class Subspace> struct Prepend;
template<class T, class Subspace> using PrependT = typename Prepend<T, Subspace>::type;

template<class T, class... Points> struct Prepend<T, List<Points...>>: Box<List<ConsT<T, Points>...>> {};

template<class T> struct Prepend<T, Nil>: Box<List<List<T>>> {};

template<class Range, class Subspace> struct Product;
template<class Range, class Subspace> using ProductT = typename Product<Range, Subspace>::type;

template<class Range, class Subspace> struct Product: Concat<PrependT<HeadT<Range>, Subspace>, ProductT<TailT<Range>, Subspace>> {};

template<class Subspace> struct Product<Nil, Subspace>: Box<Nil> {};

template<std::size_t i> using IntValue = std::integral_constant<std::size_t, i>;

template<class Seq> struct IntegerSequence;
template<class Seq> using IntegerSequenceT = typename IntegerSequence<Seq>::type;

template<std::size_t... is> struct IntegerSequence<std::index_sequence<is...>>: Box<List<IntValue<is>...>> {};

template<std::size_t n> using Range = IntegerSequenceT<std::make_index_sequence<n>>;

template<std::size_t dimensions, std::size_t range> struct CartesianCube;
template<std::size_t dimensions, std::size_t range> using CartesianCubeT = typename CartesianCube<dimensions, range>::type;

template<std::size_t dimensions, std::size_t range> struct CartesianCube: Product<Range<range>, CartesianCubeT<dimensions - 1, range>> {};

template<std::size_t range> struct CartesianCube<0, range>: Box<Nil> {};

template<std::size_t i> std::ostream &operator<<(std::ostream &s, IntValue<i>) {
        return s << '<' << i << '>';
}

template<class... Ts> std::ostream &operator<<(std::ostream &s, List<Ts...>);

namespace detail_ {

template<class L, std::size_t... is> std::ostream &printList(std::ostream &s, L, std::index_sequence<is...>) {
        return ((s << (is == 0? "" : ", ") << NthT<is, L>{}), ...), s;
}

}

template<class... Ts> std::ostream &operator<<(std::ostream &s, List<Ts...>) {
        return detail_::printList(s << "List{", List<Ts...>{}, std::index_sequence_for<Ts...>{}) << '}';
}

int main() {
        std::cout << CartesianCubeT<2, 3>{} << '\n';
}

Note that CartesianCubeT here is actually a List of Lists of integral_constants. Once you have those, converting them into run-time values is trivial. Note that cartesian_product does not even have to be a function, since the whole data set is evaluated at compile-time it can be a templated value.


text:
Q: UPDATE Changed String: How to write regex for python so that it pulls out a term and its definition? UPDATE:
As you might expect, they changed the software and so my text has changed.
Now the regex that worked does not.
Here is what worked before:
r"^ \"(?P.?)\" refers to (?P(?:(?!^ \".?\" refers to ).)*)"
with Multiline and dotall.
I have been working to fix it on https://regex101.com/.
I think the negative lookahead piece is failing.
I get the first term, but then it grabs everything after that.
Thanks for any help you can provide.
Test String:
"Address mapping table" refers to a data structure that associates logical block addresses with physical addresses of data stored on a non-volatile memory array.  The table may be implemented as an index, a map, a b-tree, a content addressable memory (CAM), a binary tree, and/or a hash table, and the like. The address mapping table may be referred to interchangeably as a Group Allocation Table (GAT).
"Asymmetric storage media" refers to a storage media having different latencies for different storage operations. Many types of solid-state storage media (e.g., memory dies) are asymmetric; for example, a read operation may be much faster than a write/program operation, and a write/program operation may be much faster than an erase operation (e.g., reading the storage media may be hundreds of times faster than erasing, and tens of times faster than programming the storage media).
"Bit line" refers to a circuit structure configured to deliver a voltage and/or conduct current to a column of a memory array.  In one embodiment, the column comprises a NAND string or memory string and may also be referred to as channel. In one embodiment, the column is referred to as a NAND string and the NAND string comprises a channel. In one embodiment, a bit line connects to a NAND string at a drain end or drain side of the NAND string. A memory array may have one bit line for each memory cell along the word lines of the memory array.

A: I have potentially overcomplicated the regex, but here goes:
regex = re.compile(
    r"^\"(?P<term>[^\"]*?)\" refers to (?P<def>(?:(?!^\"[^\"]*?\" refers to ).)*)",
    re.MULTILINE | re.DOTALL)

(if you want to mess around with it interactively, you can try it out at regex 101)
# show what it matches:
for m in regex.finditer(contents):
    groups = m.groupdict()
    print("term: %s" % groups["term"])
    print("%s" % ("-" * 60)) # make it clear where the term ends
    d = groups["def"].strip() # regex includes blank lines
    print("%s [...] %s" % (d[:20], d[-20:])) # definitions are too long to print
    print("\n%s\n" % ("=" * 60))

Output:
(note that I only printed a snippet of the definition, but the full def is matched)

term: Adjacent word line
------------------------------------------------------------
a word line physical [...] r a coupling effect.

============================================================

term: Bit line
------------------------------------------------------------
a circuit structure  [...] of the memory array.

============================================================

term: Bit line compensation voltage
------------------------------------------------------------
a voltage supplied t [...]  line is programmed.

============================================================

Regex Explanation
Flags to re.compile:

*

*re.MULTILINE: make ^ and $ match the beginning and end of a line respectively; the default is to match the beginning/end of the entire string, which we don't want

*re.DOTALL: make . also match the newline char; we need this to match the multiline definitions

What's with all the question marks:

*

*.*?: by default, .* is exceptionally greedy; the question mark makes it not greedy

The '', '+', and '?' qualifiers are all greedy; they match as much
  text as possible. Sometimes this behaviour isn't desired; if the RE
  <.> is matched against  b , it will match the entire string,
  and not just . Adding ? after the qualifier makes it perform the
  match in non-greedy or minimal fashion; as few characters as possible
  will be matched. Using the RE <.*?> will match only .

*(?P<name>...): denotes a "capturing group" so that we can grab this matched bit by name later -- not necessary, but I find it's easier to work with.

*(?:...): denotes a "non-capturing group"; this just means I needed to wrap some bit of regex in parentheses, but I didn't want it to be treated as its own group.

*(?!...): the most complicated part of this --- the "negative lookahead" expression. This means the matched text should not contain the enclosed regex. This prevents the definition match from continuing into the next term.

*Putting it together: (?!^\".*?\" refers to ).)*) says to match zero or more of any character, unless the characters begin with "${some-term} refers to "


text:
Q: Test if the device is shaken, using Titanium's acclerometer I want to use the accelerometer in Titanium to determine if the device is shaken or not.
How would I go about checking this?

A: Ti.Gesture has a shake event thats been in the Titanium SDK since version .8

shake
Fired when the device is shaken.
A shake gesture consists of a series of quick accelerations, and is represented by a series of shake events.
The timestamp property represents the interval between shake events. It is measured in milliseconds on Android and Mobile Web, and in seconds on iOS.
Note that Mobile Web detect shake gestures using the device accelerometer, if the device and browser support this. This event cannot be generated on Mobile Web in the iOS simulator. The simulator's Shake Gesture menu item generates a native shake event, but does not generate accelerometer events to the browser.

http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Gesture


text:
Q: What happens to the index of refraction of a lens if placed in water? What happens to the index of refraction and focal length of a lens that is initially in air that is then placed in water?

A: The index of refraction of the lens will remain the same (the medium remains the same, whether in a vacuum, in air, immersed in water, etc.), but the focal length will increase.
The index of refraction of water is greater than that of air, so light entering through the lens will be refracted at a smaller angle with respect to the horizontal of the lens than it would in air.

A: It depends, suppose the refractive index of the lens is same as that of water. Then, no refraction takes place, it means the focal length of the lens becomes infinite. For example, glycerin and Pyrex rod has approximately same refractive index. If you immerse Pyrex rod in glycerin, Pyrex becomes invisible.
Index of refraction doesn't change, but focal length changes according to the medium in which you place.

A: The effect of Snell's law is that the equalivent defraction is set by the ratios of the individual refactravive indexes.  So if your lens has a refractive index of 4 in air, and water having $1 \frac 13$, then the effect of putting the lens in water is $4 \div 1\frac 13$ or the same solution as the lense of refractive index $3$ in air.


text:
Q: Replace string and rest of line with other string So here's what I want to do:
I have a string origStr, which is at the beginning of a line in a Word document. After origStr is an unknown value (e.g. 23 or 2,6)
I want to find that string and replace the value after with another known value, but keep the string.
Example in my Word document:
Diam. diastole, mm: 53

[Running VBA makro where user input is 54,3]
Expected Result:
Diam. diastole, mm: 54,3

Actual result:
Diam. diastole, mm: 54,3 53

So here's what i got:
origStr = LArray(i, j - 1).Caption & ": *"
replStr = LArray(i, j - 1).Caption & ": " & TBArray(i, j).Text

With ActiveDocument.Content.Find
    .MatchWildcards = True
    .ClearFormatting
    .Text = origStr
    .Replacement.ClearFormatting
    .Replacement.Text = replStr
    .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
End With

Why isn't my old value being deleted?
Thanks in advance!

A: Word uses "lazy" pattern matching which is good in this case because otherwise it would just replace  the rest of your entire document. Vincent G gave a solution for one word (no more than one space in the rest of the line), here is something more general:
To get Word to replace everything until the end of the line, you need to include the end of the line into the search string. ^l or ^11 is the control code for new line (shift+enter), ^12 is page or section break, ^13 is carriage return.
This is the most "recent" list I found.
So "yourtext*^11" would match everything from "yourtext" until the next new line and so on.
Depending on your formatting, it could be either one of the above so you have to be careful. If you replace "*^12" but your lines end with new line, you will replace the whole paragraph.
To catch all of them, you can group them: yourtext*[^11^12^13] will match everything until the next new line or carriage return. However if we replace that, the end of the line will be replaced as well so we have to include it in the replacement text. How do we know what it was?
We can use () to define a submatch and \1, \2 etc to use these submatches in the replacement text:
origStr = LArray(i, j - 1).Caption & ": *([^11^12^13])"
replStr = LArray(i, j - 1).Caption & ": " & TBArray(i, j).Text & "\1"

Example:
before:

after replacing with origStr = "yourtext*([^11^12^13])" and replStr = "yourtext newtext\1":

Note: These expressions also work with the Find and Replace dialog, just make sure "Use Wildcards" is enabled

A: Its not really a VBA problem, the same happening in "Find and Replace" dialog.
Replace your original string with:
origStr = LArray(i, j - 1).Caption & ": <*>"


text:
Q: Is there a way to use getall() to fetch only some properties in the data? say my data stored in db is as follow:
key1 : {a:1,b:1,c:1}
key2 : {a:1,b:1,c:1}

is there any way I can use getAll() to get only the property c in each piece of data? sort of how to get the data in a column in sql database. I understand using cursor could achieve this, but the performance is nasty.

A: You could make an index on c and then use getAllKeys. Adding an index has performance implications as well, though.


text:
Q: How to stop a postback from a radpanelitem in a masterpage? I have double checked to make sure that this isn't a duplicate question...I have a masterpage that has a side nav bar and it looks like this..
<asp:Panel ID="pnl1" runat="server" Width="100px" Height="572px">
<telerik:RadPanelBar ID="RadPanelBar1" runat="server">
    <Items>
        <telerik:RadPanelItem Text="Vendors" Expanded="false" runat="server">
            <Items>
                <telerik:RadPanelItem Text="Search Vendor" NavigateUrl="../GO_Browse_Vendors.aspx" />
                <telerik:RadPanelItem Text="Add Vendor" />
                <telerik:RadPanelItem Text="Update Vendor" />
                <telerik:RadPanelItem Text="Delete Vendor" />
            </Items>
        </telerik:RadPanelItem>
    </Items>
</telerik:RadPanelBar>

when I click on Search Vendor, I get a complete postback and I really don't understand why that is happening, I want to be able to just click on an item and the page appear without having a postback.
At first I used JavaScript to open a RadWindow, and that didn't cause any postback. Then I realized, that the user will probably get lost with a bunch of Radwindows. Then I decided that I should have the Search Vendor to just be a page and use radwindows for updating a record.
I thought about using JQuery but I am at a loss on how that would work. Is there anyway I can do this without causing a postback?
I wrote this JavaScript to call a RadWindow...
function OnAreaClick(sender, args) {
        var menuItem = args.get_item().get_text();

        switch (menuItem) {
            case 'Search Vendor':
                {
                    OpenRadWindow2("WebForm9.aspx");
                }
            default: { }
        }

I'm sure that this is simple, but I am not finding it simple.

A: I got it figured out...I dug around and used JQuery.Load...No postback is happening now, this is the code that I used..
function OnAreaClick(sender, args) {
        var menuItem = args.get_item().get_text();

        switch (menuItem) {
            case 'Search Vendor':
                {
                    GetForm("GO_Browse_Vendors.aspx");
                }
            default: { }
        }
    }
    function GetForm(url) {
        $("#RZone").load(url, {}, function () { });
    }


text:
Q: FullCalendar eventClick from outside working with problems Hi I have this current JS for fullCalendar (v 1.6.4):
eventRender: function(event, element, view) {
    element.find('.fc-event-inner').attr("id", "event-" + event.id_event);
},
eventClick: function(calEvent, jsEvent, view) {
    alert("Event clicked: "+calEvent);
}

This works ok if I click on an event.
I than have this button:
$('#ext-click').click(function(){
    $('#event-120.fc-event-inner').trigger('click');
})

(Note: #event-120 is a correct id for the event)
Now, when clicking on #ext-event button nothing happens, BUT, if I click on the event-120 I get the alert, I close the alert and I press #ext-event this time the alert appears.
So #ext-event works only if I first click on event-120, otherwise nothing happens.
Expectancy:
When clicking on #ext-event I should get the event-120 alert every time.
Try this fiddle: https://jsfiddle.net/hs0q6r3v/1/
You will see by clicking the "Click-me" button as first thing, nothing happens. Click then on the event, you'll get an alert, close it and click on the "Click-me" button again, this time it works.

A: I'd recommend to rethink this user experience approach by triggering a click by button. What's the reason for that? If you want to do a select then use the fullcalendar select method, etc.
Why it's probably not working:
A fullcalendar event is different from a  with the id of a fullcalendar id. That might be the reason why the order of clicking is important cause there is a listener generated for this div showing this event. But you can't rely on that the internal Id of an event will always be reflected in the DOM.
e.g. In the latest fullcalendar release the fullcalendar event_id is not used for the id of the related
Approaches for dealing with page change:
I use both approaches in my applications

*

*New Page

*

*calendarview has optional parameter

*pass  "selected_id" to the new page

*when leaving "new_page" pass back "selected_id"

*when calendarview receives a "selected_id"  deal with it in the "eventRender" method (e.g. special styling for highlighting, ...)

*Modal Dialog
if convenient you can also use a modal dialog, so the calendarview will stay the same.


text:
Q: Why doesn't Windows let a program called by mod_authnz_external use the network? I need to use Apache (XAMPP) under Windows with mod_authnz_external, which is a module that lets you handle authentication through your own external program. (My use case is pretty complex.) The program receives a line with the username and a line with the password, and returns the result in its exit code: 0 for success, anything else for failure.
The custom-compiled mod_authnz_external has no problem with launching the external auth handler and the solution works well for simple handlers.
However, I need my auth handler to authenticate against an external service. This works well when I run the handler manually (i.e., through cmd.exe), but when the handler is invoked by the mod_authnz_external module, it gets all kinds of weird errors.
My first shot at a handler in C# looked like this:
class Program {
    static string LOGIN_ENDPOINT = "https://REDACTED";

    static bool CredentialsAreGood(string username, string password) {
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(new Uri(LOGIN_ENDPOINT));
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        NameValueCollection formData = HttpUtility.ParseQueryString(string.Empty);
        formData.Add("username", username);
        formData.Add("password", password);
        var bytes = Encoding.ASCII.GetBytes(formData.ToString());
        request.GetRequestStream().Write(bytes, 0, bytes.Length);

        try {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK /* 200 */) {
                return true;
            }
            return false;
        } catch (WebException e) {
            return false;
        }
    }

    static void Main(string[] args) {
        string username = Console.ReadLine();
        string password = Console.ReadLine();

        if (CredentialsAreGood(username, password)) {
            Console.Error.WriteLine("Access ok for " + username);
            Environment.Exit(0);
        } else {
            Console.Error.WriteLine("Access BAD for " + username);
            Environment.Exit(1);
        }
    }
}

The error I got when having this C# program invoked by mod_authnz_external occurs in the WebRequest.Create method and looks like this:

Details:

Stack trace of InnerException:
at System.Net.SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, Boolean autoReset, Boolean signaled)
at System.Net.NetworkAddressChangePolled..ctor()
at System.Net.AutoWebProxyScriptEngine.AutoDetector.Initialize()
at System.Net.AutoWebProxyScriptEngine.AutoDetector.get_CurrentAutoDetector()
at System.Net.AutoWebProxyScriptEngine..ctor(WebProxy proxy, Boolean useRegistry)
at System.Net.WebProxy.UnsafeUpdateFromRegistry()
at System.Net.WebProxy..ctor(Boolean enableAutoproxy)
at System.Net.Configuration.DefaultProxySectionInternal..ctor(DefaultProxySection section)
at System.Net.Configuration.DefaultProxySectionInternal.GetSection()

I also tried using a similar program in Java and got a different kind of error, also in networking (the host happens to exist):
Exception in thread "main" java.net.UnknownHostException: REDACTED.REDACTED.com
 at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method)
 at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source)
 at java.net.InetAddress.getAddressesFromNameService(Unknown Source)
 at java.net.InetAddress.getAllByName0(Unknown Source)
 at java.net.InetAddress.getAllByName(Unknown Source)
 at java.net.InetAddress.getAllByName(Unknown Source)
 at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
 at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:111)
 at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
 at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
 at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
 at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
 at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
 at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
 at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
 at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
 at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
 at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
 at Authenticate.checkCredentials(Authenticate.java:33)
 at Authenticate.main(Authenticate.java:21)

The same also happens when I run the Apache daemon as Administrator. The approach I'm trying works well under Linux, but the target environment is Windows. My current guess is there might be some security feature that's preventing the handler from accessing the network if it's launched by Apache, but it doesn't kick in when I launch the handler manually (both handlers work when I run them myself).
EDIT: Disabling Windows firewall also does not help.
What's causing my handlers to fail when accessing the network? How do I work around it?
Thanks a lot!

A: The most likely cause of your problem is your program is not being allowed through the windows builtin firewall. Add the allow rule and it should work.


text:
Q: VS Code Using Python 2.7.10 instead of Python 3.7.6 after activating virtual environment I have had trouble for months using packages and libraries in VS Code. Everytime I create and activate a new python virtual environment in VS Code, it defaults back to using the MacOS pre-installed python 2.7.10. A picture below shows my issue. I would like to see "/usr/local/bin/python3" when I type the command "python --version", instead I get "/usr/bin/python". Does anyone know how to fix this? Thanks.
Picture of problem

A: I'm not a MacOS user and can't see your picture due to my network, but you can create the virtual environment with a specific version of Python.
On Windows this is:
python3.8 -m venv envname

If you are creating a virtual environment by using python -m venv envname the issue is the default interpreter on your PC is set to Python 2. A quick search shows you might be able to set a different global version on a Mac with something like pyenv global 3.8.6. I'm not sure if this would have other implications for you.

A: *

*Please try to open a new VS Code terminal to let it reload the currently selected python environment. (Terminal; New Terminal; shortcut keys: Ctrl+Shift+`)

*For the global python environment in VS Code, even though we have switched the python environment, sometimes its internal terminal still uses the first python of the python environment variable. Therefore, it is recommended that you move the python you need to use to the first: (Please reopen VS Code after setting.)


text:
Q: Java: ConcurrentModificationException when iterating over hashmap? I have read this post here. However, I do not understand how to extract the value pair from the iterator such that I can put it into a conditional expression to decide whether the key-value pair should be removed.
My original code is as follow, which throws this ConcurrentModificationExceptionat runtime:
for(Map.Entry<String, Order> o: orderIDHashMap.entrySet()) {

    if(o.getValue().getOrderQuantity() == 0) {
        orderIDHashMap.remove(o.getKey());
    }
}

I tried to switch it to:
    Iterator orderIDHashMap_iterator = orderIDHashMap.entrySet().iterator();

    while(orderIDHashMap_iterator.hasNext()) {
        Map.Entry<String, Order> pair = (Entry<String, Order>) orderIDHashMap_iterator.next();
        if(pair.getValue().getOrderQuantity() ==0 ) {
            orderIDHashMap_iterator.remove();
        }
    }
}

Question: Is my code above correct in implementing iterator to remove object Order when Order quantity == 0 condition is met?  If it is wrong, can someone provide me an answer or a more efficient / elegant way to code this up .
Thanks.


text:
Q: consulta entre dos fechas con hora Estoy viendo como hacer una consulta en postgres en la cual pueda aplicar un between en algo como:
Viernes : 17:00Hrs / Domingo: 20:00 Hrs
Esto para cada semana
Si me pueden ayudar se los agradeceria.
Saludos!

A: Te recomiendo que vayas a la documetación de PostgreSQL y leas sobre la funcion EXTRACT, con ella puedes obtener varios datos de las fechas y asi poder aplicar tu filtro, sobre todo mira las opciones dow, hour y minute


text:
Q: Add primary key column in SQL table I am student of RDBMS.
I have very basic question let say I have one existing Table in SQL server. What will be script to alter table.

*

*Drop Column 'RowId' if exist.

*Drop contraint if exist.

*Add one new column 'RowId' into table.

*Make this column as primary key.

*Autoincrement type int.

A: Note: this answer was added before questions update

*

*Add new column (note: you can only have one IDENTITY column per table)

*Drop old primary key

*Add new primary key

*Drop old column if needed

Sample script:
CREATE TABLE whatever (
     OldPKColumn uniqueidentifier NOT NULL,
     CONSTRAINT PK_whatever PRIMARY KEY (OldPKColumn)
    )

ALTER TABLE whatever
    ADD RowId int NOT NULL IDENTITY (1,1);

ALTER TABLE whatever
    DROP CONSTRAINT PK_whatever;

ALTER TABLE whatever WITH CHECK
    ADD CONSTRAINT PK_whatever PRIMARY KEY CLUSTERED (RowId);

ALTER TABLE whatever
    DROP COLUMN oldPKcolumn;

And a random thought... are you trying to reset an IDENTITY column?
If so, then use DBCC CHECKIDENT

A: Just a comment to improve these great answers (can't use comments yet - I'm one reputation point away from that privilege) and as future reference for myself:
A new IDENTITY (autonumber) column can be added and made the primary key in a single statement as well:

ALTER TABLE [TableName] ADD [ColumnName] int IDENTITY PRIMARY KEY;

I prefer not to bother with constraint names when it doesn't help.
You can specify seed (and increment) values between parantheses after the IDENTITY keyword.

A: In SQL Server 2005 or newer, you could use this script:
-- drop PK constraint if it exists
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.YourTable') AND Name = 'PK_YourTable')
   ALTER TABLE dbo.YourTable
   DROP CONSTRAINT PK_YourTable
GO

-- drop column if it already exists
IF EXISTS (SELECT * FROM sys.columns WHERE Name = 'RowId' AND object_id = OBJECT_ID('dbo.YourTable'))
    ALTER TABLE dbo.YourTable DROP COLUMN RowId
GO

-- add new "RowId" column, make it IDENTITY (= auto-incrementing)
ALTER TABLE dbo.YourTable
ADD RowId INT IDENTITY(1,1)
GO

-- add new primary key constraint on new column
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (RowId)
GO

Of course, this script may still fail, if other tables are referencing this dbo.YourTable using foreign key constraints onto the pre-existing RowId column...
Update: and of course, anywhere I use dbo.YourTable or PK_YourTable, you have to replace those placeholder with the actual table / constraint names from your own database (you didn't mention what they were, in your question.....)


text:
Q: How to sort a list of objects Supposing that I have a list of Test as below:
    public class Test {
    public static enum Unit {
        DAY, WEEK, MONTH, YEAR /* , DAY_TO_DAY */
    }

    private int value;
    private Unit unit;
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public Unit getUnit() {
        return unit;
    }
    public void setUnit(Unit unit) {
        this.unit = unit;
    }
}

I will have a list of Test with the below values :
3 day,
 5 month,
 5 day,
 6 year,
 6 week,
 12 week,
and our expection result as below :
3 day, 5 day, 6 week , 12 week, 5 month, 6 year
Currently, I create a code as below
Collections.sort(tests, new Comparator<Test >() {
  @Override
  public int compare(Test o1, Test o2) {
    if(o1.getValue() > o2.getValue()) return 1;
    if(o1.getValue() < o2.getValue()) return -1;
    return 0;
  }

However, it only sort by value and not by Unit.
The result with the above implementation is :
3 day, 5 day,  5 month, 6 week , 6 year, 12 week.
Please tell me know the way to satisfy two conditions (Unit and values) in this case.
Thanks.

A: You'll need to convert first into common format, and then compare. Since days are your smallest type, you should convert the two instances you're comparing into a number of days, and then compare based on that.
But you have some disambiguation to do first. How long is a month? Is it longer than 30 days, or shorter, or the same?

A: If you simply want to compare according to your example the following code solves the problem:
Collections.sort(terms, new Comparator<Test>() {
    @Override
    public int compare(final Test o1, final Test o2) {
        int unitCompare = o1.getUnit().compareTo(o2.getUnit());
        if (unitCompare == 0) {
            return o1.getValue() - o2.getValue();
        }
        return unitCompare;
    }
});

However, this code does NOT factor in that months can have different length and the code does NOT factor in that 35 days is longer than a month.
In order to do that i suggest that the classes from the java.time package (such as java.time.Period) are used to make proper comparisons (a good trail to learn about this can be found here). If Java 8 is not an option Joda Time provides the same type of functionality.

A: You'll first have to check on the basis of Unit and then on the basis of Value in the overridden compareTo(). See here the implementation of sorting on the basis of lastname and then firstname:http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

A: Use TimeUnit to replace your Unit enum.
Your Term class could therefore have a .toMillis() method which is very simple:
public final long toMillis()
{
    return timeUnit.toMillis(value);
}

You can then just Long.compare(o1.toMillis(), o2.toMillis()) in your Comparator.
Other solutions:

*

*if you use Java 8, use the new date/time API;

*if you use Java 7- and threetenbp, use the same methods, backported;

*if you use Java 7- and Joda Time, use Period. It is nearly equivalent to that of Java 8's/threetenbp's.

A: If you really want to do it that way, assign your enums values like so:
DAY(1), WEEK(7), MONTH(31), YEAR(365)
than multiply in your comperator
Unit.getValue() *  value
e.g. 4 MONTH gives you 31 * 4 = 124 is bigger than 100 DAY.
still you have the problem that teher are months with less than 31 days. recommend to convert to some common date units e.g. joda time.

A: Please use the compareto function as below:
public int compareTo(Object o) {
        Test t1 = (Test)this;
        Test t2 = (Test)o;
        if(t1.getValue()*(t1.getUnit().getValue()+1) > t2.getValue()*(t2.getUnit().getValue()+1)) return 1;
        if(t1.getValue()*(t1.getUnit().getValue()+1) < t2.getValue()*(t2.getUnit().getValue()+1)) return -1;
        return 0;
    }

and change the enum to
 public static enum Unit {
    DAY(1), WEEK(7), MONTH(31), YEAR(365) ;/* , DAY_TO_DAY */
        private final int id;
        Unit(int id) { this.id = id; }
    public int getValue() { return id; }
    }

Now you use the collection.sort(), and it will be sorted automatically


text:
Q: Getting "TypeError: expected raster or layer name" when input is raster I have a script that adds output rasters' paths to a list and that list is used to loop through each input in a later module. I am getting the following error:

TypeError: expected raster or layer name

when I test if a path is in that list.
I have printed the list, the path is correct and has no spaces or other invalid characters (C:\Users\VanHorn\Documents\ArcGIS\scratch\Watersh_D8FlowD2.tif). The type is also raster (.tif). The TIFF also has spatial reference so that is not the issue. The file looks good when brought into ArcMap.
Here are sections of my code... the error is thrown at this line:
"if pract == acpfGWwatershed:"
# --------------------------------------------------------------------------------------------------------------
# Create lists to hold path to watersheds

def createListOfWatersheds():

    # create list to hold acpf watersheds
    acpfWatershedList = []

    # create list to hold existing watersheds
    existWatershedList = []

    return(acpfWatershedList, existWatershedList)

# --------------------------------------------------------------------------------------------------------------
# grass waterway watersheds

def acpfGWwatersheds(GWacpf, flowDir, acpfWatershedList):

    if arcpy.Exists(GWacpf):

        arcpy.AddMessage("Generating ACPF grass waterway watersheds...")

        # convert grass waterway feature to raster
        gwRas = arcpy.FeatureToRaster_conversion(GWacpf, "OBJECTID", "in_memory" + r"\gwRas", cellsize)

        # create list of grass waterway IDs
        gwIDs = [row[0] for row in arcpy.da.SearchCursor(GWacpf, "OBJECTID")]

        # generate bank cells of waterways- use later to get watersheds
        bankCells = Con(IsNull(gwRas), Expand(gwRas, 1, gwIDs), "", "")

        # buffer grasswaterways for mask
        buffDist = cellsize * 3
        gwBuffer = arcpy.Buffer_analysis(GWacpf, "in_memory" + r"\gwBuff", buffDist, "FULL", "FLAT", "NONE", "", "PLANAR")

        # mask banks to remove "headwaters"
        banks = ExtractByMask(bankCells, gwBuffer)

        # watershed
        acpfGWwatershed = Watershed(flowDir, banks, "Value")
        acpfGWwatershed.save()

        acpfWatershedList.append(acpfGWwatershed)

        del(gwRas, gwIDs, bankCells, buffDist, gwBuffer, banks)

        return(acpfWatershedList, acpfGWwatershed)

# --------------------------------------------------------------------------------------------------------------
# Runoff area treated table for suggested practices

def acpfRunoffWatersheds(catchments, acpfWatershedList, acpfTable):

    arcpy.AddMessage("Creating area treated table for ACPF practices...")
    arcpy.AddMessage(acpfWatershedList)

    # convert boundary to raster to use in Cell Statistics later
    boundaryRas = arcpy.FeatureToRaster_conversion(catchments, "riparianid", "in_memory" + r"\boundaryRas", cellsize)
    boundaryCon = Con(boundaryRas, "1000", "", "Value > 0")

    ACPFwatersheds = []

    ACPFwatersheds.append(boundaryCon)

    for pract in acpfWatershedList:
        if pract == acpfGWwatershed:
            GWcon = Con(pract, "1", "", "Value > 0")
            ACPFwatersheds.append(GWcon)

    acpfRunoffStack = CellStatistics(ACPFwatersheds, "SUM")

Complete code:
import arcpy
from arcpy import env
from arcpy.sa import *
import sys, string, os, time
arcpy.CheckOutExtension("Spatial")

arcpy.env.scratchWorkspace = env.scratchFolder

# --------------------------------------------------------------------------------------------------------------
# Create lists to hold path to watersheds

def createListOfWatersheds():

    # create list to hold acpf watersheds
    acpfWatershedList = []

    # create list to hold existing watersheds
    existWatershedList = []

    return(acpfWatershedList, existWatershedList)

# --------------------------------------------------------------------------------------------------------------
# grass waterway watersheds

def acpfGWwatersheds(GWacpf, flowDir, acpfWatershedList):

    if arcpy.Exists(GWacpf):

        arcpy.AddMessage("Generating ACPF grass waterway watersheds...")

        # convert grass waterway feature to raster
        gwRas = arcpy.FeatureToRaster_conversion(GWacpf, "OBJECTID", "in_memory" + r"\gwRas", cellsize)

        # create list of grass waterway IDs
        gwIDs = [row[0] for row in arcpy.da.SearchCursor(GWacpf, "OBJECTID")]

        # generate bank cells of waterways- use later to get watersheds
        bankCells = Con(IsNull(gwRas), Expand(gwRas, 1, gwIDs), "", "")

        # buffer grasswaterways for mask
        buffDist = cellsize * 3
        gwBuffer = arcpy.Buffer_analysis(GWacpf, "in_memory" + r"\gwBuff", buffDist, "FULL", "FLAT", "NONE", "", "PLANAR")

        # mask banks to remove "headwaters"
        banks = ExtractByMask(bankCells, gwBuffer)

        # watershed
        acpfGWwatershed = Watershed(flowDir, banks, "Value")

        desc = arcpy.Describe(acpfGWwatershed)
        arcpy.AddMessage(desc.dataType)
        arcpy.AddMessage(acpfGWwatershed)

        acpfWatershedList.append(acpfGWwatershed)

        del(gwRas, gwIDs, bankCells, buffDist, gwBuffer, banks)

        return(acpfWatershedList)

# --------------------------------------------------------------------------------------------------------------
# contour buffer strip watersheds

def acpfCBSwatersheds(CBSacpf, flowDir, acpfWatershedList):

    if arcpy.Exists(CBSacpf):

        arcpy.AddMessage("Generating ACPF CBS watersheds...")

        # convert CBS to raster
        CBSras = arcpy.FeatureToRaster_conversion(CBSacpf, "OBJECTID", "in_memory" + r"\CBSras", cellsize)

        # watershed
        acpfCBSwatershed = Watershed(flowDir, CBSras, "Value")

        acpfWatershedList.append(acpfCBSwatershed)

        del(CBSras)

        return(acpfWatershedList)

# --------------------------------------------------------------------------------------------------------------
# WASCOB watersheds

def acpfWASCOBwatersheds(WASCOBacpf, flowDir, acpfWatershedList):

    if arcpy.Exists(WASCOBacpf):

        arcpy.AddMessage("Generating ACPF WASCOB watersheds...")

        # convert WASCOB to raster
        WASCOBras = arcpy.FeatureToRaster_conversion(WASCOBacpf, "OBJECTID", "in_memory" + r"\WASCOBras", cellsize)

        # watershed
        acpfWASCOBwatershed = Watershed(flowDir, WASCOBras, "Value")

        acpfWatershedList.append(acpfWASCOBwatershed)

        del(WASCOBras)

        return(acpfWatershedList)

# --------------------------------------------------------------------------------------------------------------
# Runoff area treated table for suggested practices

def acpfRunoffWatersheds(catchments, acpfWatershedList, acpfTable):

    arcpy.AddMessage("Creating area treated table for ACPF practices...")

    # convert boundary to raster to use in Cell Statistics later
    boundaryRas = arcpy.FeatureToRaster_conversion(catchments, "riparianid", "in_memory" + r"\boundaryRas", cellsize)
    boundaryCon = Con(boundaryRas, "1000", "", "Value > 0")

    ACPFwatersheds = []

    ACPFwatersheds.append(boundaryCon)

    arcpy.AddMessage(type(acpfGWwatershed))
    arcpy.AddMessage(acpfGWwatershed)

    for pract in acpfWatershedList:
        desc2 = arcpy.Describe(pract)
        arcpy.AddMessage(desc2.dataType)
        arcpy.AddMessage(pract)
        if pract == acpfGWwatershed:
            GWcon = Con(pract, "1", "", "Value > 0")
            ACPFwatersheds.append(GWcon)
        elif pract == acpfCBSwatershed:
            CBScon = Con(pract, "10", "", "Value > 0")
            ACPFwatersheds.append(CBScon)
        elif pract == acpfWASCOBwatershed:
            WASCOBcon = Con(pract, "10", "", "Value > 0")
            ACPFwatersheds.append(WASCOBcon)

    acpfRunoffStack = CellStatistics(ACPFwatersheds, "SUM")
    acpfRunoffReclass = Reclassify(acpfRunoffStack, "Value", RemapValue([[1, "1"], [1001, "1"], [10, "2"], [1010, "2"], [100, "3"], [1100, "3"],
                                                                         [11, "12"], [1011, "12"], [101, "13"], [1101, "13"], [110, "23"], [1110, "23"],
                                                                         [111, "123"], [1111, "123"], [1000, "0"]]))

    # table with areas of stacked practices
    acpfRunoffTabulate = TabulateArea(catchments, "riparianid", acpfRunoffReclass, "Value", "in_memory" + r"\tabulateAreaACPF")
    arcpy.JoinField_management(acpfRunoffTabulate, "RIPARIANID", catchments, "riparianid", "acres")

    acpfRunoffDict = {"VALUE_0" : "pctNoTreat", "VALUE_1" : "pctGW", "VALUE_2" : "pctCBS", "VALUE_3" : "pctWASCOB", "VALUE_12" : "pctGW_CBS",
                      "VALUE_13" : "pctGW_WASCOB", "VALUE_23" : "pctCBS_WASCOB", "VALUE_123" : "pctGW_CBS_WASCOB"}

    # update table
    fieldList = [field.name for field in arcpy.ListFields(acpfRunoffTabulate)]

    keysList = acpfRunoffDict.keys()

    for field in fieldList:
        if field in keysList:

            dictvalue = acpfRunoffDict[field]
            arcpy.AddField_management(acpfRunoffTabulate, dictvalue, "DOUBLE")

            with arcpy.da.UpdateCursor(acpfRunoffTabulate, ["acres", dictvalue, field]) as cursor:
                for row in cursor:
                    row[1] = ((row[2]*0.00025)/row[0]) * 100
                    cursor.updateRow(row)

    # clean up, clean up
    keepList = ["RIPARIANID", "acres", "pctNoTreat", "pctGW", "pctCBS", "pctWASCOB", "pctGW_CBS", "pctGW_WASCOB", "pctCBS_WASCOB", "pctGW_CBS_WASCOB"]
    deleteList = []
    fList = arcpy.ListFields(acpfRunoffTabulate)
    for f in fList:
        if f.name not in keepList:
            if not f.required:
                deleteList.append(f.name)
    arcpy.DeleteField_management(acpfRunoffTabulate, deleteList)

    arcpy.CopyRows_management(acpfRunoffTabulate, acpfTable)

    del(boundaryRas, boundaryCon, pract, acpfRunoffStack, acpfRunoffReclass, acpfRunoffDict,
        fieldList, field, keysList, dictvalue, row, cursor, keepList, deleteList, fList, f, acpfRunoffTabulate)

## Inputs & Modules -----------------------------------------------------------------------------------------------

if __name__ == "__main__":

    catchments = arcpy.GetParameterAsText(0)
    flowDir = arcpy.GetParameterAsText(1)

    GWacpf = arcpy.GetParameterAsText(2)
    CBSacpf = arcpy.GetParameterAsText(3)
    WASCOBacpf = arcpy.GetParameterAsText(4)

    GWexist = arcpy.GetParameterAsText(5)
    CBSexist = arcpy.GetParameterAsText(6)
    Terrexist = arcpy.GetParameterAsText(7)
    Stripexist = arcpy.GetParameterAsText(8)
    WASCOBexist = arcpy.GetParameterAsText(9)

    acpfTable = arcpy.GetParameterAsText(10)
    existTable = arcpy.GetParameterAsText(11)

    if not(GWacpf or CBSacpf or WASCOBacpf or
           GWexist or CBSexist or Terrexist or Stripexist or WASCOBexist):

        arcpy.AddError("no practices provided...Abort!!")
        sys.exit()

    arcpy.env.overwriteOutput = True
    arcpy.env.snapRaster = flowDir
    arcpy.env.extent = flowDir
    cellsize = float(arcpy.GetRasterProperties_management(flowDir, "CELLSIZEX").getOutput(0))

    acpfWatershedList, existWatershedList = createListOfWatersheds()

    acpfGWwatershed = acpfGWwatersheds(GWacpf, flowDir, acpfWatershedList)
    acpfCBSwatershed = acpfCBSwatersheds(CBSacpf, flowDir, acpfWatershedList)
    acpfWASCOBwatershed = acpfWASCOBwatersheds(WASCOBacpf, flowDir, acpfWatershedList)
    acpfRunoffWatersheds(catchments, acpfWatershedList, acpfTable)

Note that the empty list existWatershedList would be used in a second half of this code that is identical to the first half, just different parameters.

A: The variable acpfGWwatershed is tested in the acpfRunoffWatersheds() function, but it's created in the acpfGWwatersheds() function. These aren't global variables. I don't see where you're calling these previous functions that should be returned, or passing it to the runoff function.
You'd be safest to modify this as calling acpfGWwatersheds() before your if statement in acpfRunoffWatersheds(). Probably as something similar to ws, wslist =  acpfGWwatersheds(var1, var2, var3) and if pract == ws. Or you could pass in the watershed as a parameter in the runoff function.
EDIT: After full code was posted, determined that the line below was creating a list, when the desired output was a raster.
acpfGWwatershed = acpfGWwatersheds(GWacpf, flowDir, acpfWatershedList)

At least part of the issue stems from variable scope and overlapping naming between functions. An improvement would be to clean up the variable naming and (preferably) explicitly update lists rather than passing them into functions to be modified in place. Watch the return values of functions.
You also don't need to have a function to create these lists -- it makes the code more confusing and leads to the same scope issues.
Final suggestion -- when in doubt, take the code in sections (comment out what isn't needed) and print the type (not just value) of each variable to ensure you're getting the expected results.

A: @smiller sorted through my script, and the issue was that I was changing the type of acpfGWwatershed from a raster to a list when I returned a list in the second module.


text:
Q: Natbib - Custom-bib - Merlin.mbs - Unwanted thin space between volume and num in reference list I have a problem with the .bst file, I created with the help of custom-bib (make-bst). I needed to create an individual .bst file since the Journal (Journal of Intelligent Manufacturing) is using a little mixture of styles (some Harvard, some APA, some individual). So far so good, I had no problem with custom-bib or the dbj files and creating/adapting the .bst file.
BUT: I have a problem with the formatting of the Reference list - The problem is the thin-space between the volume and the number: "46 (32)"
Even if I use the default option for
"JOURNAL VOL AND NUMBER:"
\beginoptiongroup{JOURNAL VOL AND NUMBER:}{}
\optdef{*}{}{Journal vol(num)}{as 34(2)}
the result stays the same. I figured out that this is due to the different handling of textit, it, em, see examples in the "min example".
This behaviour is also nicely described in Extra space between volume and number using Biblatex and APA
but unfortunately this solution only works for biblatex...
With the help of the merlin.pdf documentation I also found out that there are already options for this:
\optdef{i}{em-it}{Use true italics}{ie, \string\it, absolute italics
\optdef{t}{plntx}{Use only Plain TeX}{commands for fonts and testing}
See also the final options I am passing to the creation (except of adapted_style.dbj):
Processing file merlin.mbs (ay,nat,nm-rev,jnrlst,nmlm,x6,m1,keyxyr,dt-beg,yr-pa
r,note-yr,vol-it,volp-com,num-xser,bkpg-par,add-pub,edpar,bkedcap,pp,ed,xedn,an
d-xcom,xand,em-it,plntx,) -> adapted_style.bst
But still the same effect. Does anyone of you has a solution for this?
Yours sincerely, David
MWE:
\documentclass{article}
\usepackage[]{natbib}

\begin{document}
\bibliographystyle{adapted_style}
\bibliography{sample.bib}
\setcitestyle{aysep={ }}

some text \cite{Ahmad2013}

See example:

\begin{itemize}
    \item with-space:{17} (18)
    \item textit:~\textit{17}(18)
    \item it:~~~~~\it{17}(18)
    \item em:~~~~~\em{17}(18)
    \item rm:~~~~~\rm{17}(18)
\end{itemize}
\end{document}

Content of sample.bib:
@article{Ahmad2013,
author = {Ahmad, Iftikhar and Kano, Manabu},
journal = {IFAC Proceedings Volumes},
number = {32},
pages = {744--749},
publisher = {IFAC},
title = {{Some interesting paper}},
volume = {46},
year = {2013}
}

adapted_style.dbj (creates "adapted_style.bst" with latex adapted_style.dbj" see in pastebin

A: I really don't like to answer my own question...BUT in case it is helpful for someone else, I post the solution for my own problem...
Found out that this was not a problem at all, since the behaviour when using vol-it and "" is working as intentioned, it is even mentioned in the ACTUAL documentation of merlin.mbs:
\optdef{i}{vol-it}{Volume italic}{as {\string\em\space vol}(num)}
so the original function for emphasizing stuff as it results by running the dbj file in order to create the .bst file looks like that:
FUNCTION {emphasize}
{ duplicate$ empty$
    { pop$ "" }
    { "{\it " swap$ * "\/}" * }
  if$
}

the "thin space" is added on purpose, and by deleting it, it is also gone in the reference list:
FUNCTION {emphasize}
{ duplicate$ empty$
    { pop$ "" }
    { "{\it " swap$ * "}" * }
  if$
}

Yours sincerely, David


text:
Q: Matplotlib: consistent image size for publications I want to make publication-quality plots with Matplotlib. The biggest problem I am having right now is to tune the image and font sizes.
When I create a figure with several panels, I usually set a bigger figsize. For example, these three panels are created with a figsize=(12, 6 / 1.618) (pasted from Jupyter Lab, I always save to PDF files).

The lines can be perfectly seen, there is a lot of space, the figure seems nice. The problem is that in my publication this has to be a column-wise figure, so it has to be scaled down. A colum has a width of around ~3.5 inches. When the image is resized, it still looks good, but the axes labels become very tiny and unreadable. Of course, I can just simply start increasing the font sizes until I find a good size, but I would like to have a workflow that allows me to work with the lengths and sizes I have to use.
When I set the image size to figsize=(columnw, 0.5*columnw / 1.618) (so the aspect ratio is the same) as before, and set the font size around 10 (the font size of my publication) this is what I get:

So now the fonts are exactly the size I want them to be, the figure does not have to be reescaled, but the contents of the graph seem to be compressed into a very very tiny space. It just look... ugly.
Then, my question is: why using a big figsize with extremely large fontsizes gives a beautiful, readable figure when scaled, but with the a priori correct figsize without rescaling seems to be ugly? How could I work with real figsizes from the very beginning to obtain something nice?
I read some questions regarding image size with Matplotlib on this site, as well as a pair of blog posts, but I haven't found any information regarding this problem.
Thank you in advance.


text: Q: Is there an established way to quantify the number of parameters in a random forest? I'm interested in applying an F-test to random forest regression models I've trained. The formula for calculating an F-statistic (found here: https://en.wikipedia.org/wiki/F-test) requires values for $p_1$ and $p_2$, where $p_2$ is the number of parameters of the unrestricted (random forest) model. I know this is pretty unconventional, but I was just wondering if anyone has suggestions as to how I could quantify $p_2$ rigorously given the nonparametric nature of random forest methods.


text:
Q: A dance party is happening on a world with 3 genders: snails, pre-snails and post-snails. There are 8 aliens of each gender at the party. A dance party is happening on a world with 3 genders: snails, pre-snails and
post-snails. There are 8 aliens of each gender at the party. How many ways
can the aliens be divided up into triples to dance 1 if, as is the custom on this
planet, each triple consists of one snail, one pre-snail, and one post-snail?
I think the answer should be 8*8*8
but i am not sure

A: The pre-snails can be assigned to the snails in $8!$ different ways, and so can the post-snails, for a total of $8!^2=1625702400$ different configurations.


text:
Q: Rx.NET Call function again direct after all it's callbacks I want to make communication with serial port - get some data. I want to get this data in loop as fast as it's possible. So, i have function GetData() with callback, which draws data on the WPF form. How can I call this GetData function in loop right after all it's callbacks?
Like cycle GetData->Draw->GetData->Draw and so on?
Upd: Mb something like this?
var ob = Observable.Create<Data>(
  observer => {
    while(true) {
      observer.OnNext(GetDataFromSerialPort());
    }
});

A: I would create a service that exposed the serial Port data via an observable sequence. I would then inject that into my MVVM stack.
The Service would like similar to what you have, but with disposal functionality
public class MySerialPortService : IsCancellationRequested
{
    public IObservable<Data> GetData()
    {
        return Observable.Create<Data>(async (o, cts) =>
          observer => {
            while (!cts.IsCancellationRequested) {
              observer.OnNext(GetDataFromSerialPort());
            }
        });
    }
}

public class MyViewModel : IDisposable
{
    private readonly IMySerialPortService _mySerialPortService;
    private readonly ISchedulerProvider _schedulerProvider;
    private readonly SingleAssignmentDisposable _subscription = new SingleAssignmentDisposable();

    public MyViewModel(IMySerialPortService mySerialPortService, ISchedulerProvider schedulerProvider)
    {
        _mySerialPortService = mySerialPortService;
        _schedulerProvider = schedulerProvider;
    }

    public void Start()
    {
        _subscription.Disposable = _mySerialPortService.GetData()
            .SubscribeOn(_schedulerProvider.Background) //or _schedulerProvider.ThreadPool, or CreateEventLoopScheduler or what ever you do internally.
            .ObserveOn(_schedulerProvider.Foreground)   //or _schedulerProvider.Dispatcher etc...
            .Subscribe(
                val=> Update(val),
                ex=> ...
            )
    }

    public void Dispose()
    {
        _subscription.Dispose();
    }
}

The following post may be helpful - https://github.com/LeeCampbell/RxCookbook/tree/master/IO/Disk. It shows you step by step how to create and Observable Sequence that reads from Disk. You can swap the Disk IO for Serial Port IO.


text:
Q: would changing dbml to bigint work for int values our db is undergoing migration from int to bigint. In migrated partitions I have a column name in a table that is stored as bigint and in other partitions it is stored as int(to be migrated). Wondering if its possible to use a single datacontext to query both the databases. When i have the dbml as bigint and query in a db->table that has defined the column name as int. I get the below error
Specified cast is not valid.   at System.Data.SqlClient.SqlBuffer.get_Int64()
   at System.Data.SqlClient.SqlDataReader.GetInt64(Int32 i)

A: You have to do a workaround: Correctly declare all tables with their true datatype. Then convert them as part of the query. Example:
tableBigint.Select(x => x.ID)
tableInt.Select(x => (long)x.ID)

You would now be able to union them (or whatever you want to do with them) because the types match and also deserialization works.


text:
Q: Apply CancellationToken in dataflowblock In my producer-consumer application. I have:
CancellationTokenSource cTokenSource = new CancellationTokenSource();
CancellationToken cToken = new CancellationToken();
cToken = cTokenSource.Token;

Click start button, the application is running.
private async void Start_Click(object sender, RoutedEventArgs e)
{
   var producer = Producer();
   var consumer = Consumer();
   await Task.WhenAll(producer, consumer);
}

In the consumer, I used TPL.
async Task Consumer()
{
    try
    {
        var executionDataflowBlockOptions = new ExecutionDataflowBlockOptions
        {
            MaxDegreeOfParallelism = 50,
            CancellationToken = cToken
        };
        var consumerBlock = new ActionBlock<AppointmentReminder>(
       remainder =>
       {
         // blah blah for long running processes and updating UI
          var result = Run(reminder);
       },
       executionDataflowBlockOptions);

        bufferBlock.LinkTo(
        consumerBlock, new DataflowLinkOptions { PropagateCompletion = true });
        await Task.Delay(500);
    }

Now I have a cancel button, I want to stop the TPL consumer tasks while I click it. How?
private void Cancel_Click(object sender, RoutedEventArgs e)
{

A: Cancellation in .Net is cooperative. You create a CancellationTokenSource to handle the cancellation and use CancellationToken to be notified of cancellation. To cancel the token simply call CancellationTokenSource.Cancel:
cTokenSource.Cancel();

BTW, there's no much use in creating a CancellationToken directly as it can never be cancelled. You should get a token from the CancellationTokenSource:
var cTokenSource = new CancellationTokenSource();
var cToken = cTokenSource.Token;


text:
Q: Problem Notify Popup only display blue bar On Ubuntu 14.04 I have Ubuntu 14.04, but not from clean install. I update it from 13.04 -> 13.10 and 14.04.
Some day ago, I just realize that some things wrong with it's Notification Pop Up. It only display blue bar at top left screen.
I already reset my unity, but nothing happen.
Please help, whats is wrong and how to fix this.
Thanks.

A: [SOLVED]
I thinks it's duplicate with : Notify-osd notifications appear unthemed in top-left corner
I remember that this problem began when I install i3 window manager. Unfortunately i3 automatic install it's own notification daemon, dunst that "conflic" with notify-osd. So, I just have to uninstall i3 and all fixed.
sudo apt-get purge i3 i3-wm i3lock i3status dunst
sudo apt-get autoremove
killall dunst

A: I'm guessing a package is missing.  Try sudo apt-get install ubuntu-desktop, which should install any missing packages.  If that doesn't fix it, maybe you disabled something in a config file or an autostart .desktop file.

A: All you need to do is to remove the dunst notification daemon
sudo apt-get remove dunst


text:
Q: LazyInitializationException when saving one side of a relationship I have a class Patient that has a collection of Id, and a collection of Folders. When I try to save a Folder on its own it throws a LazyInitializationException because of the Patient's id collection.
Patient class looks like this:
@Entity
@Table(name = "patient")
public class Patient implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @OneToMany(mappedBy = "patient", fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
    private Set<Id> ids = new HashSet<Id>();

    @OneToMany(mappedBy = "patient", fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
    private List<Folder> folders = new ArrayList<Folder>();

    ...
}

Folder class looks like this:
@Entity
@Table(name = "folder")
public class Folder implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "patient_id", referencedColumnName = "id")
    private Patient patient;

}

Then I have a service class that does things and then saves a folder like this:
@Override
@Transactional
public void importData(Data data) {

    // do other things
    Folder folder = new Folder();
    // initialize folder values
    ...
    folder.setPatient(patient);
    folderDAO.save(folder);
    ...
}

And when it tries to save the folder in FolderDAO with:
getHibernateTemplate().saveOrUpdate(folder);

It throws:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: es.mycompany.myapp.Patient.ids, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:587)

A: with a cascade = ALL configuration, you are configuring hibernate to update the list/set of patient when the folder entity is saved, the patient list must be loaded in memory to be updated. You may be able to try to remove CASCADE = ALL and manually manage any list and set of patient class updates.

A: The issue is that you're trying to saveOrUpdate outside of the session. Hibernate.initialize will initialize your Patient collection for use prior to your saveOrUpdate, or you can manually open a hibernate session, transaction, do commit and close the resources.
Try like this: https://www.mkyong.com/hibernate/hibernate-transaction-handle-example/


text:
Q: how can I cache in public proxy the heavy image I use for my header (using background-image:url css property in the stylesheet) ok this is the image.
it is certainly too big and needs cropping but it's not the point right now:
http://exaggerated.com/images/site/front/header.png
in my stylesheet I use
#wrapper_inner {
width:100%;
height:auto;
float:left;
background-image:url(http://exaggerated.com/images/site/front/header.png);
background-position:top center;
background-repeat:no-repeat;
}

my question is could I put the image on a public proxy and use the new external url to serve this ressource faster for first time visitors ?

A: You should set HTTP headers that allow for caching, and then the user's proxy (if any) will cache the image for you. http://www.fiddler2.com/redir/?id=httpperf


text:
Q: how can I open a link in a webView (on a local file) in external browser? I have a WebView that I opened a local file from asset on it.
then, when I clik on a link for opennig another local file from asset, unfortunately, the new file replace, and does not open in the external browser.
I want the second file is opened in the external browser.
how can I do that.

edit :
I have a html file in asset named list.html. in this html file there are 20 links that refer to 20 html files in the assets. I want to open the list.html file in my WebView. then, when I click on 20 links in this file, links will be opened in external browser, not replace the list.html file.

A: Start a new activity and invoke the web browser application and pass the url to it.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

this might help, I haven't test it.