text:
Q: Encryption Program That Works With NodeJs and mbedtls First, let me start by stating that I am not a cryptographer by any means, and I am not very good at writing c code either, so please excuse me if the answer to this question is obvious or answered. I am developing a messaging program and cannot use TLS on the target platform. As a result, I need to find a way to encrypt each message using a symmetric pre shared key cipher, like AES.
I am seeking a method to encrypt and decrypt data between an mbedtls program (such as aescrypt2) on one end, and a nodejs program on the other. Mbedtls, formerly polarssl, is a library which provides encryption for embedded devices. Included with the source code are some sample programs, like aescrypt2, rsaencrypt, ecdsa and crypt_and_hash.
Aescrypt2 works fine when the resulting encrypted data is also decrypted using aescrypt2, but I cannot seem to get data encrypted with aescrypt to decrypt using nodejs crypto or any other program for that matter, including openssl. For example:
echo 'this is a test message' >test.txt
aescrypt 0 test.txt test.out hex:E76B2413958B00E193
aescrypt 1 test.out test.denc hex:E76B2413958B00E193
cat test.denc
this is a test message

With openssl:
openssl enc -in out.test -out outfile.txt -d -aes256 -k E76B2413958B00E193
bad magic number

Some sample node code that doesn't currently work
    var crypto = require('crypto');
    var AESCrypt = {};

AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
    encryptdata = new Buffer(encryptdata, 'base64').toString('binary');

    var decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv),
        decoded = decipher.update(encryptdata, 'binary', 'utf8');

    decoded += decipher.final('utf8');
    return decoded;
}

AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
    var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv),
         encryptdata = encipher.update(cleardata, 'utf8', 'binary');

    encryptdata += encipher.final('binary');
    encode_encryptdata = new Buffer(encryptdata, 'binary').toString('base64');
    return encode_encryptdata;
}

var cryptkey   = crypto.createHash('sha256').update('Nixnogen').digest(),
    iv         = 'a2xhcgAAAAAAAAAA',
    buf        = "Here is some data for the encrypt", // 32 chars
    enc        = AESCrypt.encrypt(cryptkey, iv, buf);
    var dec        = AESCrypt.decrypt(cryptkey, iv, enc);

console.warn("encrypt length: ", enc.length);
console.warn("encrypt in Base64:", enc);
console.warn("decrypt all: " + dec);

This results in either errors or garbage text every time. I have tried tweaking a variety of things as well.
I've tried this a hundred different ways, including using the -pass pass:password arg to no avail. Using nodejs, I have either gotten bad decrypt errors, or garbled nonsense back upon decryption. I have tried following many tutorials on the net, such as this one, and suggestions from this thread, and everything else I can find. I have read that different encryption programs use different standards, so compatibility across platforms/programs/languages is not always guaranteed, but I imagine somebody has been in this predicement before and knows a solution?
How would I, using nodejs, decrypt data encrypted by aescrypt2 (or a program like it)? I have only been able to make it work using a system exec call and having node execute aescrypt2 to decrypt/encrypt the data, which is not ideal, as it slows things down considerably. I am open to using a different program than aescrypt2. The only requirements are that it must run on Linux, cannot use openssl libs (because they are not supported on the target system), the program should be small and simple, due to space limitations, and foremost, the encryption/decryption needs to be compatible with nodejs. Any help would be much appreciated.

A:
How would I, using nodejs, decrypt data encrypted by aescrypt2 (or a program like it)?

Sorry to say, but there's no better answer than: by doing the exact same thing that aescrypt2 does when decrypting a file. You've linked to the source by yourself, so just perform the same steps in node.js as they do in C in the decrypt branch.
First of all, get familiar with the layout of the file containing the encrypted data:
    /*
     *  The encrypted file must be structured as follows:
     *
     *        00 .. 15              Initialization Vector
     *        16 .. 31              AES Encrypted Block #1
     *           ..
     *      N*16 .. (N+1)*16 - 1    AES Encrypted Block #N
     *  (N+1)*16 .. (N+1)*16 + 32   HMAC-SHA-256(ciphertext)
     */

So you need to extract the IV, the encrypted blocks and the HMAC from the file, not try to decrypt the whole thing as you try with openssl (your openssl example also does not use the right IV but rather tries to derive it from the key provided - read the man page).
Next, get the key right. The actual key used to encrypt/decrypt is not the one provided on the command line, but rather 8192 iterations of hashing the IV with the key passed on the command line, using SHA256.
Finally, they decrypt, using AES-256-ECB (your openssl and node.js examples use CBC!), every 16 bytes and XOR the result with the pervious 16 bytes (the IV is used for the first 16 bytes).
There's maybe more to it, I just listed the most obvious things I saw when reading through the aescrypt2.c code.
So my advise is: try to write the same logic in node.js and try to find node.js crypto calls for the respective mbedtls counterparts.
I'm not a crypto expert, but I bet that the aescrypt implementation has so many steps that feel complicated (like generating the actual key used), because they know how to do crypto and are just doing it the right way.


text:
Q: running a windows form thread while window is closed I have a windows form running a thread which reads a string and showing it in text boxes.
It has start - stop buttons to start showing words in the text boxes within the window Main_Form.
now, i need to create an opening form that handle the start stop. when you press start the same thing should happen, but Main_Form could be closed
you have a button to open the Main_Form and see the text boxes change
it only works when i type:
m_mf = new Main_Form();
m_mf.Show();
m_mf.start();

if i type
m_mf.Visible = false;

or close the Main Form window the program kills itself

A: Have you tried using Hide() rather than visible = false:
m_mf.Hide();

If you use m_mf.Close(); that will completely close the program.
This article might help you a little.

A: Do you mean to run a new form after m_mf is close, in your main function you can modify it as follows:
 Application.Run(new m_mf());
 Application.Run(new Form1());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache performance issue, after "1000 total children" Apache no longer responds to HTTP requests. Not MaxClients issue? Hoping someone can point me in the right direction as I've spent the last week trying to figure out where the "issue" is but haven't been able to, tried posting to the Apache users mailing lists but wanted to bounce it off here as well.
Running Apache 2.2.3 mod_php on CentOS 5.8.
At the same time every day when traffic is heavy we are having an issue where Apache no longer responds to any HTTP requests.
It sounded like a standard MaxClients being reached issue, but that doesn't seem to be the case.
Also, logging into the machine during this time the load average is under 1, and there is still plenty of RAM available.
Reviewing /var/log/httpd/error_log I've noticed the following patterns:
[Mon Apr 30 07:00:34 2012] [info] server seems busy, (you may need to increaseStartServers, or Min/MaxSpareServers), spawning 32 children, there are 0 idle, and 905 total children
[Mon Apr 30 07:00:35 2012] [info] server seems busy, (you may need to increase StartServers, or Min/MaxSpareServers), spawning 32 children, there are 0 idle, and 937 total children
[Mon Apr 30 07:00:36 2012] [info] server seems busy, (you may need to increase StartServers, or Min/MaxSpareServers), spawning 32 children, there are 0 idle, and 969 total children
[Mon Apr 30 07:00:37 2012] [info] server seems busy, (you may need to increase StartServers, or Min/MaxSpareServers), spawning 32 children, there are 35 idle, and 1001 total children

[Mon Apr 30 07:00:42 2012] [debug] mpm_common.c(663): (70007)The timeout specified has expired: connect to listener on [::]:80

[Mon Apr 30 07:00:49 2012] [debug] mpm_common.c(663): (70007)The timeout specified has expired: connect to listener on [::]:80

[Mon Apr 30 07:00:56 2012] [debug] mpm_common.c(663): (70007)The timeout specified has expired: connect to listener on [::]:80

[Mon Apr 30 07:01:03 2012] [debug] mpm_common.c(663): (70007)The timeout specified has expired: connect to listener on [::]:80

A few times a day, right after 1000 total children Apache stops responding and has to be restarted in order to work again.
I've reviewed the error_log from a few weeks back and it's the same pattern, the server hits 1000 total children and then immediately spits out the
[debug] mpm_common.c(663): (70007)The timeout specified has expired: connect to listener on [::]:80 error message and stops responding.
Yet the load on the server is quite low...
Even if I try and request a simple index.html file it times out.
Here is the relevant section from the config:
Timeout 45
KeepAlive On
MaxKeepAliveRequests 10000
KeepAliveTimeout 3

<IfModule prefork.c>
StartServers      80
MinSpareServers   50
MaxSpareServers  120
ServerLimit     3500
MaxClients      3500
MaxRequestsPerChild  2000
</IfModule>

Anyone know why the magic number of children Apache is able to reach is 1000 before it stops processing more requests?
Or how to make sense of the (70007)The timeout specified has expired: connect to listener on [::]:80 message?
What "timeout specified" is it referring to?
I've double check Max Open Files, it previously was at 1024 but now its at 16384, still the same problem.

A: It is a long shot, but I have had problems like this one. I don't remember exactly what error message it was, but the reason for the problem has always been a buggy PHP program which created recursive requests (i.e. the program requests a URL which in turn re-requests the same URL etc). I have seen this for example in connection with ErrorDocument settings, where the document which should have handled the error was buggy or non-existing and which triggered an error.
You can easily verify if this could be the problem in your access.log: You should have plenty of requests from your server's IP address, all in a very short time. This works until you hit the MaxClients setting or until your system runs out of resources. The only fix is to fix the PHP program in question.

A: Timeout 45

I believe it is referring to this timeout. It could be that something is opening the connection, then not doing anything (i.e. the client isn't sending anything after opening the connection or maybe a script of yours isn't closing the connection after writing data to the client) and Apache waits for 45 seconds before giving up. It then closes the connection. You could lower this so Apache times out dud connection attempts quicker but the better solution would be to try and determine why this happens in the first place.
http://httpd.apache.org/docs/2.1/mod/core.html#timeout
Maybe also check out this page for general performance issues?
http://httpd.apache.org/docs/current/misc/perf-tuning.html

A: Check if Apache's KeepAlive is on and what the value of KeepAliveTimeout is. It really should not be more than 3 seconds. It will keep the specific process/thread assigned to the client for that time.
Then grep httpd's conf dir for 1000 to see if that number is set somewhere.
grep -r '1000' /etc/httpd/conf
grep -r '1000' /etc/httpd/conf.d

Aside from that, it could be a case where your php code is (wrongly) keeping each process/thread that's handling it alive indefinitely and you're running out of them.


