text:
Q: CodePipeline + Beanstalk Connection Refused React + Express Apps I'll lay this out below in detail:
Goal
A React front-end game that uses socket.io to transfer game state data between players on the Express server.
Setup
After finding that it would be impossible/a real work-around to have both React/Express on an Amplify instance, I decided to move to CodePipeline + CodeDeploy to Beanstalk.
I have the Source coming from GitHub, a CodeBuild step, and then CodeDeploy. The CodeBuild should basically just compile based on my buildspec.yml below:
version: 0.2
  frontend:
    phases:
      preBuild:
        commands:
          - npm ci
      build:
        commands:
          - npm run build
   artifacts:
     baseDirectory: build
     files:
       - '**/*'
   cache:
     paths:

Although this is calling npm run build, which I'm not sure A) The CodeBuild/CodeDeploy will try to do with node start or B) If this will kick off my react-scripts build in package.json:
"scripts": {
    "webpack": "webpack --production",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

I'm assuming I want it to build the webpack bundle in CodeBuild, then CodeDeploy will call the proper run command, but it seems black boxed? Is there another config file?
Runtime Errors
I get Connection Refused, although my server.js file defaults to localhost and 8080:
var hostname = process.env.IP || 'localhost';
var port = process.env.PORT || 8080;

Web.std.out.log:
Sep 20 18:10:10 ip-172-31-41-5 web: > MyApp@0.1.0 start /var/app/current
Sep 20 18:10:10 ip-172-31-41-5 web: > react-scripts start
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: Project is running at http://172.31.41.5/
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: webpack output is served from
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: Content not from webpack is served from /var/app/current/public
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: 404s will fallback to /
Sep 20 18:10:12 ip-172-31-41-5 web: Starting the development server...

Ngnix error.log: 2020/09/18 03:07:30 [error] 4436#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.40.133, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8080/", host: "172.31.41.5"
Lot of moving parts so I'm sure there are several missteps here, not sure which is which.

A: Based on the comments.
By default EB will look for package.json to run your application. If it is missing, and will use use script option in your package.json to start your application. For example, if you start sample node.js application that EB provides, the file is:
package.json
{
  "name": "Elastic-Beanstalk-Sample-App",
  "version": "0.0.1",
  "private": true,
  "dependencies": {},
  "scripts": {
    "start": "node app.js"
  }
}

If you don't provide package.json nor Procfile (other option, see below) EB will expect app.js or server.js to be present to start your application.
If you don't want to use package.json, you can also use Procfile to tell EB how to start your application.

When you don't provide a Procfile, Elastic Beanstalk runs npm start if you provide a package.json file. If you don't provide that either, Elastic Beanstalk looks for the file app.js or server.js, in this order, and runs it.

Example in your case could be
web: serve -s build


text:
Q: App Declining in app updates through app center I set up Microsoft update according to the app centre documentation however I am getting the following dialogue.
https://learn.microsoft.com/en-us/appcenter/sdk/distribute/xamarin
I am using android 9.1 i used the normal download function
Steps to reproduce
1 I had to install new version on Phone so downloaded via email
2 Sent a new version to app centre for testing the below
3 Presented with that dialogue when I started the app
I places this in my OnCreate in MainActivty.cs
AppCenter.Start("{secret key}", typeof(Distribute));

And the following in my App.Xaml
AppCenter.Start("android=secret-key;",
          typeof(Distribute), typeof(Distribute));

I also placed this in OnStart
Distribute.SetEnabledAsync(true);

Can someone tell me why I am getting the below dialogue

My App is also in release mode

A: You should not have two calls to Start in different places and two Distribute types passed.

*

*If you have a Xamarin.Forms app, call to Start should happen
inside App.xaml.cs.

*If you have a Xamarin.Android app, call to Start should happen
inside MainActivity.cs.

Not the both!
typeof(Distribute) should be passed only once.
Please refer to this part of documentation.
Also, calling setEnabled is unnecessary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Move semantics on individual vector elements What is the behavior of a std::move on an individual vector element?
e.g. (grossly simplified code follows)
Will this do the proper move and do I need to erase() the moved element?
I normally use a copy constructor and a delete, will the compiler optimize for a move (synthesized) instead of using a copy constructor in some cases?
I tried using smart-pointer wrappers and didn't see a significant speedup.
Move semantics look like what I want to use.
template< class T >
class Foo
{
};

vector< Foo< T > > v1, v2;

v2.emplace_back( std::move( v1[ 2 ] );

I don't see significant speedup using move operations and I think I've implemented the move constructor and move assignment operator correctly.
Please shed some light on this problem.

A: Move semantics have two jobs:

*

*Indicate that ownership of a resource (such as some allocated memory, or a FILE* pointer, or a stream) changed hands

*Avoid unnecessary copies in the above cases.

For example, let's say we have a vector:
vector<int> a;
for(int i = 0; i < 10000; i++) {
    a.push_back(i);
}

If I write:
vector<int> b = a;

This makes a copy of every single element in a, so it's a slow operation. However, if I write
vector<int> b = std::move(a);

None of the elements in a are copied, and this ends up being a lot faster. However, a no longer owns those elements. We can demonstrate it using the below code:
#include <vector>
#include <iostream>

int main() {
    using std::vector;

    vector<int> a = {1, 2, 3};
    vector<int> b = std::move(a);
    if(a.data() == nullptr) // This should be true now
        std::cout << "a.data() is null now\n";
    if(a.size() == 0)
        std::cout << "a.size() is zero now\n";
}

On my system, using gcc and clang, this code prints
a.data() is null now
a.size() is zero now

This applies even if you have a wrapper class:
#include <vector>
#include <iostream>

template<class T>
class Wrapper {
   public:
    // Because all the members of Wrapper are public,
    // the compiler automatically generates move and copy constructors
    T value;
};

int main() {
    using std::vector;

    Wrapper<vector<int>> a = {{1, 2, 3}};
    Wrapper<vector<int>> b = std::move(a);
    // Same output as before
    if(a.value.data() == nullptr)
        std::cout << "a.data() is null now\n";
    if(a.value.size() == 0)
        std::cout << "a.size() is zero now\n";
}


text:
Q: How to dynamically update layouts in android studio I am working on a mobile application in android studio with Java. I am working with a Firebase realtime database, and in the database exists a list of "tasks" each with a name and description.
What I would like to happen is for my application to dynamically render a list of cards representing each task based on how many tasks are in the database. I also have a button that allows users to add a task, and after adding the task I would like another card to be rendered with the added task data.
I understand this to be a very routine task, and it is something I am very familiar with doing in web development. I am unsure of how to do this in android studio, as the UI is defined in a layout XML file, and I am unsure of how to dynamically change the layout XML file based on how much data is fetched from the database.
If anyone can provide any help or helpful links to how to do this it would be much appreciated.

A: You can use RecyclerView to populate views dynamically. RecyclerView is the most efficient and optimized.
Useful resources:

*

*RecyclerView official documentation.

*Using Firebase with RecyclerView Full guide video


text:
Q: CGI in Java - Legacy but interesting (for educational purposes) I folks:
I  know that CGI is jurassic and before all of you call me lunatic, I must say that this question is only for EDUCATIONAL PURPOSES (in real cases I use JSP).
I'm trying to code a "Hello World" CGI in Java, and I'm unsucessful.
So I try the same job in C#.
Both programs (C# and Java) are totally equal (line by line). The C# works and the Java don't.
Here's the code in C#:

    namespace CGI_CSharp
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Content-Type: text/html\n"); // the extra "\n" is needed
                Console.WriteLine("");
                Console.WriteLine("");
                Console.WriteLine("<title>CGI - C#</title>");
                Console.WriteLine("");
                Console.WriteLine("");

                Console.WriteLine("
Hello World !
");

                Console.WriteLine("");
                Console.WriteLine("");
            }
        }
    }

In the browser URL I wrote: http://localhost/CGI_CSharp.exe and BINGO! The C# code WORKS !
Now the same code in Java:

    public class CGI_Java
    {
        public static void main(String[] args)
        {
            System.out.println ("Content-Type: text/html\n");
            System.out.println ("");
            System.out.println ("");
            System.out.println ("<title>CGI - Java</title>");
            System.out.println ("");
            System.out.println ("");

            System.out.println ("
Hello World !
");

            System.out.println ("");
            System.out.println ("");
        }
    }

Now I've tried the URL:
http://localhost/java.exe%20CGI_Java
(as you know, the %20 is the space => (http://localhost/java.exe CGI_Java)
I get:
HTTP 404.0 - Not Found
So, I try again, now with a batch file (CGI_Java.bat) with a single line of text:
java.exe CGI_Java (content of the CGI_Java.bat)
And now, I try the URL:
http://localhost&/CGI_Java.bat
Now the browser shows:
C:\inetpub\wwwroot>java.exe CGI_Java
This is the prompt followed by the command I wrote in the batch file.
Can someone help me?
Thanks in advance.

A: What server are you using?
Is java.exe on the path for the server?
(Note that if you alter the environment variable for the path you will have to restart the server for it to pick up the changes).


text:
Q: Rails: Refactoring - json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"] Question is pretty much in the title. What's the best way to refactor something like below?
json["data"]["counts"]["followed_by"] if json &&  json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]

I want to return nil unless json["data"]["counts"]["followed_by"] exists.

A: You can use try :
json.try(:[], 'data').try(:[], 'counts').try(:[], 'followed_by')

A: I tend towards the andand gem over long try chains, e.g.,
 json.andand['data'].andand['counts'].andand['followed_by']

IMO it just looks nicer.


text:
Q: Can't use < in a sentence I am creating an HTML email and one of the sentences uses < ie <200 cp/ml. However, this causes all sorts of issues and the rest of the sentence is broken up into words with = in between each word. How do I use < or > in a sentence in HTML without breaking the code?

A: You have to escape the character by using < instead of <. < is the starting character of an html element. The opposite side is > (>).

A: You can use this characters for <  < or < opposite site > > or >

A:
Reserved characters in HTML must be replaced with character entities.

for < you have to use < and for > you have to use >
Reference

*

*HTML Entities


text:
Q: Uploading Node.js app to WinSCP server I failed to make my node app work in WinSCP. To my understanding, node version 6 is installed on the server, while my node version is at at 8+. Does it matter? I also got e.g. express, mongoose and handlebars in my app. Do I need to add those in the server as well?
What are the proper steps to upload a node app?

A: On the server, you should have node install the app. This way node will download and install the files/libraries that are required in your package.json file on the server.
try this.
Upload your project to the server and change to the directory of your project. if node_modules exists delete the folder then run.
npm install

This should create a node_module folder and install all the requirements.
Once the install is complete you should be able to run your app with.
npm start


text:
Q: How to save the access token in php? I am using this endpoint to get the long-lived token:
https://graph.facebook.com/oauth/access_token?
    client_id=APP_ID&
    client_secret=APP_SECRET&
    grant_type=fb_exchange_token&
    fb_exchange_token=EXISTING_ACCESS_TOKEN

But I want to know how can I get it with php.
I need to use the curl library ?
Or is there a simplest solution ?

A: Here is a simple curl function to use with the facebook sdk. Don't forget to change the path to the fb_ca_chain_bundle.crt.
function curl($url, $certificate = false) {

    $c = curl_init($url);

    curl_setopt($c, CURLOPT_HTTPGET, true);
    curl_setopt($c, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);

    curl_setopt ($c, CURLOPT_SSL_VERIFYPEER, TRUE);
    curl_setopt ($c, CURLOPT_CAINFO, dirname(__FILE__) . '/sdk/fb_ca_chain_bundle.crt');

    $output = curl_exec($c);

    if ($output === false) {
        curl_close($c);
        return false;
    }

    curl_close($c);
    return $output;

}

And here is the method call to get the long lived token:
§token = curl('https://graph.facebook.com/oauth/access_token?client_id='.
               $app_id.'&client_secret='.
               $app_secret.'&grant_type=fb_exchange_token&fb_exchange_token='.
               $api->getAccessToken());


text:
Q: Enable rc-local service in CentOS 8.X I'm trying to enable rc.local in CentOS 8.1, the service file exists by default, but I can't enable it:
[root@localhost ~]# systemctl enable rc-local
The unit files have no installation config (WantedBy, RequiredBy, Also, Alias
settings in the [Install] section, and DefaultInstance for template units).
This means they are not meant to be enabled using systemctl.
Possible reasons for having this kind of units are:
1) A unit may be statically enabled by being symlinked from another unit's
   .wants/ or .requires/ directory.
2) A unit's purpose may be to act as a helper for some other unit which has
   a requirement dependency on it.
3) A unit may be started when needed via activation (socket, path, timer,
   D-Bus, udev, scripted systemctl call, ...).
