String[] or ArrayList better as Key in HashMap?

Question: So I need to choose between

HashMap<String[], Object>
HashMap<ArrayList<String>,Object>

My input Parameter is: ArrayList<String> in.
The whole ArrayList<String> in cannot be the key, since it does contain elements, which are not supposed to be like a Primary Key in a database. I do know, that the first n elements of the incoming ArrayList<String> in supposed to be the primary Keys.
Which one would be faster?
Scenario:
HashMap<ArrayList<String>, Object> hmAL = new HashMap<>();
HashMap<String[], Object> hmSA = new HashMap<>();
ArrayList<String> in = new ArrayList<>();
fillWithStuff(in);

//Which one would be faster?
getObject(in,hmAL,5);
getObject(in,hmSA,5);

With Option 1:
private Object getObject(ArrayList<String> in, HashMap<ArrayList<String>, Object> hm, int n){
  return hm.get(in.sublist(0,n));
}

With Option 2:
private Object getObject(ArrayList<String> in, HashMap<String[], Object> hm, int n){
String[] temp = new String[n];
for(int i=0; i<n; i++)
  temp[i]=in.get(i);

  return hm.get(temp);
}

Considering:

Which is faster? Short the list, or copy to an array?
I'm wondering, which hash (since it is a HashMap) would be faster. Hashing of a ArrayList, or an equal-sized array. Or doesn't it make any difference?
Comment: You might find useful Guava Multimap
Comment: It's probably not a good idea to use a container as a key in a `HashMap`.
Comment: Why is it not a good idea?
Comment: Because the contents of the container could be changed after the key has been inserted, and Java does not have `const` objects.
Comment: @Fede: is there something like an inverse Guava MultiMap? Like: with Multiple Keys for one Value?
Comment: @Joel Multimap is exactly that, you can map `A->1`, `A->2`, `B->1` and `A->3`, so when you do a `GET(A)` you will receive a list with `1,2,3`
Comment: @Fede: yes, but I want multible keys to lead to one value. Something like: `(A && B)-> 1`. Noticing, that A and B are `String` and not `bool`
Answer: Using String[] is not a good idea because it does not implement hashCode(). This means if you have 2 string arrays which are different objects but with the exact same values, the map will not find it.
The implementation of 'hashCode` seems to use each of the string elements hashcode so the lookup in a map would succeed. So I'd go with this one.
That said, I would rather build a key myself based on the objects in the list.
Answer: Dealing with copying only
The subList method is implemented very efficiently in Java 7+, not requiring any copying at all. It simply returns a view directly onto the original array. Thus, in Java 7+, it will be faster than the copy element by element method. However, in Java 6, both ways are essentially equivalent.
Dealing with the method as a whole
If you look at the whole method, your choice is no longer a choice. If you want the method to function, you will have to use the first implementation. Array hashCode() does not look at the elements inside it---only the identity of the array. Because you are creating the array in your method, the Map.get() will necessary return null.
On the other hand, the List.hashCode() method runs a hash on all of the contained elements, meaning that it will successfully match if all of the contained elements are the same.
Your choice is clear.
Answer: Just to add on above two answers, I have tested in Java 7 and found on an average with list it's 50 times faster with 2000000 total elements and 1000000 elements which participate in calculating hashcode i.e. primary keys (hypothetical number). Below is the program.
public class TestHashing {

    public static void main(String[] args) {
        HashMap<ArrayList<String>, Object> hmAL = new HashMap();
        HashMap<String[], Object> hmSA = new HashMap<>();
        ArrayList<String> in = new ArrayList<>();
        fillWithStuff(in);

        // Which one would be faster?
        long start = System.nanoTime();
        getObject(in, hmAL, 1000000);
        long end = System.nanoTime();

        long firstTime = (end-start);
        System.out.println("firstTime :: "+ firstTime);

        start = System.nanoTime();
        getObject1(in, hmSA, 1000000);
        end = System.nanoTime();

        long secondTime = (end-start);

        System.out.println("secondTime :: "+ secondTime);

       System.out.println("First is faster by "+ secondTime/firstTime);
    }

    private static void fillWithStuff(ArrayList<String> in) {
        for(int i =0; i< 2000000; i++) {
            in.add(i+"");
        }
    }

    private static Object getObject(ArrayList<String> in,
            HashMap<ArrayList<String>, Object> hm, int n) {
        return hm.get(in.subList(0, n));
    }

    private static Object getObject1(ArrayList<String> in, HashMap<String[], Object> hm, int n){
        String[] temp = new String[n];
        for(int i=0; i<n; i++)
          temp[i]=in.get(i);

          return hm.get(temp);
        }
}

Output

firstTime :: 218000
secondTime :: 11627000
First is faster by 53


What are different options for objective functions available in xgboost.XGBClassifier?

