text:
Q: Accessing non-zero elements in specific row of matrix in python I have the indices of the positions of non-zero elements in a sparse matrix in python in the form
(array([0, 1, 2], dtype=int32), array([2, 0, 0], dtype=int32), array([2, 1, 3]))

or in the matrix form
[[0 2]
 [1 0]
 [2 0]]

I want to use this (or some  other method if there is one) to carry out row-by-row operations with only the corresponding non-zero elements of other matrices, like so:
for r in range(rows):
    A[r,:] = np.dot(B[r,:],C.T)

Basically I need a way to specify the row and only choose the elements from that row that correspond to the non-zero elements from the matrix B.
The part I can't get my head around is due to the fact that there can be a varying number of entries for each row/column.

A: I'm a little puzzled as to what that first tuple represents.  Is it the indexes and values of a sparse array? e.g.
In [4]: arrays=(np.array([0, 1, 2], dtype=int), np.array([2, 0, 0], dtype=int), np.array([2, 1, 3], dtype=float))
...
In [6]: from scipy import sparse
In [7]: M=sparse.csr_matrix((arrays[2],(arrays[0],arrays[1])))
In [8]: M
Out[8]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>
In [9]: M.A
Out[9]:
array([[ 0.,  0.,  2.],
       [ 1.,  0.,  0.],
       [ 3.,  0.,  0.]])

In [10]: print(M)
  (0, 2)    2.0
  (1, 0)    1.0
  (2, 0)    3.0

Matrix multiplication is defined for such an array:
In [12]: M*M.T
Out[12]:
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>
In [13]: (M*M.T).A
Out[13]:
array([[ 4.,  0.,  0.],
       [ 0.,  1.,  3.],
       [ 0.,  3.,  9.]])
In [14]: M.A.dot(M.A.T)  # dense equivalent
Out[14]:
array([[ 4.,  0.,  0.],
       [ 0.,  1.,  3.],
       [ 0.,  3.,  9.]])

I could implement a row by row multiplication with this array:
In [21]: A=M.A      # dense array
In [22]: for r in range(3):
    print(np.dot(A[r,:],A[r,:]))
4.0
1.0
9.0
# actually this is just the diagonal

In [23]: for r in range(3):   # or with the nonzero elements
    I=np.nonzero(A[r,:])
    dot = np.dot(A[r,I[0]],A[r,I[0]])
    print(dot)
4.0
1.0
9.0

for what it's worth, nonzero returns the array I copied from your post at the start:
In [24]: np.nonzero(A)
Out[24]: (array([0, 1, 2], dtype=int32), array([2, 0, 0], dtype=int32))
In [25]: A[np.nonzero(A)]
Out[25]: array([ 2.,  1.,  3.])

The sparse matrix also has a nonzero method:
In [26]: M.nonzero()
Out[26]: (array([0, 1, 2], dtype=int32), array([2, 0, 0], dtype=int32))

I feel like I'm floundering around, trying to make sense of the question and the example.

A: I found out you can use boolean array indices in python so the following does what I wanted to achieve:
for r in range(rows):
    A[r,B[r,:]!=0] = np.dot(B[r , B[r,:]!=0], C[: , B[r,:]!=0].T)

looks kind of complicated but it gets the right elements for the calculation. The only problem is when the dimension of B is larger than what it's indexing into which throws an index out of bounds error.


text:
Q: RVM is not working over SSH RVM is not working over SSH.
At the command-line:
leifg@host:~$ which ruby
/usr/local/rvm/rubies/ruby-1.9.2-p290/bin/ruby

Connected over SSH:
local:~$ ssh leifg@server 'which ruby'
/usr/bin/ruby

I'm using Ubuntu 11.04.
How do I get SSH to use the same Ruby as it is on the system?
I already verified some prequisites:

*

*Ruby was already installed using apt-get install ruby. Does that make any difference?

*sshd_config has the option "PermitUserEnvironment yes", and I restarted the daemon.

The .bashrc on the server contains these lines, but I see the same behavior when I remove them:
if [ -s "$HOME/.rvm/scripts/rvm" ] ; then
  . "$HOME/.rvm/scripts/rvm"
elif [ -s "/usr/local/rvm/scripts/rvm" ] ; then
  . "/usr/local/rvm/scripts/rvm"
fi

A: Actually, your ~/.bashrc will be executed. The problem is usually that one adds the
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

... snippet at the bottom of the file. However, the default .bashrc on ubuntu systems includes the following near the top
# If not running interactively, don't do anything
[ -z "$PS1" ] && return

That call will stop executing the rest of the script and will therefore not set the proper paths. So you can either put the rvm call at the top of the file or remove the return call.

A: "rvm" has two invocation bugs: the default installation drops the file /etc/profile.d/rvm.sh and believes any bash trick is now globally available. – This assumption is wrong.
Files in /etc/profile.d/ are "sourced" on login, but maybe not from bash, maybe not even from a shell. So the cd hook it installs is not there after the shell which runs these files exits. Actually, because of the buggy way "rvm" installs this hook, it is already gone once you run naked bash in a login-shell!
I don't know if "rvm" supports an explicit invocation for virtual environments, without relying on cding into some directory (that I consider the second bug).
There is one sane workaround:
Make your shell source /etc/profile.d/rvm.sh from e.g. ~/.bashrc. .bashrc is executed from any non-login bash, and login-bash is usually setup to source .bashrc from those login-shell files like ~/.profile
For your ssh problem: should a proper ssh-shell not be login-shell anyway?

A: I've just added at the top of ~/.bashrc (for git user) this string:
[[ -s "/usr/local/rvm/scripts/rvm" ]] && source "/usr/local/rvm/scripts/rvm"

A: From the ssh man page:

If command is specified, it is executed on the remote host instead of
  a login shell.

This should mean that your .bashrc won't get sourced, so RVM doesn't get set up.
Solution
This did the trick in the end:
ssh <host> bash --login -c <command>

Start bash as a login shell through SSH and then start the RVM installed Ruby via SSH's -c option.

A: Actually there's totally another, more safe and lightweight option.
You add "PermitUserEnvironment yes" somewhere to your sshd_config in /etc/(open)ssh
Now you are allowed to specify user environment in /home/user/.ssh/environment. So what do you put there ?
Just something like :

user# env | grep rvm > ~/.ssh/environment

so it looks like below :

user@app3:~$ cat ~/.ssh/environment
rvm_bin_path=/usr/local/rvm/bin
GEM_HOME=/usr/local/rvm/gems/ree-1.8.7-2012.02
IRBRC=/usr/local/rvm/rubies/ree-1.8.7-2012.02/.irbrc
MY_RUBY_HOME=/usr/local/rvm/rubies/ree-1.8.7-2012.02
rvm_path=/usr/local/rvm
rvm_prefix=/usr/local
PATH=/usr/local/rvm/gems/ree-1.8.7-2012.02/bin:/usr/local/rvm/gems/ree-1.8.7-2012.02@global/bin:/usr/local/rvm/rubies/ree-1.8.7-2012.02/bin:/usr/local/rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
rvm_version=1.14.5 (stable)
GEM_PATH=/usr/local/rvm/gems/ree-1.8.7-2012.02:/usr/local/rvm/gems/ree-1.8.7-2012.02@global

Note: this also works work user-install RVM (not only for the system wide)
Now your are able to use ruby in ssh non interactive sessions :

ssh user@app3 'ruby --version'
ruby 1.8.7 (2012-02-08 MBARI 8/0x6770 on patchlevel 358) [x86_64-linux], MBARI 0x6770, Ruby Enterprise Edition 2012.02

Voila!

A: Mentioned solutions work certainly fine, but mine was to run
source /usr/local/rvm/environments/<ruby version>@<gemset version>

at the start of the remote ssh call. Something like:
ssh -l <remote username> <server ip> "source /usr/local/rvm/environments/<ruby version>@<gemset version> ; <rest of the remote script>"

A: *

*(if using Capistrano) Don't use rvm1/capistrano3 or rvm/capistrano; don't set :pty.

*Change ~/.rvmrc for the runner user, on the server, to this — note that it has to come before the line where it kills itself when not running interactively:
# get rvm for non-interactive shells (eg capistrano) too
source /etc/profile.d/rvm.sh
export BASH_ENV=$HOME/.bashrc
export rvm_is_not_a_shell_function=0

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

A: I had the same problem. I realized, that I accidentally installed RVM for multiple users, too. After deleting the directory /usr/local/rvm and edit ~/.bashrc like zoonmix suggested, the problem was solved.

A: Make sure that on the server you have done something like rvm --default 1.9.2 to set RVM's Ruby to be the default. Otherwise, it will always use the default system Ruby.

A: zoomix's is the best solution. But when you change with "ruby rvm use system" in terminal or what else you get an error :
Warning! PATH is not properly set up, is not at first place.... To solve that put the snippet just before the return instead of at the top of the .bashrc file (Debian Jessie here)
case $- in
*i*) ;;
  *)
  [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
  return;; esac

redpajama_set_name: RedPajamaStackExchange


text:
Q: ampy runs into an errror, ab ttyUSB0 is after then never available, till replugin the USB wire On Ubuntu 20.04 it works very well, but after the upgrad to 22.04 it runs into an error.
You can see it in the screen image.
Plug in --> ttyUSB0 is available
Run a ampy command --> "failed to access"
And than ttyUSB0 is never available, till replugin the USB wire.
My User is int the dailout group.
If i run it as sudo or normal user the error comes up.
Also if i set up the --boud to 11520
What kind of config could be missen?


text:
Q: ObjC AES128 Encryption with binary key I'm trying to encrypt data with AES128, I get right output with key being treated as text string, but only garbage trying to treat key as binary.
Implementation I'm using is this:
- (NSData *)AES128EncryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));

[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

NSLog(@"keyPtr: %s", keyPtr);

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0x00,
                                      keyPtr, kCCKeySizeAES256,
                                      NULL , [self bytes], dataLength, buffer, bufferSize,
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}

free(buffer);
return nil;
}

The encryption in this online tool example is exactly what I need.
With my implementation I get same a correct encryption for plaintext key, but I can't find a way to treat key as hex.
Tried to modify the code above to get key as NSData but is not working, I get only garbage after encryption.
I searched and didn't found an answer on this specific subject, hope I did it right, TIA :)

A: I don't think you mean "Hex", which is a string representation.  I think you mean "binary", so simply provide the key as NSData:
- (NSData *)AES128EncryptWithKey:(NSData *)key {
    NSAssert([key length] >= kCCKeySizeAES256, @"Key too short");
    NSUInteger dataLength = [self length];

    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    NSMutableData *encrypted = [NSMutableData dataWithCapacity:bufferSize];

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0x00,
                                          [key bytes], kCCKeySizeAES256,
                                          NULL , [self bytes], dataLength,
                                          [encrypted mutableBytes], bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        [encrypted setLength:numBytesEncrypted];
        return encrypted;
    }

    return nil;
}

Note: your code contained one memory leak and I think you weren't returning the encrpypted data properly.

A: Solved modifying trojanfoe's code, thanks a lot!
- (NSData *)AES128EncryptWithKey:(NSData *)key {
NSAssert([key length] >= kCCKeySizeAES128, @"Key too short");
NSUInteger dataLength = [self length];

size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, ccPKCS7Padding,
                                      [key bytes], kCCKeySizeAES128,
                                      NULL , [self bytes], dataLength, buffer, bufferSize,
                                      &numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
    return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}

free(buffer);
return nil;
}