4) In case of template units, the unit is meant to be enabled with some
   instance name specified.

Any ideas?

A: I think it is a special unit that goes by point number 3:

3) A unit may be started when needed via activation (socket, path, timer,
     D-Bus, udev, scripted systemctl call, ...).

So you don't systemctl enable it. You enable it by making rc.local file executable, as is on non-SystemD systems.
Can be verified with systemctl cat rc-local. Take note of ConditionFileIsExecutable=/etc/rc.d/rc.local.
So as is usual with rc.local, place your commands in /etc/rc.local (symlink to /etc/rc.d/rc.local) and make the file executable via chmod +x, to have this "service" enabled/run at boot time.


text:
Q: How to COUNT in MySQL with CASE stament I have the following query
SELECT CASE u.situacionUsuario
    WHEN "A" THEN 'ALTA'
    WHEN "R" THEN 'ALTA'
    WHEN "S" THEN 'ALTA'
    WHEN "B" THEN 'BAJA'
    WHEN "T" THEN 'BAJA'
    ELSE NULL
    END AS Situacion
FROM Usuario u
WHERE
YEAR(u.fechaAsistencia)=2018 AND MONTH(u.fechaAsistencia) BETWEEN 01 AND 12
GROUP BY u.situacionUsuario, u.usuario;

That return this result
-Situacion-
|ALTA     |
|ALTA     |
|ALTA     |
|ALTA     |
|ALTA     |
|ALTA     |
|BAJA     |
|BAJA     |
|ALTA     |
|ALTA     |
|ALTA     |
|BAJA     |
|ALTA     |
|ALTA     |
|ALTA     |
----------

And the result that i want is this one.
-Situacion-TOTAL-|
|ALTA     |12    |
|BAJA     |3     |
-----------------

I used COUNT but it dosn't return the result i want
SELECT CASE u.situacionUsuario
        WHEN "A" THEN 'ALTA'
        WHEN "R" THEN 'ALTA'
        WHEN "S" THEN 'ALTA'
        WHEN "B" THEN 'BAJA'
        WHEN "T" THEN 'BAJA'
        ELSE NULL
        END AS Situacion,
    COUNT (CASE u.situacionUsuario
        WHEN "A" THEN 'ALTA'
        WHEN "R" THEN 'ALTA'
        WHEN "S" THEN 'ALTA'
        WHEN "B" THEN 'BAJA'
        WHEN "T" THEN 'BAJA'
        ELSE NULL
        END) AS Total
    FROM Usuario u
    WHERE
    YEAR(u.fechaAsistencia)=2018 AND MONTH(u.fechaAsistencia) BETWEEN 01 AND 12
    GROUP BY Situacion;

Any suggestion how can i COUNT with the cases and get the desired result?

A: Do the CASE part in a derived table. GROUP BY its result:
select Situacion, count(*) as TOTAL
from
(
    SELECT CASE u.situacionUsuario
        WHEN "A" THEN 'ALTA'
        WHEN "R" THEN 'ALTA'
        WHEN "S" THEN 'ALTA'
        WHEN "B" THEN 'BAJA'
        WHEN "T" THEN 'BAJA'
        ELSE NULL
        END AS Situacion
    FROM Usuario u
    WHERE
    YEAR(u.fechaAsistencia)=2018 AND MONTH(u.fechaAsistencia) BETWEEN 01 AND 12
) dt
GROUP BY Situacion

A: I would write this as:
SELECT (CASE u.situacionUsuario
           WHEN 'A' THEN 'ALTA'
           WHEN 'R' THEN 'ALTA'
           WHEN 'S' THEN 'ALTA'
           WHEN 'B' THEN 'BAJA'
           WHEN 'T' THEN 'BAJA'
        END) AS Situacion,
       COUNT(*) AS Total
FROM Usuario u
WHERE u.fechaAsistencia >= '2018-01-01' AND
      u.fechaAsistencia < '2019-01-01'
GROUP BY Situacion;

Notes:

*

*Strings should be delimited by single quotes.  Your code would fail to work -- for instance -- if Usuario had any columns named A or R and so on.

*Use direct date comparisons instead of date functions in the WHERE clause, when possible.  This improves optimization.

*MySQL supports column aliases in the GROUP BY.

*I'm not sure why you would want 0 if the row is NULL, so this just uses COUNT(*) for the total.

*ELSE NULL is redundant.  I don't think it adds anything to the query.

I would actually simplify this to:
SELECT (CASE WHEN u.situacionUsuario IN ('A', 'R', 'S') THEN 'ALTA'
             WHEN u.situacionUsuario IN ('B', 'T')  THEN 'BAJA'
        END) AS Situacion,
       COUNT(*) AS Total
FROM Usuario u
WHERE u.fechaAsistencia >= '2018-01-01' AND
      u.fechaAsistencia < '2019-01-01'
GROUP BY Situacion;

This reduces the likelihood of a tpo in the query causing unexpected results.

A: try embedded selection,
select Situacion, count(Situacion) from (

SELECT CASE u.situacionUsuario
    WHEN "A" THEN 'ALTA'
    WHEN "R" THEN 'ALTA'
    WHEN "S" THEN 'ALTA'
    WHEN "B" THEN 'BAJA'
    WHEN "T" THEN 'BAJA'
    ELSE NULL
    END AS Situacion
FROM Usuario u
WHERE
YEAR(u.fechaAsistencia)=2018 AND MONTH(u.fechaAsistencia) BETWEEN 01 AND 12

) group by Situacion;


text:
Q: How to understand monad in scala I just understood what type constructor and higher kinded types states for and now I'm trying to understand Monad. Here is how Monad trait looks in scalaz:
trait Monad[F[_]] extends Applicative[F] with Bind[F] { self =>
  ////

  override def map[A,B](fa: F[A])(f: A => B) = bind(fa)(a => point(f(a)))
  //The rest is omitted

}

The question is I don't kind of understand why Monad is a higher kinded type? We have standard List[T], Option[T] monads which are not higher kinded types.
I'm not a Theory Category expert so I treat monad as a container with monads laws.
Why don't we just declare a monad as follows:
trait Monad[V]{
    //...
}

Not a higher kind.
How would standard Option[T] monad look like in that case as a a subclass for instance?

A:
I don't kind of understand why Monad is a higher
  kinded type?

I think the fastest way to see why it has to be a higher kinded type is to try and create a signature for pure where the type parameter isn't itself a type constructor:
// Doesn't compile
trait Monad[V]{
  def pure[A](a: A): V[A]
}

Of course, that doesn't work because we can't write V[A] for an arbitrary type parameter, it has to be a type constructor, particularly one of kind * -> *

How would standard Option[T] monad look like in that case as a
  subclass for instance

Another thing about a Monad (and a Functor for that matter) being a type constructor is that we create a single representation of Monad[List], for example, and get it for free for all T arguments of that List because of polymorphic types and theorms for free. Again, you could not by the virtue of the signature of Monad implement it without a type constructor.

We have standard List[T], Option[T] monads which are not higher kinded
  types.

That's right. They are not higher kinded because T itself isn't required to be a type constructor for any operations of List[T] or Option[T] to work, but T in that sense can represent any type. This means that although Option[T] is of kind * -> *, I can still construct it with a List to produce a Option[List[T]].