Question: Apart from binary:logistic (which is the default objective function), is there any other built-in objective function that can be used in xbgoost.XGBClassifier ?
Answer: That's true that binary:logistic is the default objective for XGBClassifier, but I don't see any reason why you couldn't use other objectives offered by XGBoost package.
For example, you can see in sklearn.py source code that multi:softprob is used explicitly in multiclass case.
Moreover, if it's really necessary, you can provide a custom objective function (details here).
Comment: what is the binary:logistic, isn't this just the loss function?
Comment: The question was "is there any built-in objective function other than b:l", and this answer says "you can use functions other than b:l". Why on earth was this selected as the right answer?
Answer: The default objective for XGBClassifier is ['reg:linear]
however there are other parameters as well..
binary:logistic-It returns predicted probabilities for predicted class
multi:softmax - Returns hard class for multiclass classification
multi:softprob - It Returns probabilities for multiclass classification
Note: when using multi:softmax as objective, you need to pass num_class also
as num_class is number of parameters defining number of class
such as for labelliing (0,1,2), here we have 3 classes, so num_class = 3
Answer: These are the bulit-in functions available

Objective candidate: survival:aft
Objective candidate: binary:hinge
Objective candidate: multi:softmax
Objective candidate: multi:softprob
Objective candidate: rank:pairwise
Objective candidate: rank:ndcg
Objective candidate: rank:map
Objective candidate: reg:squarederror
Objective candidate: reg:squaredlogerror
Objective candidate: reg:logistic
Objective candidate: binary:logistic
Objective candidate: binary:logitraw
Objective candidate: reg:linear
Objective candidate: reg:pseudohubererror
Objective candidate: count:poisson
Objective candidate: survival:cox
Objective candidate: reg:gamma
Objective candidate: reg:tweedie
Objective candidate: reg:absoluteerror
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Typeorm gives me QueryFailedError: column reference "id" is ambiguous

Question: This is the query I'm firing off:
const updatedUser = await queryRunner.manager
    .getRepository(UserEntity)
    .createQueryBuilder('user')
    .leftJoinAndSelect('user.categories', 'cats')
    .where('id = :userId', { userId })
    .getOne();

And here is the query that is generated by typeorm:
SELECT "user"."id"               AS "user_id",
       "user"."first_name"       AS "user_first_name",
       "user"."last_name"        AS "user_last_name",
       "user"."phone"            AS "user_phone",
       "user"."password"         AS "user_password",
       "user"."password_hint"    AS "user_password_hint",
       "user"."recovery_email"   AS "user_recovery_email",
       "user"."created"          AS "user_created",
       "user"."username"         AS "user_username",
       "user"."profile_pic"      AS "user_profile_pic",
       "user"."is2fa"            AS "user_is2FA",
       "user"."refresh_token"    AS "user_refresh_token",
       "user"."profile_email"    AS "user_profile_email",
       "user"."subscriptionid"   AS "user_subscriptionId",
       "cats"."id"               AS "cats_id",
       "cats"."template_id"      AS "cats_template_id",
       "cats"."name"             AS "cats_name",
       "cats"."entry_count"      AS "cats_entry_count",
       "cats"."is_base_template" AS "cats_is_base_template",
       "cats"."can_rename"       AS "cats_can_rename",
       "cats"."can_delete"       AS "cats_can_delete",
       "cats"."userid"           AS "cats_userId",
       "cats"."position"         AS "cats_position",
       "cats"."icon_path"        AS "cats_icon_path",
       "cats"."init_name"        AS "cats_init_name",
       "cats"."isfortasks"       AS "cats_isForTasks",
       "cats"."is_locked_by"     AS "cats_is_locked_by",
       "cats"."is_locked"        AS "cats_is_locked",
       "cats"."password"         AS "cats_password",
       "cats"."state"            AS "cats_state",
       "cats"."password_hint"    AS "cats_password_hint",
       "cats"."parentcategoryid" AS "cats_parentCategoryId"
FROM   "user" "user"
       LEFT JOIN "category" "cats"
              ON "cats"."userid" = "user"."id"
WHERE  id = $1

If I remove the leftJoinAndSelect it doesn't yield that error but I need this join.
What is wrong with the query?
META:
The DBMS I'm using is PostgreSQL v. 12.3.
Comment: Does this answer your question? [SQL column reference "id" is ambiguous](https://stackoverflow.com/questions/9821121/sql-column-reference-id-is-ambiguous)
Answer: Well, as you can see there is a user.id and a cats.id available - you even select both. But in the WHERE clause you don't say which id you mean. Change 'id = :userId' to 'user.id = :userId' and it should work.


A Better Way To Write this Bash Script?

Question: This solution (listed below) works, but it doesn't look like the most practical of solutions. What I want to do is populate a folder with children with a name t_###_u and then fill those child directories with two files (one of which should be renamed to parent directory name and appended with a .c) Can anyone post a better, more elegant solution?
for i in {1..100}
do
    mkdir `printf "t_%03d_u" $i`;
    cp ./templates/* `printf "t_%03d_u" $i`;
    mv `printf "./t_%03d_u/template.c" $i` `printf "./t_%03d_u/t_%03d.c" $i $i`;
done

echo "Did it work?"

Thanks for any help in advance.
Answer: The most obvious way to improve the script is to assign a variable to the name you use:
name=`printf "t_%03d" $i`

so then you can do
mkdir ${name}_u
cp ./templates/* ${name}_u/
mv ./${name}_u/template.c ./${name}_u/$name.c

Answer: Bash 4.
for num in {001..100}
do
    path="t_${num}_u"
    mkdir "$path"
    cp ./templates/* "$path";
    mv $path/template.c  ./$path/t_${num}.c
done

Comment: That only works in Bash 4. The assignment `num=$i` is unnecessary, just use `$i` directly.
Answer: seq -w is hugely useful :)
#!/bin/bash

for i in `seq -w 1 100`
do
    mkdir t_${i}_u
    cp ./templates/* t_${i}_u
    mv ./t_${i}_u/template.c ./t_${i}_u/t_${i}_u.c
done

echo "Did it work?"

I'm sure it could be improved a bit further with computing the name of the directory once and re-using it, but this is nicer-enough that I'm fine stopping here. :)
Comment: Very nice to know of seq -w. Thanks to you and thanks to anyone else who answered.
Comment: @maerics: BSD has `jot`, but that's why `printf` should be used instead.
Answer: My only advice would be to set the zero padded string to a variable to ease reading:
for i in {1..100}
do
  s=$(printf "%03d" $i)
  mkdir t_${s}_u
  cp ./templates/* t_${s}_u
  mv ./t_${s}_u/template.c ./t_${s}_u/t_${s}.c
done

Comment: There shouldn't be spaces around the equal sign.
Comment: @denniswilliamson fixed
Answer:
for i in $(seq -w 1 100); do
 mkdir t_${i}_u
 cp templates/* t_${i}_u
 mv t_${i}_u/template.c t_${i}_u/t_${i}.c
done

haven't tested it.
Answer: You could save the result of the printf in a variable rather that re-doing it each time.  Or just use seq -w 1 100 to generate the numbers:
for i in $(seq -w 1 100)
do
    d=t_${i}_u
    mkdir $d
    cp templates/* $d
    mv $d/template.c $d/t_$i.c
done

A Better Way To Write this Bash Script?


Reposition colorbar in plotly and change color scale (R)

Question: I'm creating a scattermapbox plot using plotly and would like to:

Make the colorbar horizontal and position it on top my plot
Change the colorscale to shades of red and rename it to 'Elevation'

I've tried to follow the examples online but it doesn't work:

I added legend = list(orientation = 'h') to the layout but it made no difference. (2nd example here: https://plotly.com/r/scattermapbox/)
Added coloraxis = list(colorscale = "Reds") to the layout following the (first) example on https://plotly.com/r/scattermapbox/ without success
Other examples show it is possible to rename the colorbar by adding a named list to marker by marker = list(..., colorbar = list(title = 'My title')). There's no parameter named colorbar in the reference documentation. (example here: https://plotly.com/r/colorscales/)

On a side note, I have a mapbox token, yet, the plot appears to work with a few styles only.
Data
Sharing 50 uniformly spaced points from the entire dataset (6000 points):
structure(list(lat = c(45.547955, 45.549801, 45.551437, 45.554653,
45.559059, 45.560158, 45.563854, 45.567379, 45.5715069, 45.575817,
45.579056, 45.582672, 45.586857, 45.591194, 45.59362, 45.597103,
45.601231, 45.605034, 45.608997, 45.611233, 45.615376, 45.61932,
45.622749, 45.625629, 45.628456, 45.631489, 45.631611, 45.632305,
45.630135, 45.626793, 45.623497, 45.620045, 45.615589, 45.610992,
45.606541, 45.602821, 45.599106, 45.595169, 45.591198, 45.5872079,
45.582672, 45.578587, 45.57476, 45.570515, 45.565872, 45.56226,
45.55862, 45.555603, 45.552097, 45.548283), lon = c(-73.666939,
-73.668861, -73.674332, -73.673698, -73.672272, -73.66761, -73.664688,
-73.661179, -73.660103, -73.658028, -73.657333, -73.654381, -73.652786,
-73.651154, -73.648354, -73.644836, -73.64328, -73.641556, -73.63961,
-73.637321, -73.635498, -73.632965, -73.629128, -73.624321, -73.620491,
-73.615967, -73.613396, -73.61422, -73.618103, -73.622635, -73.627571,
-73.632332, -73.635414, -73.637466, -73.638702, -73.640244, -73.643547,
-73.646996, -73.649826, -73.651886, -73.652626, -73.6558, -73.6588359,
-73.660416, -73.662086, -73.665947, -73.668335, -73.671501, -73.666359,
-73.667671), ele = c(30.2, 27, 26.6, 25.7999999, 23.2, 26.7999999,
20, 24, 22.7999999, 20.6, 19, 22.2, 19.2, 17.3999999, 25.2, 25.2,
17, 16.6, 15.3999999, 17, 15.2, 15.6, 16.3999999, 16.7999999,
17.7999999, 17.6, 24.3999999, 18.2, 18.6, 18.6, 19.2, 17, 17.2,
18.7999999, 23.7999999, 27.7999999, 27.7999999, 26, 30.7999999,
27.2, 29.2, 24, 23.7999999, 26.6, 24.7999999, 26.2, 31, 31, 31.2,
32.6)), row.names = c(NA, -50L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x7fb33c8118e0>)

Code
plt <- plot_mapbox(data = track, mode = 'scattermapbox',
                   lat = ~lat, lon = ~lon, color = ~ele) %>%
  layout(mapbox = list(style = 'carto-positron', zoom = 10, # open-street-map works, but light, dark, basic don't work
                  center = list(lon = track[, mean(lon)], lat = track[, mean(lat)])),
    margin = list(l = 0, r = 0, t = 0, b = 0),
    legend = list(orientation = 'h'))

Answer: Use %>% colorbar() with parameters at https://plotly.com/r/reference/#scatter-marker-colorbar
Comment: Welcome to stack overflow and many  thanks for your answer. Could you please provide more details?


Using the fortran save attribute in parallel regions

Question: I have a parallel region in my fortran code that uses OpenMP and calls subroutines that use variables with the save attribute in their scope.  This is causing a problem because they are shared between threads, so my question is if there is a way to make these variables private while still being saved between subroutine calls, or will I need to input and output them?
Thanks
Answer: You can do it using threadprivate - the code below shows a couple of slightly different approaches. But please note
a) The values are only guaranteed to be preserved between parallel regions if the parallel regions use the same number of threads
b) Please think carefully whether you really need save, save and parallel programming are very rarely good bed fellows. There are one or two good uses (see e.g. Fortran OpenMP with subroutines and functions), but if there is an alternative way to do what you want to do (e.g. passing through the argument list) this will almost certainly cause you less pain in the long run
(For some reason using a proper list breaks the formatting of the code below - if someone knows how to fix that, thanks!)
ian@eris:~/work/stack$ cat threadprivate.f90
Program test

  Implicit None

  Call do_something
  Call do_something
  Call do_something

  Write( *, * )

  !$omp parallel
  Call do_something_else
  Call do_something_else
  Call do_something_else
  !$omp end parallel

Contains

  Subroutine do_something

    Use omp_lib

    Implicit None

    Integer, Save :: calls = 0

    Integer, Save :: stuff

    Logical, Save :: first = .True.
    !$omp threadprivate( first, stuff )

    calls = calls + 1

    ! Shouldn't scope threadprivate variables - they are already private
    !$omp parallel default( none ) shared( calls )
    If( first ) Then
       first = .False.
       stuff = omp_get_thread_num()
    Else
       stuff = stuff + 1
    End If
    Write( *, '( 3( a, 1x, i2, 1x ) )' ) 'do something call ', calls, &
         'thread = ', omp_get_thread_num(), 'stuff = ', stuff
    !$omp end parallel

  End Subroutine do_something

  Subroutine do_something_else

    Use omp_lib

    Implicit None

    Integer, Save :: calls = 0

    Integer, Save :: stuff

    Logical, Save :: first = .True.
    !$omp threadprivate( first, stuff, calls )

    calls = calls + 1

    If( first ) Then
       first = .False.
       stuff = omp_get_thread_num()
    Else
       stuff = stuff + 1
    End If
    Write( *, '( 3( a, 1x, i2, 1x ) )' ) 'do something else call ', calls, &
         'thread = ', omp_get_thread_num(), 'stuff = ', stuff

  End Subroutine do_something_else

End Program test
ian@eris:~/work/stack$ gfortran -std=f2008 -Wall -Wextra -O -g -fcheck=all -pedantic -fopenmp threadprivate.f90
ian@eris:~/work/stack$ export OMP_NUM_THREADS=2
ian@eris:~/work/stack$ ./a.out
do something call   1 thread =   0 stuff =   0
do something call   1 thread =   1 stuff =   1
do something call   2 thread =   1 stuff =   2
do something call   2 thread =   0 stuff =   1
do something call   3 thread =   1 stuff =   3
do something call   3 thread =   0 stuff =   2

do something else call   1 thread =   1 stuff =   1
do something else call   2 thread =   1 stuff =   2
do something else call   3 thread =   1 stuff =   3
do something else call   1 thread =   0 stuff =   0
do something else call   2 thread =   0 stuff =   1
do something else call   3 thread =   0 stuff =   2
ian@eris:~/work/stack$ export OMP_NUM_THREADS=4
ian@eris:~/work/stack$ ./a.out
do something call   1 thread =   3 stuff =   3
do something call   1 thread =   2 stuff =   2
do something call   1 thread =   1 stuff =   1
do something call   1 thread =   0 stuff =   0
do something call   2 thread =   1 stuff =   2
do something call   2 thread =   3 stuff =   4
do something call   2 thread =   0 stuff =   1
do something call   2 thread =   2 stuff =   3
do something call   3 thread =   3 stuff =   5
do something call   3 thread =   1 stuff =   3
do something call   3 thread =   0 stuff =   2
do something call   3 thread =   2 stuff =   4

do something else call   1 thread =   3 stuff =   3
do something else call   2 thread =   3 stuff =   4
do something else call   3 thread =   3 stuff =   5
do something else call   1 thread =   1 stuff =   1
do something else call   2 thread =   1 stuff =   2
do something else call   3 thread =   1 stuff =   3
do something else call   1 thread =   0 stuff =   0
do something else call   2 thread =   0 stuff =   1
do something else call   3 thread =   0 stuff =   2
do something else call   1 thread =   2 stuff =   2
do something else call   2 thread =   2 stuff =   3
do something else call   3 thread =   2 stuff =   4
ian@eris:~/work/stack$

Comment: Just nitpicking here, but you write "No need to scope already threadprivate variables". Threadprivate variables cannot appear in any data-sharing attribute clauses.
Comment: Yes, that's what I meant, but didn't express it very well. Will edit
Comment: This worked and I also learned if you assign a variable when declaring it, example: int :: i = 1, then it will have the save attribute. So I set such variables to thread private as well.
Comment: One more question, do threads share variables that have the parameter attribute? I know that won't change the outcome but maybe it would slow things down.
Comment: Parameters aren't variables - they are constants. That might sound trivial, but in fact it is important. All scoping, including threadprivate applies to variables. Thus you can't have a threaprivate constant.


Javascript xor ^ with 0 return bad result

Question: I'm using the binary xor operator ^ with 2 variables like this :
var v1 = 0;
var v2 = 3834034524;
var result = v1 ^ v2;

The result is -460932772.
Have you an idea why ?
Thank you
Comment: `3834034524 > Math.pow(2,31) - 1 // true`
Comment: How is that unexpected?
Comment: What is the point of doing that by the way?
Answer: This is an expected behavior these are signed numbers.
Just truncate the result to an unsigned integer
var result = (v1 ^ v2) >>> 0;

Answer: 3834034524, as a 32bit unsigned integer is hex E486B95C or binary 11100100100001101011100101011100. Notice that the most significant (leftmost) bit is set. This is the sign bit on 32bit signed integers.
There, that bit pattern translates to decimal -460932772. The XOR operation is forcing the result into signed integers.
Additional info: a 32bit signed integer can handle values from -2147483648 to +2147483647 (which your original value exceeded and it thus wrapped around). 32bit unsigned integers handle values from 0 to +4294967295. JavaScript is a dynamically typed language and the values may change types as needed. The number may become a floating point value, or bitwise operations may turn it into an integer, or it could become a string. There are some ways to use specific datatypes in recent versions of JavaScript, but this is not something you'd do with simple calculations.
Comment: Thank you, this is the explanation. This is not common in other languages.
Answer: The ToInt32 operation does not preserve the sign - it casts your number to a signed 32-bit representation. Since 3834034524 is larger than 231, it will overflow and result in a negative integer.

  010           --ToInt32-->  000000000000000000000000000000002
^ 383403452410  --ToInt32-->  111001001000011010111001010111002
                                         V xor V
= -46093277210  <-fromInt32-  111001001000011010111001010111002
Comment: "The ToInt32 operation does not preserve the sign" --- this phrase looks suspicious
Comment: @zerkms: Yeah, but I think it's quite accurate. Step 5 is "*If `int32bit` is greater than or equal to 231, return `int32bit` − 232, otherwise return `int32bit`*"


Call on_press callback multiple times on key held down event

Question: I am trying to record from my microphone while i press down a button, problem is that the library I am using is not able to detect on hold event. It only detect on press, which happens once, which means that the microphone only records one sample..
import pyaudio
import wave
from pynput import keyboard

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

def on_press(key):
    if key == keyboard.Key.cmd_l:
        print('- Started recording -'.format(key))
        try:
            data = stream.read(CHUNK)
            frames.append(data)
        except IOError:
            print 'warning: dropped frame' # can replace with 'pass' if no message desired
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

print("* recording")

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

I am using pynput for keyboard events and pyaudio for recording.
it seems to record when cmd_l is pressed down and stops when i release. problem is the audio file generated doesn't contain anything, or is pretty short as in 0.19s long.
I guess it could have to do with stream.read has to be called multiple times, and the keypress is only being recorded once hence only one sample is being recorded.
but if that is the case how do i make it call stream.read multiple times, while also detecting also detecting when it is being released?
or are there libraries that support on_hold mechanism on keyboards?
Updated approach with threading:
from pynput import keyboard
import time
import pyaudio
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)
        print self.stream.is_active()

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            return (in_data, pyaudio.paContinue)
        elif self.key_pressed == False:
            return (in_data, pyaudio.paComplete)
        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print "start Stream"

    elif listener.key_pressed == False and started == True:
        print "Something coocked"
        listener.stream.stop_stream()
        listener.stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False

I tried a different approach introducing two threads, which one monitoring the keyboard, and the other one sorts out the recording. But this solution keeps dropping the frames, hence nothing is actually being recorded?..
how come?
Answer: You can do something like in this answer where you run a function periodically on a separate thread. Seems to be the easiest solution.
Answer: Here's an example of how you might do it: I have modified your code by making a separate thread do the recording. The keyboard press/release sets the state of an Event, and the thread records chunks in a loop when the Event is set. A separate Event is used to tell the thread to terminate after recording is done. This records multiple 32Kb chunks for me (8192 * 2 chans * 16 bits).
import pyaudio
import wave
from pynput import keyboard
import threading

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

recordingEvent = threading.Event()    # set to activate recording
exitEvent = threading.Event()         # set to stop recording thread

def on_press(key):
    if key == keyboard.Key.ctrl:
        print('- Started recording -'.format(key))
        recordingEvent.set()
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.ctrl:
        print('{0} stop'.format(key))
        recordingEvent.clear()
        keyboard.Listener.stop
        return False

def do_recording():
    while (not exitEvent.is_set()):
        if (recordingEvent.wait(0.1)):
            try:
                data = stream.read(CHUNK)
                # print len(data)
                frames.append(data)
            except IOError:
                print 'warning: dropped frame' # can replace with 'pass' if no message desired

class myRecorder(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        do_recording()

# start recorder thread
recordingThread = myRecorder()
recordingThread.start()

# monitor keyboard
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

# stop recorder thread
exitEvent.set()
recordingThread.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

NB I used the Ctrl key instead of the Cmd key, as it suited my machine better. Hope this is useful.
Comment: I tried a similar solution (i think, you seem to have more threads than I have?)... but I can't record with yours or mine, it keeps  giving  IOerror.


Mimemail + SMTP + Mail System: inline images make body empty

Question: I'm trying to send HTML mails on a Drupal 7 install.
For this, I use Mail System, SMTP authentication and Mime mail modules.
I used settings as Alternative approach on this page http://drupal.org/node/1200142
The mail content is built within custom modules I'm writing (not by rules or simplenews, I mean).
I tweaked default Mail mime template to my needs, within a separate, light drupal theme.
My mails are sent (and received) without error when they contain only HTML and styles.
There are no error also when I had images with absolute url: Mime mail is leaving them as such.
I need to embed a few small images within my mails and when I try to do so, accordingly to what's written in Mime Mail README, I get a "Message body empty" at the top of my page when my code tried to send the mail.
I placed dpm($message) along the Mime mail code to locate where the body content is left empty.
I finally reached the
class MimeMailSystem implements MailSystemInterface
located in mimemail/includes/mimemail.mail.inc
Body content was still there.
Then the class MimeMailSystem__SmtpMailSystem implements MailSystemInterface
in default/files/mailsystem/MimeMailSystem__SmtpMailSystem.mail.inc
Again, my content was still there, along with inline BASE64 encoded images.
So the content disappears somewhere after that (in Mail System ?)
As I pointed it out here, switching Site-wide default MailSystemInterface class in Mail System settings from
MimeMailSystem__SmtpMailSystem
to
MimeMailSystem
allows the mail to be sent with its images, but the mail is no more sent through SMTP.
I'm pretty sure this is not due to a bug within one of the 3 modules, but I can't figure what I'm doing wrong.
The only thing I doubt from here is how I build the mail content :

I build some variable HTML content
I store it in $message['body'][] in my module's hook_mail implementation
then I print $body in my mimemail-message.tpl.php within static HTML part of the mail

The images I try to embed are in public files. I tried to link them :

with relative paths like sites/default/files/<filename>
with relative paths like public://<filename>

with no success.
Does anyone has a magical one character solution for something I missed ? ;)
Regards,
Answer: Further investigations lost me into the SMTP Authentication Support module
It's complicated enough and I couldn't locate something to help me find what was the problem coming form my configuration.
After a quick search within issues of Mime mail, someone was linking to another module to handle SMTP connection: enter link description here
Basically it works the same way than SMTP Authentication support but its benefit is you don't have to create a bridge mail system class between it and Mime mail, it's natively integrating with Mime mail.
To make it work properly, I had to configure Mail system as such :

Site-wide default MailSystemInterface class: MimeMailSystem
Mime Mail module class: MimeMailSystem
PHPMailer module class: DrupalPHPMailer

and in Mime mail settings :
 - set Mail engine to PHPmailer


sql 2008 hard drive configuration

Question: I'm building out a new SQL Server 2008R2 64BIT, will be running two user database of about 20gb and 15gb, maybe 50/50 read/write, and about 210 users
Base hardware would be DL380, 48GB, and Intel® Xeon® X5660 (6 core, 2.80 GHz, 12MB L3, 95W) x 2.
I'm planning to setup hard drive configuartion as below
Raid 1 72gb SAS 10k for OS
Raid 1 146gb SAS 15k (T-Logs)
Raid 1 146gb SAS 15k (TempDB)
Raid 10 146gb SAS 15k x 4 (DB Files)
I would kindly need your advise with this.
Thanks,
Mike
Comment: It's probably a little bit of overkill to put TempDB on it's own RAID array.
Answer: Maybe you should use SSD hard disk if you can for TempDB etc.

sql 2008 hard drive configuration


I sight read at 20 bpm, and not getting any faster

Question: I'm working through Berklee Press' Modern Method for Guitar 1.  I start every new piece at 40 1/8th notes per minute, so 20 bpm.  40 bpm (1/4 notes per minute) is the lowest my metronome goes, so I just make each tick an 1/8th note instead of a 1/4 note.  40 bpm seems like it's too fast for me to read a new piece.
For most pieces, I just start at 20 bpm and I work up to only 40 bpm.  I realize that that's still very slow, but I'm not trying to memorize the song, nor prepare for a performance.  Working up to faster speeds seems like it's less about reading music and more about muscle memory.  For the pieces or exercises that are more speed specific, I will work up to 80+ bpm.
The problem that I'm wondering about is that I'm not really getting faster at sight reading music.  Every new piece I start at 20 bpm. I can't imagine sight reading a song at its intended tempo.
Is there a better way to approach this.  Instead of starting slow, should I start faster and just make a ridiculous amount of mistakes?  I already make mistakes at 20 bpm.  I have seen questions and answers like this one that say to slow down to practice songs.  Should I burn my guitar and cut off my hands?
I realize that each piece is getting more difficult, so maybe if I were to start at the beginning of the book, or find another book with easier pieces, then I could start faster.  I would appreciate your thoughts on this!
Comment: This is a good question, which in the OP's case is about guitar, but the meat of the question is not specific to guitar. Should it be edited and retagged to make it less guitar-centric?
Comment: Something I've not seen in the answers below is the importance of learning to sight read rhythms *without* the instrument.  Clapping, speaking (da da daaa da da da etc.), singing, tapping on the table; the important thing is to remove the technical aspect from your sight reading and work on being able to interpret what the rhythms sound like *without* having to slow it right down.  Separate out the problem of how fast your technique allows you to finder the correct notes and how well you can sight-read rhythm into two separate parts.
Comment: @Some_Guy: Great advice! My drum teacher said "If you can't sing it, you can't play it."
Comment: Consider using a phone app for a metronome. There must be one that lets you go down to 20, and then increase by 1 at a time, for example. If the jump to 40 is too hard, try starting the next couple new songs at 21, then at 22, etc., and work your way up.
Answer: The advice about starting slow and gradually increasing is certainly not wrong, but I'd consider adding another "mode" of practicing especially when it comes to sight reading.
So the default mode is to focus on being correct rather than fast. When you want to learn the piece or when dealing with a method book that is teaching things in addition to just sight-reading, default to starting slow and working your way up. Find trouble spots and "loop" them, etc.
But (sometimes) to practice sight-reading or just as an occasional exercise to get yourself out of a rut, try to focus on moving forward without worrying so much about mistakes.

Go a bit faster than you normally would or are comfortable. The goal isn't to see how fast you can play it, but just to force you to keep up and start reading ahead.
Don't worry about mistakes. Don't start over. Don't loop trouble spots. Just keep moving forward trying to keep up.
Don't let yourself memorize anything because that defeats your goal of learning to sight-read. Get some new reading material that isn't your method book. Berklee has companion books specifically for this, or you can use violin music (alt link), fake books, randomly generated music, whatever. Just as long as it's the appropriate difficulty and you aren't familiar with it.

Then as far as your method book, see if that helps you increase the speed of the pieces that you're trying to actually learn. It should improve both your speed of actually recognizing and playing notes as well as your ability to look ahead to what you're playing next.
Don't worry about getting every exercise in your method book up to speed (maybe a bit higher than 40 though if you can get there). Do worry about getting them correct before moving on the next. And do internalize the point of the lesson (new key, fingering, or rhythm, etc). But only cherry pick certain pieces to truly perfect and get up to speed. Otherwise you'll never move forward into new positions, etc.
And, yeah, every once in a while you should start back at the beginning or an earlier point in the book and review some of the pieces. But you have to balance that with constant progress forward as well.
Comment: There are two different things the OP needs to learn. The object of *sight reading* is to play unseen music, first time, at its correct tempo. If you have to leave out some notes etc, so be it - but *you have to keep going, whatever happens.* If you are sight-reading in a band or orchestra and you can't keep time, the result will be a train wreck. On the other hand if you are *learning a piece*, the most important thing is *accuracy,* not speed - but don't get sidetracked by to *memorize* the piece at the same time as you are *learning* it - first, learn to play it *from the written score.*
Comment: One of my teachers put it surprisingly simply: "The only way to get good at playing fast is to practice playing fast." Slow practice is great for working out kinks, but only practicing at speed will get you up to speed.
Answer: Practice sight reading without a metronome at all.
I find playing the rhythm exactly enough to stay in step with a metronome is a small challenge in itself and will hold you back if you want to work on reading faster, because by trying to sight read with a metronome, you're fighting on two fronts and stretching your attention thin.
So when you play the piece for the first couple of times, just play without a metronome - you can tap your foot if that helps, but just go as fast as you can play the correct notes and make the rhythm somewhat right - you can speed up on easy-to-read passages and slow down on the more complicated ones. The goal is to read and finger the notes right as fast as you can, and just keep enough of the rhythm to get an impression of how the piece will sound later on in your practice.
Sight reading is all about recognizing patterns fast, so by reading and playing each part as fast as you can read and finger it, you can move different patterns up at different speeds without having to wait for the most complicated stuff to pick up speed. Soon your library of recognized patterns that you can read and play fast will grow and you will be able to  read and play pieces with these patterns reasonably fast. The more difficult parts will catch up after you don't have to think much about the easy parts anymore.
Now after you've played the piece a couple of times at your variable sight reading pace, get out a metronome and work out the intricacies of the rhythm.
Comment: Practicing without a metronome in the beginning is excellent advice in general, but *especially* for guitarists.  When learning a new piece on guitar (unlike, say, the flute), there will always be parts where your fingers aren't yet ready for the transition, the first readings of a guitar piece are always going to be very "stop start", unless you slow it down a ridiculous amount.
Answer: Practice as fast as you can without making mistakes, or fumbling.  This almost always initially means slowly.  And be alert to the fumbling.  You're not playing it without mistakes when you try out a few wrong finger positions before settling on the right one.  Get the transitions right too!   If you're having to play TOO slowly, it may be that you haven't found the direct route to the next position.
Answer:
Instead of starting slow, should I start faster and just make a ridiculous amount of mistakes?

No, from my experience it is better to start slow and work on correcting mistakes. The speed will come naturally. If you start fast, mistakes won't correct themselves naturally.
However, keep in mind there is a lot to read on a sheet of music: The note itself, it's duration, how it fits into the beat, while remembering the key, etc.
There are ways to practice reading some of that information in isolation, without a guitar in hand and without worrying about the rest. For example, practice reading the rhythm:

Every day, take a sheet of music
Set a metronome to a slow comfortable speed, for example 40 bpm
tap your foot to the metronome beat
Say the beat number out loud (1 2 3 4)
Tap your strumming hand on your lap for each note on the sheet of music, but don't say the beat nor tap your hand when there is a silence

By being persistant, you will be able to increase the speed and then, reading the rhythm will become automatic and it will be one fewer thing slowing you down while playing.
If you would like to follow a formal method including gradually more complex exercices, here is a a book I used and which helped me a lot: https://www.justinguitar.com/en/PR-012-UnderstandingRhythmicNotation.php
For notes identification, you could do a similar exercice, but you could name the notes instead of tapping your hand.
Hope this helps
Answer: I too am using the modern method , what I do set my metronome and batter through the exercises then get to a point , stop after a fortnight or so then go back and review ,I'm not memorising the peices  , each time I review I increase the speed Incrementaly, because the exercises get more technical as you move forward  going back to the beginning I got up to 80bpm in no time , and just keep doing that and you get there
Answer: I am a big fan of SightReadingFactory.com, and I feel that it has made a big difference in my reading.  For instance, maybe you could work specifically on starting at a lower level and setting the metronome just beyond your comfort zone.  Think of it as speed work for your reading.  Two things that work for me: don't stop.  Yes you will make mistakes, but learning to keep going is important. Second, practice looking ahead.  While you are waiting for that full note to finish, see what's coming to in the next bar.  There is a place for reading slowly and methodically, but you might surprise yourself and gain confidence by trying those speed drills.
Good luck!
Brian King
BTW I am not affiliated with SightReadingFactory.com in any way.  I just use it and love it.
Comment: If "sight reading factory" is a product name it probably should have capital letters.
Answer: Based on my experience with typing, morse code, music, ... , set the metronome speed well below what you can handle. At this slower pace, you'll tend to read ahead while playing the current note(s), a form of multi-tasking. Then slowly speed up the metronome. Again you want to try be reading at least one note ahead of what you're currently playing.
Answer: My initial reaction was that it's pointless to practice sight-reading specifically and that you will automatically get faster in parallel to learning to play, more easily reading single notes, reading several notes at once and just guessing notes instead of reading them all (the latter can be dangerous but also highly effective). Likewise for your finger's ability to do the work, this is all about muscle-memory, you'll build up a muscle repertoire so to speak. You will never sight-play at the same level as if you practiced a piece and if you are working through a method book each new method will (and should) have something new to slow you down.
But methods shouldn't be the only thing you are playing. And when you are playing other things, written to sound nice instead of being an appropriate challenge and teaching you something, then exactly the slow steady method practice should enable you to sight read comparatively fast.
(This is just my subjective experience with some other instruments and the styles of music I play. I think it probably applies in general, but can't be sure)


Is multiplication by $n$ a closed map for an abelian topological group

Question: Let $G$ be an abelian topological group. Let $n$ be an integer and consider $G\to G$ given by sending $x\mapsto nx$.
Is this a closed map? I do not have any particular reason to think it should be, but it would make a certain step in something I am reading much easier, so I am curious about whether it is true or not.
It might be useful to assume that $G$ is Hausdorff and locally compact, but those might not be necessary.
Thanks for any help, direction, or insight.
Answer: No, not necessarily, even if $G$ is locally compact Hausdorff.  For instance, let $A$ be any infinite discrete abelian group where every element has order dividing $n$ (e.g., an infinite direct sum of copies of $\mathbb{Z}/n$) and let $G=A\times \mathbb{R}$.  Let $(a_k)$ be a sequence of distinct elements of $A$, and consider the set $C=\{(a_k,1/k):k\in\mathbb{N}\}\subset G$.  Then $C$ is closed, since the $a_n$ are all distinct.  But the image of $C$ under multiplication by $n$ is $\{(0,n/k:k\in\mathbb{N})\}$, which is not closed, because $(0,0)$ is in its closure.


Rule triggers twice

Question: Simple rule to send account email after updating a commerce license.

Export
<code>{ "rules_membership_activation_email_notification_v2" : {
    "LABEL" : "Membership activation email notification v2",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-10",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_license" ],
    "ON" : { "commerce_license_update" : [] },
    "DO" : [
      { "user_send_account_email" : {
          "account" : [ "commerce-license:owner" ],
          "email_type" : "status_activated"
        }
      }
    ]
  }
}
</code>
Debug
<code>Rules debug information:
" Reacting on event After updating an existing commerce license.

    0 ms Reacting on event After updating an existing commerce license.
    12.037 ms Evaluating conditions of rule Membership activation email notification v2. [edit]
    12.046 ms AND evaluated to TRUE.
    " Rule Membership activation email notification v2 fires. [edit]
        0 ms Rule Membership activation email notification v2 fires.
        0.207 ms Evaluating the action Send account e-mail. [edit]
        55.557 ms Rule Membership activation email notification v2 has fired.
    67.623 ms Finished reacting on event After updating an existing commerce license.

" Reacting on event After updating an existing commerce license.

    0 ms Reacting on event After updating an existing commerce license.
    0.111 ms Evaluating conditions of rule Membership activation email notification v2. [edit]
    0.122 ms AND evaluated to TRUE.
    " Rule Membership activation email notification v2 fires. [edit]
        0 ms Rule Membership activation email notification v2 fires.
        0.113 ms Evaluating the action Send account e-mail. [edit]
        28.104 ms Rule Membership activation email notification v2 has fired.
    28.243 ms Finished reacting on event After updating an existing commerce license.
</code>
As you can see it triggers twice and sends two duplicate emails, should send one.
Tried with other random actions, they all trigger twice.
Got another rule that sends email on new license creation after checkout and it is not duplicate, it only triggers once as it should.
Comment: If the Rule is being run twice, it's because you've "updated an existing commerce license" twice. Which implies there is other code modifying the license.
Answer: Issue was solved with this https://www.drupal.org/project/commerce_license/issues/2205923#comment-8525711

This works just like for any other entity type, you check that commerce-license:status is not equal to commerce-license:original:status (confirming that it has just changed), and then in the next condition you check that commerce-license:status is expired.

Except 'original' now is 'unchanged'.
Don't know how or why, but it works.

Rule triggers twice


SQL Select records for this week and the next week

Question: http://gyazo.com/bc0f6794c260fdb97ee79e016abd0a11
the dag column means day or date and contains a datetime.
How can I select the records for this week and the next week, using the dag column?
I've got the following working code in PHP, but it also selected a dozen records from last year, but I don't want that.
$sth = $dbh -> prepare('SELECT * FROM ' . $cfg -> db_user . '_veld_wedstrijden WHERE thuisteam LIKE "'.$cfg -> db_user.'%" OR uitteam LIKE "'.$cfg -> db_user.'%" AND dag >= CURDATE() + INTERVAL 7 DAY ORDER BY dag ASC');
$sth -> execute();

The last bit of the query is where it selects them by the date.
Comment: Your first LIKE is what is picking up the old records
Comment: Ah I see what I did wrong here, thank you.
Comment: No problem, if it fixed the problem then you are welcome to answer this yourself or consider checking @Tim Dev's answer out.
Answer: First of all your make sure you use parentheses around your  (thuis OR uit) selection.
Second of all your current date operation is: get all matches with a date bigger than (today + 7 days).
You said in title you want all matches for this week and the next week. So from today 'till 14 days.
Use between like this
SELECT * FROM ' . $cfg -> db_user . '_veld_wedstrijden
WHERE
    ( thuisteam LIKE "'.$cfg -> db_user.'%"  OR uitteam LIKE "'.$cfg -> db_user.'%")
AND
    dag BETWEEN CURDATE() AND CURDATE() + INTERVAL 2 WEEK

Comment: Indeed, thanks very much, learned something new today about between and parentheses :)
Comment: Just one note - it is better to pass dates to queries so that it could be cached correctly.


How to I add offset to datetime in XSLT?

Question: I want to add whatever's in the offset the variable originalDate parameter passed to DAYFORMAT template.
Here's the XML:
<StartDate xmlns:b="http://schemas.datacontract.org/2004/07/System">
  2020-10-27T23:00:00Z
  60
</StartDate>

This is my code which formats the date but I'm not sure how I can add offset minutes to the DateTime?
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="StartDate">
    <date>
        <display>
            <xsl:call-template name='DAYFORMAT'>
                <xsl:with-param name="originalDate" select="node()"/>
            </xsl:call-template>
        </display>
    </date>
</xsl:template>
<xsl:template name="DAYFORMAT">

    <xsl:param name="originalDate"/>
    <xsl:variable name="day" select="substring($originalDate,9,2)"/>
    <xsl:variable name="month" select="substring($originalDate,6,2)"/>
    <xsl:variable name="year" select="substring($originalDate,1,4)"/>

    <xsl:variable name="Y">
        <xsl:choose>
            <xsl:when test="$month < 3">
                <xsl:value-of select="$year - 1"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$year + 0"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:variable name="y" select="$Y mod 100"/>
    <xsl:variable name="c" select="floor($Y div 100)"/>
    <xsl:variable name="d" select="$day+0"/>
    <xsl:variable name="m">
        <xsl:choose>
            <xsl:when test="$month < 3">
                <xsl:value-of select="$month + 12"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$month + 0"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:variable name="w" select="($d + floor(($m + 1) * 2.6) + $y + floor($y div 4) + floor($c div 4) - $c * 2 - 1) mod 7"/>
    <xsl:variable name="www">
        <xsl:choose>
            <xsl:when test="$w = 0">Sun</xsl:when>
            <xsl:when test="$w = 1">Mon</xsl:when>
            <xsl:when test="$w = 2">Tue</xsl:when>
            <xsl:when test="$w = 3">Wed</xsl:when>
            <xsl:when test="$w = 4">Thu</xsl:when>
            <xsl:when test="$w = 5">Fri</xsl:when>
            <xsl:when test="$w = 6">Sat</xsl:when>
        </xsl:choose>
    </xsl:variable>
    <xsl:variable name="monthName">
        <xsl:choose>
            <xsl:when test="$month=01">January</xsl:when>
            <xsl:when test="$month=02">February</xsl:when>
            <xsl:when test="$month=03">March</xsl:when>
            <xsl:when test="$month=04">April</xsl:when>
            <xsl:when test="$month=05">May</xsl:when>
            <xsl:when test="$month=06">June</xsl:when>
            <xsl:when test="$month=07">July</xsl:when>
            <xsl:when test="$month=08">August</xsl:when>
            <xsl:when test="$month=09">September</xsl:when>
            <xsl:when test="$month=10">October</xsl:when>
            <xsl:when test="$month=11">November</xsl:when>
            <xsl:when test="$month=12">December</xsl:when>
        </xsl:choose>
    </xsl:variable>
    <xsl:value-of select="$www"/>
    <xsl:text></xsl:text>
    <xsl:value-of select="$day"/>
    <xsl:text></xsl:text>
    <xsl:value-of select="$monthName"/>
    <xsl:text></xsl:text>
</xsl:template>
</xsl:stylesheet>

The following is the desired result:
<Display>Sat 28 November</Display>

How can I do this?
Comment: Are you really limited to XSLT 1.0? This is much easier if your processor supports XSLT 2.0+.
Comment: michael.hor257k, I can use 2.0
Answer: In XSLT 2.0, this could be as simple as:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:b="http://schemas.datacontract.org/2004/07/System"
exclude-result-prefixes="xs b">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="StartDate">
    <xsl:variable name="adjusted-dateTime" select="xs:dateTime(b:DateTime) + b:OffsetMinutes * xs:dayTimeDuration('PT1M')"/>
    <Display>
        <xsl:value-of select="format-dateTime($adjusted-dateTime, '[FNn,*-3] [D] [MNn]')"/>
    </Display>
</xsl:template>

</xsl:stylesheet>

Demo: https://xsltfiddle.liberty-development.net/bEJbpGC


Auto completion with multiple unordored words

Question: I'm using this script and I want to modify/update it to work in this way:
In my database I have for example: hello world, my name is John. When I search Hello World or orld, m or name i I want to find the item, but if I search world hello or name John it doesn't work. So, I'm looking for the way to make it work. Could someone help me ?
Many Thanks
index.php

Search.php
<?php
    include('admin/db.php');
    if($_POST)
    {
        $q = $_POST['search'];
        $sql_res = mysql_query("select id, name, email, infos from autocomplete where name like '%$q%' or email like '%$q%' or infos like '%$q%' order by id LIMIT 100");
        while ($row = mysql_fetch_array($sql_res))
        {
            $username = $row['name'];
            $email = $row['email'];
            $infos = $row['infos'];
            $b_username = ''.$q.'';
            $b_email = ''.$q.'';
            $b_infos = ''.$q.'';
            $final_username = str_ireplace($q, $b_username, $username);
            $final_email = str_ireplace($q, $b_email, $email);
            $final_infos = str_ireplace($q, $b_infos, $infos);
        ?>

                <?php echo $final_username; ?>

            <?php echo $final_email; ?>

            <?php echo $final_infos; ?>

    <?php }
} ?>

Comment: The MySQL `LIKE` clause isn't smart enough to find records with words in a different order. Your best bet would be to split the search query into words and cycle through each word adding a point to each search result that comes up, then ordering the results by how many points it has.
Comment: You should also update the script to use MySQli or PDO. Depending on your db you're using you could try using  MATCH() ... AGAINST.
Answer: you should take look to levenshtein function.
http://php.net/manual/fr/function.levenshtein.php
Try to make your own algo, it will increase your skill.
Answer: i'm french too ! :D
Here you search a query like "name is" you're request search in Name, email, and info column all results who contain exactly "name is".
If you want to search word by word you need to use a boucle for each word in you're search query store in a tempory table the results and return all the result who contain each word.
There's maybe an other solution look here : SQL SELECT WHERE field contains words


Muitas linhas em um arquivo csv

Question: O cenário da minha duvida é o seguinte: Tenho um sistema que lê um arquivo que possui em torno de 3 milhões de linhas, cada linha tem um separador, eu identifico cada item na linha, faço o devido tratamento que deve ser feito em cada um desses itens, e transformo cada linha em um objeto, sendo que este objeto mais tarde é adicionando em uma lista, que é salvo depois no banco de dados. As linhas que possuem defeito devem ir para outra lista para que um arquivo com as linhas defeituosas seja gerado.
O problema acontece quando a quantidade de linhas é por exemplo 5 milhões, ocasionando estouro de memória. Gostaria de saber se alguém já passou por isso, e como resolveu?
Answer: Eu trabalho no PHP. Quando tenho um processamento deste tipo que 'estora' o tempo do servidor, faço uma pagina que irá consumir um serviço que será processado em background pelo servidor.
O que na maioria das vezes é dar timeout do navegador, mas o sistema continua processando.
Então utilizo dessa abordagem. Chamo um serviço que irá, por exemplo, processar o arquivo e posteriormente pode enviar um email retornando o relatório do arquivo processado ou disponibilizar o relatório em um link no sistema.

Muitas linhas em um arquivo csv


JavaServer faces redirecting form

Question: Hello I have that form:
        <h:form>
            <h:selectOneRadio layout="pageDirection" value="#{votesBean.answer}">
                <f:converter converterId="PollConverter"/>
                <f:selectItems value="#{pollsBean.selectItems}"/>
            </h:selectOneRadio>
            <h:messages/>
            <h:commandButton value="#{msgs.vote}" action="/profile/main.xhtml"/>
        </h:form>

But when I submit this form, page no redirects to  main.xhtml, but refresh current page (viewpoll.xhtml, I 'think because there are errors in form), but not include view parameters. I use view parameter to know current poll… in result I get nullpointer exception, because I don't have poll id.
Answer:
If you would like to navigate directly without validation and conversion, use immediate="true" in h:commandButton.
Otherwise, there might be a failure in Request Processing Life Cycle, Eg. validation phase.
Finally, your URL(/profile/main.xhtml) address is incorrect.

JavaServer faces redirecting form


How to convert a TAR file into an ISO file

Question: I have a Linux TAR file that I would like to convert directly into an ISO.  Is there a way to do this, preferably, without having to extract the contents of the file first?
This would be similar to the following question; however, this is focused on plain or straight-up tar files and not related to bzip or a bzipped tar.
This is also something that I intended to use within a script and the reason that I do not want to extract it first.
Comment: Theoretically it could be done without having to extract each of the files *to disk* (they have to be extracted from the archive in order to be put into the new image), but I don't know of anything that does.
Comment: Why do you want to do this without extracting the tar?
Comment: I wonder if there is a way to pipe it to something like stdin and then pipe it on over to the iso file ???
Comment: I am not sure if this would work or not, since I am not 100% for sure what the command is doing. -- tar -jxf /dev/stdin file.tar | mkisofs -o file.iso -stream-media-size 512
Comment: The -stream-media-size option was actually made for this! :-) See [the genisoimage man page](http://linux.die.net/man/1/genisoimage) for info -- currently it mentions tar in the docs for this option (and uses it in the examples for it).
Answer: Use AVFS to access the contents of the tar archive as if it was a directory. AVFS is a virtual filesystem built on FUSE. Point your favorite ISO builder to the directory inside the tar archive.
mountavfs
cd ~/.avfs/path/to/archive.tar\#
genisoimage -o /path/to/iso .

Comment: @ Gilles - thanks for the idea.  This looks like it might be an excellent idea; however, I am on CentOS 6 and am running into problems trying to get AVFS installed.
Answer: If your primary objectives are to expedite the process and to avoid unnecessary disk activity for performance reasons, and you have plenty of RAM to spare relative to the size of your tarball, you can extract the .tar into RAM using tmpfs. This option is very likely the fastest available, unless you're able to get @bulleric's pipe approach to work and you're reading from one disk and writing to another.
Answer: archivemount /file.tar /media/ISO

or uncompressed .tar and
genisoimage -o myfile.iso directory_src

(can be folder /media/ISO or point mount /media/cdrom)
Answer: You must extract it but you dont must extract it to your harddrive
you can use stdtout  and pipe it to genisoimage or mkisofs
tar --to-stdout xf tareddata.tar | genisoimage -o image.iso  tareddata
test it:
mount -o loop image.iso /mnt
you can write a small script to automize this issue
greez bull
Comment: And how would it tell one file from the next?
Comment: When I run this I get a series of errors, the first is: tar: You must specify one of the `-Acdtrux' or `--test-label'  options.  The next error is:  I: -input-charset not specified, using utf-8 (detected in locale settings).  The last error is:  genisoimage: No such file or directory. Invalid node - 'tareddata'.
Comment: the first problem i solvet  i have take a wrong option in tar ;  the 2nd one hmm in my opinion the first directory get extractet the same name as the  as the unextracted directory like tardata.tar tardata
Comment: Sorry, I'm fairly sure there's no way this can work; -1 .


How to set value of child pop op elements from parent window using Javascript?

Question: I am calling a pop up window from a parent page using :
var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');

I then try to set the value of two spans which are on chil pop up from parent window using this childWindow object.
 childWindow.onload = function () {
alert('this msg does not shows up when run on IE8');
                var hidden1 = childWindow.document.getElementById('hidden1');
                var hidden2 = childWindow.document.getElementById('hidden2');
                hidden1.innerHTML = rowindex;
                hidden2.innerHTML = controlname;
            };

this code works fine as long as I am using chrome. But it refuses to work on IE8. There are no console errors either.
I tried removing childWindow.onload = function () { } but then the page would just sort of refresh on both chrome and IE8.
UPDATE
This did not work either.
   function CallPopUp(rowindex,controlname ) {
            function popupLoad() {
                alert('this msg does not shows up when run on IE8');
                var hidden1 = childWindow.document.getElementById('hidden1');
                var hidden2 = childWindow.document.getElementById('hidden2');
                hidden1.innerHTML = rowindex;
                hidden2.innerHTML = controlname;
            }

            var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
            if (childWindow.document.readyState === "complete") {
                popupLoad();
            } else {
                childWindow.onload = popupLoad;
            }

Comment: what is type of hidden?
Comment: its just a span.. with class named hidden. It is visible at the moment.I am planning on giving it css style hidden later on
Comment: @Adil This code works fine on chrome. But when I run this on IE8 the span remains blank.
Comment: @Adil it seems that the function is not even getting executed on IE8 since I put alert at the first line and it did not show up.
Answer: If test.aspx is in the browser cache, it is possible that the onload event has already happened before you attach your event handler so you're missing it (IE is known to do this with image load events).  I'd suggest you check document.readyState before attaching your event handler.
function popupLoad() {
    alert('this msg does not shows up when run on IE8');
    var hidden1 = childWindow.document.getElementById('hidden1');
    var hidden2 = childWindow.document.getElementById('hidden2');
    hidden1.innerHTML = rowindex;
    hidden2.innerHTML = controlname;
}

var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
if (childWindow.document.readyState === "complete") {
    popupLoad();
} else {
    childWindow.onload = popupLoad;
}

As another option, you can put the values into the query parameters for the URL:
`"test1.aspx?hidden1=" + rowindex + "&hidden2=" + controlname`

and then have the popup window load it's own fields from it's own onload handler from what's in the query string. Then, you can keep the code in the popup window self contained and you don't have to try to modify one window from another.
If you don't want the user to see this or be able to edit it, you can turn off the location bar in the popup window.
Comment: check my update. I tried your code but it did not work
Comment: @Arbaaz - not much we can do but issue blind guesses if you can't show us the actual running page URL with the issue.  Actual debugging requires a running example.
Comment: I know.
Well if you have to set value of child pop up window's span with values from parent window. How would you do it?
Comment: @Arbaaz - One way to do it is to put the values into the query parameters for the URL `"test1.aspx?hidden1=" + rowindex + "&hidden2=" + controlname` and then have the popup window load it's own fields from it's own onload handler from what's in the query string.  Then, you can keep the code in the popup window self contained and you don't have to try to modify one window from another.  I'm sure you can modify one window from another (with the same origin), but I can't see what your issue is without being able to debug it.
Comment: I know but I dont want to edit url in some browser which might allow it.
Comment: @Arbaaz - I've offered you a work-around and you haven't offered enough info for us to help you further or something we can debug.  Not much else we can do here.
Comment: What you have offered is helpful and appreciated. I am now doing it the way you have suggested. I wonder if its possible to make sure that user can not edit url in pop up on any browser.
Edit your answer and add what you have posted as a comment, I will be marking your answer soon.
Comment: @Arbaaz - info from my comments added to my answer.


Twilio Programmable Chat - not able to run the quickstart project

Question: I was trying to run  twilio quickstart code for programmable chat, but I was getting the below error.
Logging in...
There was an error creating the chat client:
Error: Fetch resource from "Client/v1/Configuration" failed.
Please check your .env file.
configurations seems proper in Twilio Server Starter Kit Environment Setup.

Adding Few more information as requested.
I don't have a code for now, I am testing my api for conversation using postman, I am trying to read the the list of messages using postman, but I get authentication error, just wanted to know the format of request body to pass the credential.
Comment: Are you seeing any errors in the terminal where the server is running? (As a note, the [programmable chat service is being sunset in July](https://www.twilio.com/changelog/programmable-chat-end-of-life) and you should use the [Conversations API](https://www.twilio.com/docs/conversations) instead.
Comment: Thanks..! In that can you please send me any reference quickstart project from twilio for using conversation api, I am planning to have front end in angular and the server in C#.net for my chat application, any reference example will make my job easier...
Comment: I linked to the documentation, there are quick start applications there, I'm sure you can find them.
Comment: Thanks @philnash, that helped, I could create a conversation, add participants and send messages, but when i try to retrieve the list of message sent, I get unauthorized response, can you please let me know what is the format I should pass my authorization,

url -https://conversations.twilio.com/v1/Conversations/CHXXXXX/Messages
body - {
 "Authorization": "ACXXXXXXXXXXX:eXXXXXXXXXXX"
}

response -
,
    "detail": "Your AccountSid or AuthToken was incorrect.",
    "message": "Authentication Error - No credentials provided",
    "status": 401
Comment: Can you update your question with the full code you're using? I can use that to write a proper answer for you.
Comment: @philnash, added the requested information, can you please check
Answer: To authenticate the API request properly in Postman you need to add your Account SID and Auth Token (or API Key and secret) as the username and password for Basic Auth under the Authorization tab.
Comment: it worked, I could get the message list.....! Thanks for your time and support.
Comment: Awesome, glad to hear it!


How to prevent the user profile page of a blocked user to show up?

Question: When a user is blocked the (core) user profile is still accessible. I would rather show a message "this user profile has been removed".
I could write an exception into the user-profile.tpl.php. Is there a better way?
Answer: You should be able to implement hook_user_view in a custom module.
First create a page which contains your preferred content (e.g. "This user profile has been removed").  Let's call this node/1337 for now.
Secondly, you want something along the lines of the following:
<code>function mymodule_user_view($account, $view_mode, $langcode) {
  if ($account->status == '0') {
    drupal_goto('node/1337');
  }
}
</code>
There are other parameters you can pass to drupal_goto if you wish (such as HTTP response code) - check out the API for more info :-)
Comment: Ooh, another note..you might want to put some authentication in for user 1 - as it's written, the code will block user 1 out of the profile as well.  Sorry.
Comment: that's great, thank you. Looks like I can use the same code to hide the admin profile.
Answer: You can try to alter the page callback of user profile page, change the access callback to point to your custom function that determine whether a user is blocked.


NUMA placement failed, performance might be affected

Question: I'm running SuperMicro 6048R-E1CR36H Storageserver on Ubuntu Xenial 16.04.03 LTS and Xen
Kernel:  4.4.0-97-generic
Xen: xen-hypervisor-4.6-amd64:amd64/xenial-security 4.6.5-0ubuntu1.2
Problem: when I run xl create or xl restore, I get this error message:
libxl: notice: libxl_numa.c:499:libxl__get_numa_candidate: NUMA placement failed, performance might be affected

On other xen-systems I haven't noticed the same message, how would I be able to fix this error?
Here is the xl info. I'm running 24 cores on 2x Xeon E5-2620 v3 chips.
https://ark.intel.com/products/83352/Intel-Xeon-Processor-E5-2620-v3-15M-Cache-2_40-GHz
host                   : myserver
release                : 4.4.0-97-generic
version                : #120-Ubuntu SMP Tue Sep 19 17:28:18 UTC 2017
machine                : x86_64
nr_cpus                : 24
max_cpu_id             : 23
nr_nodes               : 2
cores_per_socket       : 6
threads_per_core       : 2
cpu_mhz                : 2400
hw_caps                : bfebfbff:2c100800:00000000:00007f00:77fefbff:00000000:00000021:000037ab
virt_caps              : hvm hvm_directio
total_memory           : 130967
free_memory            : 5
sharing_freed_memory   : 0
sharing_used_memory    : 0
outstanding_claims     : 0
free_cpus              : 0
xen_major              : 4
xen_minor              : 6
xen_extra              : .5
xen_version            : 4.6.5
xen_caps               : xen-3.0-x86_64 xen-3.0-x86_32p hvm-3.0-x86_32 hvm-3.0-x86_32p hvm-3.0-x86_64
xen_scheduler          : credit
xen_pagesize           : 4096
platform_params        : virt_start=0xffff800000000000
xen_changeset          :
xen_commandline        : placeholder
cc_compiler            : gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
cc_compile_by          : stefan.bader
cc_compile_domain      : canonical.com
cc_compile_date        : Fri Oct 13 15:42:52 UTC 2017
xend_config_format     : 4

Comment: Without more information really it's impossible to say. The required information is how many CPUs of what type do you have? What  does 'xl info' report about the CPU?
Comment: I edited the question to show xl info.
Answer: I was getting this message on Debian when I forgot to limit Dom0 memory.
For GRUB2 add or edit the following line in the /etc/default/grub file:
GRUB_CMDLINE_XEN_DEFAULT="dom0_mem=512M,max:512M"
More about this: https://wiki.xenproject.org/wiki/Xen_Project_Best_Practices
Answer: From xl info output, it looks like you have very little available free memory. You're almost certainly trying to launch a VM with more memory that what's available, that could be the reason for this message (I suppose that some VMs are already running on this host).
I suppose that grep vmx /proc/cpuinfo returns something, too?
Comment: grep vmx /proc/cpuinfo return empty so I'll check my BIOS settings. There is 128GB of total memory on the system. The command `free -m
              total        used        free      shared  buff/cache   available
    Mem:         110146       41342       61781         499        7022
    62287
    Swap:          3904        3157         746`
Comment: @PHZ.fi-Pharazon so you have virtualization turned off. Probably not a good thing on a virtualization server :) Is your xf info output still the same 6 months later?


Undefined symbol with Python extention using OpenCV C API

Question: I am expanding a C-extension to use uses OpenCV, and to start, cvtColor, but I am getting an undefined symbol error.  I think it may be me mixing up C and C++, or maybe loading the library incorrectly.  I have the error boiled down to this C code:
test.c:
#include <cv.h>

void BGR2HLS(const void * srcv, void * dstv, int elems) {
    const uint8_t * src = (uint8_t *) srcv;
    uint8_t * dst = (uint8_t *) dstv;
    cvtColor(src, dst, CV_BGR2HLS);
}

which I compile using:
gcc -fPIC -shared -o test.so test.c -L/usr/lib/ `pkg-config --cflags opencv` -lopencv_imgproc -lopencv_core

I see /usr/lib/libopencv_imgproc.so exists, and everything compiles without error.
I then try to run this Python script:
import numpy as np
import os.path
import ctypes
import cv2

test_module = ctypes.CDLL(
    os.path.join(os.path.dirname(__file__), './test.so'))

test_module.BGR2HLS.argtypes = [
    ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int
]

if __name__ == '__main__':
    img_data = cv2.imread('../test_data/FixedUIDesign.jpg')
    h, w, d = img_data.shape
    img_data_out = np.array(img_data, dtype=np.uint8)
    test_module.BGR2HLS(img_data.ctypes.data, img_data_out.ctypes.data, h*w)

and get the following error (I was experiment with adding the RTLD_GLOBAL flag):
Traceback (most recent call last):
  File "c_tests.py", line 6, in <module>
    os.path.join(os.path.dirname(__file__), './test.so'), ctypes.RTLD_GLOBAL)
  File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: ./test.so: undefined symbol: cvtColor

I see opencv_imgproc exists, and I can point to it when I compile without errors.  I can see there is something similar to the symbol I want as well:
$ nm -D /usr/lib/libopencv_imgproc.so | grep cvtColor
00000000000b65a0 T _ZN2cv8cvtColorERKNS_11_InputArrayERKNS_12_OutputArrayEii

Is the odd name a symptop of the issue?  What is wrong/missing with how I'm building/using the extension?
Comment: possible duplicate of [Ctypes "symbol not found" for dynamic library in OSX](http://stackoverflow.com/questions/2900512/ctypes-symbol-not-found-for-dynamic-library-in-osx)
Comment: I never solved this, but I swithced to using C++ and it works.
Answer: Switching to C++ solves the problem.  Luckily I have the flexibility.


Handling quasi-perfect separation in a zero-inflated negative binomial regression in R

Question: I want to run a zero-inflated negative binomial regression in R, but one of my variables exhibits quasi-complete separation and throws errors for both the negative binomial and logistic pieces.  I've been using the zeroinfl() function in the pscl package:
pop_dense_zinb <-
   zeroinfl(thing_count ~
                dataset[["variable_causing_issues"]],
         data = dataset,
         dist = "negbin",
         EM = TRUE)

Errors:
Warning: glm.fit: fitted rates numerically 0 occurred
Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
Error in glm.fitter(x = X, y = Y, w = w, start = start, etastart = etastart,  :
  NA/NaN/Inf in 'x'

What can I do (in general, and particularly in R)?  Is there an R package that can handle penalized likelihood methods like Firth in a zero-inflated negative binomial regression?  I don't want to toss this variable because it's the best predictor of the outcome, which makes a lot of sense empirically, as well.
Comment: Please edit to clarify if you are asking about how this is addressed in general, or if you're just asking for r code / packages. The latter is off topic here, but the former would be a good question for our site.
Comment: I'm interested in both what statistical method is most appropriate and how to program said method in R.  Edited!
Answer: I wouldn't know of a bias-adjusted zero-inflated model (a la Firth & Kosmidis). However, it's fairly easy to combine a bias-adjusted binary regression model with a hurdle regression.
The standard hurdle(y ~ ...) model can also be estimated by separately calling glm(factor(y > 0) ~ ..., family = binomial) and zerotrunc(y ~ ..., subset = y > 0) (using the countreg package from R-Forge).
Instead of estimating the binary zero hurdle part (y = 0 vs. greater) with glm(..., family = binomial) you can use brglm2 or logistf etc. The zero-truncated count part is not affected by this and can either be taken from hurdle() as before or equivalently from zerotrunc().


Migrating specific nodes from Drupal 6 to Drupal 7

Question: I have an existing Drupal 6 site, and an updated version of the same site running on Drupal 7. Setting up the Drupal 7 site did take a lot longer than I planned, and the old Drupal 6 site accumulated some more content in the meantime. I now want to migrate some new nodes from the old site to the new one, but not all of them as many already exist on the new site in updated versions.
I did find the Migrate module, but from what I can tell this seems to be a framework, and not an out of the box solution.
Is there an easy way to migrate specific nodes, either hand-picked or based on selection criteria like node type and creation date, between two Drupal installations of different major versions?
Answer: The easiest way I know is export your nodes from Drupal 6 by using Node Export . Then you can import your node to Drupal 7 by Feeds module. This has update and replace exsisting nodes options. Just make sure you set one of the source as an "Unique" on Mapping setting, like "uid" or "title" of the node. Hope this help
Answer: Migrate module.
We migrated an entire site using this module and migrating nodes was the easiest. The documentation is pretty well written. Let me know if you decide to go down that path. I could maybe help get you setup.
Answer: I think the answer is "no". But in the realm of non-easy ways, you might try

depending on the number of the nodes in question, is recreating them by hand possible?
if it's an option to re-run your original upgrade process on the new snapshot of the site, that might be the easiest way.  If that might be destructive to things you've created on the D7 site, try diving into the Features module for how to move site-building elements between sites.  It's work, but it builds character.
I would investigate Node Export and Feeds next, as H-L suggested.
Migrate and migrate_d2d are very effective tools written for a developer audience.  This will solve your problem very quickly, however if it's your first time using it, it will take a little while to get up to speed on the framework.


Problem with ESLint, React/TS when trying to use export * syntax

Question: Is it possible to use export * from './X' with absolute import paths and eslint in react/typescript? I wanted to have single index.ts file in components folder that would export everything else but eslint gives me weird error when i'm trying to do this.
My current structure looks like this:
src/components/Example1/Example1.tsx
import React from 'react';

export type Props = {};
export const Example1 = (props: Props) =>

src/components/Example1/index.ts
export * from './Example1';

src/components/index.ts
export * from './Example1';

Both index files gives me error:
0:0  error  Parsing error: Cannot read property 'name' of undefined
Also when i try to import anything from the components/index file using an absolute path import { Example1 } from 'components'; i have an error:
1:43  error  Parse errors in imported module 'components': Cannot read property 'name' of undefined (undefined:undefined)  import/namespace
1:43  error  Parse errors in imported module 'components': Cannot read property 'name' of undefined (undefined:undefined)  import/named

This is my .eslintrc.json file
  {
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "root": true,
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:import/warnings",
    "plugin:import/errors",
    "plugin:import/typescript",
    "prettier/@typescript-eslint",
    "prettier",
    "prettier/react"
  ],
  "plugins": [
    "react",
    "react-hooks",
    "jsx-a11y",
    "@typescript-eslint",
    "prettier"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "settings": {
    "react": {
      "version": "detect"
    },
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"],
        "moduleDirectory": ["node_modules", "src/"]
      }
    }
  },
  "rules": {
    "prettier/prettier": "error",
    "import/newline-after-import": "error",
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": [
      "warn",
      { "args": "after-used", "argsIgnorePattern": "^_" }
    ]
  }
}

This is my tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": "./src"
  },
  "include": ["src"]
}

My current package.json:
{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "private": true,
  "dependencies": {
    "@apollo/react-hooks": "^3.1.3",
    "@material-ui/core": "^4.9.5",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/styles": "^4.9.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "@types/jest": "^24.0.0",
    "@types/material-ui": "^0.21.7",
    "@types/node": "^12.0.0",
    "@types/react": "^16.9.0",
    "@types/react-dom": "^16.9.0",
    "@types/react-router-dom": "^5.1.3",
    "@types/styled-components": "^5.0.1",
    "@types/yup": "^0.26.32",
    "apollo-boost": "^0.4.7",
    "env-cmd": "^10.1.0",
    "formik": "^2.1.4",
    "graphql": "^14.6.0",
    "i18next": "^19.3.3",
    "i18next-browser-languagedetector": "^4.0.2",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-i18next": "^11.3.3",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0",
    "styled-components": "^5.0.1",
    "typescript": "~3.7.2",
    "yup": "^0.28.3"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.23.0",
    "@typescript-eslint/parser": "^2.23.0",
    "eslint": "^6.8.0",
    "eslint-config-prettier": "^6.10.0",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-prettier": "^3.1.2",
    "prettier": "^1.19.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "build:staging": "env-cmd -f .env.staging yarn build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lint": "tsc --noEmit && eslint . --ext .js,.tsx,.ts --max-warnings=0",
    "lint:fix": "eslint . --ext .js,.tsx,.ts --fix",
    "watch": "react-scripts start",
    "deploy": "yarn build && firebase deploy",
    "deploy:staging": "yarn build:staging && firebase use staging && firebase deploy"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I'm also using lerna with yarn workspaces to easily handle MERN app.
Deleting eslint package / configs, node_modules did not help me, i still have Cannot read property 'name' of undefined error. It is super weird because in clean CRA everything works. I spent last 4 hours trying to solve this problem and finally used a workaround with importing types to root index file and reexporing them as new type but it's definately a painful solution. I need to keep isolatedModules. Maybe someone had similar problem?
Comment: huh, interestingly we're both using GraphQL/apollo. So the way i fixed it  was by changing my import style. I don't have a better work around other than
```import { Blah } from './blah'
export {
  Blah
}````
Comment: Did you try with `as` keyword like `export * as Example from './Example1'`
Comment: Yep, it gives me: "Parsing error: 'from' expected. eslint", super weird
Comment: Does this related to your question? https://eslint.org/docs/7.0.0/rules/no-restricted-exports#known-limitations
Comment: I',m not using default exports so i guess there's no way this rule could help
Comment: Just started happening to me today too. Only change was some package updates.. i smell something broken in some core toolchain piece.
Comment: @Dooomel what versions of CRA and Typescript do you have? Maybe you can post your `package.json`
Comment: @DavidG sure, i edited my question with package.json file. As you see i',m using react-scripts 3.4.0 and typescript ~3.7.2
Answer: The problem was @typescript-eslint package, check out the issue for more info:
https://github.com/typescript-eslint/typescript-eslint/issues/1746
Fast fix for this is to downgrade packages to version 2.22.0:
@typescript-eslint/eslint-plugin
@typescript-eslint/parser
@Edit This helped with lint error but my CRA build is still crashing, I guess i will have to wait for package fix


Notification - Customizar Actions

Question: Gostaria de saber se é possível customizar um Notification com suas Actions.
Exemplo:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.customnotification);
Notification.Builder builder = new Notification.Builder(this)
        .setSmallIcon(R.drawable.ic_ico)
        .setAutoCancel(true)
        .setContentIntent(pIntent)
        .setContent(remoteViews)
        .addAction(R.drawable.ic_sim, "Sim", intent)
        .addAction(R.drawable.ic_nao, "Não", outraIntent);

Quando removo o .addAction, ele carrega corretamente o content.

Mas quando incluo, ele exibe o layout padrão da Notification.

Desde já agradeço!
Answer: Como você está utilizar uma custom view como layout da notificação, em vez de usar addAction(), o seu layout deverá disponibilizar botões que, quando clicados, executarão as actions.
Os intent's intent e outraIntent são atribuídos a esses botões da seguinte forma:
remoteViews.setOnClickPendingIntent(R.id.button1, intent);
remoteViews.setOnClickPendingIntent(R.id.button2, outraIntent);

Ver RemoteViews.setOnClickPendingIntent
Comment: Funcionou corretamente ! Muito Obrigado!

Notification - Customizar Actions


Jquery Como somar valores de input em tempo real?

Question: Sou iniciante e tenho um sistema em que o usuário pode adicionar vários inputs dinamicamente, preciso que ao digitar os valores (em decimais)  a soma total seja exibida em uma div. Se alguém puder me ajudar ficarei mto agradecido.
Answer: Você pode utilizar a função keyup() do jQuery, para realizar uma ação sempre que alguma número for inserido em um input.
Documentação do keyup: https://api.jquery.com/keyup/.

$(".NomeClasseInputs").keyup(function(){
    var soma = 0;
    $(this).each(function() {
        soma += parseFloat($(this).val());
    });
})

O keyup() vai ser executado sempre que houver alguma ação dentro de algum input, e a função de dentro está passando por cada input e realizando a soma dos valores.
Lembrando que para isso funcionar todos os inputs devem possuir a mesma classe. A soma ficará armazenada na variável soma, que você pode inserir em qualquer div com o .html():

$('.idDiv').html(soma);