With this I get same output as that online tool.
I know it's potentially insecure, thanks for the advice, but I need it for my own use only, will not being distributed so only thing I need is it to work properly and output same result as that tool.
Thanks everybody!


text:
Q: Headers warning
Possible Duplicates:
Warning: Cannot modify header information - headers already sent by
what is output buffering?

I recently bought a hosting plan from Bluehost and moved my website here. Before, my website was working, and I haven't recieved any errors, but now, when I try to login I recieve this error:

Warning: Cannot modify header information - headers already sent by (output started at /home/rugbyspi/public_html/inc/offline_header.php:15) in /home/rugbyspi/public_html/index.php on line 84

The problem is the header function. I think I can't use this function in middle of the code, but on my other host I can do this.
Any idea how to fix this problem?
<?php
session_start();
if (isset($_SESSION['username'])) {
   include_once('inc/homepage_header.php');
   include_once('lib/stats_func.php');
   include_once('lib/user_time_func.php');
   update_last_active($username);
?>

   <?php include_once('inc/sidebar_statistics.php'); ?>

   <?php include_once('inc/sidebar_follow.php'); ?>

<?php echo $lang['ann']; ?>

      <?php
      if(!isset($_REQUEST["start"])) {
         $start = 0;
      }
      else {
         $start = $_REQUEST["start"];
      }
      $query = mysql_query ("SELECT * from news where lang='$language'")
      or die ("Couldn't connect to the do database.");
      $d=0;
      $f=0;
      $g=1;
      $query = mysql_query ("SELECT * from news where lang='$language' order by id DESC Limit $start, 7") or die ("Couldn't connect to the do database.");
      while($news = mysql_fetch_array($query)) {
         ?>

<?php echo $news['tsubmit']; ?>          <?php echo $news['title']; ?>

         <?php
         echo $news['body'];
      }
      echo "

";
      echo $lang['pages'] . ': ';
      while($order = mysql_fetch_array($query)) {
         if($f%7==0) {
            echo "$g";
            $g++;
         }
         $d++;
         $f++;
      }
      ?>

<?php
   include_once('inc/footer.php');
}
else {
   include_once('inc/offline_header.php');
   include_once('lib/stats_func.php');
?>

   <?php include_once('inc/sidebar_statistics.php'); ?>

   <?php include_once('inc/sidebar_follow.php'); ?>

      <?php echo $lang['welcome']; ?>

      <?php
      if (isset($_POST['submit'])) {
         $username = $_POST ['username'];
         $password = $_POST ['password'];
         $username = strip_tags ($username);
         $password = md5 ($password);
         mysql_real_escape_string($username);
         $query = mysql_query ("SELECT id FROM users WHERE username='$username' AND password='$password'")
         or die ("Couldn't connect to the do database.") ;
         $result = mysql_fetch_array($query);
         if($result) {
            $_SESSION['username'] = $username;
            header('Location: index.php');
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
               $ip=$_SERVER['HTTP_CLIENT_IP'];
            }
            elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
               $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            else {
               $ip=$_SERVER['REMOTE_ADDR'];
            }
            $time = time();
            mysql_query ("INSERT into logins (userid, time, ip)
            VALUES ('$result[id]', '$time', '$ip')")
            or die ("Couldn't connect to the database.");
         }
         else {
            echo $lang['login_error'];
         }
         echo '

';
      }
      ?>

<?php echo $lang['about']; ?>

      <?php echo $lang['intro']; ?>

<?php
}
   include_once('inc/footer.php');
?>

A: You must have some echoed text before you've started the session. Try removing any of the output before session_start(), or move that function to offline_header.php

A: It would be great if You provided a code from the line 15 an before from the error generating file.
Anyway this error is caused by output done before session_start() or other header() function is called.
It doesn't matter whether it was Your output (like echo, print, etc) it also could be an output from error message (Notice, Warning) that could be turned off at previous hosting but now they appear before You call some header function...
You should check Your code on the line 15 and also all the code before whether it is generating some error or there is direct output...
Hope it helps.

A: As the error indicates, you cannot modify header information (which is what the header function does) once the header has already been sent. The headers get sent the first time you output text.
Before line 84 you have various places where text is output (for example lines 61, 63 and 65), and there could be more opportunities in the file which you include. This means that you cannot use the header function before theses lines, or possibly before any of the include calls in that else branch.
You should restructure your code to put
if (isset($_POST['submit'])) {...

as the first thing in the else branch, and don't output any html or other text until you know if the query succeeded, so that you know if you want to redirect to the index page.


text:
Q: How to filter on another class property with NSPredicate? I have following classes

EntityOne
- Property1 : string
- Property2 : int
- Property3 : Array of EntityTwo

EntityTwo
- Property1 : string
- Property2 : int

I want to write a NSPredicate which filters on EntityTwoObj.property1 when I perform it on an array which holds EntityOne objects.
Is it possible?
I have tried following:
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:
@"Property1 CONTAINS[cd] %@
OR Property2 CONTAINS[cd] %@
OR Property3.Property1 CONTAINS[cd] %@",
newString, newString, newString];

But it's not working.
If I removed the last filter, it's working fine then.

A: Thanks @Larm, I could solved it by adding ANY operator with my predicate.
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:
@"Property1 CONTAINS[cd] %@
OR Property2 CONTAINS[cd] %@
OR ANY Property3.Property1 CONTAINS[cd] %@",
newString, newString, newString];


text:
Q: Build the rewrite rule with specific path At first, I sorry to make the simple question but I really didn't know how to build the rule with my special path.
My project path is like:
www.example.com/cate/123456/guide/index.html
www.example.com/cate/123456/guide/001.html
www.example.com/cate/123456/guide/002.html
www.example.com/cate/123456/guide/003.html
www.example.com/cate/123456/guide/004.html
...and more