text:
Q: Bash script runs manually in terminal but is not executed from crontab I have a bash script that I want to be executed every 15 minutes, so I added this line to my crontab:
7,22,37,52 * * * * /path/to/my/script.sh

I've checked the directory path to be correct and the script runs correctly if I just run /path/to/my/script.sh manually from any directory. I have this bang line in my script:
#!/usr/bin/env bash

My script also references other scripts in the same directory as it, and I have run chmod +x on all scripts that are needed. I set the MAILTO to my email address and I was getting some Cron Daemon emails when I changed the line in my crontab to:
7,22,37,52 * * * * sh /path/to/my/script.sh

But I never received emails upon using
 7,22,37,52 * * * * /path/to/my/script.sh

or
7,22,37,52 * * * * bash /path/to/my/script.sh

I made sure cron is running and I've also tried redirecting the output of my script to a log file, which is also only written in when I include the sh. However, if I run sh /path/to/my/script.sh from the home directory, it does not work. The only ways my script actually runs is if (from any directory) I call /path/to/my/script.sh or bash /path/to/my/script.sh. I'm pretty new to writing bash scripts so any help is very welcome.

A: @pvas The cron user environment should be treated with extra special care. The assumption that most users have is that they will have access to paths, directories, permissions etc. This is far from the case. Cron runs in a minimal environment and you must set up EVERYTHING - Paths, Permissions and the location where the scripts are running from.
1) I set up the environment myself.
2) I use fully expanded paths in my crontabs.
3) I make sure any directories that need to be read have read permissions.
4) I make sure that my password does not expire because that will block cron when it does.
5) Make sure underlying scripts are explicitly invoked (by Perl, Bash, Python whatever).
6) Pipe the command on the cron line to a LOG file (even better a log file with a TIMESTAMP).
Fix these things and then try again. Cron is particular, you need to set up everything.
For example:
#SETUP ENVIRONMENT
SHELL=/bin/bash
source /home/userfoo/.bash_profile

#RUN THE SCRIPT everyday at 11:50pm (23:50)
50   23  *    *   *  userfoo /home/userfoo/script.sh >> LOGFILE.txt

<<

A: Crontab entries should have the following format
m h  dom mon dow   command

which confirms that your entry below
7,22,37,52 * * * * /path/to/my/script.sh

is correct. Having said that, you must close the crontab editor(:wq) for the changes to come to effect.
It is suggested you go through [ this ] cross site post which portrays the possible issues with cron jobs.

More about hashbang [ here ].


text:
Q: Save plots generated within a loop in R I am looking for a way to save ggplots and flextables to the workspace and later combine these objects that were generated within a loop.
Here is a simple example:
for (i in 1:3) {x<-rnorm(20, 5, 5-i); hist(x)}

In this example, x is overwritten every time and a new histogram is generated. I would want to store each histogram that is generated within the loop in the current workspace and later combine those histograms in one plot (without having to actually save each one of them). How can I go about that best?
Thanks a lot in advance!

A: We could set the par and get the plots into a single page
par(mfrow = c(3, 1))
for (i in 1:3) {
    x<-rnorm(20, 5, 5-i)
     hist(x)
  }

If we want to store the plots and print, then create a NULL list to store the objects, and then do the plotting later
p1 <- vector('list', 3)
for(i in seq_along(p1)) {
    x<- rnorm(20, 5, 5-i)
    p1[[i]] <- hist(x)
}
par(mfrow = c(3, 1))
for(p in p1) plot(p)


text:
Q: Access is multiplying my query count by 38.... why? My data looks like

ID   -  InputID

*

*1   -    data1

*2    -   data2

*3   -    data2

*4   -    data2

*5   -    data6

If I run a query that produces the count of each data input:
SELECT First(InventoryData2.InputID) AS FirstOfInputID, Count(InventoryData2.InputID) AS InputItemCount FROM InventoryInputT, InventoryData2 GROUP BY InventoryData2.InputID HAVING (((Count(InventoryData2.InputID))>=1));

Which, based on the data, SHOULD provide something along the lines of

data1: 1

data2: 3

data3: 1

HOWEVER, access shows my count totals as:

data1: = 38

data2: = 114

data3 = 38

ANY IDEA WHY?

A: Because the query is producing a Cartesian product. That is, each and every row from InventoryInputT is being matched to each and every row in InventoryData2, a cross product, because the query specifies a join operation with no condition to limit which rows are to be matched with each other.
The GROUP BY operation is collapsing the rows. Remove the GROUP BY clause and all of the aggregate functions, return just the detail rows, and you will see what's happening.


text:
Q: Python - Work with everything in the list one by one I have a list my_list = []
In this list are some int's so my_list = [1,2,3,4]
Now I want to work with every number one by one, without knowing there are only 4 int's. There could be 1000 things in the list. I thought about sth like:
i = len(self.my_list)
while i > 0:

    print(my_list[i])

    i -=1

but I got this error: IndexError: list index out of range

A: What you could do is iterate over each item in the list:
for i in my_list:
   print(i,i**2)

A: I usually using this method:
my_list = [1,2,3,4]
i=0
while(i < len(my_list)):
    print(my_list[i])
    i+=1

with while you have control of index.


text:
Q: Custom control of multiple seek bars I have 5 seek bars in an Activity that are working perfectly. Their min/max are each set from 0 to 100. I need to make sure that at least one of the seek bars is always at its max level- 100. For example if sb1=sb2=sb3=sb4=50 and sb5=100 then sb5 is unable to move but sb1-4 remain moveable. If sb2 is moved to 100 then all sb's are enabled. How do I edit my CASE statements below or is there a better way to achieve this?
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
{

    switch (arg0.getId())
    {
    case R.id.sb1:
        tv1.setText(arg1);
        break;
    case R.id.sb2:
        tv2.setText(arg1);
        break;
    case R.id.sb3:
        tv3.setText(arg1);
        break;
    case R.id.sb4:
        tv3.setText(arg1);
        break;
    case R.id.sb5:
        tv3.setText(arg1);
        break;
    }
}