text:
Q: GET parameters not working with Restler framework I'm having a hard time getting Restler to work properly with nginx.
In the first place I couldn't even get Math.php/add to work (returned 404).
But I managed this way (I've seen a lot of people struggle with this):
root         /var/www/test/;

location ~ [^/]\.php(/|$) {
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    if (!-f $document_root$fastcgi_script_name) {
        return 404;
    }

    fastcgi_pass   unix:/var/run/php5-fpm/socket.socket;
    fastcgi_index index.php;
    include fastcgi_params;
}

location /api { //map /api to public directory
    try_files $uri /api/public/index.php;
}

fastcgi_param
fastcgi_param   QUERY_STRING            $query_string;
fastcgi_param   REQUEST_METHOD          $request_method;
fastcgi_param   CONTENT_TYPE            $content_type;
fastcgi_param   CONTENT_LENGTH          $content_length;

fastcgi_param   SCRIPT_FILENAME         $document_root$fastcgi_script_name;
fastcgi_param   SCRIPT_NAME             $fastcgi_script_name;
fastcgi_param   PATH_INFO               $fastcgi_path_info;
fastcgi_param   REQUEST_URI             $request_uri;
fastcgi_param   DOCUMENT_URI            $document_uri;
fastcgi_param   DOCUMENT_ROOT           $document_root;
...

Attention: cgi.fix_pathinfo=1
Everything works fine now except that I cant receive any GET parameter using ?parameter=
For example, the Math example doesn't work.
If I call /api/math/add?n1=6&n2=4 it returns 2
But the multiply example works: GET /math/multiply/4/3 returns {"result":12}
<?php
class Math
{
    /**
     * @param int $n1
     * @param int $n2
     *
     * @return int
     */
    function add($n1 = 1, $n2 = 1)
    {
        return $n1 + $n2;
    }
}

routes.php
//==== GET v1/math/add ====

$o['GET']['v1/math/add'] = array (
    'className' => 'Math',
    'path' => 'v1/math',
    'methodName' => 'add',
    'arguments' =>
    array (
        'n1' => 0,
        'n2' => 1,
    ),
    'defaults' =>
    array (
        0 => 1,
        1 => 1,
    ),
    'metadata' =>
    array (
        'description' => '',
        'longDescription' => '',
        'param' =>
        array (
            0 =>
            array (
                'type' => 'int',
                'name' => 'n1',
                'default' => 1,
                'required' => false,
                'from' => 'query',
            ),
            1 =>
            array (
                'type' => 'int',
                'name' => 'n2',
                'default' => 1,
                'required' => false,
                'from' => 'query',
            ),
        ),
        'return' =>
        array (
            'type' => 'int',
            'description' => '',
        ),
        'resourcePath' => 'v1/math/',
    ),
    'accessLevel' => 0,
);

$_SERVER variable on index.php
Array
(
    [TEMP] => /tmp
    [TMPDIR] => /tmp
    [TMP] => /tmp
    [PATH] => /usr/local/bin:/usr/bin:/bin
    [HOSTNAME] =>
    [USER] => ftp
    [HOME] => /var/www/
    [FCGI_ROLE] => RESPONDER
    [QUERY_STRING] =>
    [REQUEST_METHOD] => GET
    [CONTENT_TYPE] => application/x-www-form-urlencoded
    [CONTENT_LENGTH] =>
    [SCRIPT_FILENAME] => /var/www/test/api/public/index.php
    [SCRIPT_NAME] => /api/public/index.php
    [PATH_INFO] =>
    [REQUEST_URI] => /api/math/add?n1=6&n2=4
    [DOCUMENT_URI] => /api/public/index.php
    [DOCUMENT_ROOT] => /var/www/test
    [SERVER_PROTOCOL] => HTTP/1.1
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_SOFTWARE] => nginx/1.4.2
    [HTTPS] =>
    [REDIRECT_STATUS] => 200
    [HTTP_CONNECTION] => keep-alive
    [HTTP_CACHE_CONTROL] => no-cache
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
    [HTTP_CONTENT_TYPE] => application/x-www-form-urlencoded
    [HTTP_ACCEPT] => */*
    [HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch
    [HTTP_ACCEPT_LANGUAGE] => pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
    [PHP_SELF] => /api/public/index.php
    [REQUEST_TIME_FLOAT] => 1380738349.0903
    [REQUEST_TIME] => 1380738349
)

A: Solved with this:
location /api {
    if (!-f $request_filename) {
        rewrite ^(.*)$ /api/index.php last;
    }

    if (!-d $request_filename) {
        rewrite ^(.*)$ /api/index.php last;
    }
}


text:
Q: How to expand \fpeval{} results numerically? I' m trying to use xfp to create some automated homework solutions. For short documents it works like a charm, but for longer one the compiling time grows exponentially. For example:
\def\GDUbeta{30} % upstream beta
\def\GDUMa{3.0} % upstream Mach number
\def\GDUP{101} % upstream pressure
\def\GDUT{295} % upstream temp
%------ Modify initial values above this line ------
\def\GDUtheta{\fpeval{atand(2*cotd(\GDUbeta)*(\GDUMa^2*sind(\GDUbeta)^2-1)/( (1.4+cosd(2*\GDUbeta))*\GDUMa^2+2 ))}} % upstream theta
\def\GDUMan{\fpeval{\GDUMa*sind(\GDUbeta)}} % upstream Ma normal
\def\GDUPratio{\fpeval{1+2*1.4/(1.4+1)*(\GDUMan^2-1)}} % upstream pressure ratio
\def\GDUTratio{\fpeval{(1+2*1.4/(1.4+1)*(\GDUMan^2-1))*((2+(1.4-1)*\GDUMan^2)/((1.4+1)*\GDUMan^2))}} % upstream pressure ratio
\def\GDDMan{\fpeval{sqrt((2+(1.4-1)*\GDUMan^2)/(2*1.4*\GDUMan^2-(1.4-1)))}}
 % downstream Ma normal
\def\GDDMa{\fpeval{\GDDMan/sind(\GDUbeta-\GDUtheta)}} % downstream Ma
% Closed form solution of beta --->
\def\GDtanmu{\fpeval{tan(asin(1/\GDDMa))}} % tan Mach angle
\def\GDClosec{\fpeval{\GDtanmu^2}}
\def\GDClosea{\fpeval{((1.4-1)/2+(1.4+1)/2*\GDClosec)*tand(\GDUtheta)}}
\def\GDCloseb{\fpeval{((1.4+1)/2+(1.4+3)/2*\GDClosec)*tand(\GDUtheta)}}
\def\GDClosed{\fpeval{sqrt(4*(1-3*\GDClosea*\GDCloseb)^3/((27*\GDClosea^2*\GDClosec+9*\GDClosea*\GDCloseb-2)^2)-1)}}
\def\GDClosee{\fpeval{(\GDCloseb+9*\GDClosea*\GDClosec)/(2*(1-3*\GDClosea*\GDCloseb))}}
\def\GDClosef{\fpeval{\GDClosed*(27*\GDClosea^2*\GDClosec+9*\GDClosea*\GDCloseb-2)/(6*\GDClosea*(1-3*\GDClosea*\GDCloseb))}}
\def\GDCloseg{\fpeval{tan(1/3*atan(1/\GDClosed))}}
\def\GDDbeta{\fpeval{atand(\GDClosee-\GDClosef*\GDCloseg)}}
% <--- Closed form solution of beta
\def\GDphi{\fpeval{\GDDbeta-\GDUtheta}} % angle of reflected shock
\def\GDRMa{\fpeval{\GDDMa*sind(\GDDbeta)}} % reflect shock Mach number
\def\GDRPratio{\fpeval{1+2*1.4/(1.4+1)*(\GDRMa^2-1)}} % reflect pressure ratio
\def\GDRTratio{\fpeval{\GDRPratio*((2+(1.4-1)*\GDRMa^2)/((1.4+1)*\GDRMa^2))}} % reflect temp ratio
\def\GDRMan{\fpeval{sqrt((2+(1.4-1)*\GDRMa^2)/(2*1.4*\GDRMa^2-(1.4-1)))}} % reflect pressure ratio
\def\GDRAMa{\fpeval{\GDRMan/sind(\GDphi)}} % reflected actual Mach number
\def\GDRP{\fpeval{\GDRPratio*\GDUPratio*\GDUP}} % reflected pressure
\def\GDRT{\fpeval{\GDRTratio*\GDUTratio*\GDUT}} % reflected temp
\def\GDSPratio{\fpeval{(1+(1.4-1)/2*\GDRAMa^2)^(1.4/(1.4-1))}} % stagnation pressure ratio
\def\GDSP{\fpeval{\GDSPratio*\GDRP/1000}} % stagnation pressure
\def\GDSTratio{\fpeval{1+(1.4-1)/2*\GDUMa^2}} % stagnation temp ratio
\def\GDST{\fpeval{\GDSTratio*\GDUT}} % stagnation temp
%------ DO NOT modify calculations above this line ------

The above calculation is 100% working, the problem is every time I insert these intermediate values in the homework solutions, it's calling all macros above it recursively and making it very very slow to compile.
I know this is kind of ugly coding in LaTeX, but is there any way to expand and cache fpeval to floating point numbers, just to avoid calling these macros for exponentially growing number of times?

A: If the calculations are static, that is, when you change a value you recompile and every value depends strictly only on previous calculated ones, you can try changing \def with \edef.
If not, you can try using pgfmath declare function instead, but the accuracy will suffer (sometimes a lot).

A: The problem is that when you use, say \GDUtheta in \GDDMa, you're not applying the value, but the operations needed to compute it.
If you have carefully laid out the variables so each one only depends on the previous ones, you can do the evaluation.
I suggest to use the built-in methods.
\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\fpset}{mm}
 {
  \fp_zero_new:N #1
  \fp_set:Nn #1 { #2 }
 }
\NewExpandableDocumentCommand{\fpuse}{m}{\fp_use:N #1}

\ExplSyntaxOff

\fpset\GDUbeta{30} % upstream beta
\fpset\GDUMa{3.0} % upstream Mach number
\fpset\GDUP{101} % upstream pressure
\fpset\GDUT{295} % upstream temp
%------ Modify initial values above this line ------
\fpset\GDUtheta{atand(2*cotd(\GDUbeta)*(\GDUMa^2*sind(\GDUbeta)^2-1)/( (1.4+cosd(2*\GDUbeta))*\GDUMa^2+2 ))} % upstream theta
\fpset\GDUMan{\GDUMa*sind(\GDUbeta)} % upstream Ma normal
\fpset\GDUPratio{1+2*1.4/(1.4+1)*(\GDUMan^2-1)} % upstream pressure ratio
\fpset\GDUTratio{(1+2*1.4/(1.4+1)*(\GDUMan^2-1))*((2+(1.4-1)*\GDUMan^2)/((1.4+1)*\GDUMan^2))} % upstream pressure ratio
\fpset\GDDMan{sqrt((2+(1.4-1)*\GDUMan^2)/(2*1.4*\GDUMan^2-(1.4-1)))}
 % downstream Ma normal
\fpset\GDDMa{\GDDMan/sind(\GDUbeta-\GDUtheta)} % downstream Ma
% Closed form solution of beta --->
\fpset\GDtanmu{tan(asin(1/\GDDMa))} % tan Mach angle
\fpset\GDClosec{\GDtanmu^2}
\fpset\GDClosea{((1.4-1)/2+(1.4+1)/2*\GDClosec)*tand(\GDUtheta)}
\fpset\GDCloseb{((1.4+1)/2+(1.4+3)/2*\GDClosec)*tand(\GDUtheta)}
\fpset\GDClosed{sqrt(4*(1-3*\GDClosea*\GDCloseb)^3/((27*\GDClosea^2*\GDClosec+9*\GDClosea*\GDCloseb-2)^2)-1)}
\fpset\GDClosee{(\GDCloseb+9*\GDClosea*\GDClosec)/(2*(1-3*\GDClosea*\GDCloseb))}
\fpset\GDClosef{\GDClosed*(27*\GDClosea^2*\GDClosec+9*\GDClosea*\GDCloseb-2)/(6*\GDClosea*(1-3*\GDClosea*\GDCloseb))}
\fpset\GDCloseg{tan(1/3*atan(1/\GDClosed))}
\fpset\GDDbeta{atand(\GDClosee-\GDClosef*\GDCloseg)}
% <--- Closed form solution of beta
\fpset\GDphi{\GDDbeta-\GDUtheta} % angle of reflected shock
\fpset\GDRMa{\GDDMa*sind(\GDDbeta)} % reflect shock Mach number
\fpset\GDRPratio{1+2*1.4/(1.4+1)*(\GDRMa^2-1)} % reflect pressure ratio
\fpset\GDRTratio{\GDRPratio*((2+(1.4-1)*\GDRMa^2)/((1.4+1)*\GDRMa^2))} % reflect temp ratio
\fpset\GDRMan{sqrt((2+(1.4-1)*\GDRMa^2)/(2*1.4*\GDRMa^2-(1.4-1)))} % reflect pressure ratio
\fpset\GDRAMa{\GDRMan/sind(\GDphi)} % reflected actual Mach number
\fpset\GDRP{\GDRPratio*\GDUPratio*\GDUP} % reflected pressure
\fpset\GDRT{\GDRTratio*\GDUTratio*\GDUT} % reflected temp
\fpset\GDSPratio{(1+(1.4-1)/2*\GDRAMa^2)^(1.4/(1.4-1))} % stagnation pressure ratio
\fpset\GDSP{\GDSPratio*\GDRP/1000} % stagnation pressure
\fpset\GDSTratio{1+(1.4-1)/2*\GDUMa^2} % stagnation temp ratio
\fpset\GDST{\GDSTratio*\GDUT} % stagnation temp
%------ DO NOT modify calculations above this line ------

\begin{document}

GDRPratio = \fpuse{\GDRPratio}

GDST = \fpuse{\GDST}

GDUT = \fpuse{\GDUT}

\end{document}


text:
Q: Firebase Reset Password Link is failing because it's using rotated/old API Key I rotated the API Key that is used for setting up the firebase/auth app. Upon calling sendPasswordResetEmail successfully, I receive a link that is using the previous API Key.
Here's the API Key:

Here's the link that was generated:
https://XXXXXXXXXX.firebaseapp.com/__/auth/action?mode=resetPassword&oobCode=XXXXXXX&apiKey=AIzXXXXXXXXXXXXXXXKPQ&lang=en

notice it ends with KPQ, which is the old key. The link does not work, it says it's expired.
If I swap out the API Key with the new one in the link, then I'm able to continue the forget password flow.
Does anyone know how to fix this? I'm using the updated API key in the app's config.

A: Firebase support suggested waiting for changes to happen on the backend. What I ended up doing to fix the issue was creating a new credential/api key (not rotate the existing one), and deleting the old ones. The issue still persisted for the weekend, it is now working though.


text:
Q: Symfony custom method repository not able to access in controller I have two database connections in symfony. I have created a method in repository and tried to access that method in controller. But, I am not able to access that method,and I get an error (undefined method getSuitelog()) Please let me know how to access the queries and method from repository in controller.
<?php

namespace App\Controller\Testing;

use App\Entity\Testing\CpSelection;
use App\Entity\Testing\CpTests;
use App\Repository\CpSelectionRepository;
use App\Repository\CpTestsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Session\Session;

class TestingController extends AbstractController
{

    #[Route('/testing/id/{{id}}', name: 'index')]
    public function CpTestSuit($id): Response
    {
        // $entityManager = $this->get('doctrine.orm.testing_entity_manager');
        $repository = $this->getDoctrine()
                    ->getManager('testing');
        $cpsuit =  $repository->getRepository(CpSelection::class, 'CpSelection')
                    ->getSuitelog($id);
        $cpTests = $repository->getRepository(CpTests::class, 'CpTests')
                    ->findAll(); //

        return $this->render('testing/index.html.twig', [
            'controller_name' => 'TestingController',
            'suite' => $cpsuit,
            'tests' => $cpTests,
        ]);

    }

Repository with getSuitelog method:
<?php

namespace App\Repository;

use App\Entity\Testing\CpSelection;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method CpSelection|null find($id, $lockMode = null, $lockVersion = null)
 * @method CpSelection|null findOneBy(array $criteria, array $orderBy = null)
 * @method CpSelection[]    findAll()
 * @method CpSelection[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class CpSelectionRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, CpSelection::class);
    }

    public function getSuitelog($suite_id = NULL) {

        $where = "";
        $values = array ();
        if ($suite_id != NULL) {
            $where = " where id = ? ";
            $values = array (1 => $suite_id);
        }
        $query = "SELECT * FROM App:CpSelection" . $where;
        return $this->getEntityManager()
            ->createQuery(
                $query
            )
            ->execute()
            ->getArrayResult();

    }

My Entity class looks like
<?php

namespace App\Entity\Testing;

use Doctrine\ORM\Mapping as ORM;

/**
 * CpSelection
 * @ORM\Entity(repositoryClass="App\Repository\CpSelectionRepository")
 * @ORM\Table(name="cp_selection")
 */
class CpSelection
{
......
}

A: Custom repository injection example:
#[Route('/testing/id/{{id}}', name: 'index')]
public function CpTestSuit($id, CpSelectionRepository $myCustomRepository): Response
{
...
}

Update:
To get this work we should use autowiring (is enabled by default in symfony DI-container) and rewrite repository so that it do not extend  any basic repository. Instead, inject EntityManager into Repository constructor, and then inject this concrete repository into controller action. If you type-hint arguments, symfony autowiring will do all other job.
Details are explained here https://tomasvotruba.com/blog/2017/10/16/how-to-use-repository-with-doctrine-as-service-in-symfony/


text:
Q: Separate bibliographies on same page I would like to scan the bib file for entry type, put them into 3 categories, and show those separate with title. I got this working with the code below. I would like to change two things:

*

*Delete the strange output at the footcite (blx@hook@citekey@next);

*Put all three bibliographies below eachother, so no new page.

How can I do that?

\documentclass{report}

\usepackage[backend=bibtex,citestyle=verbose-ibid,bibstyle=numeric,sorting=nyt]{biblatex}

\DeclareBibliographyCategory{websites}
\DeclareBibliographyCategory{spoken}
\DeclareBibliographyCategory{books}

\AtEveryCitekey{
  \ifentrytype{misc}{
    \iffieldundef{howpublished}{
      \addtocategory{websites}{\thefield{entrykey}}
    }{
      \addtocategory{spoken}{\thefield{entrykey}}
    }
  }{
  }
}

\AtEveryCitekey{
  \ifentrytype{book}{
      \addtocategory{books}{\thefield{entrykey}}
  }
}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
%books
@book{3,
  author = {Menger, Carl},
  title = {Grunds{\"a}tze der Volkswirtschaftslehre},
  publisher = {Braum{\"u}ller},
  year = {1982}
}

%spoken
@misc{4,
  author = "Janssen, Jan",
  title = "",
  month = may,
  year = "2014",
  howpublished = "Congres"
}

%websites
@misc{5,
  author = {The Guardian},
  title = {Cyprus banks remain closed to prevent run on deposits},
  url = "http://www.theguardian.com/world/2013/mar/26/cyprus-banks-closed-prevent-run-deposits",
  urldate = "2014-11-15"
}
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}

\tableofcontents
\chapter{Chapter}
Some text
\footcite{3,4,5}

\addcontentsline{toc}{chapter}{Bibliography}
\printbibliography[category=books,title={Books}]
\printbibliography[category=websites,title={Online articles}]
\printbibliography[category=spoken,title={Conferences}]

\end{document}

A: Thanks to lockstep's editing of the tags, I found the answer myself.
\documentclass{report}

\usepackage[backend=bibtex,citestyle=verbose-ibid,bibstyle=numeric,sorting=nyt]{biblatex}

\DeclareBibliographyCategory{websites}
\DeclareBibliographyCategory{spoken}
\DeclareBibliographyCategory{books}

\AtEveryCitekey{
  \ifentrytype{misc}{
    \iffieldundef{howpublished}{
      \addtocategory{websites}{\thefield{entrykey}}
    }{
      \addtocategory{spoken}{\thefield{entrykey}}
    }
  }{
  }
}

\AtEveryCitekey{
  \ifentrytype{book}{
      \addtocategory{books}{\thefield{entrykey}}
  }
}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
%books
@book{3,
  author = {Menger, Carl},
  title = {Grunds{\"a}tze der Volkswirtschaftslehre},
  publisher = {Braum{\"u}ller},
  year = {1982}
}

%spoken
@misc{4,
  author = "Janssen, Jan",
  title = "",
  month = may,
  year = "2014",
  howpublished = "Congres"
}

%websites
@misc{5,
  author = {The Guardian},
  title = {Cyprus banks remain closed to prevent run on deposits},
  url = "http://www.theguardian.com/world/2013/mar/26/cyprus-banks-closed-prevent-run-deposits",
  urldate = "2014-11-15"
}
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}

\tableofcontents
\chapter{Chapter}
Some text
\footcite{3,4,5}

\addcontentsline{toc}{chapter}{Bibliography}

\chapter*{Bibliography}
\section*{Books}

\begingroup
\let\clearpage\relax
\printbibliography[category=books,heading=none]
\endgroup

\section*{Online articles}
\begingroup
\let\clearpage\relax
\printbibliography[category=websites,heading=none]
\endgroup

\section*{Conferences}
\begingroup
\let\clearpage\relax
\printbibliography[category=spoken,heading=none]
\endgroup

\end{document}


text:
Q: Oracle ctxsys.context DRG-10599 column is not indexed I have ctxsys.context index on one column. When i execute below query i give DRG-10599: column is not indexed error. I check index and update it.
Query:
SELECT s.dsa_id FROM service_search s
  WHERE CONTAINS(s.fld_search, 'someData') >0

Index ddl:
  CREATE INDEX "ARCHIVE_SER"."IDX_SEARCH_CTX" ON
    "ARCHIVE_SER"."service_search" ('FLD_SEARCH')
    INDEXTYPE IS "CTXSYS"."CONTEXT"  PARAMETERS ('SYNC ( ON COMMIT)')

A: You have a typo in your index DDL, so it should not have worked. The ('FLD_SEARCH') column is in single-quotes, which makes it a VARCHAR instead of an identifier. Probably it would be easier to spot errors like this if you didn't use so many double-quotes. :)
This works fine for me.
create table service_search (fld_search varchar2(4000));

CREATE INDEX IDX_SEARCH_CTX ON service_search (FLD_SEARCH)
  INDEXTYPE IS CTXSYS.CONTEXT  PARAMETERS ('SYNC ( ON COMMIT)');

select * from service_search s where contains(s.fld_search, 'someData') > 0;


text:
Q: Android Studio - Could not resolve com.android.tools.build:gradle:3.5.2 I just downloaded and attempted to build my first app using this as a guide:
https://developer.android.com/training/basics/firstapp/creating-project
The issue I am having is just about the same as this one:
ERROR: Could not find com.android.tools.build:gradle:3.5.2
EDIT: My issue is identical to this one - Could not resolve com.android.tools.build:gradle:3.2.1
Errors are below bottom. Also none of the suggestions in that post resolved this issue. I have also tried various combinations of offline and local cache as per other similar stackoverflow posts. Proxy settings are on "auto detect" and when pressing test connection and using goggle.com, its successful. My exact issue is a timeout when trying to retrieve .pom file. I can type in the location of the POM in a browser and I have downloaded the file without issue. I have it but not sure where to put it or if putting it will resolve the issue.
Gradle appears to be installed correctly in: C:\Users\xxxxx.gradle\wrapper\dists\gradle-5.4.1-all\3221gyojl5jsh0helicew7rwx
Gradle build file:
    buildscript {
        repositories {
            google()
            jcenter()
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.5.2'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            google()
            jcenter()

        }
    }

    task clean(type: Delete) {
        delete rootProject.buildDir
    }

Errors:
Could not resolve com.android.tools.build:gradle:3.5.2.
Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.5.2/gradle-3.5.2.pom'
Edit again: distributionUrl=https://services.gradle.org/distributions/gradle-5.4.1-all.zip

A: The answer is very simple, in this case. Even though I set the proxy to auto detect and test connection worked, proxy was still the issue. After pulling my hair out, I finally figured that I needed manual proxy config. The Host name kept causing an "Invalid Host Name" error, even though it was cut and pasted from my browser.
In proxy settings Manual proxy config in Android Studio:
Host Name: "http://myproxy.something" FAILS
 Host Name: "myproxy.something"  WORKS!!!!
After removing, the gradle error went away.


text:
Q: Start Vagrant box on boot with ~/.profile (Budgie 17.04) I'm trying to set up my system to automatically boot my two main Vagrant boxes when my computer turns on but it's throwing an error saying no such file or directory when I added this to the bottom of ~/.profile
bash cd ~/Develop/Websites/scotch && vagrant up
bash cd ~/Develop/Websites/homestead && vagrant up

I can paste that line (minus the bash) into a terminal though and it works fine.
I'm told I shouldn't use ~/.profile for this and should possibly use a cron @reboot.
How would I format that since it's not a script that runs necessarily? It's not a file you run, it's a command that has to be in a specific folder.

A: It looks like you want to run these commands in a sub-shell to not affect the working directory of the shell running the .profile script.
You can use the -c option to run a shell with commands given on the command line:
bash -c 'cd ~/Develop/Websites/scotch && exec vagrant up'

However, it would be simpler to use the sub-shell feature of the current shell instead:
( cd ~/Develop/Websites/scotch && exec vagrant up )


text:
Q: Python convert rows into array i have a CSV dataset which contains all 7x7 image data. There are 7800 rows and 49 columns. Each row represent one image. The data looks like this.
dataset image

I need to apply array to each rows so that i could reshape all the datas into 2D dimension array which have the shape like this but in 7x7. Shape example:

I am using python so what should i do ??

A: You can change df into matrix and reshape it:
df.as_matrix().reshape(-1, 7, 7)

A: I'd do it like this:
pd.Series(df.values.reshape(-1, 7, 7).tolist()).apply(np.array)

It's the df.values.reshape(-1, 7, 7) that does the bulk of the work.
array([[[101,  62,  20,   9, 125, 160, 144],
        [214,  66,   0,  25, 170,  93,  51],
        [209,  11,  56,  80, 204, 156, 189],
        [ 95, 211,  26, 172, 207,  39, 249],
        [ 73, 160, 105, 167, 189, 230,  75],
        [ 49, 116, 109, 168, 215, 186,  35],
        [ 68, 154, 185,  12, 186,  78, 252]],

       [[247,  18,  14,  67,  67,  89,  93],
        [110, 174, 139,  88, 123, 131, 254],
        [232,   3,  52,  46, 113,   6, 141],
        [221, 220, 116, 141,  65,  54,  84],
        [203,  51, 222, 204, 237, 121,  80],
        [199,   4, 102, 169,   0, 108, 144],
        [ 23, 249, 127,  20, 226,   2, 214]],

       [[ 22, 188,  68,  65,   4,  32,  33],
        [ 63, 241, 120, 147, 253, 162, 255],
        [158, 228,  18,  56, 193, 232, 183],
        [153,   0, 188, 131,  42, 106, 156],
        [ 51,  70, 219, 156,  94,  50,  43],
        [  0, 130, 203,  47, 245, 108, 250],
        [164, 246, 180,  58, 220, 188,  49]]])


text:
Q: Import from excel to data table vb.net I have imported the excel sheet to data table by using the below code but the few cell value could not be loaded properly. instead of the cell value it is displayed as null.
Please refer the attached the image of the excel and data table.
Dim conStr As String = ""

conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'"
conStr = String.Format(conStr, Path)
Dim connExcel As New OleDbConnection(conStr)
Dim cmdExcel As New OleDbCommand()
Dim oda As New OleDbDataAdapter()
cmdExcel.Connection = connExcel
'Get the name of First Sheet
connExcel.Open()
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim SheetName As String = ""
If dtExcelSchema.Rows.Count > 0 Then
    SheetName = dtExcelSchema.Rows(dtExcelSchema.Rows.Count - 1)("TABLE_NAME").ToString()
End If
connExcel.Close()
'Read Data from First Sheet
connExcel.Open()
cmdExcel.CommandText = "SELECT * From [" & SheetName & "]"
oda.SelectCommand = cmdExcel
oda.Fill(dt)
dt.TableName = SheetName.ToString().Replace("$", "")
connExcel.Close()
Return dt

A: You are facing this issue because your column contains mixed data types, so the OLEDB provider will take the dominant data type and convert all other datatype values to NULL.
Try adding IMEX=1 to the extended properties in the connection String:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"

*

*What is IMEX in the OLEDB connection string?
If it doesn't work, try adding a dummy row after the Header, in this row add a string value ex xyz and in the code delete this row after reading the data.


text:
Q: Target nested tables InDesign script I am trying to change the width of  a column in this nested table, but it isn't working. What am I doing wrong? It works fine when the table is not nested.
Un-nested works:
app.activeDocument.stories.everyItem().tables.everyItem().columns[0].width = "53mm";

Nested doesn't work:
app.activeDocument.stories.everyItem().tables.everyItem().tables.everyItem().columns[0].width = "53mm";

A: insert .cells.everyItem().texts[0] will solve this issue.
try this code
app.activeDocument.stories.everyItem().tables.everyItem().cells.everyItem().texts[0].tables.everyItem().columns[0].width = "53mm";


text:
Q: Hadoop: How can i merge reducer outputs to a single file? I know that "getmerge" command in shell can do this work.
But what should I do if I want to merge these outputs after the job by HDFS API for java?
What i actually want is a single merged file on HDFS.
The only thing i can think of is to start an additional job after that.
thanks!

A: You get a single Out-put File by Setting a single Reducer in your code .
Job.setNumberOfReducer(1);

Will work for your requirement , but costly

OR

Static method to execute a shell command.
Covers most of the simple cases without requiring the user to implement the Shell interface.

Parameters:
env the map of environment key=value
cmd shell command to execute.
Returns:
the output of the executed command.

org.apache.hadoop.util.Shell.execCommand(String[])

A:
But what should I do if I want to merge these outputs after the job by HDFS API for java?

Guessing, because I haven't tried this myself, but I think the method you are looking for is FileUtil.copyMerge, which is the method that FsShell invokes when you run the -getmerge command.  FileUtil.copyMerge takes two FileSystem objects as arguments - FsShell uses FileSystem.getLocal to retrieve the destination FileSystem, but I don't see any reason you couldn't instead use Path.getFileSystem on the destination to obtain an OutputStream
That said, I don't think it wins you very much -- the merge is still happening in the local JVM; so you aren't really saving very much over -getmerge followed by -put.


text:
Q: OAuth Google API for Java unable to impersonate user I would like to impersonate a user and add files to the users Google Drive on their behalf from a server process.  I've setup a service account and can successfully access the Drive as the service account adding and listing files, etc. using the following code:
  /** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();

  public static void main(String[] args) {
    try {
        GoogleCredential credential =
                new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                  .setJsonFactory(JSON_FACTORY)
                  .setServiceAccountId("XXXXX@developer.gserviceaccount.com")
                  .setServiceAccountScopes(DriveScopes.DRIVE)
                  .setServiceAccountPrivateKeyFromP12File(new File("c:/junk/key.p12"))
                  .build();
        Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
        drive.files().list().execute();
  } catch (Exception e) {
     e.printStackTrace();
  }

This works, however only returns files that are associated to what I assume is associated with the service accounts drive (?).
According to the JavaDoc, GoogleCredential can also be used to impersonate a user by adding the service account users email address as follows:
        GoogleCredential credential =
                new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                  .setJsonFactory(JSON_FACTORY)
                  .setServiceAccountId("XXXXX@developer.gserviceaccount.com")
                  .setServiceAccountScopes(DriveScopes.DRIVE)
                  .setServiceAccountPrivateKeyFromP12File(new File("c:/junk/key.p12"))
                  .setServiceAccountUser("usera@domain.com") //<-- impersonate user a
                  .build();

However, when executing this code, the following exception is thrown:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "access_denied"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:103)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:303)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:323)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:340)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:508)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:260)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:796)
at com.google.api.client.googleapis.json.GoogleJsonResponseException.execute(GoogleJsonResponseException.java:198)
at com.google.api.client.googleapis.services.GoogleClient.executeUnparsed(GoogleClient.java:237)
at com.google.api.client.http.json.JsonHttpRequest.executeUnparsed(JsonHttpRequest.java:207)
at com.google.api.services.drive.Drive$Files$List.execute(Drive.java:1071)

Am I missing a step or configuration setting?
Thanks,
David

A: I found a similar question as mine: Can a Google Apps Admin manage users files with Drive SDK? to mine which has helped me figure out the answer.
The cPanel documentation is a little misleading as it refers to enabling the consumer key and then adding the domain to the Manage API client access screen.  This appears to be valid for the gdata api and not the new Google Drive api.  By adding the client id as suggested in the other question and granting access to the Drive scope I'm now able to impersonate a user.

A: Get your admin to add scopes to xxxxx.apps.googleusercontent.com via admin panel:
I added the following to work on spreadsheets:
https://www.googleapis.com/auth/drive
https://docs.google.com/feeds
https://spreadsheets.google.com/feeds


text:
Q: S3 increase latency with low volume I use S3 to store some images, my max TPS is around 250, however towards the end and beginning of the day when there is low traffic (less than 1 per minute), the Latency goes up a little.
Keys are random
Is this normal with S3?
Am I missing some configuration that can avoid this?
This is my config:
ClientConfigurationParameters:
connectionTimeout = 1000;
socketTimeout     = 50000;
requestTimeout    = 5000;
executionTimeout  = 15000;
maxConnections    = 1000;

with low TPS (below 1 per minute latency starts to go up a little) my suspicious is that socketConnection is getting closed and re-opened every time in that case.
Below is the graphic pattern of TPS vs Latency.


text:
Q: Rails - re-using partial Instead of the standard show, edit, delete, I have the following in my views/users/index.html.erb

      <%= link_to user, class: 'btn btn-default' do %>

      <% end %>

      <%= link_to edit_user_path(user), class: 'btn btn-default' do %>

      <% end %>

      <%= link_to user, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger' do %>

      <% end %>

How can I re-use this code for all other models in the app?

A: Create a layouts/_toolbox.html.rb partial and place the following modified version in it:

    <%= link_to my_model, class: 'btn btn-default' do %>
        See me
    <% end %>

    <%= link_to [:edit, my_model], class: 'btn btn-default' do %>
        Edit me
    <% end %>

    <%= link_to my_model, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger' do %>
        Destroy me
    <% end %>

And then you can use it with:
<%= render partial: "layouts/toolbox", locals: {my_model: model_instance} %>

A: You can move it to a partial layout and pass the variables as locals.
Notice that the partial name must begin with "_", for example: _actions.html.erb
Then render the partial from the code and pass the locals.
<%= render partial: "actions", locals: {user: @user} %>


text:
Q: Substituting values on the command line I want to run sql from the command line:
mysql -u user -p database -e "INSERT INTO table VALUES ( NULL, [hash] , NOW(), 0);

I want to replace [hash] with the response of another command line command:
date +%s | md5sum

Is there a way to make that substitution?

A: Yes, assuming you are using bash (and closing the open quote) -
mysql -u user -p database \
  -e "INSERT INTO table VALUES ( NULL, $(date +%s | md5sum) , NOW(), 0);"


text:
Q: Media wiki AWC forum I am using a forum extension in mediawiki called AWC forum
I need to get a summary of the today' posts on daily basis through email.
Can anyone suggest how should be the structure of the php for this?

A: I once thought of using it, but I used the Disqus Widget instead. You can handle everything from there, but I do not know if that covers what you aim to do.


text:
Q: Обратиться к номеру ячейки в массиве по имени элемента Простая задача - обратиться к номеру элемента в массиве по его значению. Не учитывая коллизии получилось так:
my $i = 0;
my %mapping = map {$_ => $i++} @heights; #@heights - массив чисел

Однако, этот вариант перезаписывает значение по ключу $_, если в массиве встретились два одинаковых числа. Как преобразовать этот код, чтобы сделать %mapping - хешем списков? Т.е., у каждого ключа будет список номеров ячеек массива heights, где этот ключ встретился.

A: В общем случае задача решается с помощью List::MoreUtils.
#!/usr/bin/env perl

use Modern::Perl;
use List::MoreUtils qw/firstidx indexes/;

my @data = ( 9, 1, 2, 3, 4, 1, 2 );

# ищем первый индекс злемента со значением 1:
my $idx = firstidx { $_ == 1 } @data;
say $idx;

# ищем все индексы злементов со значением 1:
my @indexes = indexes { $_ == 1 } @data;
say join ',', @indexes;

Если хочется именно свой велосипед соорудить - имеет смысл смотреть как всё устроено внутри этого модуля. Там много чего ещё полезного есть :)
P.S. Ну и не стоит обходить вниманием и List::Util, и Array::Utils.

Если же таких обращений может быть много, то да, имеет смысл сконвертировать массив в хэш списков индексов. Вот, набросал практически готовый вариант:
#!/usr/bin/env perl

use Modern::Perl;

my @data = ( 9, 1, 2, 3, 2, 1, 2 );
my %indexes = array2indexes( \@data );

say 'Indexes of 1: '.( $indexes{1} ? join( ',', @{ $indexes{1} } ) : 'none' );
say 'Indexes of 2: '.( $indexes{2} ? join( ',', @{ $indexes{2} } ) : 'none' );
say 'Indexes of 9: '.( $indexes{9} ? join( ',', @{ $indexes{9} } ) : 'none' );
say 'Indexes of 7: '.( $indexes{7} ? join( ',', @{ $indexes{7} } ) : 'none' );

# функция конвертирует массив в хэш, ключами которого являются
# элементы исходного масссива, а значениями - списки индексов
# этих самых элементов:
sub array2indexes
{
    my ($array) = @_;
    my $i = 0;
    my %indexes;
    for ( @{$array} ) {
        unless ( defined $indexes{$_} ) {
            $indexes{$_} = [ $i++ ];
        }
        else {
            push @{ $indexes{$_} }, $i++;
        }
    }
    return wantarray ? %indexes : \%indexes;
}

Вывод:
Indexes of 1: 1,5
Indexes of 2: 2,4,6
Indexes of 9: 0
Indexes of 7: none

A: use strict;
use warnings;
use utf8;

use Data::Dumper;

my @heights = (38, 21, 32, 38, 21, 21, 9);
my %mapping;

my $i = -1;
map { $i++; push @{ $mapping{$_} //= [] },  $i; } @heights;

print Dumper \%mapping;

Вывод:
$VAR1 = {
      '21' => [
                1,
                4,
                5
              ],
      '38' => [
                0,
                3
              ],
      '32' => [
                2
              ],
      '9' => [
               6
             ]
    };


text:
Q: Can I host asp.net webform web application on services fabric? I am researching about azure service fabric and found nothing about how to host asp.net webform web application on service fabric? My application is built on asp.net version 4 and it is a monolithic app not microdevices based. Is it possible to host on service fabric?

A: ASP.NET webforms uses the System.Web assembly which is coupled to IIS. Service fabric uses OWIN for self-hosting the ASP.NET web apps. Thus, it is not possible to host asp.net webforms inside service fabric.


text:
Q: Understand Regular Expression What does this regular expression mean \w+(?=@). Im trying to understand how this expression will pull users from the AD, currently it is omitting all characters before a special Character. Ex: Viny.Trucker will result only in .Truck. I want the whole name Viny.Trucker to be extracted.
Any help is greatly appreciated.

A: It means find "any number of word characters (a-z, A-Z, 0-9 and _) immediately followed by an @ symbol. The @ symbol won't be included in the matched characters. If you want to include the '.' character in the expression, you can try (\w|.)+(?=@)

A: Try this : http://www.regexr.com/ It comes with very nice explanation when you hover over chars.
And here is your regex : http://www.regexr.com/38ndp

A: It matches the characters before an @-character.
\w+    Match at least one word-character, i.e. letters, numbers and underscores.
(?=@)  Match an @-character without including it in the match.

A: Jan AAgaard is right, it matches all word characters before an @.
How does it do this?
\w+   Matches ones or more word-chracters.
(?=@) This is called a positive-lookahead. It means require the following to come after the characters, but don't include that in the match.

A better alternative
Now, it seems that you want to match every character before an @, the easy way to to this is
[^@]+(?=@)

If you know that there will always be a @ in a line you could even use
[^@]+

and just take the first match.
If there will always be a certain set of chracters allowed before the @, you could even specify those in a character class: Simply put all of them in square brackets, e.g.:
[a-zA-Z0-9._]

A: It's searching for any character, digit or underscore followed by @
\w+(?=@)

Match a single character that is a "word character" (letters, digits, and underscores) «\w+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=@)»
   Match the character "@" literally «@»

Positive and Negative Lookahead

Negative lookahead is indispensable if you want to match something not
  followed by something else. When explaining character classes, this
  tutorial explained why you cannot use a negated character class to
  match a q not followed by a u. Negative lookahead provides the
  solution: q(?!u). The negative lookahead construct is the pair of
  parentheses, with the opening parenthesis followed by a question mark
  and an exclamation point. Inside the lookahead, we have the trivial
  regex u.
Positive lookahead works just the same. q(?=u) matches a q that is
  followed by a u, without making the u part of the match. The positive
  lookahead construct is a pair of parentheses, with the opening
  parenthesis followed by a question mark and an equals sign. You can
  use any regular expression inside the lookahead (but not lookbehind,
  as explained below). Any valid regular expression can be used inside
  the lookahead. If it contains capturing groups then those groups will
  capture as normal and backreferences to them will work normally, even
  outside the lookahead. (The only exception is Tcl, which treats all
  groups inside lookahead as non-capturing.) The lookahead itself is not
  a capturing group. It is not included in the count towards numbering
  the backreferences. If you want to store the match of the regex inside
  a lookahead, you have to put capturing parentheses around the regex
  inside the lookahead, like this: (?=(regex)). The other way around
  will not work, because the lookahead will already have discarded the
  regex match by the time the capturing group is to store its match.

http://www.regular-expressions.info/lookaround.html


text:
Q: Copying value in assembly language Consider
mov reg, 5

where reg is considered to be some register. This statement copies the value 5 to a register.
My Question is:
If the mentioned register is divided into two parts, higher and lower, which part of the register will store the value and why?

A: In x86, mov always loads a whole register. It loads the register named in the instruction. But the named register might be part of another register. For example, cx is the low 16 bits of ecx.
Other processor architectures have other ways to load partial registers. For example, MIPS has lui to load the upper half of a register.

A: Registers in CPU are usually implemented with "bits", each "bit" holds from logical point of view value 0 or 1 (unless you want to talk about quantum computers, I will assume you mean common CPUs like x86, ARM, Z80, ...).
Integer values in assembler source, like mov reg,5 are then during assembly process converted into binary encoding: 5 = 0b101. If target reg is 16 bit register, after executing the instruction it will hold binary value 0000_0000_0000_0101 (which when interpreted as decimal integer is "5"). Now if you split that 16 bit register into high and low 8 bit values, those will be 0000_0000 (high 8 bits), 0000_0101 (low 8 bits).
In math terms the 16 bit register can hold values (when the bits are interpreted as unsigned integer values) from range 0..65535 (65535 = 216-1). If it contains some value V, then the top 8 bits contain value V_high = V div 256 (256 = 28, and "div" means integer division with truncating result), and lower 8 bits contain value V_low = V mod 256.
To compose the two values back into original 16 bit value: V = V_high * 256 + V_low.
Or from point of view of "bit manipulation" functions: V = (V_high<<8) | V_low. (ORing the two values after shifting the V_high to it's proper position 8 bits "left/up"). And V_high = shr V,8 (doing "div 256" by right shift), V_low = and V,0xFF (doing "mod 256" by using and to clear upper bits and keep only 8 lower ones).
In hexadecimal formatting each digit is exactly 4 bits "wide", so by using hexadecimal formatting you can easily "see" single bits set, like 0xA521 = 0b1010_0101_0010_0001, and after splitting that value into two 8 bit parts you will get 0xA5 from high 8 bits, and 0x21 from low 8 bits. (0xA521 = 42273 = 165*256 + 33, 165 is 0xA5, 33 is 0x21).
In answer to your question, both registers will PARTIALLY store the value 5, one storing its high bits (all zeroes), the other storing its low bits (still value 5 (bits 1_0_1) as long as we are talking about "part" of at least 3 bits size).
Also notice how the register always contains only the bit values, nothing else. How you interpret those (signed/unsigned integer, IEEE-754 floating point number, 16 0/1 true/false boolean array, or some completely custom interpretation) is up to the code, which does use the register value.
For example 32 bit value 1095069860 = 0x414570a4 = 0b01000001010001010111000010100100 is about 1 billion when interpreted as 32 bit integer (both signed and unsigned), but when you interpret those bits as 32 bit IEEE 754 "float", it means value 12.340000152587890625 (closest possible value to the "12.34" I did enter into asm source). The register itself is not aware, what the bits are supposed to mean, the meaning is given by the following code using the bit values.


text:
Q: Adding a one letter limit to a hangman game Upon creating the hangman game, I realized that the user can get away with using more than one letter at at a time, while using just one life. However, I do not know where/how to make it so the program rejects the guess, if it has more than one letter. Any help?
import time
print('Lets play hangman')
print("""
       _______
       |    |
       |    O
       |    |
       |  \- -/
       |    |
       |   / \\
       |  /   \\
   ____|____
   \n""")

print("""
you get 7 lives to guess the letters in the word. if you guess
incorrectly more of the hangman will appear and you lose a life. when you have
used your 7 lives, the man will have hung and you will have lost. If you guess a
correct letter, it will be show and if you guess the word without using the 7
turns, you win!
\n""")

easy_words = ['string', 'loop', 'python', 'print', 'run']
medium_words = ['module', 'input', 'logic', 'output']
hard_words = ['graphics window', 'variable', 'iteration', 'modules']
random_words = ['string', 'loop', 'python', 'print', 'run', 'graphics window', 'variable', 'iteration', 'modules', 'module', 'input', 'logic', 'output    ']
time.sleep(2)
print ("What level would you like to play at? Easy, Medium or Hard or Random?")
level_of_difficulty = input()
time.sleep(2)
print ("The program is now generating your word...")
if level_of_difficulty == 'Easy':
    generated_word = random.choice(easy_words)
elif level_of_difficulty == 'Medium':
    generated_word = random.choice(medium_words)
elif level_of_difficulty == 'Hard':
    generated_word = random.choice(hard_words)
elif level_of_difficulty == 'Random':
    generated_word = random.choice(random_words)
else:
    generated_word = random.choice(random_words)
guessed = ''

lives = 7

while lives > 0:

    missed = 0
print()
    for letter in generated_word:
        if letter in guessed:
            print (letter,end=' ')
        else:
            print ('_',end=' ')
            missed = missed + 1
    if missed == 0:
        print ('\n\nYou win!')
        quit()
        break
    guess=input("please guess a letter:")

    guessed = guessed + guess
        if guess not in generated_word:

            print ('\n that letter is not in this word, your lives have been decreased by 1.')
        print ('please try another letter.')
        lives = lives - 1
        missed = missed + 1

        print('your new lives value is')

        print(lives)

        if lives < 7:
            print('''   _______
   |    |   ''')
            if lives < 6:
                print('   |    O    ')
            if lives < 5:
                print('   |    |    ')
            if lives < 4:
                print('   |  \- -/  ')
            if lives < 3:
                print('   |    |    ')
            if lives < 2:
                print('   |   / \\  ')
            if lives < 1:
                print('   |  /   \\ ')
            if lives == 0:
             print('___|___      ')

             print('GAME OVER! You have run out of lives and lost the game')
             print('the secret word was')
             print(generated_word)
             quit()

At time of asking question, I did not have access to my code so I had to copy/paste from my previous questions. This means that there may be a couple of mistakes in my code. Apologies.

A: Change your guess input to:
guess = ""
while len(guess) != 1:
    guess=input("please guess a letter:")

A: To accept only one letter, and warn the user in the case of multiple letters, do the following:
guess = ""

while len(guess) != 1:
    guess=input("please guess a letter:")
    if len(guess) != 1:
        print( "Please guess only one letter.")


text:
Q: How can I use R to download the stock price at a particular date based on the company name from Master Index I'm struggling to download the stock price in R.
Here are my questions.

*

*I used getMasterIndex to download the MasterIndex of all SEC filings and filter 10-k reports (I only need 10-k reports for analysis)

*I need to use the company.name from the MasterIndex to download the stock price for each company at the previous day of filing date (which means I need to get the stock price for companies at different dates). But I failed by using the getSymbol function since it requires tickers instead of company names. So I need to first transfer the company.name to tickers? and then download the stock price based on the corresponding (filing date-1)?

But is there any way to directly download the stock price from the company.name of MasterIndex?
I attached the previous code and the getsymbol code below.
Please help me out of this problem. Much thanks!
master_indexes <- list.files("Master Indexes/",pattern="Rda")
all_indexes <- data.frame()

for(master_index in master_indexes){
  load(paste0("Master Indexes/",master_index))
  this_index <- year.master
  all_indexes <- bind_rows(all_indexes,this_index)
  print(master_index)
}

head(all_indexes)
company_filing_info <- all_indexes %>%
  filter(form.type =="10-K")

companies <- company_filing_info$company.name

library(tidyquant)

for (i in companies) {
  getSymbols(companies,
           src = "yahoo",
           auto.assign = TRUE)
}

A: A possible solution. The issue is that the way edgar output company names is different from others for some reason.
My example data with SEC Filings in 2022
edgar::getMasterIndex(2022, "myemail-2022@gmail.com")
load("Master Indexes/2022master.Rda")

df <- year.master %>%
  as_tibble() %>%
  filter(form.type == "10-K") %>%
  mutate(company.name = company.name %>%
           str_squish())

# A tibble: 6,906 x 6
   cik     company.name         form.type date.filed edgar.link quarter
   <chr>   <chr>                <chr>     <chr>      <chr>        <int>
 1 1000209 MEDALLION FINANCIAL~ 10-K      2022-03-14 edgar/dat~       1
 2 1000228 HENRY SCHEIN INC     10-K      2022-02-15 edgar/dat~       1
 3 1000229 CORE LABORATORIES N~ 10-K      2022-02-10 edgar/dat~       1
 4 1000298 IMPAC MORTGAGE HOLD~ 10-K      2022-03-11 edgar/dat~       1
 5 1000623 SCHWEITZER MAUDUIT ~ 10-K      2022-03-01 edgar/dat~       1
 6 1000683 BLONDER TONGUE LABO~ 10-K      2022-03-31 edgar/dat~       1
 7 1000694 NOVAVAX INC          10-K      2022-03-01 edgar/dat~       1
 8 1000697 WATERS CORP DE       10-K      2022-02-24 edgar/dat~       1
 9 1000753 INSPERITY INC        10-K      2022-02-11 edgar/dat~       1
10 1001082 DISH Network CORP    10-K      2022-02-24 edgar/dat~       1
# ... with 6,896 more rows

Now, download the .Rdata from my Drive will give you a data frame of stocks, which has company names and their respective tickers
# A tibble: 6,255 x 4
   symbol company_name                industry               market_cap
   <chr>  <chr>                       <chr>                  <chr>
 1 A      Agilent Technologies        Life Sciences Tools &~ 34.97B
 2 AA     Alcoa                       Metals & Mining        9.08B
 3 AAC    Ares Acquisition            Blank Check / SPAC     1.23B
 4 AACG   ATA Creativity Global       Diversified Consumer ~ 35.23M
 5 AACI   Armada Acquisition I        Blank Check / SPAC     204.51M
 6 AADI   Aadi Bioscience             Biotechnology          249.63M
 7 AAIC   Arlington Asset Investment  Mortgage Real Estate ~ 96.11M
 8 AAL    American Airlines Group     Airlines               8.77B
 9 AAMC   Altisource Asset Management Real Estate Managemen~ 22.16M
10 AAME   Atlantic American           Insurance              55.09M
# ... with 6,245 more rows

Merge stocks with df
stocks %>%
  merge(., df, by.x = "company_name", by.y = "company.name") %>%
  as_tibble()

# A tibble: 101 x 9
   company_name   symbol industry market_cap cik   form.type date.filed
   <chr>          <chr>  <chr>    <chr>      <chr> <chr>     <chr>
 1 American Home~ AMH    Equity ~ 14.18B     1562~ 10-K      2022-02-25
 2 Ameris Bancorp ABCB   Banks    2.86B      3515~ 10-K      2022-02-28
 3 Aon plc        AON    Insuran~ 56.42B     3152~ 10-K      2022-02-18
 4 Apollo Strate~ APGB   Shell C~ 848.70M    1838~ 10-K      2022-03-17
 5 Bank of Marin~ BMRC   Banks    515.27M    1403~ 10-K      2022-03-15
 6 Beam Global    BEEM   Electri~ 149.82M    1398~ 10-K      2022-03-31
 7 Blue Foundry ~ BLFY   Banks-R~ 347.40M    1846~ 10-K      2022-03-14
 8 California Ba~ CALB   Banks    158.12M    1752~ 10-K      2022-03-23
 9 CC Neuberger ~ PRPB   Shell C~ 1.08B      1812~ 10-K      2022-03-01
10 CC Neuberger ~ PRPC   Blank C~ 544.28M    1821~ 10-K      2022-03-31
# ... with 91 more rows, and 2 more variables: edgar.link <chr>,
#   quarter <int>

library(tidyquant)

final_df <- merged_df %>%
  mutate(date.filed = date.filed %>% as.Date(),
         price_before_filing = map2(.x = symbol,
                                    .y = date.filed,
                                    ~ tq_get(.x, from = as.Date(.y) - 1) %>%
                                      slice(1) %>%
                                      pull(adjusted)) %>%
           as.numeric()) %>%
  select(symbol, company_name, price_before_filing, everything())

# A tibble: 101 x 10
   symbol company_name       price_before_fi~ industry market_cap cik
   <chr>  <chr>                         <dbl> <chr>    <chr>      <chr>
 1 AMH    American Homes 4 ~            37.4  Equity ~ 14.18B     1562~
 2 ABCB   Ameris Bancorp                49.3  Banks    2.86B      3515~
 3 AON    Aon plc                      281.   Insuran~ 56.42B     3152~
 4 APGB   Apollo Strategic ~             9.75 Shell C~ 848.70M    1838~
 5 BMRC   Bank of Marin Ban~            35.1  Banks    515.27M    1403~
 6 BEEM   Beam Global                   18.4  Electri~ 149.82M    1398~
 7 BLFY   Blue Foundry Banc~            13.6  Banks-R~ 347.40M    1846~
 8 CALB   California BanCorp            22.4  Banks    158.12M    1752~
 9 PRPB   CC Neuberger Prin~             9.89 Shell C~ 1.08B      1812~
10 PRPC   CC Neuberger Prin~             9.85 Blank C~ 544.28M    1821~
# ... with 91 more rows, and 4 more variables: form.type <chr>,
#   date.filed <date>, edgar.link <chr>, quarter <int>


text:
Q: Boostrap-5 carousel is not working as it should be I'm learning to build websites, and I'm been doing it by myself with tutorials and stuff. I'm in the part of learning to use bootstrap, but when I try to use the carousel it doesn't work, the slide get stocked in the first picture and no matter how much I wait or how much I push any of the bottons, it does not work.
This is the code from the site, I got the link in my code but it does not work, while others elements from the site, work perfectly:

  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">

    Previous
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">

    Next
  </button>

A: You should add bootstrap.min.css and bootstrap.bundle.min.js CDN references to the project

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Demo</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">

      <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">

        Previous
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">

        Next
      </button>

References

*

*Get started with Bootstrap v5.2

*Carousel with Bootstrap v5.2


text:
Q: MemGrapg connection to PowerBI / Tableau Cam memgraph connect to any of the standard visualization products such as PowerBI , Tableau. N4j seems to have recently launch a enterprise version of PowerBI connector.

A: As of now, Memgraph does not have an ODBC connection to connect to such sources. However, it is in the works to make visualization products as one of the destinations for Memgraph analytics.
The thing is that PowerBI can connect to a streaming dataset and accept incoming data while making ad-hoc dynamic visualizations. This is not the same though as making queries to static data to the database and visualizing it as capabilities of streaming dataset is a bit low on the PowerBI side.
Haven't yet checked Tableau, so no info on that side.
For concrete use cases and technical help, try checking their Discord page at https://discord.com/invite/memgraph


text:
Q: Docker - Could not load X509 key pair I am on a fresh install of Docker on OSX El Capitain 10.11.4. I am getting this error when I try any commands with docker.
Could not load X509 key pair: crypto/tls: private key does not match public key. Make sure the key is not encrypted

I can run docker-machine just fine, but not start any docker containers.
Docker version (the only docker command that is working so far)
Brunos-iMac:~ brunoban$ docker -v
Docker version 1.10.3, build 20f81dd

Docker machine version
Brunos-iMac:~ brunoban$ docker-machine -v
docker-machine version 0.6.0, build e27fb87

Docker machine ls
Brunos-iMac:~ brunoban$ docker-machine ls
NAME      ACTIVE   DRIVER       STATE     URL                              SWARM   DOCKER    ERRORS
default   *        virtualbox   Running   tcp://192.168.99.100:2376           v1.10.3

Docker machine env
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export   DOCKER_CERT_PATH="/Users/brunoban/.docker/machine/machines/default"
export DOCKER_MACHINE_NAME="default"
# Run this command to configure your shell:
# eval $(docker-machine env)

I tried regenerating the certs with docker-machine regenerate-certs (even with the --force flag), but nothing seems to be working. Can anyone shed a light?
Thanks

A: Warning: My scenario is different from the original question, but my error message is the same.
I get the same error message when I try to add a new stack using the Portainer UI and a composition file.
My scenario is configured as follows:

*

*Ubuntu 16.04.5 LTS as O.S. host;

*Docker-ce version: 19.03.13 (API: 1.40)

*Portainer-ce (2.0.0);

*Portainer Agent (2.0.0);

My docker-compose.yaml using portainer/agent(it doesn't work like that)
    version: '2'

    services:

        portainer_agent:
            image: portainer/agent
            container_name: task.agent
            volumes:
                - /var/run/docker.sock:/var/run/docker.sock
                - /var/lib/docker/volumes:/var/lib/docker/volumes
            ports:
                - "9001:9001"
            networks:
                - agent_network
            restart: always

        # The portainer instance for managing Docker containers locally
        # To run on localhost in standalone mode
        # https://documentation.portainer.io/v2.0/deploy/linux/#docker-standalone
        portainer:
            image: portainer/portainer-ce
            command: -H tcp://task.agent:9001 --tlsskipverify
            volumes:
                - portainer_data:/data
                - /var/run/docker.sock:/var/run/docker.sock
                - /var/lib/docker/volumes:/var/lib/docker/volumes
            ports:
                - "8000:8000"
                - "9000:9000"
            networks:
                - agent_network
            restart: always

    networks:
      agent_network:
        attachable: true

    volumes:
        portainer_data:

Now, I realized that the goal of the portainer agent is to provide an alternative solution for executing commands when the docker is running as a cluster. In standalone mode, the agent is not required.
Looking at the official documentation of Portainer in the "Docker Standalone" session, I found the following:
"Use the following Docker commands to deploy the Portainer Server; note that the agent is not required on independent hosts, however, it does provide additional functionality if used (see Portainer and agent scenario below):"
The solution for my scenario
So, I just run Portainer without an Agent and when I deploy any stack using the Portainer UI, it's working fine.
I hope this helps someone who has the same error message.


text:
Q: Auto saving run configuration android studio I am making espresso tests for an android app and I wonder if there's a way to automatically save the run configurations for each test on Android Studio? ie, is there a way in which each time I run a new test, the configurations will save without me having to manually do so?

A: When you view the run configuration dialog in Android Studio, there should be a "share" checkbox at the top right of the dialog.  If you check this box, it will save the configuration into the .idea folder of the project.  See "runConfigurations" folder and the runConfigurations.xml file under .idea.  If save or check these files into source control, you will be able to share and reuse these configurations when you import the project again.


text:
Q: Read and write global variable I read a router param in my MainComponent in this way:
  ngOnInit(){
      this.activatedRoute.params.subscribe(params => {
         const id = params['id'];
         console.log(id);
     });
 }

I need to read "id" in another component (ContactComponent) that is no related to MainComponent, here's my routing:
const routes: Routes = [
{ path: 'contatti', component: ContattiComponent },
{ path: 'main/:id', component: MainComponent}
  ];

my idea was to store "id" in a global variable and then read in ContactComponent that global variable.
I have no idea on how to do so.


text:
Q: get parent element by class using jquery I have following html structure for example.

When i click on elements with class sms i need to get data-id attribute of element with class message.
What i've done using jquery. It doesn't work for me. How can i get parent element by class?
Thanks in advance!
$('.sms').click(function(){
    var id = $(this).parent('.msg-button').siblings('.message').data("id");
    alert(id);
})

A: You need to use .closest(). .parent() will search only the direct parent node, since you are looking for a matching ancestor element use .closest()

$('.sms').click(function() {
  var id = $(this).closest('.message').data("id");
  alert(id);
})

          sms

A: You need to use parents() instead of parent()
$('.sms').click(function(){
    var id = $(this).parents('.message').data("id");
    alert(id);
});

A: Use closest() to find the ancestor in hierarchy with specified selector
$('.sms').click(function(){
    var id = $(this).closest('.message').data("id");
    alert(id);
});

A: .parents(selector)
 ParentS will search up in the DOM


text:
Q: Win10 touch keyboard on login screen Until recently the touch keyboard on my Toshiba encore showed up when I touched the pin entry field, now it doesn't. Windows 10 runs in tablet mode and once logged in the keyboard works as expected, i.e. touch an input field and the keyboard comes up. And it's reproducible: login screen, no keyboard. Logged in, keyboard works flawless.
What extra (-hidden) settings are there for the logon session?


text:
Q: How to unregister BroadcastReceiver My app uses a BroadcastReceiver to get sms in this way:
SmsBR.java
public class SmsBR extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Object[] pdus = (Object[])bundle.get("pdus");
            final SmsMessage[] messages = new SmsMessage[pdus.length];

            for (int i = 0; i < pdus.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            }
            if (messages.length > 0)
                //doSomething();
            }
        }
    }
}

Manifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".Activity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".SmsBR">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
        </intent-filter>
    </receiver>
</application>

In this way SmsBR is always ON. I want to register it when a service starts (onCreate()) and unregister it when the service is destroyed (onDestroy()). How can I do this?

A: onDestroy() is not guaranteed to be called. When you start Activity from Activty, onPause() and onStop() method called instead of onDestroy().
onDestroy() calls when you hit back button or call finish() method.
Hence, broadcast receiver should be registered in onStart() or onResume(), and unregister receiver in onPause() or onStop().
If you unregister receiver in onDestroy() method, it might cause a memory leak in App.

A: Edit:
For an Activity:
In order to register your broadcast receiver from within your app, first, remove the <receiver> tag from your AndroidManifest.xml file. Then, call registerReceiver(BroadcastReceiver receiver, IntentFilter filter) in your onResume(). Use unregisterReceiver(BroadcastReceiver receiver) in your onPause() to unregister the Broadcast receiver.
For a Service:
Remove the receiver tag from the manifest file. You can then register your Broadcast receiver with the same method in the onCreate() and unregister in the onDestroy().
EDIT: Sample Code:
public class MyActivity extends Activity {
  private final BroadcastReceiver mybroadcast = new SmsBR();

  public void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mybroadcast, filter);
  }

  public void onPause() {
    super.onPause();

    unregisterReceiver(mybroadcast);
  }
}

A: First remove receiver tag from manifest,
then:
for service :
@Override
public void onCreate() {

    myReceiver = new SmsBR();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.intent.action.SMS_RECEIVED");// add any actions you want
    registerReceiver(myReceiver , filter);

 }

@Override
public void onDestroy() {
    super.onDestroy();
    if (myReceiver != null)
        unregisterReceiver(myReceiver);
}

for Activity:
public class MyActivity extends Activity {
  private final BroadcastReceiver mybroadcast = new SmsBR();

  public void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(mybroadcast, filter);
  }

  public void onPause() {
    super.onPause();

    if (mybroadcast!= null)
       unregisterReceiver(mybroadcast);
  }
}


text:
Q: Find two vectors whose sum is close to query vector Basically, this question is some sort of research question. I post it here to gain more hints from you. Suppose you have a set S of n d-dimension vectors. Given a d-dimension query vector, I want to find two vectors from S whose sum is close to the query vector, in term of cosine distance.
Right now, my solution is enumerating all possible combinations of S, results to n^2 possible sum-vectors. Then hash these n^2 vectors into b buckets using Local sensitive hashing. When given the query vector, we hash the query into one of the b buckets and check all the possible sum-vectors in that bucket, to see which one is closest. This will need O(b) space and O(n^2/b) searching time. This is just an space time trade off.
Is there any other good solutions ? Any hints are welcome ! I don't need the exact closest results, approximation results are more welcome!


text:
Q: Axios throwing CanceledError with Abort controller in react I have built an axios private instance with interceptors to manage auth request.
The system has a custom axios instance:
const BASE_URL = 'http://localhost:8000';
export const axiosPrivate = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
});

A custom useRefreshToken hook returns accessToken using the refresh token:
const useRefreshToken = () => {
  const { setAuth } = useAuth();

  const refresh = async () => {
    const response = await refreshTokens();
    // console.log('response', response);
    const { user, roles, accessToken } = response.data;
    setAuth({ user, roles, accessToken });
    // return accessToken for use in axiosClient
    return accessToken;
  };

  return refresh;
};

export default useRefreshToken;

Axios interceptors are attached to this axios instance in useAxiosPrivate.js file to attached accessToken to request and refresh the accessToken using a refresh token if expired.
const useAxiosPrivate = () => {
  const { auth } = useAuth();
  const refresh = useRefreshToken();

  useEffect(() => {
    const requestIntercept = axiosPrivate.interceptors.request.use(
      (config) => {
        // attach the access token to the request if missing
        if (!config.headers['Authorization']) {
          config.headers['Authorization'] = `Bearer ${auth?.accessToken}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    const responseIntercept = axiosPrivate.interceptors.response.use(
      (response) => response,
      async (error) => {
        const prevRequest = error?.config;
        // sent = custom property, after 1st request - sent = true, so no looping requests
        if (error?.response?.status === 403 && !prevRequest?.sent) {
          prevRequest.sent = true;
          const newAccessToken = await refresh();
          prevRequest.headers['Authorization'] = `Bearer ${newAccessToken}`;
          return axiosPrivate(prevRequest);
        }
        return Promise.reject(error);
      }
    );

    // remove the interceptor when the component unmounts
    return () => {
      axiosPrivate.interceptors.response.eject(responseIntercept);
      axiosPrivate.interceptors.request.eject(requestIntercept);
    };
  }, [auth, refresh]);

  return axiosPrivate;
};

export default useAxiosPrivate;

Now, this private axios instance is called in functional component - PanelLayout which is used to wrap around the pages and provide layout.
Here, I've tried to use AbortControllers in axios to terminate the request after the component is mounted.
function PanelLayout({ children, title }) {
  const [user, setUser] = useState(null);
  const axiosPrivate = useAxiosPrivate();
  const router = useRouter();

  useEffect(() => {
    let isMounted = true;
    const controller = new AbortController();
    const signal = controller.signal;

    const getUserProfile = async () => {
      try {
        const response = await axiosPrivate.get('/api/identity/profile', {
          signal,
        });
        console.log(response.data);
        isMounted && setUser(response.data.user);
      } catch (error) {
        console.log(error);
        router.push({
          pathname: '/seller/auth/login',
          query: { from: router.pathname },
        });
      }
    };
    getUserProfile();

    return () => {
      isMounted = false;
      controller.abort();
    };
  }, []);

  console.log('page rendered');

  return (

      <Sidebar className='h-screen w-[10rem]' />

        <PanelHeader title={title} classname='left-[10rem] h-[3.5rem]' />
        {children}

  );
}

export default PanelLayout;

However, the above code is throwing the following error:
CanceledError {message: 'canceled', name: 'CanceledError', code: 'ERR_CANCELED'}
code: "ERR_CANCELED"
message: "canceled"
name: "CanceledError"
[[Prototype]]: AxiosError
constructor: ƒ CanceledError(message)
__CANCEL__: true
[[Prototype]]: Error

Please suggest how to avoid the above error and get axios to work properly.

A: I also encountered the same issue and I thought that there was some flaw in my logic which caused the component to be mounted twice. After doing some digging I found that react apparently added this feature with with the new version 18 in StrictMode where useEffect was being run twice. Here's a link to the article clearly explaining this new behaviour.
One way you could solve this problem is by removing StrictMode from your application (Temporary Solution)
Another way is by using useRef hook to store some piece of state which is updated when your application is mounted the second time.
// CODE BEFORE USE EFFECT

const effectRun = useRef(false);

useEffect(() => {
    let isMounted = true;
    const controller = new AbortController();
    const signal = controller.signal;

    const getUserProfile = async () => {
      try {
        const response = await axiosPrivate.get('/api/identity/profile', {
          signal,
        });
        console.log(response.data);
        isMounted && setUser(response.data.user);
      } catch (error) {
        console.log(error);
        router.push({
          pathname: '/seller/auth/login',
          query: { from: router.pathname },
        });
      }
    };

    // Check if useEffect has run the first time
    if (effectRun.current) {
      getUserProfile();
    }

    return () => {
      isMounted = false;
      controller.abort();
      effectRun.current = true; // update the value of effectRun to true
    };
  }, []);

 // CODE AFTER USE EFFECT

Found the solution from this YouTube video.

A: I, too, encountered this issue. What made it worse is that axios doesn't provide an HTTP status code when the request has been canceled, although you do get error.code === "ERR_CANCELED". I solved it by handling the abort within the axios interceptor:
axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.code === "ERR_CANCELED") {
      // aborted in useEffect cleanup
      return Promise.resolve({status: 499})
    }
    return Promise.reject((error.response && error.response.data) || 'Error')
  }
);

As you can see, I ensure that the error response in the case of an abort supplies a status code of 499.

A: I faced the same problem in similar project, lets start by understanding first the root cause of that problem.
in react 18 the try to make us convenient to the idea of mounting and unmounting components twice for future features that the are preparing, the the useEffect hook now is mounted first time then unmounted the mounted finally.
so they need from us adapt our projects to the idea of mount and unmount of components twice
so you have two ways, adapting these changes and try to adapt your code to accept mounting twice, or making some turn around code to overcome mounting twice, and I would prefer the first one.
here in your code after first mount you aborted your API request in clean up function, so when the component dismount and remount again it face an error when try to run previously aborted request, so it throw exception, that's what happens
1st solution (adapting to react changing):
return () => {
      isMounted = false
      isMounted && controller.abort()
    }

so in above code we will abort controller once only when isMounted is true, and thats will solve your problem
2nd solution (turn around to react changing):
by using useRef hook and asign it to a variable and update its boolean value after excuting the whole code only one time.
const runOnce = useRef(true)

useEffect(()=>{
 if(runOnce.current){
   //requesting from API
  return()=>{
   runOnce.current = false
  }
 }
},[])

3rd solution (turn around to react changing):
remove React.StrictMode from index.js file