With 123456 is the category number, it will be changed automatically but the file structure inside will be same.
Now I have the mobile version:
www.example.com/cate/123456/guide/**m_index.html**
www.example.com/cate/123456/guide/m_001.html
www.example.com/cate/123456/guide/m_002.html
www.example.com/cate/123456/guide/m_003.html
www.example.com/cate/123456/guide/m_004.html
...and more

So my question is How can I redirect to m_*.html when access by mobile?
Ex:
index.html -> m_index.html
001.html -> m_001.html
...
Any suggest?

A: You can try this rule in your site root .htaccess:
RewriteEngine On

RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sony|symbian|nokia|samsung|mobile|windows ce|epoc|opera" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "mini|nitro|j2me|midp-|cldc-|netfront|mot|up\.browser|up\.link|audiovox"[NC,OR]
RewriteCond %{HTTP_USER_AGENT} "blackberry|ericsson,|panasonic|philips|sanyo|sharp|sie-"[NC,OR]
RewriteCond %{HTTP_USER_AGENT} "portalmmm|blazer|avantgo|danger|palm|series60|palmsource|pocketpc"[NC,OR]
RewriteCond %{HTTP_USER_AGENT} "smartphone|rover|ipaq|au-mic,|alcatel|ericy|vodafone\/|wap1\.|wap2\.|iPhone|android"[NC]
RewriteRule ^ - [E=MOBILE:1]

RewriteCond %{ENV:MOBILE} =1
RewriteRule ^(cafe/[\w-]+/guide)/?$ /$1/m_index.html [L,NC,R=301]

RewriteCond %{ENV:MOBILE} =1
RewriteRule ^(cafe/[\w-]+/guide)/(?!m_)([\w-]+\.html)$ /$1/m_$2 [L,NC,R=301]


text:
Q: Windows 10 registry settings for IP Address? Is there any specific Windows 10 process that triggers the assigning of an IP address? Which part of the registry is responsible for the IP address? I am currently using Windows 10 and I am looking at the
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Tcpip/Parameters/Interfaces section of the registry, and I am unsure of which processes are fully responsible for my public and and private IP address. Could somebody perhaps point me to the right registry entry/s or the right Windows files and possibly explain what they do? I'm looking to learn more about how Windows works with IP addresses.

A: You did right by looking at the "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces" key, for IPv4.  IPv6 looks like it uses a key called Tcpip6 in the middle of that, instead of just Tcpip.
Under there are keys related to interfaces.  It is possible to set a static address, and the address will be stored in one of those keys.  The name of the value will be IPAddress.  Other addresses include SubnetMask and DefaultGateway.  All of those are REG_MULTI_SZ.
However, those values may not exist.  If you have REG_DWORD named EnableDHCP set to 1, then they probably don't exist (or have an effect) if a DHCP server is provided.  In that case, it looks like the DHCP client, built into Microsoft Windows, will look for a DHCP server and then note which DCHP server it used a response from, storing that value in a REG_SZ value named DhcpServer.  Other REG_SZ values of DhcpIPAddress and DhcpSubnetMask, and a REG_MULTI_SZ named DhcpDefaultGateway may note the addresses that get used when DHCP is being used.

I am unsure of which processes are fully responsible for my public and and private IP address.

Typically your private IP address is assigned by DHCP.  Address that start with 169.254 typically indicate a DHCP failure (possibly caused by a failed DHCP server, or some sort of networking issue.)  Addresses that don't start with 127, 10, 192.168, or 172.16. through 172.31. are typically assigned by the ISP, and most commonly get used as the WAN address of a specialized computing device that is often called a "router" (or some other term, like "firewall", or "modem").
If you want to learn more about this type of topic, I suggest trying to read up on IP address, DHCP, static IP addresses, subnetting, host bits, the private IP address ranges, NAT, and port forwarding.  Those ought to be some terms that you can use to search for some educational material.  If you want to learn even more, you could look into study/training material for the CompTIA Network+, which should cover even more topics.  (It sounds like a single high quality book would teach you quite a lot about the topic.)  Colleges teach this type of material.  If you have further questions, please consider creating a new question (rather than just expanding this question).

A:
Is there any specific Windows 10 process that triggers the assigning
  of an IP address?

No, there is not. The computer's IP address is assigned by the router
to use inside your home network, and is received by Windows via the
DHCP protocol. If contact with a DHCP server is impossible,
Windows will typically assign itself the IP address of 169.254.0.1,
called an APIPA number.
Your router is assigned its external/public IP address by the Internet supplier,
again via DHCP.
For information how your internet supplier is assigned its own range of IP addresses, see
Internet Assigned Numbers Authority (IANA)
and also
How Are IP Addresses Assigned.

A:
I am unsure of which processes are fully responsible for my public and
  private IP address.

There are two issue here:
First: In most home setups the public IP address is handed out by your ISP. It is not configured from your computer.
Secondlyt, your local IP address, network mask, default gateway etc can be configured on your computer. Usually we call this a static IP. It is rare to see that ion home computers though. Most of the time it will be done via DHCP, which means that your computer asks the DHCP server (builnd into your SoHo 'router/modem/AP/server' for the nessecary information. It might store the last answer it got from that. I am not sure if that is in the registry or not though.


text:
Q: Session replication in Glassfish Cluster on EC2 I've built a cluster on Glassfish administred via SSH, where there are 2 instances. I deployed an application that shows the "Session id".
This application has in the web.config:
<distributable/>

And in the sun-web.xml:
<session-config>
    <cookie-properties>
         <property name="cookieDomain" value="compute.amazonaws.com"/>
    </cookie-properties>
</session-config>

I enabled "Availability" in Edit Application.
But when I access the 2 web app versions I see different session ids.
Can anyone help me?
EDIT: As some users noticed, in EC2 is not supported multicast. A solution comes with Glassfish v3.1.2, that allows two other different ways to discover a cluster when multicasting is not permitted (by listing instances ip or making it auto-generate the list). Here's specified how to start a cluster in a non-multicasting environment: Administering Glassfish Server Clusters

A: Read the High Availability Administration Guide for v3.1.2, specifically section "Discovering a Cluster When Multicast Transport Is Unavailable". Haven't tried it yet, but looking forward. Cheers!

A: First thing to try would be trying to validate if the multicast works on your your setup, use below asadmin command.
asadmin validate-multicast

You can checkout this simple Youtube Video about how to do that
http://www.youtube.com/watch?v=sJTDao9OpWA
In case Multicast does not work, you may want to try the non multicast option that is supported on Recent release of Glassfish 3.1.2
The release notes say that it supports non multicast clustering

New Support for non-Multicast clustering.  GlassFish High-Availability
  clustering is now possible in environments where multicast is
  disabled.

I was not able to find any documentation that provides steps for setting up the non Multicast cluster. There may be one for the enterprise support customers.

A: As some users noticed, in EC2 is not supported multicast. A solution comes with Glassfish v3.1.2, that allows two other different ways to discover a cluster when multicasting is not permitted (by listing instances ip or making it auto-generate the list). Here's specified how to start a cluster in a non-multicasting environment: Administering Glassfish Server Clusters


text:
Q: Is this possible to document(word) transfer by using SOAP or XML_RPC? HI All,
Now i want to send a file(c# Client) to server using SOAP.but i dont know whether it is possible to send file by using SOAP.Does anybody having knowledge about file transfer using SOAP or any other for example XML-RPC, please send me your  thoughts...
Thanks & Regards,
P.SARAVANAN.

A: The easiest way is to read the file (e.g. file_get_contents()), encode it in some way (e.g. base64_encode()) and pass it to the SOAP or XML-RPC call as a parameter. Example:
$soap = new SoapClient('url/to/your.wsdl');
$soap->upload(base64_encode(file_get_contents('file/to/upload')));

This, of course, assumes a SOAP server that has a method called upload that accepts base64_encoded files.


text:
Q: how to direct to another php page i want to direct user to another page after succesful login. below is my code. how to resolve this?

$result = mysqli_query($mysqli, $query);
 //$result = mysqli_multi_query($mysqli, $query);
$data = mysqli_fetch_array($result);

$data= var_dump($data);
echo $data;

if($data != "NULL"){

  header("Location:home2.php");
}
else {
 echo "sorry" ;
}

A: Remove
$data= var_dump($data);
echo $data;

and you will be redirected.
If you echo anything before to use header this function does not work.


text:
Q: Macro to Insert VBA code automatically from Personal.xlsb to one predefined sheet of my activeworkbook I just wonder if there is way to run a macro from Personal.xlsb in order to insert code in the Sheet3(stack) of my active workbook and run the code.
The code that I would like to insert in the Sheet3(stack) of my active workbook is the following one:
Const FontSize As Integer = 12
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
LargeSize = FontSize * 1.2
With Cells.Rows
       .Font.Size = FontSize
       .Interior.Color = xlNone
End With
With Target.EntireRow
        .Font.Size = LargeSize
        .Interior.Color = 49407
End With
End Sub

Thanks in advance for your help.


text:
Q: Implementing pipe in my own shell with two child process I'm writing my own shell. Below is part of it. I want to implement pipe with two child processes.
But when I execute below code, some commands work, some don't. 'who | sort', 'ls | sort' work but 'll | sort', 'cat file | sort' make my shell stop. I have to 'cntrl + c' to escape from my shell. I don't understand why some commands work and some don't. Please somebody point out what I'm missing?
int pipefd[2];
int pipePos = checkPipePos(argc, argv); //find '|' command position in argv

if (pipe(pipefd) == -1) {
        printf("Creating pipe failed\n");
        return;
    }

    if (fork() == 0) {
        close(pipefd[0]);
        dup2(pipefd[1], 1);
        execlp(argv[0], argv[0], NULL);
    }

    if (fork() == 0) {
        close(pipefd[1]);
        dup2(pipefd[0], 0);
        execlp(argv[pipePos + 1], argv[pipePos + 1], NULL);
    }

    close(pipefd[0]);
    close(pipefd[1]);

    while (wait(NULL) >= 0);

A: I see one possible problem here, which may or may not explain the non-deterministic results.
In your child process, after you're dup-ing one of the pipe's file descriptor, you're not closing the original ones.
dup2(oldfd, newfd) duplicates oldfd onto newfd, but oldfd is still open. Both oldfd and newfd file descriptors now point to the same file. See the dup2 man page.
Typically, aftering dup2()-ing a file descriptor, you'll want to close() the oldfd.
So, what's going to happen here is that one of the child processes will have the same file descriptor on stdout and on some other, random file descriptor, and the other child process will have the same situation with stdin.
This may or may not cause a problem, depending on what the child process does. Can't really say for sure, but you'll definitely want to fix this, and see if it helps.

A: Your pipe logic is correct.
ll | sort doesn't work because ll is not a executable file.
cat file | sort doesn't work because you are not passing the file argument.
Sam Varshavchik's improvement is valid. It's a good-to-fix, but it won't cause any serious problem. All it causes is wasting one more file descriptor slot.


text:
Q: Ext filesystem: what happens if a journal is replayed after a crash I read some things about the ext filesystem journaling, including the man pages, but still do not fully grasp the mechanism.
What exactly happens with data and metadata when replaying a journal with e2fsck after a crash?
What is different if the journal_data option is enabled?
Are there differences between ext3 and ext4?

A: There is quite a detailed paper on the implementation of the journal layer:
http://e2fsprogs.sourceforge.net/journal-design.pdf


text:
Q: Combining mayavi and matplotlib in the same figure I will be making animations. In each frame I want to contain both a mayavi plot obtained with
mlab.pipeline.iso_surface(source, some other superfluous args)

and a matplotlib plot obtained using simply
pylab.plot(args)

I have scripts to do both separately, but have no idea how to go about combining them into one figure. I want the end product to be one script which contains the code from both the scripts that I currently have.

A: AFAIK, there is no direct way because the backends used are so different. It does not seem possible to add matplotlib axes to mayavi.figure or vice versa.
However, there is a "kind of a way" by using the the mlab.screenshot.
import mayavi.mlab as mlab
import matplotlib.pyplot as plt

# create and capture a mlab object
mlab.test_plot3d()
img = mlab.screenshot()
mlab.close()

# create a pyplot
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.plot([0,1], [1,0], 'r')

# add the screen capture
ax2 = fig.add_subplot(122)
ax2.imshow(img)
ax2.set_axis_off()

This is not necessarily the nicest possible way of doing things, and you may bump into resolution problems, as well (check the size of the mayavi window). However, it gets the job done in most cases.

A: Adding to the answer by DrV which helped me a great deal, you can work with the mlab figure to set resolution before screenshot such as with batch plotting:
mfig = mlab.figure(size=(1024, 1024))
src = mlab.pipeline.scalar_field(field_3d_numpy_array)
mlab.pipeline.iso_surface(src)
iso_surface_plot = mlab.screenshot(figure=mfig, mode='rgba', antialiased=True)
mlab.clf(mfig)
mlab.close()

# Then later in a matplotlib fig:
plt.imshow(iso_surface_plot)


text:
Q: Opencv plane detection with AR marker Say I have an aruco on a table, how can I place an object (say image) on the table using the aruco to calculate the table plane. I don't want to place the object on the aruco, but rather on the same plane (like next to it, before it (closer to the viewer) etc).
Assume I know how to detect the aruco corners. It's the perspective transform to another table location I'm looking.
-- EDIT --
Adding sample image of what I am trying to achieve:
(please ignore my bad photoshop skills)

Now I know I can use opencv perspective transform between the business card to the aruco detected corners, but wouldn't that distort the b-card to be square? how can I calculate the "correct" destination coords of the b-card on the table? so I would use them in getPerspectiveTransform (and not the aruco corners).

A: if you are trying to place a 3D object next to the aruco code, just place the object center like (0,1,0) in the world, aruco assume the marker center as world origin aruco world origin, and use the rt transfrom from pose estimated(solvepnp) as the world to camera transform in your 3D rendering setup like opengl, ogre or Unity3D. dont forget to adjust your camera with the calibrated parameters with the real camera you captuer image. that's not easy if you are not familiar with 3D rendering things, but I believe that you can find some code or even plugins for Unity3D.
if you are trying to place a 2D image, next to the aruco code, there is an easier, "not so 3D" way. with the 4 detected corner points in 2D origin image space, cv::aruco::detectMarkers(image, dictionary, corners, ids); you can get the perspective transform from the image you want to puts in, to origin source image with the marker, Mat cv::getPerspectiveTransform (   InputArray  src, InputArray  dst, int     solveMethod = DECOMP_LU  )   . then you can apply  this perspective transform to the image you wants to put in with cv::warpPerspective (InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar &borderValue=Scalar()). the overlay this to the original image.
if you want something like, next to the marker, just project points like (1,1,0) to the 2D image with rt transform from pose estimation. and replace the 4 2D points.


text:
Q: Update the grid when using registration form (WebUserControl) open in apopup i have a grid view on a page and i have webusercontrol which contains the registration for and this usercontrol open in a popup and when i click finish submit of registration this will add the new entry in database. but my grid still show previos records untill i refresh the page . so how can i rebind the grid on click of Submit button of user control?
thanks

A: You need to refresh parent page on popup window closing.
This link would be help. Closing-child-pop-up-and-refreshing-parent-page
Or you can check the javascript code below.
function refreshParent() {

  window.opener.location.href = window.opener.location.href;
  if (window.opener.progressWindow)
  {
    window.opener.progressWindow.close()
  }
  window.close();

}


text:
Q: Splitting dataframe column items and counting them in Pandas/Python I have a dataframe with a column called 'Name' that contains ordered items. Here is an example of what the data inside the column looks like:

I want to split each cell so that I can get a list of unique items ordered or split the contents of each cell and for each menu item += 1 to the counter.
I cannot seem to figure out how to go about splitting the cell contents to append them to a list so that I can then run a for loop of some kind and find out the unique count for each item.

A: IIUC, you can try:
df1 = (df['Name'].str.split(', ').explode().to_frame('Items')
                 .reset_index().assign(Count=1)
                 .pivot_table(index='index', columns='Items',
                              values='Count', aggfunc='sum', fill_value=0))

out = pd.concat([df, df1], axis=1)

Output:
>>> out
            Name  A  B  C  D  E  F
0  A, B, C, D, A  2  1  1  1  0  0
1     B, C, E, C  0  1  2  0  1  0
2  A, F, D, C, A  2  0  1  1  0  1


text:
Q: ffmpeg take long time for creating video from images I am trying to create video from images.
but it takes too much time if I select more than 10 images.
Can anybody help me to resolve this problem.
I am using the following command:
ffmpeg -y -r 1/5 -i frame_%05d.jpg -c:v libx264 -r 30 video.mp4;

Thanks in advance.

A: Ok try to make the change to your command like this.
ffmpeg -y -r 1/5 -i img%03d.jpg -strict experimental -vcodec libx264 -preset ultrafast -crf 30 out.mp4";

I tried this and it took just 3 seconds to execute the command for 30 images (size 10kb each ) which is pretty fast. You even can reduce this time by changing -crf to a lower number.
Cheers. :)


text:
Q: Из потока читаются не все данные Вопрос следующий. Клиент пишет в поток строку байт. Сервер её принимает. Но принимает он только часть, т.е. часть байт в конце строки просто пропадает куда-то.
Объект потока - NetworkStream stream = null; и NetworkStream clientStream;. Количество байт, которое пишется и читается одинаковое. В чем тут ошибка?
Функция отправки запроса (клиент):
public int SendRequest(string command, EditorForm data)
{
    ConstructRequest(command, data);

    stream.Write(Encoding.UTF8.GetBytes(request), 0, request.Length);
    return 0;
}

Функция приёма запроса (сервер):
public string RecieveRequest()
        {
            StringBuilder builder = new StringBuilder();
            byte[] buffer = new byte[64];

            int countBytes = 0;
            do
            {
                countBytes = clientStream.Read(buffer, 0, buffer.Length);
                builder.Append(Encoding.UTF8.GetString(buffer, 0, countBytes));
            }
            while (clientStream.DataAvailable);
            data = builder.ToString();

            DistructRequest();

            return data;
        }


text:
Q: Why do files in /proc/self end up being owned by root if a program has its setuid bit set? I have this small program:
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <sys/prctl.h>

extern char **environ;

int main()
{
   char * const arglist[] = { "/bin/ls", "-l", "/proc/self/maps", NULL };
   uid_t uid, euid, suid;
   gid_t gid, egid, sgid;

   getresuid(&uid, &euid, &suid);
   printf("Before: uid: %u, euid: %u, suid: %u\n", uid, euid, suid);
   uid = euid;
   setresuid(uid, euid, suid);
   getresuid(&uid, &euid, &suid);
   printf(" After: uid: %u, euid: %u, suid: %u\n", uid, euid, suid);

   getresgid(&gid, &egid, &sgid);
   printf("Before: gid: %u, egid: %u, sgid: %u\n", gid, egid, sgid);
   gid = egid;
   setresuid(gid, egid, sgid);
   getresuid(&gid, &egid, &sgid);
   printf(" After: gid: %u, egid: %u, sgid: %u\n", gid, egid, sgid);

   printf("Get result == %d\n", prctl(PR_GET_DUMPABLE, 0, 0, 0, 0));
   printf("Set result == %d\n", prctl(PR_SET_DUMPABLE, 1, 0, 0, 0));
   printf("Get result == %d\n", prctl(PR_GET_DUMPABLE, 0, 0, 0, 0));

   if (fork())
   {
      return 0;
   }
   execve(arglist[0], arglist, environ);
}

I compile this program into an executable named small-test and change it's ownership to a testing user:
[omnifarious@foohost ~]$ ls -l small-test
-rwxrwxr-x. 1 testing testing 8512 Oct 23 12:55 small-test

Then I run the program:
[omnifarious@foohost ~]$ ./small-test
Before: uid: 1001, euid: 1001, suid: 1001
 After: uid: 1001, euid: 1001, suid: 1001
Before: gid: 1001, egid: 1001, sgid: 1001
 After: gid: 1001, egid: 1001, sgid: 1001
Get result == 1
Set result == 0
Get result == 1
-r--r--r--. 1 hopper hopper 0 Oct 23 14:50 /proc/self/maps

So far, so good. Then I do this:
[omnifarious@foohost ~]$ sudo chmod ug+s ./small-test
[omnifarious@foohost ~]$ ls -l ./small-test
-rwsrwsr-x. 1 testing testing 8512 Oct 23 12:55 ./small-test
[omnifarious@foohost ~]$ ./small-test
Before: uid: 1001, euid: 1002, suid: 1002
 After: uid: 1002, euid: 1002, suid: 1002
Before: gid: 1001, egid: 1002, sgid: 1002
 After: gid: 1002, egid: 1002, sgid: 1002
Get result == 0
Set result == 0
Get result == 1
-r--r--r--. 1 root root 0 Oct 23 12:59 /proc/self/maps

Why does /proc/self/maps end up being owned by root instead of by testing or omnifarious? Note that the result does not change if I remove the fork.
The reason this is vexing me is that I need create a program that puts itself in a namespace as a user other than the one that executed it. This is so that I don't have access to cgroups and other things owned by the user that started the program. But I'm not being allowed to write to the program's uid_map or gid_map and so I can't set up the namespace properly.
Note: I edited this question to include a call to prctl to set (and read) the DUMPABLE flag as an answer (and the manual) indicated that resetting this should fix the owner on /proc/self/* files. It didn't, as you can see by the new program.
Edit: The above program has a bug in which it is calling setresuid instead of setresgid. This is what caused my problem even after adding the call to prctl. The prctl(PR_SET_DUMPABLE, 1); call has no effect if the real and effective group and user ids of the process are not the same.

A: Any suid process will default to have its /proc/self directory owned by root for security reasons (to prevent users from inducing a core dump and inspecting its memory for valuable info).
You can set the owner after a suid by manually making the process dumpable with the prctl PR_SET_DUMPABLE.

Here's proc(5), containing a description of what's going on and how to affect it:
   /proc/[pid]
          There is a numerical subdirectory for each running
          process; the subdirectory is named by the  process
          ID.

          Each /proc/[pid] subdirectory contains the pseudo-
          files  and  directories  described  below.   These
          files are normally owned by the effective user and
          effective group ID of the process.  However, as  a
          security  measure, the ownership is made root:root
          if the process's "dumpable" attribute is set to  a
          value other than 1.  This attribute may change for
          the following reasons:

          *  The  attribute  was  explicitly  set  via   the
             prctl(2) PR_SET_DUMPABLE operation.

          *  The  attribute  was  reset  to the value in the
             file   /proc/sys/fs/suid_dumpable    (described
             below), for the reasons described in prctl(2).

          Resetting  the  "dumpable"  attribute to 1 reverts
          the ownership of the /proc/[pid]/*  files  to  the
          process's real UID and real GID.

Below, suid_dumpable has this to say about why the default is what it is:
          1 ("debug")
                 All  processes  dump  core  when  possible.
                 (Reasons  why  a process might nevertheless
                 not dump core are  described  in  core(5).)
                 The  core  dump  is owned by the filesystem
                 user ID of the dumping process and no secu‐
                 rity is applied.  This is intended for sys‐
                 tem debugging situations only: this mode is
                 insecure  because  it  allows  unprivileged
                 users to examine  the  memory  contents  of
                 privileged processes.

And as a bonus, prctl(2) lists non-suid circumstances that affect dumpability:
   PR_SET_DUMPABLE (since Linux 2.3.20)
          (...)
          Normally,  this  flag is set to 1.  However, it is
          reset to the current value contained in  the  file
          /proc/sys/fs/suid_dumpable  (which  by default has
          the value 0), in the following circumstances:

          *  The process's effective user  or  group  ID  is
             changed.

          *  The  process's  filesystem  user or group ID is
             changed (see credentials(7)).

          *  The process executes (execve(2)) a  set-user-ID
             or  set-group-ID program, resulting in a change
             of either the effective user ID or  the  effec‐
             tive group ID.
          (...)


text:
Q: Use function in a controller inside a folder that is defined in subfolder Controllers Ok, guys, this is the case...
I am working in an old porject made it with CodeIgniter v2 (currently all is in localhost). For new features I created a folder called v1 inside the api folder
The structure of the project:

controllers

api

v1

visit.php
orders.php

controller1.php
controller2.php

The problem is that I can not access to the visit.php controller
to test purposes I set the visit controller in the api folder an access it whit this:
localhost/projectname/index.php/api/visit/visits

visits is the function in the visit controller

With this way everything works!! but, when I set the visit controller in the v1 folder I get a 404 page not found error.
localhost/projectname/index.php/api/v1/visit/visits

Extra
Another think that have keep in mind is. This project is using a library to the REST API so, in the visit controller are tho functions
public function visits_get(){
  // return an arrays of visits
}

public function visits_post(){
  // to add a new visit in a bd
}

So, the function will be called depends on the request method
I have been reading and I found that I have to configure the route.php, actually I did it but without success.
Thanks and I hope you understand what I am asking!
ROUTE.php
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$route['default_controller'] = "welcome";
$route['404_override'] = '';

This is all that the route.php has in it ._.

A: To my knowledge, any controllers falling outside the application/controllers/controller_name.php naming convention need to be explicitly defined inside the routes.php file, otherwise CI will not look inside subfolders. It's not much of a problem, actually, add something like this for your controllers:
//You'll need to do this for all of your API controllers, unfortunately
$route['api/v1/(:any)'] = 'api/v1/$1';
//If you have controllers taking arguments, eg. /api/v1/stuff/1
$route['api/v1/(:any)/(:any)'] = 'api/v1/$1/$2';

//Catch-all route for 404's, recommended
$route['api/(:any)'] = 'api/v1/error_api';

Have a look at the routing docs for CodeIgniter 2 for more info.


text:
Q: 403 forbidden error when crawling a website using python requests on Heroku I have written a crawler script that sends a post request to "sci-hub.do" and i've set it up running on Heroku . But when it tries to send a post or get request, i mostly get 403 forbidden message.
Strange thing is that this only happens when that script is running on Heroku cloud and when i run it on my PC it's all good and i get the 200 status code.
I have tried using a session but it did not work.
I also checked robots.txt of that website and set a User-Agent header to "Twitterbot/1.0" but it still failed.
What am i doing wrong? Why is it only happening when the script is running on Heroku.
I'm pretty sure that the webserver is detecting my script as a crawler bot and tries to block it. But why even after adding a proper "User-agent"?

A: Try to add a usual User Agent like:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36

Maybe you will need to use a random User-Agent for every request. Then you can install and use https://pypi.org/project/fake-useragent/


text:
Q: ¿Como puedo obtener una barra de rutas en eclipse? ¿Como puedo obtener la barra que se ve en la imagen en eclipse?

A: Se llaman breadcrumbs y la barra aparece dando click derecho al código y despues show in breadcrumbs


text:
Q: Getting different LRC (Long Range Checksum) result I'm trying to send a request to a TCP/IP terminal. My LRC function as below:
public byte GetLRC(byte[] bArr)
    {
        byte LRC = 0x00;
        foreach (byte b in bArr)
        {
            LRC ^= b;
        }
        return LRC;
    }

But the problem is my LRC and their sample LRC are totally different. How can they calculate this?
My message data request is almost the same as their except the LRC.
Sample data:
Hex: 0 66  30  30  30  30  30  30  30  30  32  34  31  30  33  30  30  31  30  1C  54  32  0   2   30  31  1C  34  33  0   1   30  1C  34  30  0   12  30  30  30  30  30  30  30  30  30  30  30  31  1C  34  32  0   12  30  30  30  30  30  30  30  30  30  30  30  30  1C  79
Bytes:
{byte[68]}
[0]: 0
[1]: 102
[2]: 48
[3]: 48
[4]: 48
[5]: 48
[6]: 48
[7]: 48
[8]: 48
[9]: 48
[10]: 50
[11]: 52
[12]: 49
[13]: 48
[14]: 51
[15]: 48
[16]: 48
[17]: 49
[18]: 48
[19]: 28
[20]: 84
[21]: 50
[22]: 0
[23]: 2
[24]: 48
[25]: 49
[26]: 28
[27]: 52
[28]: 51
[29]: 0
[30]: 1
[31]: 48
[32]: 28
[33]: 52
[34]: 48
[35]: 0
[36]: 18
[37]: 48
[38]: 48
[39]: 48
[40]: 48
[41]: 48
[42]: 48
[43]: 48
[44]: 48
[45]: 48
[46]: 48
[47]: 48
[48]: 49
[49]: 28
[50]: 52
[51]: 50
[52]: 0
[53]: 18
[54]: 48
[55]: 48
[56]: 48
[57]: 48
[58]: 48
[59]: 48
[60]: 48
[61]: 48
[62]: 48
[63]: 48
[64]: 48
[65]: 48
[66]: 28
[67]: 121

My data:
0   66  30  30  30  30  30  30  30  30  32  34  31  30  33  30  30  31  30  1C  54  32  0   2   30  31  1C  34  33  0   1   30  1C  34  30  0   12  30  30  30  30  30  30  30  30  30  30  30  31  1C  34  32  0   12  30  30  30  30  30  30  30  30  30  30  30  30  1C  1F

{byte[68]}
[0]: 0
[1]: 102
[2]: 48
[3]: 48
[4]: 48
[5]: 48
[6]: 48
[7]: 48
[8]: 48
[9]: 48
[10]: 50
[11]: 52
[12]: 49
[13]: 48
[14]: 51
[15]: 48
[16]: 48
[17]: 49
[18]: 48
[19]: 28
[20]: 84
[21]: 50
[22]: 0
[23]: 2
[24]: 48
[25]: 49
[26]: 28
[27]: 52
[28]: 51
[29]: 0
[30]: 1
[31]: 48
[32]: 28
[33]: 52
[34]: 48
[35]: 0
[36]: 18
[37]: 48
[38]: 48
[39]: 48
[40]: 48
[41]: 48
[42]: 48
[43]: 48
[44]: 48
[45]: 48
[46]: 48
[47]: 48
[48]: 49
[49]: 28
[50]: 52
[51]: 50
[52]: 0
[53]: 18
[54]: 48
[55]: 48
[56]: 48
[57]: 48
[58]: 48
[59]: 48
[60]: 48
[61]: 48
[62]: 48
[63]: 48
[64]: 48
[65]: 48
[66]: 28
[67]: 31


text:
Q: Text To Speech - Custom Rate (not on the slider) In System Preferences, under Dictation & Speech, there is a Speaking Rate setting:

Is there a way to change the Speaking Rate to a value that is not on that slider bar?
For example, if I want the speech rate to be faster than the maximum slider value, how can I do that? There's a way to make the terminal speak certain lines of text faster (e.g. say --rate 500 "hello world"), but I'd like it to be the system-wide setting.
Can this be set using something like default write com.example.apple.speech.rate 999?

A: I discovered that you can change the VoiceDataRateArray in ~/Library/Preferences/com.apple.speech.voice.prefs.plist
I just changed the value of Item 2 to a value of value 500 and rebooted.
Thanks to tyler over at https://groups.google.com/forum/#!topic/macvisionaries/HOR7NWxsDQA

A: Just to add to the two existing answers, I'd add that you can also do the activity monitor commands in terminal, so you can skip a ton of steps. Doesn't seem like you even need to enter the code separately.
plutil -convert json ~/Library/Preferences/com.apple.speech.voice.prefs.plist -o - | python -c 'import json, sys;d=json.load(sys.stdin);[x.__setitem__(-1, 720) for x in d["VoiceRateDataArray"]];json.dump(d, sys.stdout)' | plutil -convert binary1 -o ~/Library/Preferences/com.apple.speech.voice.prefs.plist -

killall com.apple.speech.speechsynthesisd
killall SpeechSynthesisServer

A: Thanks to this thread and others, I've cobbled together a bash.sh solution that enables you to change the value quickly via terminal.
check it out! https://github.com/insasquatchcountry/TTSpeed
In the README.md is a copy/past install script for people like me who aren't very shell savvy.

A: Adding to user3621156's answer, change each of the Item 2 values to 500.
If you don't want to reboot, you can open Activity Monitor, search for speech and force quit each of the matching processes under your username. Then, open speech settings and toggle the shortcut key and the next time you use it it should be faster.


text:
Q: Como calcular a MODA com valor bimodal em um data.frame no R? Preciso calcular a MODA dos valores em linha em um data.frame. Como no R não existe uma função já definida para MODA, usei uma função customizada:
moda = function(x) {
  z = table(as.vector(x))
  names(z)[z == max(z)]
}

teste1 = moda(c(1,2,3,4,5,5,5))

print(teste1)
[1] 5

A função moda funciona muito bem por sinal, agora vamos para um outro caso:
teste2 = moda(c(1,1,1,2,3,4,5,5,5))

    print(teste2)
    [1] "1" "5"

No teste2, o vetor possui valor bimodal e a função moda exibe dois valores. Agora vamos para o terceiro caso usando um data.frame:
print(DADOS)

 Linha  A   B   C   D   E
 L1     4   3   2   1   4
 L2     1   11  1   1   1
 L3     0   1   2   2   4
 L4     2   0   0   8   0

Neste caso vou ter que criar mais uma coluna com valores de cada linha calculados pela MODA:
DADOS = DADOS %>%
rowwise() %>%
mutate(MODA = moda(c(A,B,C,D,E)))

print(DADOS)

 Linha  A   B   C   D   E  MODA
 L1     4   3   2   1   4   4
 L2     1   11  1   1   1   1
 L3     0   1   2   2   4   2
 L4     2   0   0   8   0   0

Funcionou perfeitamente, porém chegamos na "situação problema". Neste último caso vou usar um data.frame diferente:
print(DADOS_2)

Linha  A   B   C   D   E
L1     4   3   2   2   4
L2     1   11  1   1   1
L3     0   1   2   3   4
L4     2   0   0   8   0

Como no caso anterior vou ter que criar mais uma coluna com valores de cada linha calculados pela MODA:
DADOS_2 = DADOS_2 %>%
rowwise() %>%
mutate(MODA = moda(c(A,B,C,D,E)))

print(DADOS_2)

Error: Column `MODA` must be length 1 (the group size), not 2

O R me exibe a mensagem de erro, porque na base DADOS_2 a linha L1 traz um exemplo claro de valor bimodal L1=(4,3,2,2,4). E por se tratar de um valor bimodal, o R não consegue atribuir dois valores em uma coluna só.
O que devo fazer nesse caso? Como posso calcular a MODA em linha com valor bimodal em um data.frame?

A: Você pode solucionar este problema com tidyverse. Antes, crio um exemplo reprodutível:
data <- data.frame(
  a = c(1, 2, 2, 7, 3),
  b = c(2, 2, 1, 1, 2),
  d = c(1, 3, 2, 2, 3),
  e = c(2, 3, 1, 2, 2)
)

Vou usar a função que você criou:
moda = function(x) {
  z = table(as.vector(x))
  names(z)[z == max(z)]
}

Segue o código:
library(tidyverse)

res <- data %>%
  mutate(my_mode_1 = pmap(., lift_vd(moda))) %>%
  mutate_if(is.list, as.character) %>%
  mutate(my_mode_2 = str_remove_all(string = my_mode_1, pattern = '[(),c"]')) %>%
  separate(col = my_mode_2, sep = ' ',
       into = c('mode_1', 'mode_2', 'mode_3'), fill = 'right') %>%
  mutate_at(c('mode_1', 'mode_2', 'mode_3'), as.numeric) %>%
  select(- my_mode_1)

res

  a b d e mode_1 mode_2 mode_3
1 1 2 1 2      1      2   <NA>
2 2 2 3 3      2      3   <NA>
3 2 1 2 1      1      2   <NA>
4 7 1 2 2      2     NA   <NA>
5 3 2 3 2      2      3   <NA>

Dois pontos:

*

*Na linha 4 há apenas uma moda. Por isso, em mode_2, não existe valor.

*Note que criei, propositalmente, uma coluna adicional. Pois, se existissem 3 modas, a terceira seria ali alocada. Mas, nada te impede de remover esta coluna com um select.


text:
Q: how to select kendo-drop down in selenium webdriver using python or java in kendo dropdown, I get only class name can't get other elements from inspect element so what should I do
I get only this fields by inspecting element
Shardul Patel

A: Use keyboard keys in selenium to move up and down to select the kendo drop down values.
Actions action = new Actions(driver);
action.sendkeys(keys.DOWN).build().perform();

Use with your webelement and get the desired results. Do let me know in case of any concerns.


text:
Q: Date since 1600 to NSDate? I have a date that's stored as a number of days since January 1, 1600 that I need to deal with. This is a legacy date format that I need to read many, many times in my application.
Previously, I'd been creating a calendar, empty date components and root date like this:
self.gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar
                    ] autorelease];
id rootComponents = [[[NSDateComponents alloc] init] autorelease];
[rootComponents setYear: 1600];
[rootComponents setMonth: 1];
[rootComponents setDay: 1];
self.rootDate = [gregorian dateFromComponents: rootComponents];
self.offset = [[[NSDateComponents alloc] init] autorelease];

Then, to convert the integer later to a date, I use this:
[offset setDay: theLegacyDate];
id eventDate = [gregorian dateByAddingComponents: offset
                                          toDate: rootDate
                                         options: 0];

(I never change any values in offset anywhere else.)
The problem is I'm getting a different time for rootDate on iOS vs. Mac OS X. On Mac OS X, I'm getting midnight. On iOS, I'm getting 8:12:28. (So far, it seems to be consistent about this.) When I add my number of days later, the weird time stays.

OS       | legacyDate | rootDate                  | eventDate
======== | ========== | ==========================|==========================
Mac OS X | 143671     | 1600-01-01 00:00:00 -0800 | 1993-05-11 00:00:00 -0700
iOS      | 143671     | 1600-01-01 08:12:28 +0000 | 1993-05-11 07:12:28 +0000

In the previous release of my product, I didn't care about the time; now I do. Why the weird time on iOS, and what should I do about it? (I'm assuming the hour difference is DST.)
I've tried setting the hour, minute and second of rootComponents to 0. This has no impact. If I set them to something other than 0, it adds them to 8:12:28. I've been wondering if this has something to do with leap seconds or other cumulative clock changes.
Or is this entirely the wrong approach to use on iOS?

A: I imagine you're right about the leap seconds/cumulative clock changes accounting for the time issue. Are the dates you're dealing with actually in the past, or is it purely an arbitrary epoch?
In either case, you could try defining a new epoch that's much closer to present day (say, the Cocoa epoch). Calculate a day delta between the new epoch and the old and save it as a constant. When you need to process a date, apply this delta to the date and then use your existing NSCalendar technique, but with your new epoch instead of the old. That will hopefully avoid the clock drift issue you're seeing.

A: It looks like the right answer is to make things simpler. Instead of making a rootDate, I just build the date from components every time. This should be no slower, and is still keeps the code really close to the idea.
Initial setup:
self.gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar
                    ] autorelease];
self.components = [[[NSDateComponents alloc] init] autorelease];
[components setYear: 1600];
[components setMonth: 1];

(Obviously, properties and ivars are adjusted.)
Later, to actually convert a legacy date to a NSDate:
[components setDay: 1 + theLegacyDate];
id eventDate = [gregorian dateFromComponents: components];

This has these advantages for me:

*

*It users fewer ivars.

*It's less code.

*It always returns midnight on that day, regardless of whether DST is in effect.

A: Note that iOS takes into account very obscure rules for various time zones. It is most likely that midnight, Jan 1st. 1600 in your timezone actually was at 7:12:28 UTC. There have been many cases where people complained about bugs in date conversions and then someone figured out that actually they are in a time zone that made some strange calendar change many years ago.
You need to find out first what exact NSDate your data represents. "Number of days since Jan 1st 1600" is nonsense, because you need a time zone! What you should do: Find a "legacy" number where you know what day it is supposed to represent. For example, if you "know" that 143671 is supposed to be 11th May 1993 in your time zone, then start with that date as the root date and add (x - 143671) days to it.


text:
Q: Composer in Alpine Docker PHP Fatal error UPDATE: php-curl extension was causing Segmentation Fault.
I am running docker pipelines with alpine 3.15 and PHP 7.0 and 7.1 on an ARM64.
I install composer using
COPY --from=composer:latest  /usr/bin/composer /usr/bin/composer

Since yesterday, 5th of April, all pipelines fail with the following error:

PHP Fatal error:  Declaration of Composer\IO\BaseIO::hasAuthentication($repositoryName) must be compatible with Composer\IO\IOInterface::hasAuthentication(string $repositoryName) in phar:///usr/bin/composer/src/Composer/IO/BaseIO.php on line 20

I tried using older versions of composer, but on all them I get:

Segmentation fault

This was working fine for the past 6 months. So something changed recently on the composer builds.
I also tried running on Intel and to install the composer the classical way, however, I also get the same errors.

A: You are installing composer:latest, which as of today will install Composer 2.3. And you are doing it on PHP 7.0 and PHP 7.1.
Those PHP versions are no longer supported by Composer 2.3 (nor by PHP, for what it's worth).

As announced in the 2.2 release notes, Composer 2.3 increases the required PHP version to >=7.2.5 and thus stops supporting PHP 5.3.2 - 7.2.4. The 2.2 LTS is still there for users stuck on older PHP versions.

Your options are:

*

*Upgrade PHP so use something supported. If you have to remain in v7, you can at least upgrade to PHP 7.4

*Use an older version of composer. Instead of an unconstrained "latest" tag, point to a specific one you know it's supported.

You can try with version 2.2, which I think should work. If not, keep going backwards until you find one that works with your stack.
COPY --from=composer:2.2  /usr/bin/composer /usr/bin/composer

This WON'T work:
FROM php:7.1-cli-alpine

COPY --from=composer:2.3  /usr/bin/composer /usr/bin/composer

RUN mkdir /someproject
WORKDIR /someproject

RUN composer create-project symfony/skeleton .

But this will:
FROM php:7.1-cli-alpine

COPY --from=composer:2.2  /usr/bin/composer /usr/bin/composer

RUN mkdir /someproject
WORKDIR /someproject

RUN composer create-project symfony/skeleton .


text:
Q: Tick/Draw Method I'm looking for the Tick and draw method, and I'm not sure where they are. Do I have to make them from scheduler, if so how?
I've heard that the draw method is only called 4 frames per second when 'paused', so does it exist somewhere?

A: Well. The draw method is called when needed by the framework. You just need to create the method and draw what you need there.
-(void)draw{

    // Draw stuff

}

The tick method is were all you calculations should be. Not in the draw method. Here's an example of how to init the schedule of a tick method. Place it in the init method.
[self schedule: @selector(tick:) interval:1.0/30.0];

-(void) tick: (ccTime) dt
{

  // Do calculations

}

A: From Cocos docs:

'tick' the scheduler. You should NEVER call this method, unless you know what you are doing.

As for draw, the method is called on each CocosNode to draw its contents. From the docs again:

override this method to draw your own node.

Draw will be called if your node needs drawing, and if so, as many times as your refresh rate is set to. You can override draw in your nodes to do custom OpenGL drawing for instance, or to alter the way a CocosNode is drawn.


text:
Q: i want to toggle between two functions this code works only one time but i want to make it work each time i click let callOne = true;
let hamburger = document.getElementById("hamburger");

hamburger.addEventListener("click", (e) => {toggleFct();});

function one() {t1.play();callOne = false;}

function two() {t0.play(); callOne = true;}

function toggleFct() { callOne ? one() : two();}

let t1 = gsap.timeline({ paused: true, reversed: true });
t1.to(".div-first", { ease: "power2.in", x: "-200%", duration: 2 });
t1.to(".div-second", { ease: "power2.in", x: "-300%", duration: 2 },"-=2");
t1.to(".div-third", { ease: "power2.in", x: "-400%", duration: 2 }, "-=2");
t1.to(header, { ease: "power2.in", x: "-400%", duration: 2 }, "-=2");
t1.to(wrap, { ease: "power2.in", x: "-400%", duration: 2 }, "-=2");
let t0 = gsap.timeline({ paused: true, reversed: true });
t0.to(".div-first", { ease: "power2.in", x: "100%", duration: 2 });
t0.to(".div-second", { ease: "power2.in", x: "200%", duration: 2 }, "-=2");
t0.to(".div-third", { ease: "power2.in", x: "300%", duration: 2 }, "-=2");
t0.to(header, { ease: "power2.in", x: "400%", duration: 2 }, "-=2");
t0.to(wrap, { ease: "power2.in", x: "0%", duration: 2 }, "-=2");

A: let callOne = true;
let hamburger = document.getElementById("hamburger");
hamburger.addEventListener("click", (e) => {toggleFct();});
function one() {t1.play(0);callOne = false;}
function two() {t0.play(0); callOne = true;}
function toggleFct() { callOne ? one() : two();}

A: When I try to do the following :
let callOne = true;

function one() {console.log("one");callOne = false;}

function two() {console.log("two"); callOne = true;}

function toggleFct() { callOne ? one() : two();}

It works just fine...
btw you can rewrite
hamburger.addEventListener("click", (e) => {toggleFct();});

as...
hamburger.addEventListener("click", toggleFct)


text:
Q: Product of cohomology groups I have a complex smooth projective scheme $X$ with the sheaf of Kähler differentials $\Omega_{X/\mathbb{C}}$ (or only $\Omega$). Denote its analytification $X^{an}$ with analytification morphism $h:X^{an} \rightarrow X$. I already know that $h^*\Omega^{X/\mathbb{C}} \cong \Omega_{X^{an}}$ the sheaf of holomorphic $1$-forms on $X^{an}$. My goal is to define a wedge product:
\begin{align*}
H^{q_1}(X, \Omega^{p_1}) \times H^{q_2}(X,\Omega^{p_2}) &\rightarrow H^{q_1+q_2}(X, \Omega^{p_1+p_2}) \\
(\alpha, \beta) \rightarrow \alpha \wedge \beta
\end{align*}
My first attempt is to use Čech cohomology and mimic the cup product of singular cohomology. In our setting Čech cohomology is the same as sheaf cohomology, moreover there is a finite standard affine covering of $X$, on which we can compute the cohomology. Let $\check{\alpha} \in \check{C}^{p_1}(X, \Omega^{q_1})$ and $\check{\beta} \in \check{C}^{p_2}(X, \Omega^{q_2})$ be the representative of $\alpha, \beta$, respectively, then we can define a represetative of $\alpha \wedge \beta$ on the intersection $i_0,i_1, \ldots, i_{p_1+p_2}$ as $\check{\alpha}_{i_0,i_1, \cdots, i_{q_1}} \wedge \check{\beta}_{i_{q_1}, i_{q_1 + 1}, \cdots, i_{q_1 + q_2}}$ where the wedge here means:
\begin{align*} \Omega^{p_1}(U_{ i_0,i_1, \cdots, i_{q_1}}) \times \Omega^{p_2}(U_{i_{q_1}, i_{q_1+1}, \cdots, i_{q_1 + q_2}}) &\rightarrow \Omega^{p_1 + p_2}(U_{i_0,i_1, \cdots, i_{q_1+q_2}}) \\
\gamma_1 \times \gamma_2 &\mapsto \gamma_1|_{U_{i_0,i_1, \cdots, i_{q_1+q_2}}} \wedge \gamma_2|_{U_{i_0,i_1, \cdots, i_{q_1+q_2}}}.
\end{align*}
I can prove that this is well-defined. The same thing can be done to get a wedge product:
$$ H^{q_1}(X^{an}, \Omega^{p_1}_{X^{an}}) \times H^{q_2}(X^{an},\Omega^{p_2}_{X^{an}}) \rightarrow H^{q_1+q_2}(X^{an}, \Omega^{p_1+p_2}_{X^{an}}) $$
But we also know that $H^{q}(X^{an}, \Omega^{p}_{X^{an}}) = H^{p,q}_{\bar\partial}(X^{an},\mathbb{C})$ the Dolbeault cohomology and here we have the usual wedge product between differential forms. So my questions are:
1) Is there a better way to define the wedge product between the cohomology groups categorically without using Čech cohomology
2) With either definition how can we prove the compatibility between the second and third row:
$\require{AMScd}$
\begin{CD}
H^{q_1}(X, \Omega^{p_1})  \times H^{q_2}(X,\Omega^{p_2})@>>> H^{q_1+q_2}(X, \Omega^{p_1+p_2})\\
@VVV @VVV\\
H^{q_1}(X^{an}, \Omega^{p_1}_{X^{an}}) \times H^{q_2}(X^{an},\Omega^{p_2}_{X^{an}}) @>>> H^{q_1+q_2}(X^{an}, \Omega^{p_1+p_2}_{X^{an}})\\
@VVV @VVV\\
H^{p_1,q_1}_{\bar{\partial}}(X^{an}, \mathbb{C}) \times H^{p_2,q_2}_{\bar{\partial}}(X^{an},\mathbb{C}) @>>> H^{p_1+p_2,q_1+q_2}_{\bar{\partial}}(X^{an},\mathbb{C})
\end{CD}


text:
Q: Thought experiment with the speed of light Every time we look at a star we are looking to the past. That's because the light of that star needed to travel long distances at the speed of light. When the light reaches our sight maybe the star no longer exists, since it had to come a long way to arrive here.
That led me to a thought experiment: we now can look, not sure about the exact number, but 11 or 12 billion years ago, it is said that the universe has 13,7 billion or so.
What we would see, if we look at the light from 13,7 billion years? The universe being formed?

A: This is not a thought experiment, we can, in fact, see the oldest light in the universe:
The oldest radiation is the cosmic microwave background, dating from the recombination period when the universe after about 400000 years after the Big Bang had cooled down enough for atoms to form. There is no earlier radiation for us to see because the hot universe prior to recombination was not transparent for electromagnetic radiation due to scattering by free electrons and protons.


text:
Q: Code Assist never worked Working with Mathematica 11.1.1.0 - code assist does not work at all.  All the Options Inspector fields seem correct. Could be some missing files from $BaseDirectory? That directory does contain a file "CodeAssistHistory9.0.m" does seems odd.
Mathematica 6 and 9 were both loaded on this machine.  Could it be that the installation failed to copy some files as a result.
I could try a reinstall but the first install had problems that Wolfram support took about 10 days to resolve.


text:
Q: Setting Parameters in CI4s redirecting function is there any possible way to send parameters within the redirection function from Codeigniter 4?
Important, it is a named route:
$routes->get('edit', 'Test_Controller::editTest/$1', ["as" => "editTest", "filter" => 'testFilter']);

And i want to do a redirect like this:
this works fine:
return $this->redirectTo('test/edit/' . $id1);

this would be nice, if it works:
return redirect('editTest', array($passingID));

or
return redirect('editTest')->with($passingID);

Why? I have HMVC and I would like to name every module with the same routes but different functions ofc. And this would help me having same site urls. (edit, add, a.s.o.)

A: The short answer is no its not possible. Take a look at system/Common.php and you'll see there is only 1 parameter to the redirect() function.
The longer answer however is take a look at what the redirect function does.
function redirect(?string $route = null): RedirectResponse
    {
    $response = Services::redirectresponse(null, true);

    if (! empty($route)) {
        return $response->route($route);
    }

    return $response;
}

Based on the current (4.1.4) redirect function you'll see it calls route().  It turns out that route() allows a second parameter which are the parameters.
So the solution would probably be to do your own redirect() function (see https://codeigniter.com/user_guide/extending/common.html?highlight=common) and allow a second parameter.


text:
Q: Design suggestions for executing tasks that will be triggered based on configuration In my web application, there is a web page displaying certain fields and its value. The values can be edited by the users. Once the values are edited, they are persisted into the database. Now comes the problem where i need suggestions. Once the values are updated into DB, i need to run few modules which are time consuming. So this time consuming part may or may not be done instantaneously depending on the configuration. The options in the configuration can be Instantaneous, Hourly, Daily, Weekly or Monthly. So if it instantaneous i have to run the modules or else i should trigger the task at the specified time based on the configuration.
Is job scheduler, a good way of solving this problem? Heard about Quartz.NET. Are there any .NET libraries available to achieve this. Pls provide suggesions.

A: It much recommended to store these jobs in a queue and create another asynchronize service  to execute the queue jobs. So you will not load all the effort on the web-server (IIS) and the application will not lost the jobs in case of the web-server restart or the web-application restarts.
To create this solution, you will have 3 points to think about.
Queue design and management
Sure you can use one of the Queuing servers (e.g. MSMQ, ActiveMQ, ZeroQ). But I recommend to use a new table on your database as a queue for simplicity. Find in the following link how to use database table as a queue.
http://rusanu.com/2010/03/26/using-tables-as-queues/
Job Scheduling
You have two options here Windows Task Scheduler and QuatrZ.NET. I recommend to use QuatrZ.Net for this part as it is more customizable and can fit for all your needs.
Hosting Service
You can use QuartZ.NET server deployment or you can build your own hosting service using .NET 4 Managed Extensibility Framework (MEF) and based on QuartZ IJob contract and its Corn expressions.


text:
Q: Use NVIDIA Hybrid gpu only for CUDA and not for KDE Plasma There is a similar question and I have been following this answer here on askubuntu: https://askubuntu.com/a/1158183/254943. This solution worked exactly as I want. Sadly after the most recent update, the solution stopped working and Xorg is now using nvidia again.

*

*| NVIDIA-SMI 450.66       Driver Version: 450.66       CUDA Version: 11.0     |

*Linux XXX 5.4.0-48-generic #52-Ubuntu SMP Thu Sep 10 10:58:49 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

*plasmashell 5.18.5 | Qt: 5.12.8 | KDE Frameworks: 5.68.0 | kf5-config: 1.0

$ cat  /usr/share/X11/xorg.conf.d/11-nvidia-prime.conf

# DO NOT EDIT. AUTOMATICALLY GENERATED BY gpu-manager

Section "OutputClass"
    Identifier "Nvidia Prime"
    MatchDriver "nvidia-drm"
    Driver "nvidia"
    Option "AllowEmptyInitialConfiguration"
    Option "IgnoreDisplayDevices" "CRT"
    # Option "PrimaryGPU" "Yes"   <<< commented out
    ModulePath "/x86_64-linux-gnu/nvidia/xorg"
EndSection

# added
Section "OutputClass"
    Identifier "intel"
    MatchDriver "i915"
    Driver "modesetting"
    Option "PrimaryGPU" "yes"
EndSection

I have tried to debug It by myself but I can't get it fixed.
$ nvidia-smi  # shows running process /usr/lib/xorg/Xorg

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.66       Driver Version: 450.66       CUDA Version: 11.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  GeForce GTX 105...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   50C    P8    N/A /  N/A |      6MiB /  4040MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      1257      G   /usr/lib/xorg/Xorg                  4MiB |
+-----------------------------------------------------------------------------+

A: I think have figured it out. First I have re-moved the 10-nvidia.conf file. Instead I have added a 10-intel.conf. Then I have commented out every line the 11-nvidia-prime.conf, it is basically an empty file. Since this file gets created/overwritten at every start/stop of xserver one needs to protect it with chattr +i
$ pwd
/usr/share/X11

$ ls -l xorg.conf.d/
total 36K
drwxr-xr-x 2 root root 4.0K Okt 20 20:15 .
drwxr-xr-x 6 root root 4.0K Okt 20 18:12 ..
-rw-r--r-- 1 root root   92 Okt 22  2019 10-amdgpu.conf
-rw-r--r-- 1 root root  327 Okt 20 18:10 10-intel-only.conf
-rw-r--r-- 1 root root 1.4K Sep  4 15:34 10-quirks.conf
-rw-r--r-- 1 root root   92 Okt 22  2019 10-radeon.conf
-rw-r--r-- 1 root root  341 Okt 20 20:15 11-nvidia-prime.conf
-rw-r--r-- 1 root root 1.5K Mai 30 15:34 40-libinput.conf
-rw-r--r-- 1 root root 3.4K Mär 11  2020 70-wacom.conf

ls -l bak.xorg/
drwxr-xr-x 2 root root 4.0K Okt 20 20:08 .
drwxr-xr-x 6 root root 4.0K Okt 20 18:12 ..
-rw-r--r-- 1 root root  206 Okt  5 11:19 10-nvidia.conf
-rw-r--r-- 1 root root  333 Okt 20 20:08 11-nvidia-prime.conf

$ cat xorg.conf.d/10-intel-only.conf
Section "ServerLayout"
    Identifier "Layout0"
    Option "AutoAddGPU" "false"
    Screen 0 "IntelScreen"
EndSection

Section "Device"
    Identifier "IntelDevice"
    BusID "PCI:0:2:0"
    Driver "intel" # or maybe "modesetting"?
EndSection

Section "Screen"
    Identifier "IntelScreen"
    Device "IntelDevice"
EndSection


text:
Q: WinUtils & Spark 3.1.1 Failures I'm trying to create a Windows 10 developer vm with a Conda environment and PySpark but seeing constant problems with getting Spark & winutils to work.
Environment:

*

*Windows 10 19042 (Fully Patched)

*MiniConda

*PySaprk 3.1.1

*Java 11.0.11

I have created C:\Hadoop\bin and downloaded winutils from here https://github.com/cdarlint/winutils/tree/master/hadoop-3.2.1/bin (I've also tried 3.2.0).
HADOOP_HOME is C:\Hadoop and Path has %HADOOP_HOME\bin in it. JAVA_HOME is correct.
This code works:
location = 'C:/myfiles/file.csv'
df = spark.read.format("csv").options(header=True).load(location)

This code fails:
location = 'C:/myfiles/'
df = spark.read.format("csv").options(header=True).load(location)

Error message:
An error occurred while calling o35.load.
: java.lang.UnsatisfiedLinkError: 'boolean org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(java.lang.String, int)'
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:645)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1230)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1435)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:493)

Winutils is being picked up because if I delete it the first example above then breaks as well in the expected way.
It seems that winutils is incompatible with Spark 3.1.1 and specifically a folder of files? I find it hard to believe that.
Bizarrely though I have another machine with pySpark 3.1.1 and this version of winutils and it works! Same Java version as well. I'm lost - I've even copied the winutils files from teh working machine to this one and it still didn't work.
Can anyone guide me on what that error means at least to help me understand where the issue could be?

A: In my case, I was able to resolve the issue by adding the hadoop.dll from the same link as provided in the question above(here) to the same location as winutils. Just keep a check there is no version mismatch.


text:
Q: How to pause javascript after executing a script for some time and then resume? i'm trying to make js gallery with image change, when user rollovers the thumbnail.
I have made it successfully and used css3 fade-in animation for image change, it works ok, but if I rollover my cursor on thumb1, dont wait for the animation to finish and rollover on another thumbnail the image changes without animation. It is hard to explain because my English is not the best, so i'll give you my code.
    <?xml version="1.0" encoding="utf-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="#css21" media="screen"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="Window-target" content="_top" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Untitled-1</title>

So, I think if I pause javascript for 1500ms after executing "onmouseover" user will not be able to execute the function again when rollovering another thumbnail, how can I do that? Or maybe there are more options to fix the image change effect?
Thank you for your answers.

A: You can use the setTimeout function
Example:
// run this code after 1500ms
setTimeout(function () {
   // this code will run later;
   alert("Hello World");
},1500);

UPDATE: In your case
xImg[ i ].onmouseover = function() {
    var that = this;
    setTimeout(function () {
        var xIndex = Number( that.id.match(/\d+/)[ 0 ] );
        xScreen.style.background = " url(" + that.src + ") no-repeat top center";
    },1500);
}

A: I would give imageGallery a property like imageGallery.isReady = true; When the function starts, set the property to false. Then, at the end of your function, do setTimeout(function() {imageGallery.isReady = true;}, 1500);
When the function is called, just check if imageGallery.isReady = true; If it's not, don't execute the function; if it is, execute it.
Edit: Alternatively, you could remove the event listener when the function starts, and then add it again after a setTimeout();


text:
Q: can we clear sessionStorage before html on load Can anyone help me to know how i can clear sessionStorage before my HTML onload event call? I want to clear al the data stored in sessionStorage before my html rendered

A: Just run the sessionStorage.clear() before the entiry HTML:
<html>
    <head>
        <script>
            sessionStorage.clear();
        </script>
    </head>
    <body>
        <!-- HTML -->
    </body>
</html>


text:
Q: Sound is lower in ubuntu than windows, pulseadio error Good Evenning, I would like to know if someone knows how to solve the following problem.
I have two operative systems in my computer, each one in a different disk.
The problem is that when I use ubuntu 20.04, the sound in general is lower than when I use windows which I have no idea why.
I haven looking in internet for ways to solve it, everyone said that the problem is made by pulseaudio.
When I execute it I got the follow:
'''pulseaudio
E: [pulseaudio] pid.c: Daemon already running.
E: [pulseaudio] main.c: Ha fallado pa_pid_file_create().'''
Which according to what I read it's a problem, so I tried to solve it using the different ways that I have found now, but I none works.
I have tried uninstalling it, I have tried to getting access to the local file, and another ways but none works.
It's sound fine when I use a speaker, and a little better when I use headphones, but not when is the sound from the machine.
Could anyone help me?


text:
Q: How do I set up commons-logging to use logback? We use slf4j + logback, and happened to have some third-party libraries which use commons-logging. How do I set it up to use logback?

A: The answer is to not use commons-logging.jar, since SLF4J was designed to do what commons-logging does but better. As @MahdeTo refers to, you need to use jcl-over-slf4j.jar.
Check out the documentation from the slf4j website on migrating from commons-logging.

A: Just add jcl-over-slf4j to the dependencies of your project (check current version at https://search.maven.org/search?q=g:org.slf4j%20AND%20a:jcl-over-slf4j&core=gav)

A: I come across this question too, and found out jcl-over-slf4j.jar indeed can solve the problem, I couldn't understand that why commons-logging couldn't use logback automatically, since commons-logging is log interface and logback is implementation, they should integrate automatically, until I found this:

The Apache Commons Logging (JCL) provides a Log interface that is
  intended to be both light-weight and an independent abstraction of
  other logging toolkits. It provides the middleware/tooling developer
  with a simple logging abstraction, that allows the user (application
  developer) to plug in a specific logging implementation.
JCL provides thin-wrapper Log implementations for other logging tools,
  including Log4J, Avalon LogKit (the Avalon Framework's logging
  infrastructure), JDK 1.4, and an implementation of JDK 1.4 logging
  APIs (JSR-47) for pre-1.4 systems. The interface maps closely to Log4J
  and LogKit.

Obviously not all the log interface can integrate nicely with log implementation which mean, if you really want to use logback, jcl-over-slf4j.jar is your only solution now because JCL only support Log4J, Logkit, JDK 1.4.

A: for those all who wants to keep the final package size smaller; checkout
mvn dependency:tree result of your project and if any dependency to commons-logging exists, exclude them as well. Since the jcl-over-slf4j.jar contains both Log and LogFactory classes with exact same package structure, these commons-logging jars will be extra on your final package.


text:
Q: Identify dateformat matlab I am looking for a way to identify the dateformat when adding a cellstr.
Thus when I run the function:
customFunction('2017/01/06')

that it returns
'yyyy/mm/dd'

How can this be achieved?

A: You could use java.text.SimpleDateFormatinside inside matlab function
import java.text.SimpleDateFormat;

sdf = SimpleDateFormat('yyyyMMdd')

sdf.parse(  char('20180410') )

ans =

Tue Apr 10 00:00:00 IST 2018

You'll have to add try ... catch.. for all possible formats and loop over each.
        "yyyy-MM-dd'T'HH:mm:ss'Z'",   "yyyy-MM-dd'T'HH:mm:ssZ",
        "yyyy-MM-dd'T'HH:mm:ss",      "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
        "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd HH:mm:ss",
        "MM/dd/yyyy HH:mm:ss",        "MM/dd/yyyy'T'HH:mm:ss.SSS'Z'",
        "MM/dd/yyyy'T'HH:mm:ss.SSSZ", "MM/dd/yyyy'T'HH:mm:ss.SSS",
        "MM/dd/yyyy'T'HH:mm:ssZ",     "MM/dd/yyyy'T'HH:mm:ss",
        "yyyy:MM:dd HH:mm:ss",
        "yyyyMMdd"


text:
Q: Are there any Specific Configuration Changes to Consider when Building an App for Sharepoint Online? I'm accustomed to building and deploying solutions for on-premises Sharepoint instances.  I was wondering if there's any configuration changes that must be made to ensure an app can be deployed to Sharepoint Online?
Thanks much for your help and guidance.

A: In terms of SharePoint-hosted apps, you can deploy seamlessly to a local SharePoint farm or to SharePoint Online just by setting the "Site URL" property of the app project to the appropriate URL.


text:
Q: How to configure an Eclipse Java format that avoids joining Javadoc lines? I'm running into a peculiar behavior when formatting Java code using Eclipse (see image, below).  Even though that I have "Never join lines" checked under Comments->General Settings, it seems to want to join lines within a Javadoc comment when they use {@code} tags.
I've found one possibly-related question on StackOverflow, but it seems to be my problem in reverse.  I only suspect it could be related due to the presence of {@code} tags.
Here's the Eclipse Java format setting:

Here's the improperly-formatted Javadoc comment:

Any ideas on how to get this to work, such as a magic setting I am overlooking?  To be clear, I am not interested in:

*

*Disabling formatting on Javadoc blocks.  I want formatting to be applied.

*Using @formatter:off and @formatter:on or any other manual/workaround approaches.  There are a ton of instances of this in the code I am trying to format.

A: How about adding
 between your {@code} statements ? This should give you the following result:
 *
 * @return {@code true} - if the override was successfully recorded.

 *         {@code false} - if the override was not successfully recorded.
 *


text:
Q: Imputing missing values using sklearn IterativeImputer class for MICE I'm trying to learn how to implement MICE in imputing missing values for my datasets. I've heard about fancyimpute's MICE, but I also read that sklearn's IterativeImputer class can accomplish similar results. From sklearn's docs:

Our implementation of IterativeImputer was inspired by the R MICE
  package (Multivariate Imputation by Chained Equations) [1], but
  differs from it by returning a single imputation instead of multiple
  imputations. However, IterativeImputer can also be used for multiple
  imputations by applying it repeatedly to the same dataset with
  different random seeds when sample_posterior=True

I've seen "seeds" being used in different pipelines, but I never understood them well enough to implement them in my own code. I was wondering if anyone could explain and provide an example on how to implement seeds for a MICE imputation using sklearn's IterativeImputer? Thanks!

A: IterativeImputer behavior can change depending on a random state. The random state which can be set is also called a "seed".
As stated by the documentation, we can get multiple imputations when setting sample_posterior to True and changing the random seeds, i.e. the parameter random_state.
Here is an example of how to use it:
import numpy as np
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer

X_train = [[1, 2],
           [3, 6],
           [4, 8],
           [np.nan, 3],
           [7, np.nan]]
X_test = [[np.nan, 2],
          [np.nan, np.nan],
          [np.nan, 6]]

for i in range(3):
    imp = IterativeImputer(max_iter=10, random_state=i, sample_posterior=True)
    imp.fit(X_train)
    print(f"imputation {i}:")
    print(np.round(imp.transform(X_test)))

It outputs:
imputation 0:
[[ 1.  2.]
 [ 5. 10.]
 [ 3.  6.]]
imputation 1:
[[1. 2.]
 [0. 1.]
 [3. 6.]]
imputation 2:
[[1. 2.]
 [1. 2.]
 [3. 6.]]

We can observe the three different imputations.

A: A way to go about stacking the data might be to change @Stanislas' code around a bit like so:
mvi = {} # just my preference for dict, you can use a list too
# mvi collects each dataframe into a dict of dataframes using index: 0 thru 2

for i in range(3):
    imp = IterativeImputer(max_iter=10, random_state=i, sample_posterior=True)
    mvi[i] = np.round(imp.fit_transform(X_train))

combine the imputations into a single dataset using
# a. pandas concat, or
pd.concat(list(dfImp.values()), axis=0)

#b. np stack
dfs = np.stack(list(dfImp.values()), axis=0)

pd.concat creates a 2D data, on the other hand,np.stack creates a 3D array that you can reshape into 2D. The breakdown of the numpy 3D is as follows:

*

*axis 0: num of iterated dataframes

*axis 1: len of original df (num of rows)

*axis 2: num of columns in original dataframe

create a 2D from 3D
You can use numpy reshape like so:
np.reshape(dfs, newshape=(dfs.shape[0]*dfs.shape[1], -1))

which means you essentially multiply axis 0 by axis 1 to stack the dataframes into one big dataframe. The -1 at the end just means that whatever axes is left off, use that, in this case it is the columns.


text:
Q: How can i know when the library is fully loaded how can i t change this code to run the function when the js library finish loading? uisng vanilla javascript
because i'm using a timer that didn't worked for slow internet connection
imported = document.createElement('script');
imported.src = 'https://pastebin.com/raw/dRap1YD8';
document.head.appendChild(imported);

    var delayInMilliseconds = 1000;

setTimeout(function() {
.
.
.
}, delayInMilliseconds);

Note that pastebin is just for test

A: What you are looking for is the onLoad method. Take a look here at the api, It's gonna look like
imported.onload = function() { alert('loaded'); }

A: Do like:
var imported = document.createElement('script');
imported.onload = function(){
  /* it's loaded - do stuff here */;
}
imported.src = 'https://pastebin.com/raw/dRap1YD8';
document.head.appendChild(imported);