@Override
public void onStartTrackingTouch(SeekBar arg0)
{
    // TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar arg0)
{
    // TODO Auto-generated method stub

}```


text:
Q: Unexpected visual element in a simple Tab layout The screen shot below is of a simplified version of the application from the Tab Layout tutorial. You can see a black horizontal line below the tabs. Why is it there and how can I remove it?

A: Try removing the android:padding attribute from the FrameLayout. If you want padding around everything but the top then you'll have to use the padding/Left/Right/Bottom attributes.

A: I think that line results from how the tabs are implemented.  If you look at one of my questions about a strange black line I found that it was an artifact of the ActivityGroup that I was using.  This is the same widget that tabs use.


text:
Q: Logout PHP sessions - update only last record I'm doing a new program about attendence with PHP and JS. I create a Login by username/pw. I'm working with sessions.
I want put logout and do it hours worked (I know do difference between hours, using datediff.
But when I update time logout, It does update to ALL results but I want update only last record this person.. and not all results this person (session).
$sql = "UPDATE `login` SET `datelogout` = NOW() WHERE `uid` = '$session_id' ";

I just wanna update record logout by day and by session login this day!
Thanks!

A: Try something like this.
UPDATE  login SET datelogout=NOW() where uid ='$sessionid' orderby Sno DESC
LIMIT 1


text:
Q: Windows Equivalent to "chmod -R a-w" What is the Windows equivalent to "chmod -R a-w" to recursively remove write permissions of a directory?  The tricky part is to leave the rest of the permissions the same (e.g. if subfolderA is only readable by groupA, do NOT open the folder permissions to Everyone).

A: I would say there is no "equivalent" way as the design of access control on Windows is quite different from that on Linux.
Anyway, you may achieve something similar with the icacls command, PowerShell script, VBScript, etc.
For each file there can be grant rules and deny rules attached to users or groups. And deny rules overrides grant rules. So you may have different ways depending on existing ACL configurations on the files. E.g.:

*

*Users inherit both read and write permission: add a rule to deny write

*Users inherit read permission and a rule that allow write is already exist on the file: just remove the allow write rule

Here is an example for case 1 to add a rule that deny a bunch of write permissions using icacls:
icacls C:\myFolder /deny UserOrGroup:(WD,AD,WDAC,WO,WEA,WA,DE,DC) /T

To add the rules for multiple users/groups, you will need to wrap it with a loop in batch script.
Since you have tagged powershell in you question, a PowerShell script similar to the above icacls example is:
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("UserOrGroup", "DeleteSubdirectoriesAndFiles, Write, Delete, ChangePermissions, TakeOwnership", "Deny")

Get-ChildItem 'C:\myFolder' -Recurse | ForEach-Object {
    $acl = Get-Acl $_.FullName
    $acl.AddAccessRule($rule)
    Set-Acl $_.FullName $acl
}

PowerShell is more complicated but provides more flexibility. E.g. you can get user/group from existing rules on the file/folder and add the deny rule dynamically.
Note: You can probably find even more relevant question and examples in serverfalult, superuser or stackoverflow with keywords like "windows chmod", "powershell acl", "icacls", etc.


text:
Q: docker build question no permission to read from I'm trying to build a docker image
I get this error
sudo docker build . -t django-demo
error checking context: 'no permission to read from '/home/benny/.ICEauthority''

any ideas why this is happening?
--------------------------
ubuntu 18.04
Docker version 18.09.9

A: Generally to solve this kind of problem you should add a .dockerignore file in which you list all the files you don't want to be sent to the build's context (ie. the files that docker don't need to build your image).
In your case simply creating a .dockerignore with the following content should solve the issue :
.ICEauthority

Note that specifically in your case though, you should not run your docker build command directly from your home directory, because all the content of your home is being sent to the build's context (which is heavy, might make you run out of disk space or generate permission issues).

A: Create a new directory, place your Dockerfile in this new directory and then run your sudo docker build . -t django-demo command from that directory. This should solve your problem. Found related problems and solution in this external thread.


text:
Q: Row counts across aggregated tables I have multiple tables in a postgres database that hold perfectly unique information.  The information, when properly joined together in a query, will produce all every possible combination that I'm looking.  The information I'm looking for are complete SKUs.
To generate a complete SKUs, this query produces the desired results:
Functional Query
SELECT
    materials.code,
    "part_base_parts".code as part_base_parts_id,
    shanks.code AS shank_id,
    measurements.description
FROM
    "part_base_parts"
LEFT JOIN "part_types" ON "part_base_parts"."part_type_id" = "part_types"."id"
RIGHT JOIN "parts_to_shanks" ON "part_base_parts"."id" = "parts_to_shanks"."part_base_part_id"
RIGHT JOIN "parts_to_measurements" ON "part_base_parts"."id" = "parts_to_measurements"."part_base_part_id"
RIGHT JOIN "parts_to_materials" ON "part_base_parts"."id" = "parts_to_materials"."part_base_part_id"
JOIN materials ON "parts_to_materials"."material_id" = materials."id"
JOIN shanks ON "parts_to_shanks"."shank_id" = shanks."id"
JOIN measurements ON "parts_to_measurements"."measurement_id" = measurements."id"
ORDER BY
    part_base_parts_id ASC,
    materials.code ASC,
    shank_id ASC,
    measurements.description ASC

Given this query, I produce 32,640 records (without indexing applied) with a query time of .82 seconds.  Something like this...
Given Output
code    part_base_parts_id  shank_id    description
AA      5105                A           03.0
.
. 32,638 rows in here.
.
ST      6939                D           9/16

This is only getting me half way there, though.  I need to take the results back from the query and produce the total number of counts from each column.  So the result that I need to have would be:
Desired Results
code: AA - ###0
      ...
      ST - ###0
part_base_parts_id: 5105 - ###0
                    ...
                    6939 - ###0
shank_id: A - ###0
          ...
          D - ###0
description: 03.0 - ###0
             ...
             9/16 - ###0

Is there a way to produce the "desired results" from Postgres?

A: If you want them in rows then sure.
WITH cte AS(
    SELECT
        materials.code,
        "part_base_parts".code as part_base_parts_id,
        shanks.code AS shank_id,
        measurements.description
    FROM
        "part_base_parts"
    LEFT JOIN "part_types" ON "part_base_parts"."part_type_id" = "part_types"."id"
    RIGHT JOIN "parts_to_shanks" ON "part_base_parts"."id" = "parts_to_shanks"."part_base_part_id"
    RIGHT JOIN "parts_to_measurements" ON "part_base_parts"."id" = "parts_to_measurements"."part_base_part_id"
    RIGHT JOIN "parts_to_materials" ON "part_base_parts"."id" = "parts_to_materials"."part_base_part_id"
    JOIN materials ON "parts_to_materials"."material_id" = materials."id"
    JOIN shanks ON "parts_to_shanks"."shank_id" = shanks."id"
    JOIN measurements ON "parts_to_measurements"."measurement_id" = measurements."id"
    ORDER BY
        part_base_parts_id ASC,
        materials.code ASC,
        shank_id ASC,
        measurements.description ASC
)
SELECT key, value, count(*)
FROM(
  SELECT 'code' AS key, code AS value
  FROM cte
  UNION ALL
  SELECT 'part_base_parts_id', code
  FROM cte
  UNION ALL
  SELECT 'shank_id', shank_id
  FROM cte
  UNION ALL
  SELECT 'description',  description
  FROM cte
) AS q
GROUP BY key, value
ORDER BY key, value


text:
Q: Web Audio API - Can't get simple audio to play I'm trying to learn the Web Audio API from the MDN tutorial but even the most basic example — no modular synthesis, just playing a simple mp3 file — doesn't seem to work on my end.
I can see the dataset value being switched in the console, the play/pause on the controls change state, and in Firefox and Safari (but not in Chrome) the track locator even advances and the "playing" icon displayed on the browser tab.
(I've added the controls attribute to the audio tag just to have a progress indicator visible).
I can also download the file from the DOM controls and play it using the OS, and I've tried it with three different MP3 files. The computer's speakers are obviously working.
BTW, creating audio with oscillators and the AudioContext object works fine.
I'm out of ideas.
HTML
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <audio controls src="song.mp3"></audio>
    <button data-playing="false" role="switch" aria-checked="false">
        Play/Pause
    </button>

JS
'use-strict'

const aCtx = new AudioContext();
const el = document.querySelector('audio');
const track = aCtx.createMediaElementSource(el);
const button = document.querySelector('button');

button.addEventListener('click', function() {
    console.log(this);

    if (aCtx.state === 'suspended') {
        aCtx.resume();
    }

    if (this.dataset.playing === 'false') {
        el.play();
        this.dataset.playing = 'true';
    } else {
        el.pause();
        this.dataset.playing = 'false';
    }
}, false);


text:
Q: How to setup the 3dots menu inside Image.network in flutter I'm looking an example to implement the 3 dots menu inside a picture on my feed of my app... any ideas?
Example

A: The example in the question is not to use an icon in the photo. Like this:
       Column(
                children: [
                  Row(children: [...,Icon()],),
                  Image.network(),
                ],
              )

But if you want to use icon in the photo, you can use Stack. Like this:
Container(
          height: 250,
          width: 250,
          child: Stack(
            children: [
              Container(
                child: Image.network(
                  "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg",
                  fit: BoxFit.cover,
                ),
                width: MediaQuery.of(context).size.width,
              ),
              Container(
                alignment: Alignment.topRight,
                child: Icon(
                  Icons.more_horiz,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        )


text:
Q: What do su - usrnm get? I will running some closed source programs in the current logging Konsole window by su - usrnm command, I know that'll share the desktop screen with the programs running under usrnm, not safe enough, and what other information will share to usrnm? like clipboard, etc...

A: If your distribution arranges for X11 GUI access across su - <username> (i.e. you can successfully start new GUI programs as the su'd user), then the program has full access to your session on the X11 display server. That means:

*

*it can capture your keystrokes and mouse movements, even outside the program's visible windows if it wants to (it can open an invisible borderless full-screen window that passes all key/mouse events through to windows under it, and then snoop everything)

*it has access to the GUI session's clipboard

*if a program uses X11 properties to e.g. detect and communicate with other instances of itself, the closed source program can see and participate in that communication

Anything else depends on what X11 protocol extensions you're using, what desktop environment you're using, and other details.
If the closed-source program does not need a GUI, you can revoke its X11 access pretty easily, by doing these things after su'ing but before starting the closed-source program:
$ unset DISPLAY
$ unset XAUTHORITY
$ rm ~usrnm/.Xauthority

What remains is just a terminal session, similar to what you'd get by doing a
ssh -x -a usrnm@localhost


text:
Q: Talend - Check columns lenght before inserting into mysql database I'm trying to use Talend Open Studio for Data Integration for a BI school project. I have a txt file with some data like this :
NoClient;Name;Region;State;City;Postcode
24;Edna Thomas;West;California;Laguna Niguel;92677

I used jobs to transform data and insert it into tables. It works nicely.
Now, I'd like to handle SQL errors. For example, if the column length specified in the DB is 10 and if the job tries to insert a 11 length data in that column, I will get an SQL error.
How can I achieve it ? Is there a specific feature in tMysqlOutput or should I simply use triggers like this to check data before inserting :
CREATE TRIGGER my_trigger
BEFORE INSERT
ON my_table
  FOR EACH ROW BEGIN

    IF (SELECT LENGTH(NEW.Noclient)>255) THEN
    // instructions
END IF

Hope it's clear enough ! Thanks in advance, sorry for bad english :-)

A: Maybe you can do a check in each variable in a tmap.
Like for example :
StringHandling.LEN(var) <= 10 ? var : StringHandling.LEFT(var,10)

And you adapt in function of the size of your field.

A: There's a component for this: tSchemaComplianceCheck
A nice example can be found at:
http://dwetl.com/2015/03/30/data-validation-using-tschemacompliancecheck/


text:
Q: How to build a './configure && make && make install' software against a custom library which I also build? I am building tmux-2.0 from sources on a pretty regular Linux host. First attempt failed as it turned out that the version of libevent installed is older than required, so I proceeded to download and build libevent-2.0.22 from sources (current at the time of writing) first.
Building of libevent succeeded flawlessly, and I thought I could then retry building tmux with the following:
PKG_CONFIG_PATH=$PATH_TO_MY_BUILT_LIBEVENT/lib/pkgconfig ./configure ...

The above invocation succeeded, so did subsequent make and make install.
Running my newly build tmux, however, aborts with a missing shared object, not surprisingly libevent-2.0.so.5:
tmux: error while loading shared libraries: libevent-2.0.so.5: cannot open shared object file: No such file or directory

I thought building against a custom library implies it will also be used at runtime? ldd on my tmux gives me:
linux-vdso.so.1 =>  (0x00007fff8f5ff000)
libutil.so.1 => /lib64/libutil.so.1 (0x0000003cf8800000)
libncurses.so.5 => /lib64/libncurses.so.5 (0x0000003cf7e00000)
libevent-2.0.so.5 => not found
librt.so.1 => /lib64/librt.so.1 (0x0000003ce8600000)
libresolv.so.2 => /lib64/libresolv.so.2 (0x0000003cea200000)
libc.so.6 => /lib64/libc.so.6 (0x0000003ce7600000)
libtinfo.so.5 => /lib64/libtinfo.so.5 (0x0000003cf7200000)
libdl.so.2 => /lib64/libdl.so.2 (0x0000003ce7e00000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x0000003ce8200000)
/lib64/ld-linux-x86-64.so.2 (0x0000003ce7200000)

So, libevent-2.0.so.5 is not found.
Do I need to resort to setting, I don't know, LIBS, LDFLAGS or some other variables or switches to configure script above, so that, I don't know, the paths to my newly built libevent are embedded in tmux binary, courtesy of ld?
I do not have root access - university Linux workstation - and frankly I don't need one, I think. I also do not want to muck about with LD_LIBRARY_PATH or the like. Suffice to say, doing LD_LIBRARY_PATH=$PATH_TO_MY_LIBEVENT/lib tmux works fine. But I want it to work "by default", locating and using my libevent.
I guess the solution would apply to pretty much any software using the "GNU build system". What's the right thing to do here?

A: You built against a library, but the system doesn't know where the library is. Since you don't want to install the library, but rather leave it in the place where you built it, you could solve it with -rpath= option of the linker — it embeds a search path for libraries into the executable file.
Just rebuild your application with it being added to your LDFLAGS, like LDFLAGS="-rpath=/home/mypath/to/libevent" (but note, it is a linker option, and it is possible that in the makefile as a linker used the gcc itself — gcc does not know the option, then you need to write it likeLDFLAGS="-Wl,-rpath=/home/mypath/to/libevent" to force gcc to pass the option down to the actual linker)
By the way, actually you can change rpath even without recompiling the application — there's a tool patchelf for that job.


text:
Q: Date Field Mixed (Date and Text) Formatting I've had a look around and can't find an actual answer to this.
I have a .csv to download every day. In it includes a text field 7+2 digits long. The 7 digits are in format CYYMMDD and the 2 digits are blank spaces.
This would be today's date: "1190729  " (without the quotes)
I've tried about 20 ways to convert this to a regular date, but I can't get every record to update properly
So far

*

*The QueryTable uses type 2 (Text)

*I =TRIM the text, place it back in the same location

*I change the text into a recognisable date

*"Paste as Text"

*Then I get the same thing every time. Any date where the DAY is 13 or more, is a text field. 12 and under is a date field

*The best way to fix it is to F2 but this is meant to be a totally automated report
I have tried changing dd/mm/yyyy to every other version I can think of (as for my excel m/d/yyyy is the default)
I've also tried moving .Value = .Value to the bottom, putting it in twice etc. but to no avail

Private Sub CopyDateTime(ByVal lastRowBeforeImport As Long)

Dim ws As Worksheet, ws2 As Worksheet
Dim tempsheet As String
Dim lastRowAfterImport, lastRowTemp
Set ws = Worksheets("Report")

'Bottom populated cell of Column "B"
lastRowAfterImport = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row

    tempsheet = "temp"

Worksheets.Add
ActiveSheet.Name = tempsheet

Set ws2 = Worksheets("temp")
    With ws.Range(ws.Cells(lastRowBeforeImport, 5), ws.Cells(lastRowAfterImport, 6))
        'Copy new date and time to tempsheet'
        .Copy Destination:=ws2.Range("A1")
    End With

lastRowTemp = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row

    With ws2.Range(Cells(1, 3), Cells(lastRowTemp, 3))
        .FormulaR1C1 = "=TRIM(RC[-2])"
        .Value = .Value
        .Copy Destination:=ws2.Range("A1")
        .Delete
    End With

    With ws2.Range(Cells(1, 3), Cells(lastRowTemp, 3))
        .FormulaR1C1 = "=RIGHT(RC[-2],2)&""/""&MID(RC[-2],4,2)&""/20""&MID(RC[-2],2,2)"
        .Value = .Value
        .NumberFormat = "dd/mm/yyyy"
    End With

    With ws2.Cells(1, 4)
        .FormulaR1C1 = "=MID(TEXT(RC[-2],""000000""),3,2)&"":""&LEFT(TEXT(RC[-2],""000000""),2)&"":""&RIGHT(RC[-2],2)"
    End With

    'Delete tempsheet'
        Application.DisplayAlerts = False
    'Worksheets(tempsheet).Delete
        Application.DisplayAlerts = True
End Sub

A: If you have "1190729  " in A2 then the formula
=DATE(2000+(MID(A2,2,2)),(MID(A2,4,2)),(RIGHT(TRIM(A2),2)))

will produce the date 29th July 2019 in your current date format

A: From MSDN:

Date variables are stored as IEEE 64-bit (8-byte) floating-point
  numbers that represent dates ranging from 1 January 100, to 31
  December 9999, and times from 0:00:00 to 23:59:59.

Your VBA function may parse well string formats from CSV, but you are creating a string value which is not a proper Excel data type for dates.
Use =DATEVALUE function to convert the string representation of the DATE (ex. 29/7/2019) to the actual Excel date.
For example in your case: cell.Value = DATEVALUE(TRIM(RC[-2]))
Once in the proper data type, you can change the date format using the NumberFormat property.
More about DATEVALUE from MSDN.


text:
Q: Possible to return Json data from C# class library I am creating a report which requires returning Lists, and Json data to a web page. I'm working with a multi-tiered application. The web project is created using MVC but the heavy lifting is done in class libraries in separate projects.
I am returning a report object to my controller from a class library but I wanted to know is it possible to return a mix of Lists and Json in the model? Ideally I would like the report model to be similar to the following:
public class Report
{
    public List<TopSellers> TopSellers { get; set; }
    public List<MonthlySales> MonthlySales { get; set; }
    public Json ShopSales { get; set; }

}

This way, the list stuff can be rendered as normal, but the jQuery could grab the Json being return to render the graphs I'm using.
Is this possible?
I have tried to declare it similar to this however the only option I get is 'JsonReaderWriterFactory'.
My exposure of Json up until now has been null so if someone could help me out, or point me in the right direction I'd be very grateful!
Thanks.

A: You could use the JSON.net library to serialize your object to a json string and set it to your ShopSales property.
http://json.codeplex.com/
report.OriginalList = objectToSerialize;

var jsonStr = JsonConvert.Serialize(objectToSerialize);
report.ShopSales = jsonStr;

return report;

On the client you can use the ShopSales property with jQuery.

A: The only approach I see here (and which I have also adopted once) is to create an HTTP Handler in your class library which intercepts certain requests and directly writes JSON onto the response (JSON.net is worth taking a look at).
Instead of the HTTP Handler you could also take a look on whether you could directly leverage the build-in ASP.net routing mechanism.
Your class library has then to be added as reference to a front-end project (i.e. ASP.net MVC / WebForms) obviously and the handler has to be registered there.


text:
Q: How to benchmark internet connection speed, but not just top download speed of one big file? I'm not sure if there's a term for what I'm looking for, but I'm not talking about just connectivity or just testing speed here.
When I was on cable, webpages virtually always loaded very quickly.  A few months back we switched to Verizon Fios and at first it was great.  Now we still have much faster upload and download speeds than we did with cable, however I often wait several seconds for a webpage to simply load.  Between having webpages load immediately and being able to download big files quicker I would generally choose to have snappier load times because I spend a lot more time loading pages then I do downloading big files.
After complaining, Verizon came out and did something that helped (they said it had something to do with two boxes being too close to each other and they moved them further apart).  However, the load speed of the average page is definitely still not what I expect it to be.  I don't know how to show them that there is a problem though.  If I go to do a speed test it's going to look fine.  Are there any other utilities I can use to benchmark other aspects of connection speed besides just the top download speed of a single big file?
EDIT:  Thought I should point out that just a few days ago I was trying to access a computer in my house using remote desktop from another computer in the same house.  The connection kept pausing momentarily... it never totally disconnected but for connecting to another computer just one room over it definitely should have been a much better connection.  So I was inclined to think the issue had something to do with the router that Verizon provided us.  However, they sent me a new one and it didn't fix the issue so I don't know.
EDIT2: I might not have made the problem sound as bad as it really is.  In addition to pages often taking longer than I feel they should take to load, they often just don't load until I close the tab and try again in a new one.


text:
Q: I want to write a text file into s3 bucket using java through putobjectrequest I want to create/write a text file into s3 bucket using java.i'm using file output stream writer to write a content.

A: Take a look at the Amazon S3 client putObject() function that includes an InputStream:
public PutObjectResult putObject(String bucketName,
                                 String key,
                                 InputStream input,
                                 ObjectMetadata metadata)
                          throws SdkClientException,
                                 AmazonServiceException


text:
Q: Java Regular Expression I have a below peace of code :
     Pattern p = Pattern.compile("^\\d|^\\W|^\\s");
     Matcher m = p.matcher("stack overflow");

Can somebody explain the above regex pattern ? What it does ?
I have to make it not allow spaces in between with the existing functionality .e.g. it should not allow "stack overflow " since it contains spaces .
EDIT
Below  pattern I tried is working fine for me . Thanks all for your suggestion:
[a-zA-Z0-9_$#]

A: Your regular expression matches either a single digit, OR any single char that is NOT a word OR any single char that is a white space char.
Any of those three alternatives must start at the beginning of the subject because you have ^ in each alternation.
Based on your description, i think you want an expression like this:
^[\w#$]+$

Which will match anything containing one or more word characters [A-Za-z0-9_], hash #, and dollar $. Word characters do not include spaces, so this should work.
I've added anchors ^ and $ which ensure that it only matches the whole string (is this what you want?) If you just want it to match at the beginning as in your example, then remove the $.
Note that as in your example, you will need to escape the \ in your java code like this:
Pattern p = Pattern.compile("^[\\w#$]+$");

A: To add to other answers: I think you are looking for a pattern like "^\\S*$", which means: match any number of non-space characters (\\S*) from beginning (^) to the end ($).


text:
Q: How can I make IntelliSense only open up when I tell it to instead of when I type? The fact that it opens every time I type just rubs me the wrong time. Most of the time I know what I want to type in and sometimes I'm making dumb mistakes because of IntelliSense opening up at the wrong time, ex. when I try to reference variable called 'dummy' that I just created like a line ago, but VisualStudio in its infinite wisdom tries to offer that I for sure meant constant, class or a namespace called DUMMY that is declared somewhere else in the code or even in third-party library.
I'd rather have "Intelli" Sense open up only when I explicitly tell it to, like with a keyboard shortcut.


text:
Q: Capture specific rows of a ListObject to an array I need help trying to figure out something I haven't done before in Excel VBA.  I'm trying to assign specific (consecutive) rows of a listobject to an array.  Is this possible?
Previously I was using code to copy over the entire table into the array, which worked, but it would capture unused blank rows I didn't want included.  I was able to get some FUNCTIONS up and running which capture the first and low filled row numbers of the listobject for reference, but I cannot figure out how to assign ONLY this range of rows from the listobject into the array
This, for instance, works to assign only the 1st row:
varESInvoiceBreakdown = PrimeLO.ListRows(1).Range.Value
However, this doesn't work to capture the first two rows.  I get an error
varESInvoiceBreakdown = PrimeLO.ListRows("1:2").Range.Value
Even though it indicates in a segment of this article that you can reference multiple rows in this manner
https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables
I was hoping to reference the two integer variables I have setup for the row selection.
Sincerely,
Kris

A: You can't index into the ListRows collection like that. Use DataBodyRange.Rows.
varESInvoiceBreakdown = PrimeLO.DataBodyRange.Rows("1:2").Value

With variables:
Dim startRow as Long
Dim endRow as Long

startRow = 1
endRow = 2

varESInvoiceBreakdown = PrimeLO.DataBodyRange.Rows(startRow & ":" & endRow).Value


text:
Q: Faenza / Ubuntu Mono power icon problems Im having problems applying a new icon theme in ubuntu 11.10 specifically with the power icon. Ive installed faenza succesfully, and the gnome tweak tool to change the icons, but the power icon doesnt seem to be updating:

No matter what i change the icon theme to now, i cant seem to get the power icon to return to the default one, let alone the faenza one. Any suggestions where im going wrong?

A: I had this problem too.  I prefer the Faenza-Dark variant but has a rubbish battery icon like in your screenshot.  If you used the ppa to install the icons then you should have a Faenza-Ambiance/Radiance theme to choose which fixes it, but as I prefer the -Dark variant I had to make a custom version.  What I did was copied Faenza-Dark to another folder like Faenza-Custom sudo cp -r /usr/share/icons/Faenza-Dark /usr/share/icons/Faenza-Custom
Then edit  it.  sudo nano /usr/share/icons/Faenza-Custom/index.theme delete everything in it and paste in this
[Icon Theme]
Name=Faenza-Custom
Inherits=Faenza
Comment=Icon theme project with tilish style, by Tiheum

Directories=status/22,stock/22

[status/22]
Size=22
Context=Status
Type=Fixed

[stock/22]
Size=22
Context=stock
Type=Fixed

then use gnome-tweak-tool to choose the Faenza-Custom theme and it will have the fixed battery icon

A: I had this problem too using Radiance theme, but I fixed it replazing the folder icons from /usr/share/Faenza-Radiance/status/22 with /usr/share/icons/ubuntu-mono-light/status/22


text:
Q: How to open set this to any object in jquery? If I have a function like this
function foo(a) {
    $(this).html(a);
}

var r = $("#hello");

and I can't change the function foo, what can I do to call foo using r, such that inside foo, this will refer to the object selected by r?
I tried this
r.each(function(i, x) {
    foo(1);
});

but it did not work. The this referred to the window object.

A: That's because when you call a function by itself, this will be set to the global object (or undefined) unless the function scope was previously bound.
To use the function the way you wanted, write it like this:
r.each(foo);

That will pass the function directly and ensure this is set to the same value as it would be if the body of foo was inside of your anonymous function.
If you want to pass additional parameters to foo which are not passed by each, you will have to call it using call or apply:
r.each(function() {
  foo.call(this, 1);
});


text:
Q: Is this function Lipschitz continuous? Let  $\mu \in \mathbb R^d$ be given. Is the function $f:\mathbb R^d \to \mathbb R^d$ defined as $f(x) := \exp(-\|x- \mu\|) (\mu - x)$  Lipschitz continuous?
More specifically, for any $x, y \in \mathbb R^d$,
is there a $D\in \mathbb R$ such that
$$
| \exp(-\|x- \mu\|) (\mu - x) - \exp(-\|y- \mu\|) (\mu - y)] |
\leq D\|x-y\|?
$$
$\| \|$ is the Euclidean norm.
Thanks!

A: Since this looks like a homework, I will just outline the proof.

*

*First note that this is the same as proving $$f(x)=e^{-\|x\|}x, x\in \mathbb{R}^n$$ is Lipschitz.

*Each component $f_i$ of $f$ is a $C^1$ function on $\mathbb{R}^n$ with partial derivative given by
$$\frac{\partial f_i}{\partial x_i}=\left\{\begin{array}{ll}e^{-\|x\|}\left(1-\frac{x_i^2}{\|x\|}\right) & \mbox{ if }x\neq 0\\1&\mbox{ if }x= 0\end{array}\right.$$
and for $j\neq i$, $$\frac{\partial f_i}{\partial x_j}=\left\{\begin{array}{ll}-e^{-\|x\|}\frac{x_ix_j}{\|x\|} & \mbox{ if }x\neq 0\\0&\mbox{ if }x= 0\end{array}\right.$$

*Note that all partial derivatives of $f_i$ are also bounded on $\mathbb{R}^n$.

*Now you can apply mean value theorem for functions from $\mathbb{R}^n$ to $\mathbb{R}^n$ to prove that $f$ is Lipschitz.

A: Here is a long-winded answer. I didn't even think to check differentiability of
$e^{-\|x\|}x_1$ at $x=0$ (because $x \mapsto e^{-\|x\|}$ is not differentiable at $x=0$). See @TCL's answer for a much more succinct approach.
First prove that $\phi_1(x) = e^{-\|x\|}x_1$ is locally Lipschitz continuous. Let $K$ be a convex, compact set, then the scalar function $t \mapsto e^{-t}$ has a bounded derivative on $K$. Let the bound be $L_K$, hence $\|e^{-\|x\|} - e^{-\|y\|}\| \le L_K \left| \|x\|-\|y\| \right| \le L_K \|x-y\|$ for $x,y \in K$. The function $x \mapsto x_1$ is also Lipschitz continuous with rank $1$. Hence we have $|\phi_1(x) -\phi_1(y) | \le |e^{-\|x\|}x_1 - e^{-\|x\|}y_1 + e^{-\|x\|}y_1 -e^{-\|y\|}y_1 | \le |x_1-y_1| + L_K|y_1| \|x-y\|$ Since $K$ is bounded, we see that $\phi_1$ is Lipschitz on any convex, compact set.
Note that $\phi_1$ is clearly smooth except for possibly $x=0$.
Now we will show that $\phi_1$ is globally Lipschitz continuous. Choose $x,y$ and let $\eta(t) = \phi_1(x+t(y-x))$. Since the set $\{x+t(y-x)\}_{t \in [0,1]}$ is convex and compact, $\eta$ is Lipschitz, hence absolutely continuous. It follows that $\eta$ is differentiable a.e. and $\eta(1)-\eta(0) = \int_0^1 \eta'(t) dt$. In particular, if $|\eta'(t)| \le B$ a.e., then $|\eta(1)-\eta(0)| \le B$. We see that if $x \neq 0$, then $\eta'(t) = \frac{\partial \phi_1(x+t(y-x))}{\partial x} (y-x)$.
A quick calculation shows that $\frac{\partial \phi_1(x)}{\partial x} = e^{-\|x\|} e_1^T -x_1 e^{-\|x\|} \frac{x^T}{\|x\|}$, which gives $\| \frac{\partial \phi_1(x)}{\partial x} \| \le 1+ |x_1|e^{-\|x\|} \le 1+ e^{-1}$. It follows that $|\eta'(t)| \le (1+e^{-1}) \|x - y \|$ a.e., and so
$|\eta(1)-\eta(0)| = |\phi_1(x)-\phi_1(y)| \le (1+e^{-1}) \|x - y \|$. Since $x,y$ were arbitrary, we see that $\phi_1$ is globally Lipschitz continuous, with rank $\le 1+e^{-1}$.
Exactly the same analysis applies to $\phi_k$ defined by $\phi_k(x) = e^{-\|x\|}x_k$. It follows that the function $\phi(x) = e^{-\|x\|}x$ is globally Lipschitz continuous.
Since $f(x) = \sum_k \phi(\mu_k-x)$, it follows that $f$ is globally Lipschitz continuous.
Note that in the proof above, the function is proved to be locally Lipschitz continuous in order to show that the restriction is absolutely continuous. This allows us to focus on the derivative of the restriction instead, which we show is bounded, hence the function is globally Lipschitz continuous.


text:
Q: Combining the data of randomly selected participants with dplyr I have the following data frame 'df'.
Each participant (here 10 participants) saw several stimuli (here 100), and made
a judgment about it (here a random number). For each stimuli, I know the true
answer (here a random number; a different number for each stimuli but always
the same answer for all participanst)
participant <- rep(1:10, each=100)
stimuli <- rep(1:100, 10)
judgment <- rnorm(1000)
df1 <- data.frame(participant, stimuli, judgment)
df2 <- data.frame(stimuli=1:100, criterion=rnorm(100))
df <- merge(df1, df2, by='stimuli') %>% arrange(participant, stimuli)

Here is what I am trying to do:
1) Taking n randomly selected participants (here n is between 1 and 10).
2) Computing the mean of their judgments per stimuli
3) Computing the correlation between this mean and the true answer
I want to perform step 1-3 for all n (that is, I want to take 1 randomly selected participants and perform steps 1-3, then I want to take 2 randomly selected participants and perform steps 1-3 ... 10 randomly selected participants and perform steps 1-3.
The results should be a data frame with 10 rows and 2 variables: N and the correlation. I want to work only with dplyr.
My solution is based on lapply. Here it is:
participants_id = unique (df$participant)

MyFun = function(Data) {

HelpFun = function(x, Data) {
# x is the index for the number of participants.
# It Will be used in the lapply call bellow
participants_x = sample(participants_id, x)
filter(Data, participant %in% participants_x) %>%
  group_by(stimuli) %>%
  summarise( mean_x = mean(judgment),
             criterion = unique(criterion) ) %>%
  summarise(cor = cor(.$mean_x, .$criterion))
  }
 N <- length(unique(Data$participant))

lapply(1:N, HelpFun, Data) %>% bind_rows()
}

MyFun(df)

The problem is that this code is slow. Since every selection is random, I
perform all this 10,000 times. And this slow. On my machine (Windows 10, 16 GB) 1000 simulations take 2 minutes. 10,000 simulations takes 20 minutes. (I also tried with loops but it did not help, although for some reasons it was a little bit faster). It has to be a solution faster. After all, a computations are not so complicated.
Below I wrote 100 simulations only in order to not interfere with your computer.
    system.time(replicate(100, MyFun(df), simplify = FALSE ) %>% bind_rows())
Any idea about making all of this faster?

A: Using data.table and for loops we can get 10 times faster solution.
My function:
minem <- function(n) { # n - simulation count
  require(data.table)
  participants_id <- unique(df$participant)
  N <- length(unique(df$participant))
  dt <- as.data.table(df)
  setkey(dt, stimuli)
  L <- list()
  for (j in 1:n) {
    corss <- rep(0, N)
    for (i in 1:N) {
      participants_x <- sample(participants_id, i)
      xx <- dt[participant %in% participants_x,
               .(mean_x = mean(judgment),
                 criterion = first(criterion)),
               by = stimuli]
      corss[i] <- cor(xx$mean_x, xx$criterion)
    }
    L[[j]] <- corss
  }
  unlist(L)
}

head(minem(10))
# [1]  0.13642499 -0.02078109 -0.14418400  0.04966805 -0.09108837 -0.15403185

Your function:
Meir <- function(n) {
  replicate(n, MyFun(df), simplify = FALSE) %>% bind_rows()
}

Benchmarks:
microbenchmark::microbenchmark(
  Meir(10),
  minem(10),
  times = 10)
# Unit: milliseconds
#      expr       min        lq      mean    median        uq       max neval cld
#  Meir(10) 1897.6909 1956.3427 1986.5768 1973.5594 2043.4337 2048.5809    10   b
# minem(10)  193.5403  196.0426  201.4132  202.1085  204.9108  215.9961    10  a

around 10 times faster
system.time(minem(1000)) # ~19 sek

Update
If your data size and memory limit allows then you can do it much faster with this approach:
minem2 <- function(n) {
  require(data.table)
  participants_id <- unique(df$participant)
  N <- length(unique(df$participant))
  dt <- as.data.table(df)
  setkey(dt, participant)
  L <- lapply(1:n, function(x)
    sapply(1:N, function(i)
      sample(participants_id, i)))
  L <- unlist(L, recursive = F)
  names(L)  <- 1:length(L)
  g <- sapply(seq_along(L), function(x) rep(names(L[x]), length(L[[x]])))
  L <- data.table(participant = unlist(L), .id = as.integer(unlist(g)),
                  key = "participant")
  L <- dt[L, allow.cartesian = TRUE]
  xx <- L[, .(mean_x = mean(judgment), criterion = first(criterion)),
          keyby = .(.id, stimuli)]
  xx <- xx[, cor(mean_x, criterion), keyby = .id][[2]]
  xx
}

microbenchmark::microbenchmark(
  Meir(100),
  minem(100),
  minem2(100),
  times = 2, unit = "relative")
# Unit: relative
#        expr       min        lq      mean    median        uq       max neval cld
#   Meir(100) 316.34965 316.34965 257.30832 257.30832 216.85190 216.85190     2   c
#  minem(100)  31.49818  31.49818  26.48945  26.48945  23.05735  23.05735     2  b
# minem2(100)   1.00000   1.00000   1.00000   1.00000   1.00000   1.00000     2 a

But you will need to test yourself.


text:
Q: Comprobar si hay grid de preguntas en un diccionario Tengo un archivo pickle que representa preguntas y respuestas en un formato diccionario y me gustaria saber donde estan los que estan grid de preguntas como la siguiente para puestarlas en un csv como gcoronel99 lo hicé aqui:

La estructura de este ejemplo esta como la siguente:
{'question': 'To what extent are the following factors considerations in your choice of flight? ',
   'answers': [None,
    7,
    [[514996986,
      [['Very important consideration'],
       ['Important consideration'],
       ['Neutral'],
       ['Not an important consideration'],
       ['Do not consider']],
      0,
      ['The airline/company you fly with'],
      None,
      None,
      None,
      None,
      None,
      None,
      None,
      [1]],
     [396483948,
      [['Very important consideration'],
       ['Important consideration'],
       ['Neutral'],
       ['Not an important consideration'],
       ['Do not consider']],
      0,
      ['The departure airport'],
      None,
      None,
      None,
      None,
      None,
      None,
      None,
      [1]],
     [971070641,
      [['Very important consideration'],
       ['Important consideration'],
       ['Neutral'],
       ['Not an important consideration'],
       ['Do not consider']],
      0,
      ['Duration of flight/route'],
      None,
      None,
      None,
      None,
      None,
      None,
      None,
      [1]],
     [1685960105,
      [['Very important consideration'],
       ['Important consideration'],
       ['Neutral'],
       ['Not an important consideration'],
       ['Do not consider']],
      0,
      ['Price'],
      None,
      None,
      None,
      None,
      None,
      None,
      None,
      [1]],
     [231217486,
      [['Very important consideration'],
       ['Important consideration'],
       ['Neutral'],
       ['Not an important consideration'],
       ['Do not consider']],
      0,
      ['Baggage policy'],
      None,
      None,
      None,
      None,
      None,
      None,
      None,
      [1]],
     [940990935,
      [['Very important consideration'],
       ['Important consideration'],
       ['Neutral'],
       ['Not an important consideration'],
       ['Do not consider']],
      0,
      ['Environmental impacts'],
      None,
      None,
      None,
      None,
      None,
      None,
      None,
      [1]]]]}

Pero para los demas (si ya existen) pueden variar en funcion de la lineas o columnas. En el caso general pienso que una grid se reconoce cuando hay, en las answers multiples tabulas de tabulas de tabulas.
Entonces intenté saber si funciona a lo menos con el ejemplo arriba:
import pickle

dic = pd.read_pickle(r'Python/interns.p')

def isGrid(qa):
    d_answers = qa['answers']
#     print("qa['question']: ", qa['question'])
    if qa['question'] == 'To what extent are the following factors considerations in your choice of flight?':
        try:
            print("qa['question']: ", qa['question'])
            answers = d_answers[2]
            if len(answers)>1:
                print(True)
                return True
        except TypeError:
            print("truc")

for qa_set in dic:
    for qa in qa_set:
        bool_grid = isGrid(qa)

Pero obtengo:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1062-6d260b7f25bc> in <module>
     18 for qa_set in dic:
     19     for qa in qa_set:
---> 20         bool_grid = isGrid(qa)
     21
     22 # isGrid(qa)

<ipython-input-1062-6d260b7f25bc> in isGrid(qa)
      4
      5 def isGrid(qa):
----> 6     d_answers = qa['answers']
      7 #     print("qa['question']: ", qa['question'])
      8     if qa['question'] == 'To what extent are the following factors considerations in your choice of flight?':

TypeError: string indices must be integers

A: ¿Por que se obtiene el error?
Primero revisemos que implica iterar sobre un diccionario:
for key in dic:
    print(key)

Se pensaría que este ciclo imprimiría cada par ordenado del diccionario, algo así:
question: To what extent are the following factors considerations in your choice of flight?
answers: [None, 7, [[514996986, [['Very important consideration'], ['Important consideration'], ['Neutral'], ['Not an important consideration'], ['Do not consider']], 0, ['The airline/company you fly with'], None, None, None, None, None, None, None, [1]], [396483948, [['Very important consideration'], ['Important consideration'], ['Neutral'], ['Not an important consideration'], ['Do not consider']], 0, ['The departure airport'], None, None, None, None, None, None, None, [1]], [971070641, [['Very important consideration'], ['Important consideration'], ['Neutral'], ['Not an important consideration'], ['Do not consider']], 0, ['Duration of flight/route'], None, None, None, None, None, None, None, [1]], [1685960105, [['Very important consideration'], ['Important consideration'], ['Neutral'], ['Not an important consideration'], ['Do not consider']], 0, ['Price'], None, None, None, None, None, None, None, [1]], [231217486, [['Very important consideration'], ['Important consideration'], ['Neutral'], ['Not an important consideration'], ['Do not consider']], 0, ['Baggage policy'], None, None, None, None, None, None, None, [1]], [940990935, [['Very important consideration'], ['Important consideration'], ['Neutral'], ['Not an important consideration'], ['Do not consider']], 0, ['Environmental impacts'], None, None, None, None, None, None, None, [1]]]]

¿Qué pasa realmente?
Realmente solo imprime los valores de las llaves como los strings que son:
question
answers

Entonces el ciclo anidado de
for qa_set in dic:
    for qa in qa_set:
        bool_grid = isGrid(qa)

Esta ejecutando la función, con cada letra de ambas palabras. Esto se puede comparar imprimiendo el valor de qa por pantalla:
for qa_set in dic:
    for qa in qa_set:
        print(qa)

muestra
q
u
e
s
t
i
o
n
a
n
s
w
e
r
s

Entonces el error en la linea d_answers = qa['answers'] tiene sentido ahora. La letra individual es un string y se está intentando acceder a una llave como si fuera un diccionario. En otras plabras lo ocurre es esto:
d_answers = "q"['answers']

Por esto mismo ocurre el error
TypeError: string indices must be integers

los string no tiene llaves, solo indices. El primer error que obtienes se da debido al segundo.
¿Realmente la función isGrid() funciona?
La respuesta es que no, en el condicional
if qa['question'] == 'To what extent are the following factors considerations in your choice of flight?':

Estás evaluando si esa llave es igual a ese string, si te fijas en el diccionario dic el valor de la llave ["question"] es este string que evaluas, pero con un espacio al final. Para no modificar los datos la solución sería esta:
if qa['question'].strip() == 'To what extent are the following factors considerations in your choice of flight?':

Debido a que el método .strip() elimina los espacios al final y principio de una cadena.
¿Es necesario ejecutar la función con cada par ordenado de dic?
A mi punto de vista no, debido a que en la función se opera con ambos pares ordenados del diccionario. Solo basta con usar como parámetro de la función a dic.
La función:
def isGrid(qa):
    d_answers = qa['answers']
    if qa['question'].strip() == 'To what extent are the following factors considerations in your choice of flight?':
        try:
            print("qa['question']: ", qa['question'])
            answers = d_answers[2]
            if len(answers) > 1:
                print(True)
                return True
        except TypeError:
            print("truc")

Usando a dic como parámetro:
isGrid(dic)

devolvería
qa['question']:  To what extent are the following factors considerations in your choice of flight?
True

Claramente tendrás tus razones para realizar esa iteración, no sé que tienes en el picke. Sin embargo, al menos ya sabes por que se produce tu error.


text:
Q: Do I have to downgrade Cocoapods for Xcode 9 (GoogleDataTransport-error) Hi I can't fix the error and  I rely on you guys. I had to update some pods and therefore I updated my CocoaPods since then I get the

I am wondering if it is because of my Xcode 9.2 and SDK 'iOS 11.2' but updating Xcode is not an option. I tried to delete pods, xcworkspace, Podfile, podfile.lock and delete /Users/XXXX/Library/Developer/Xcode/DerivedData but it did not work...

any suggestions how I can fix the issue


text:
Q: AngularJS disable scrolling except for specific elements and children - jqlite or directive I want to disable scrolling by default except for specific elements and their children in an AngularJS/Cordova hybrid application.
I don't want to introduce jQuery into the app so I am trying to use Angular's jqlite (the stripped down essentials of jQuery). I'm also open to using a directive to solve the problem if you have any suggestions.
As you can see below I'm using jqlite's parent() method to see if the element's parent has the scrollable class. However this is not effective because it would be better to check the element itself and any parents up the DOM tree. jQuery has a parents() method to do this but jqlite does not.
Any ideas how to use jqlite to check all parents of an element or how to get the desired solution from a directive?
// disable scrolling by default unless inside a `scrollable` element
document.addEventListener('touchmove', function (e) {
    var scrollable = false;
    // todo: need to go all the way up the DOM tree instead of just one level up
    var items = angular.element(e.target).parent();
    angular.forEach(items, function (o) {
        var item = angular.element(o);
        if (item.hasClass("scrollable")) {
            scrollable = true;
        }
    });

    if (!scrollable) {
        e.preventDefault();
    }
}, true);


text:
Q: there is connection but why i don't get the response retrofit Hey I have php server in there there is username : jonik password 123456
i created on android page for login i'm testing this 2 things im getting response but i dont know where just in the log there is my success response i want to put it in the mainactivity so maybe i can do if statment to go to next activity and i have this error ((((i get this error after the connection with the server com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $)))
MainActivity
   private Communicator communicator;
private String username, password;
private EditText usernameET, passwordET;
private Button loginButtonPost, loginButtonGet;
private TextView information, extraInformation;
private final static String TAG = "MainActivity";
public static Bus bus;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    communicator = new Communicator();

    usernameET = (EditText)findViewById(R.id.usernameInput);
    passwordET = (EditText)findViewById(R.id.passwordInput);
    //This is used to hide the password's EditText characters. So we can avoid the different hint font.
    passwordET.setTransformationMethod(new PasswordTransformationMethod());

    loginButtonPost = (Button)findViewById(R.id.loginButtonPost);
    loginButtonPost.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            username = usernameET.getText().toString();
            password = passwordET.getText().toString();
            usePost(username, password);
        }
    });

    information = (TextView)findViewById(R.id.information);
    extraInformation = (TextView)findViewById(R.id.extraInformation);
}

private void usePost(String username, String password){
    communicator.loginPost(username, password);
}

ServerResponse
 public class ServerResponse implements Serializable {
    @SerializedName("returned_username")
    private String username;
    @SerializedName("returned_password")
    private String password;
    @SerializedName("message")
    private String message;
    @SerializedName("response_code")
    private int responseCode;

    public ServerResponse(String username, String password, String message, int responseCode){
        this.username = username;
        this.password = password;
        this.message = message;
        this.responseCode = responseCode;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }
}

serverEvent
public class ServerEvent {
private ServerResponse serverResponse;

public ServerEvent(ServerResponse serverResponse) {
    this.serverResponse = serverResponse;
}

public ServerResponse getServerResponse() {
    return serverResponse;
}

public void setServerResponse(ServerResponse serverResponse) {
    this.serverResponse = serverResponse;
}

interface
public interface Interface {
@FormUrlEncoded

@POST("/cult_tickets/request.php")
void postData(
              @Field("username") String username,
              @Field("password") String password,
              Callback<ServerResponse> serverResponseCallback);

Communicator
 public class Communicator {
    private static  final String TAG = "Communicator";
    private static final String SERVER_URL = "http://192.168.3.105";
    public void loginPost(String username, String password){
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(SERVER_URL)
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .build();
        Interface communicatorInterface = restAdapter.create(Interface.class);
        Callback<ServerResponse> callback = new Callback<ServerResponse>() {
            @Override
            public void success(ServerResponse serverResponse, Response response2) {
                if(serverResponse.getResponseCode() == 0){
                    BusProvider.getInstance().post(produceServerEvent(serverResponse));
                }else{
                    BusProvider.getInstance().post(produceErrorEvent(serverResponse.getResponseCode(), serverResponse.getMessage()));
                }

            }

            @Override
            public void failure(RetrofitError error) {
                if(error != null ){
                    Log.e(TAG, error.getMessage());
                    error.printStackTrace();
                }
                BusProvider.getInstance().post(produceErrorEvent(-200,error.getMessage()));
            }
        };
        communicatorInterface.postData(username, password, callback);
    }

@Produce
public ServerEvent produceServerEvent(ServerResponse serverResponse) {
    return new ServerEvent(serverResponse);
}

@Produce
public ErrorEvent produceErrorEvent(int errorCode, String errorMsg) {
    return new ErrorEvent(errorCode, errorMsg);
}
}

finally busprovider
public class BusProvider {

private static final Bus BUS = new Bus();

public static Bus getInstance(){
    return BUS;
}

public BusProvider(){}

}

A: Even without seeing your JSON string you can tell from the error message that it is not the correct structure to be parsed into an instance of your class.
Gson is expecting your JSON string to begin with an object opening brace. e.g.
{
But the string you have passed to it starts with an open quotes
"


text:
Q: How to Send SOAP Header with XMLDP from SSRS XML DataService I'm trying to use a vendor's web service via the XML Data Source within SSRS (2008R2.)
I've nearly solved it all with the exception that the vendor's web service requires a soap header with a client identification block.
I've found no way in the documentation to send a soap header via the XMLDP query langauge.
I'v been watching the actual soap sent by the XML Data source with Fiddler and it actually looks like it omits the SOAP Header Entirely.
Main question: Is this even possible?
The Microsoft documentation I've found omits mention of SOAP headers, and other non-authoritative sources indicate that I need to create my own Custom Data Extension and deploy this to the SSRS Server.
Creating a new CDE and deploying to the server is beyond scope for this project.
Thanks,
PS: I'm using the  method of calling the web service in-case that is relevant.

A: My solution ended up being:
Create a new pass-through web-service I could call which in-turn called the vendor web-service.  Since this will be short lived solution the small amount of pain created by the extra step is acceptable.
To be sure, there was no found way to use the XMLDP to send the required SOAP header.


text:
Q: Scikit-Learn Random Forest regression: mix two sets of true values (y) I am training Random Forests with two sets of "true" y values (empirical). I can easy tell which one is better.
However, I was wondering if there is a simple method, other than brute force, to pick up the values from each set that would produce the best model. In other words, I would like to automatically mix both y sets to produce a new ideal one.
Say, for instance, biological activity. Different experiments and different databases provide different values. This is a simple example showing two different sets of y values on columns 3 and 4.

4a50,DQ7,47.6,45.4
3atu,ADP,47.7,30.7
5i9i,5HV,47.7,41.9
5jzn,GUI,47.7,34.2
4bjx,73B,48.0,44.0
4a6c,QG9,48.1,45.5

I know that column 3 is better because I have already trained different models against each of them and also because I checked a few articles to verify which value is correct and 3 is right more often than 4. However, I have thousands of rows and cannot read thousands of papers.
So I would like to know if there is an algorithm that, for instance, would use 3 as a base for the true y values but would pick values from 4 when the model improves by so doing.
It would be useful it it would report the final y column and be able to use more than 2, but I think I can figure out that.
The idea now is to find out if there is already a solution out there so that I don't need to reinvent the wheel.
Best,
Miro
NOTE: The features (x) are in a different file.

A: The problem is that an algorithm alone doesn't know which label is better.
What you could do: Train a classifier on data which you know is correct. Use the clasifier to predcit a value for each datapoint. Compare this value to the two list of labels which you already have and choose the label which is closer.
This solution obviously isn't perfect since the results depends on quality of the classfier which predicts the value and you still need enough labeled data to train the classifier. Additionaly there is also a chance that the classifier itself predicts a better value compared to your two lists of labels.

A: Choose column 3 and column 4 both together as target/predicted/y values in Random Forest classifier model fitting - and predict it with your result.  Thus, your algorithm can keep track of both Y values and their correlation to predicted values. Your problem seems to be Multi-output classification problem, where there are multiple target/predicted variables (multiple y - values ) as you suggest.
Random forest supports this multi-output classification using random forest. Random Forest fit(X,y) method supports y to be array-like y : array-like, shape = [n_samples, n_outputs]
multioutput-classification
sklearn.ensemble.RandomForestClassifier.fit
Check multi-class and multi-output classification


text:
Q: A function that takes two arguments- a function f and a list l and applies the function over the elements of the list and returns them as a list I made a function:
def remove_trailing_newlines(s):
  s_clean = s.rstrip()
  return s_clean

This function will remove the trailing \n at end of string s.
Now I want to apply the same to every element (which is string) of a list.
I want to create a function mapl(f, l) where f is remove_trailing_newlines() and l is a list on which we have to apply f and return it as a list
For example:
on the list l = ['Apple\n','banana\n','mango\n']
I want the output as : l = ['Apple','banana','mango']
using the mapl(f,l) function

A: You are looking for:
list(map(remove_trailing_newlines, l))

We can pass custom function and apply the function to each element of the list.
You can also directly call rstrip inside map as in @yatu's answer.

A: I think you want to make a function like a builtin map function by yourself. Try the following:
def remove_trailing_newlines(s):
    s_clean = s.rstrip()

    return s_clean

def mapl(f,l):
    ret = []
    for i in l:
        ret.append(f(i))
    return ret

l = ['Apple\n','banana\n','mango\n']

new_list = mapl(remove_trailing_newlines,l)
print(new_list)

>> ['Apple', 'banana', 'mango']

Let me know if it does not fulfill your requirement


text:
Q: JPA + Spring Data - Can't get or delete persisted objects I have a complex class hierarchy that looks like the following:
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Person {
    protected String ssn;
    protected int age;

    @Id
    public int getSsn() {
        return ssn;
    }

    @Column
    public int getAge() {
        return age;
    }

    // Setter omitted
}

@MappedSuperclass
@IdClass(EmployeeKey.class)
public abstract class Employee extends Person {

    protected String badgeNumber;

    @Id
    public String getBadgeNumber() {
        return badgeNumber;
    }

    // Setter omitted
}

public class EmployeeKey implements Serializable {
    private String ssn;
    private String badgeNumber;

    // Getters & setters omitted
}

@Entity
@Table(name = "Contractors")
public class Contractor extends Employee {
    private Date contractExpiration;

    @Column
    public Date getContractExpiration() {
        return contractExpiration;
    }

    // Setter omitted
}

Then I have a repository for contractors
JpaRepository<Contractor, EmployeeKey> repo;

When I save objects using the repository it works fine, however if I try to get or delete objects I get the following exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Unknown entity bean class: class com.Employee, please verify that this class has been marked with the @Entity annotation.; nested exception is java.lang.IllegalArgumentException: Unknown entity bean class: class com.Employee, please verify that this class has been marked with the @Entity annotation.
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:296)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy25.findOne(Unknown Source)
    at com.EmployeeDaoSqlTest.repoGet(EmployeeDaoSqlTest.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalArgumentException: Unknown entity bean class: class com.Employee, please verify that this class has been marked with the @Entity annotation.
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:707)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:588)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
    at com.sun.proxy.$Proxy22.find(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findOne(SimpleJpaRepository.java:214)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
    ... 38 more

I do have all three classes in my persistence.xml file.

A: Your JPA provider doesn't know about the Contractor type. Make sure you list it in the persistence.xml or set LocalContainerEntityManagerFactoryBean.setPackagesToScan(…) to make sure the entity type is discovered automatically and known to the persistence provider.


text:
Q: How can I use a 64-bit id in Django using Postgres as a backend? I am trying to create a 64-bit id in Django (3.1), somewhat like this stackoverflow answer, and store it in Postgres (13.1).
For reference, here is their proposed Django model:
class MyClass(models.Model):
    id = models.BigIntegerField(default = fields.make_id, primary_key=True)

with their make_id modified to return a 64-bit integer with the highest bit set:
def make_id():
    return 13528776667777991352

If I use this proposal, I get an error when trying instance.save():
django.db.utils.DataError: bigint out of range

That seems correct to me.  That number has the highest bit set:
$ python -c "print(f'{13528776667777991352:>64b}')"
1011101110111111110111101011001101101000100000000000001010111000

It will be too large for a signed 64-bit int, but not too large for unsigned:
$ python -c "print(13528776667777991352 > (2**63-1))"
True
$ python -c "print(13528776667777991352 < 2**64)"
True

Postgres docs say the range of bigint is -2**63 to 2**63-1.  (The numbers in the docs are -9223372036854775808 to +9223372036854775807.)
I am surprised that no one commented on that stackoverflow answer.  Since time is shifted into the highest bit position, I feel like anyone would hit this right away.  I may be missing something obvious.
I've thought of a few options.

*

*Write a Django custom field (say "UnsignedBigIntegerField") that slides the number from [-2**63, 2**63-1] to [0, 2**64] by adding 2**63 when it gets saved, and subtracting that when it gets loaded.  A hack to be sure.

*Write a Django custom field that wraps some other Postgres type, like a byte string or bitfield, or fixed-precision numeric.
How can I use a 64-bit id in Django 3.1 using Postgres 13.1 as a backend?
This will be used as an id, so Postgres lookups should be as fast and efficient as possible.
EDIT: My current solution is to leave the highest bit unset. So, I have a 63-bit id.  That fits Postgres's constraint, and is fairly simple.  It is annoying that I have to leave a bit on the table.


text:
Q: Dropdown is hiding inside flash.swf

         Red
         Orange

         <object height="251" width="504">
         <param value="Flash.swf" name="movie">
         <param value="Transparent" name="wmode">
         <embed width="504" height="251" src="Flash.swf"/> //here flash is hiding drop
         </object>

Here flash.swf is hiding the dropdownmenu .I want the dropdown outside the flash but it displaying inside the flash

A: You don't have the wmode parameter in the embed tag:
<embed width="504" height="251" src="Flash.swf" wmode="transparent" />

The <param based wmode only targets Internet Explorer


text:
Q: c++ const conundrum I have the following code in 3 files:
Defines.h
#ifndef Defines_h
extern const unsigned int SIZE;

#endif

Defines.cpp
#include "Defines.h"

const unsigned int SIZE = 10;

Main.cpp
#include "Defines.h"

int main()
{
    int x[SIZE] = {0};
}

On compiling I get the error at the array definition line as:
error C2057: expected constant expression and
C2466: cannot allocate an array of constant size 0
Why does this happen, after all I have SIZE which is indeed a constant ?

A: Move const unsigned int SIZE = 10; into the header and remove the extern line. With a simple const int value it is safe and harmless to declare it directly in-header.

A: const are implicitly static, you need an extern even on the SIZE definition. includes file will not link because it is looking for a const unsigned int SIZE with external linkage.


text:
Q: Go send null in json type JobTitles struct {
    Titles []string `json:"titles"`
}

chiefTitles := []string{"CEO", "CFO", null, "CMO"}

jsonOut := JobTitles{chiefTitles}

In the code above, I would like to be able to send null as one of the values in my json string array. However, the above will not compile and if I add double quotes to null it becomes a string not the value null.
How can I send null in my json response in GO?
This article seems to help, but looks to be the inverse of my question..

A: In order to represent that type with the value 'null' it would have to be a pointer. The problem isn't that you can't use null but rather that a string can't have that value. Here is a quick example I made in the playground; https://play.golang.org/p/SXO5sBl2mR
package main

import "fmt"
import "encoding/json"

type Test struct {
    A *string
    B *string
}

func main() {
        s := "Something"
        t := Test{A:&s, B:nil}
        b, err := json.Marshal(t)
        if err != nil {
            fmt.Println(err)
        }
    fmt.Println(string(b))
}

As DaveC mentioned using pointers makers the initilization a bit more cumbersome but you can use the same type of constructs I have above; declare a string, use the & that string in the composite literal.

A: You will have to use *string instead, and create a helper function to make it easier, something along the lines of:
func main() {
    chiefTitles := []*string{sP("CEO"), sP("CFO"), nil, sP("CMO")}

    b, _ := json.Marshal(JobTitles{chiefTitles})

    fmt.Println(string(b))
}

type JobTitles struct {
    Titles []*string `json:"titles"`
}

func sP(s string) *string {
    return &s
}

playground


text:
Q: How to make container height match the child listView item size I build my app homeScreen that contains multiple part of widget and most of the is basically a listView with different size, and I put them all inside column widget.
the problem is this listView is actualy come from streamBuilder so the content inside the list is dynamic (come from firebase) so there is gonna be a time it will contain 5 items for example or 0 items.
And as far as I know when I use streambuilder or listview in general I need to warp this widget in something like container with predefined height and if the listview items only 1 and I predefined the height to be for 5 items then it will show a big white space of nothing (since the container is for 5 items but to that user, he/she only have 1 items)
Container(
  height: screenHeight * 0.4,
  child: StreamBuilder<List<Place>>(
    stream: database.placesStream(),
    builder: (context, snapshot) {
      return ListItemsBuilderNoScroll<Place>(
        snapshot: snapshot,
        itemBuilder: (context, place) => _buildPlaceList(screenWidth, screenHeight, place),
      );
    },
  ),
),

So how to fix this issue or am I using the wrong widget for this situation?

A: This seems to be a legit problem, but more of a logic problem than design. Instead of directly building the listview by default, you may check of data being available on the stream you are listening to.  Set a flag or something on the basis of which you decide whether to build the listview to display or not.
Additionally, once the get the list you need to display on the list view, you may also change the size of the container by the checking the list length.
Anyway, this is a seven-month-old question, hopefully, you have found the solution to your problem.
Happy Coding!
GS


text: Q: How to invoke Talend job upon s3 file created event I'm using Talend as my ETL tool which takes data from S3 bucket, cleans and then load into Redshift. But in case of real-time ETL processing, how to invoke ETL(Talend job) upon file created event in S3?


text:
Q: Grep lines for multiple words and the line ending, and then replace line ending if matched I need to grep a long text file for lines that contains multiple possible words and also end in "=1", and then replace the line with the same text except change the "=1" to "=0".
I'm using BBEdit.
So far I have this to find lines that contains the desired match that also ends with 1:
^(.*test|.*disabled|.*inactive|.*server).*(=1)

I'm unable to do the replacement successfully though.
Here are some example lines of text from the file:
OU>2020,OU>Disabled Accounts,DC>net,DC>example,DC>com=1
OU>Distribution Groups,DC>net,DC>example,DC>com=1
OU>Exchange Servers,DC>net,DC>example,DC>com=1
CN>Users,DC>net,DC>example,DC>com=1
OU>Test Servers,OU>Servers,OU>ABC,DC>net,DC>example,DC>com=1

As an example, the first line above would have its =1 changed to =0 like:
OU>2020,OU>Disabled Accounts,DC>net,DC>example,DC>com=0

Other matches would follow that pattern.

A: After playing around with it more, this seems to work:
Find:
(^.*(test|disable|inactive|server).*)(=1)$

Replace:
\1=0


text:
Q: Xamarin Forms overlaps systems title - how to hide FitsSystemWindows I am working on Xamarin Forms application. In the top section app overlaps with the android system topbar  (No the application bar) I am using my own custom nav bar not using inbuild.
Please suggest how to set the Android.Views.View.FitsSystemWindows property in Xamarin Forms


text:
Q: How to ignore some word from string replace using regex I have string which contain 5 to 6 word and i would like to replace some word with highlighter style.
$(document).ready(function() {
     var str = "Micromax Samsung S3 Microsoft Galaxy S";
     var arr = ["Micro", "s"];
     arr.forEach(function(item) {
          str = str.replace(new RegExp(item.replace(/\+/g, "\\+"), "g"), ''+ item +'');
     })
     $('#dvHtml').html(str);
});

But i am getting every s in the entire string including  but i don't want to replace .
Can any body help me to exclude or ignore following items from replace

*

*

*
Output should be
Now this will replace Micro with Micro and s with s
Following are output

A: You need change your regexp something like this
var str = "Micromax Samsung S3 Microsoft Galaxy S";
var arr = ["Micro", "s"];
var t = str.replace(new RegExp('\\b('+arr.join('|')+')',"gi"), '$1');

$('#dvHtml').html(t);

in this

*

*\b - find in begin word

*arr.join('|') - return string like a|b - so find any of them

*gi - flag for global and ignore case
you can try it on JSFiddle

A: Here you have another solution.
function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function highlight(str, needle){
      var parts = str.split(/<[/]?span.*?>/gi);
      for(var i=0; i<parts.length; i++){
          if(i%2 == 0){
              parts[i] = parts[i].replace(new RegExp("("+escapeRegExp(needle)+")", 'gi'), '$1');
          }else{
              parts[i] = ''+ parts[i] +'';
          }
      }
      return parts.join('');
}

$(document).ready(function() {
   var str = "Micromax Samsung S3 Microsoft Galaxy S";
   var arr = ["Micro", "S"];
   arr.forEach(function(item) {
        str = highlight(str, item);
   });
   console.log(str);
   $('#dvHtml').html(str);
});

The advantage of this one is that you can reapply the highlight method as many times as you want on the processed string.
JSFiddle: http://jsfiddle.net/edgarinvillegas/4ZK7W/2/
Also, you can have special characters in the string to search.
For example, var arr = ["Micro", "Sam|"] does not highlight "Sam", but highlights "Sam|" if it existed in the str .
Cheers, from La Paz Bolivia

A: Don't reinvent the wheel. Here you have a highlight plugin that deals with that problem:
http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
Hope it helps. Cheers, from La Paz, Bolivia