Make sure you put your load Event before you assign the .src, otherwise it may never fire.


text:
Q: what is query to change the data type of Date from string date time format in elastic search? I am working on an elastic search. I need to change the data type from string to date format.
The field name and its value is the date and 2020-02-01 08:17:22.438000. Now it is I  string data type. I need to change into the date-time format in the elastic search itself.


text:
Q: How to rename list on double click but keep the icons next to it I have a list with  along with icons , Im using this javascript function to allow user to rename the element and change it, but how do i make it so that the icon will still remain but the name will change? Currently i remove() the current name and replace it with the new one and obviously it would rem,ove the icon as well.. how do i keep the icon (could be multiple different ones) even tho the names change.
List -

SourceName

SourceName

SourceName

Javascript -
 var oriVal;
$("#sourceList").on('dblclick', 'a', function () {
    oriVal = $(this).text();
    $(this).text("");
    $("<input type='text'>").appendTo(this).focus();
});
$("#sourceList").on('focusout', 'a > input', function () {
    var $this = $(this);
    $this.parent().text($this.val() || oriVal);
    $this.remove();
});

See Fiddle example - Rename List

A: You can copy the image to a global variable, then restore it using this variable:

$(document).ready(function() {

  var oriVal;
  var oriIcon;
  $("#sourceList").on('dblclick', 'a', function() {
    oriIcon = $(this).find('i');
    oriVal = $(this).text();
    $(this).text("");
    $("<input type='text'>").appendTo(this).focus();
  });
  $("#sourceList").on('focusout', 'a > input', function() {
    var $this = $(this);
    $this.parent().text($this.val() || oriVal).prepend(oriIcon);
    $this.remove();
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>

SourceName

SourceName

SourceName

A: May this you want to implement?

$("#sourceList").on('dblclick', 'a', function () {
    oriVal = $(this).text();
    $(this).find('span').text("");
    $("<input type='text'>").appendTo(this).focus();
});
$("#sourceList").on('focusout', 'a > input', function () {
    var $this = $(this);
    $this.parent().find('span').text($this.val() || oriVal);
    $this.remove();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>

SourceName

SourceName

SourceName

A: You can preserve the original DOM.
Also, I would advise not to use global variables -

$("#sourceList").on('dblclick', 'a', function() {
  $("<input type='text'>").appendTo(this).focus();
  $(this).find('span').text('');
});
$("#sourceList").on('focusout', 'a > input', function() {
  var $this = $(this);
  $this.siblings('span').text(this.value);
  $this.remove();
});

SourceName

SourceName

SourceName

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>


text:
Q: Install pip in Travis virtualenv I have a Python 3 project with a pytest suite, and want to run it on Travis.
I'm trying to write a test.sh script that can work both on the developer machine and Travis CI as well, which has to setup the virtualenv, install the packages, run pytest and then destroy the virtualenv. I can't use Tox because it doesn't follow dependency links, which we are using.
The script (simplified) is:
python3 -m venv .venv
pip install -e . --process-dependency-links --allow-all-external
.venv/bin/pip install pytest
.venv/bin/pytest
rm -rf .venv

on my machine it works, but on Travis this fails because inside the .venv/bin there is no pip executable, nor pip2 or pip3.
I tried to enforce the installation of it with .venv/bin/python3 -m pip install --upgrade pip but still there's no binary.
Running python3 -m venv --help I see there's an optional flag --without-pip available, and the same help text says that pip is bootstrapped by default. How can I ensure that pip is present in a virtualenv?
EDIT: a likely solution is to use python3 -m pip install pytest to install the pytest package instead of invoking pip as a command directly


text:
Q: Deployment Issue In Symfony2 - Can't Find Registered Bundles? I'm transferring my project from the laptop to a test/production server. I'm copying the files to the server via FTP. So far, I can access the /web/config.php file and /web/app_dev.php files alright.
However, when I go to try and load a page it comes up with the following error:

ReflectionException: Class Knp\Menu\ItemInterface does not exist

In the error report, all the files look to be held in the following root directory:

/var/www/vhosts/domain.co.uk/subdomains/dev/httpdocs/

On the laptop however, the root directory was www:

C:\wamp\www

Everything on the test server is held in the httpdocs folder. What do I need to do to fix this error?
Cheers
EDIT:
I have moved everything in to a www folder, held within httpdocs folder. It's completely broken doing that, no pages will load.

A: The issue occured from an incorrectly configured .htaccess file on the development server.
During the configuration, the root directory wasn't changed to /web. Once this was changed however, the plugin worked.