text:
Q: Draw a border line for a specific width I want to bring my Sketch file to HTML/CSS in the browser.
How can I implement the white line just between the small and big text, as shown in the image below?

A: If don't want to include any additional html element then you can use pseduo element:after.
h2:after {
  display:block;
  content:" ";
  width: 80px;
  height: 5px;
  background: grey;
  margin-top: 5px;
}

fiddle

A: You can add an empty div with a bottom border & custom width, which is of cleaner and shorter code:

body {
    background-color: blue;
    color: white;
}
#mydiv {
    border-bottom: 4px solid white;
    width: 33%;
}
#myline {
    height: 4px;
    background-color: white;
    border: 0px solid black;
    width: 33%;
}
A div:

A horizontal line:

That's 4 lines for the HR and 2 for the div, and that's without making the hr align to the left.

If you don't want to add another element you can use ::after on any element - just make it have display: block and set the color, width, height etc. similar to the above code.

A: You can add tag
 and him specify needed width, height,color...


text:
Q: How to decide whether the given value is float or double in Java? What is the data type for the number 9.6352 in Java?
Actually if I postfix the number with 'd' or 'f'. then it will be quite easy to decide.
But if I leave it as alone, then which will be the default type of the number in java?

A: By default, any floating point data type without 'f' or 'F' postfixed, is considered as of type double.
Since the given number doesn't end with 'f'/'F', it is of type double.
We can optionally add 'd' or 'D' at the end to mark it as a double type, but again, it is optional.

A: For you interest;

*

*0xD is 13, 0xF is 15

*0D is (double) 0 and 0F is (float) 0.

A: Go check out the JLS section on floating point literals (§3.10.2):

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.

So it's a double if it's not suffixed.

A: By default it's double primitive type.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use `gke-gcloud-auth-plugin` programmatically (as a replacement for the gcp auth plugin) I've some existing code that will break on GKE with Kubernetes 1.26 clusters as a result of the change from the built-in GCP auth provider to gke-gcloud-auth-plugin.
I understand how to revise the code to leverage the gke-gcloud-auth-plugin binary (see below) but I am running the code in a serverless (Cloud Functions) environment and am unable to install binaries and so this isn't a solution for me.
I'm looking to deploy the code as a single binary that can get-credentials, and populate an api.Config so that the runtime's identity can be used to (repeatedly) authenticate the code to a GKE cluster as I'm able to do currently on <1.26 clusters.
Before I spend too much time trying to work this change into my code, I'm hoping that someone else has already done something similar and can provide a solution or even pointers.
The code uses Google's Golang Kubernetes Engine API to get-credentials which it uses to populate an api.Config which it then uses to interact with a cluster.
ctx := context.Background()
containerService, _ := container.NewService(ctx)
name := fmt.Sprintf("projects/%s/locations/%s/clusters/%s",
    clusterProject,
    clusterLocation,
    clusterName,
)
rqst := containerService.Projects.Locations.Clusters.Get(name)
resp, _ := rqst.Do()
cert, _ := base64.StdEncoding.DecodeString(resp.MasterAuth.ClusterCaCertificate)
server := fmt.Sprintf("https://%s", resp.Endpoint)

apiConfig := api.Config{
    APIVersion: "v1",
    Kind:       "Config",
    Clusters: map[string]*api.Cluster{
        clusterName: {
            CertificateAuthorityData: cert,
            Server:                   server,
        },
    },
    Contexts: map[string]*api.Context{
        clusterName: {
            Cluster:  clusterName,
            AuthInfo: clusterName,
        },
    },
    AuthInfos: map[string]*api.AuthInfo{
        clusterName: {
            [see below]
            },
        },
    },
}

The code currently uses the GCP auth provider which enables me to provide a single binary that performs the GCP auth:
AuthProvider: &api.AuthProviderConfig{
    Name: "gcp",
    Config: map[string]string{
        "scopes": "https://www.googleapis.com/auth/cloud-platform",
    },

Using the gke-gcloud-auth-plugin client-go credential plugin requires a callout to the gke-gcloud-auth-plugin binary which generates an ExecCredential that is then parsed by client-go:
Exec: &api.ExecConfig{
    Command:            "gke-gcloud-auth-plugin",
    APIVersion:         "client.authentication.k8s.io/v1",
    InstallHint:        "Requires gke-gcloud-auth-plugin",
    ProvideClusterInfo: true,
    InteractiveMode:    api.IfAvailableExecInteractiveMode,
},

I'm looking for a way to integrate the above api.Config construction with the gke-gcloud-auth-plugin as a library to (continue to use) the (Cloud Functions) runtime identity (via Application Default Credentials) as a mechanism for acquiring access tokens to authenticate the client (code) against the GKE cluster without requiring the installation of kubectl, gcloud or gke-gcloud-auth-plugin.
The OAuth mechanism underlying GCP auth plugin provider and gke-gcloud-auth-plugin is unchanged (which helps), I just don't yet understand how to incorporate this into kubectl's new auth mechanism.
References

*

*Google Issue Tracker How to use gke-gcloud-auth-plugin programmatically as a replacement for GCP auth plugin

*kubectl auth changes with GKE 1.26

*client-go api.Config

*client-go credentials plugins

*gke-gcloud-auth-plugin

*GCP auth plugin

A: I just saw this v1.26 GKE breaking change and agree that installing gcloud (which is few GB large) for a simple Golang client-go app is overkill and even unfeasible for containerized apps
Perhaps your approach of reimplementing a subset of GCP auth is the way to go. One such implementation can be found here: https://pkg.go.dev/github.com/traviswt/gke-auth-plugin
I've just tried the link above and it works beautifully. No need to bundle gcloud with your Golang app. Just replace in your kubeconfig:
command: gke-gcloud-auth-plugin -> command: gke-auth-plugin
For reference, you can get your kubeconfig via using gcloud and kubectl:
gcloud container clusters get-credentials <CLUSTER_NAME> --zone <ZONE> --project <PROJECT_NAME>

kubectl config view --flatten

Using this as a reference, you can use Golang to generate the kubeconfig with google-cloud-go (Reference that will need modification for v1.26 breaking change) and bypass gcloud completely


text:
Q: Would using rainbow tables to detect weak user passwords feasible? As I understand in most security breach where the list of hashed password are compromised, attackers do use brute-force to try to find weak password and, invariably, they always find quite some (like in the recent Github breach).
If I'm not mistaken in most cases when a user creates an account, the password is sent, encrypted (due to TLS / SSL), to the website which then adds some salt and stores the hash + salt.
Even in most sophisticated cases (like when bcrypt is used), upon account creation there's one point in time at which the server does have the password in cleartext.
My question is: couldn't you use, at that very moment when you have the password in the clear that the user is trying to use for his new account, a gigantic rainbow-table on the server side to check for billions and billions of weak passwords in a split-nanosecond?
Then if you detect that a weak password is used, you'd simply tell to the user that his password is too simple and that, no, using "edcrfvtgb1" isn't smart.
I mean: if attackers manage to brute-force weak-password even though they have to deal with the problem of the salt, couldn't servers benefit from the fact that, when the users creates a new account, they do know the password in the clear to simply look it up in a big rainbow table when the user creates his account?
This doesn't seem hard to implement and seen harddisk sizes these days, it's probably not problematic to store a big rainbow table on the server side.
Am I missing something obvious or would this help catch a lot of weak passwords and, hence, mitigate the endless accounts compromise we keep seeing on a nearly daily basis?

A: The lookup time would be negligible, so this is a feasible way to prevent the use of weak passwords. However as @thorsten mentions in his comment, if you're implementing this on top of other password content requirements and some user enters a password that meets those requirements but is also in your table, it would be difficult to describe to the user exactly what was wrong with the password in a way that's easy for anyone to understand.
As @Mike eluded to in a comment, this type of security measure wouldn't be implemented with a rainbow table (which as he said is a map of hashes to plaintext strings), it would be implemented with a simple list of weak passwords. You don't need the hashes in this case.

A: TL;DR - yes & no.  Yes it can be done but no, it shouldn't be done as you suggest.

My question is: couldn't you use, at that very moment when you have the password in the clear that the user is trying to use for his new account, a gigantic rainbow-table on the server side to check for billions and billions of weak passwords in a split-nanosecond?

No, you can't - or at least, not as you suggested.
To make the approach you suggested viable would require compromising the security of the site.  And there's better ways to accomplish what you want to do.
Why? The problem is a misunderstanding with how rainbow tables work.  And here are the issues.

*

*A rainbow table is precomputed

*A the salt added to a new user's password for hashing should be random
A good salt will be at least 10 - 16 characters long (see 1, 2, 3), which will add ~80-128 bits more of entropy to the overall password.  Even with a 10 character salt and an 8 character password (both weak), that's 2.2 x10^43 potential combinations.  A rainbow table with that many combinations would require more disk space than most can afford.
If you used a fixed salt (which isn't recommended as it compromises the security), then you would be able to relatively easily build a rainbow table that could be used as you suggested.  But a fixed salt partially defeats the purpose of using a salt to begin with.
Rainbow tables are useful attack vectors when salts aren't used or when the salt is a fixed length.  Without a random salt, it's easy enough to take the hashed value from the password file and look up the cleartext password in the rainbow table.
Using random salts force an attacker to use brute force to crack the password.  There's just too many combinations to be stored to make a lookup approach worthwhile.  Technology advancements have also made brute force approaches more practical.  As of Dec 2012, some of the fastest GPU backed brute force password cracking systems could process 350 billion passwords per second.  (see here for reference)  With technology advancements, that rate will only increase.

Am I missing something obvious or would this help catch a lot of weak passwords and, hence, mitigate the endless accounts compromise we keep seeing on a nearly daily basis?

Yes, you're kind of missing something about rainbow tables but we just beat that subject into the ground with the above.
As I alluded to earlier, there are easier ways to do what you're suggesting.  They can even be done client side via javascript so you don't have to incur a roundtrip penalty for the server to tell the client / new user that their password is too weak.
Password vaults like KeePass* have a built in password entropy indicator.  Using the "edcrfvtgb1" password example that you provided, we see it only has 50 bits of entropy which is relatively weak.  Current recommendations are to have passwords with 98 to 128 bits of entropy depending upon how secure you need it to be.

You could use a javascript plugin that measures password entropy to provide immediate feedback to the new user or a user who is changing their password.  This link goes into some detail with actual code and also contrasts against older methods of handling passwords.  Running a web search against javascript password strength meter comes back with more than enough hits to kickstart additional research.
So your original thought is good, and yes the broader question that you are asking can be done.  From my observation, I have seen a number of sites start to incorporate password strength meters to help guide users in selecting passwords.
 * I just happen to know of KeePass, there are many other excellent password vaults out there that offer the same functionality.

... and the obligatory xkcd link.  Hat tip to Marjan Venema for posting it first in a comment.

So just how much data would that be?
10 bytes of salt + 8 bytes of password yields 144 bits.
2^144 is ~2.2x10^43 combinations.
Each combination will need at least 18 bytes for salt+password and 60 bytes for a bcrypt hash.  (see here)  For a total of (at least) 78 bytes per combination.
2.2x10^42 combinations * 78 bytes = ~1.7x10^45 bytes.
Shrinking that down a bit yields: 1,438,846,037,749,345,026,048 YB (yotta bytes)
Or perhaps we could call that 1.4 penta-yotta bytes.  I call it "a lot."


text:
Q: Error when try to run my project in cmd I have a structure code like this :

I want to run my program using mcd using javac, like this : javac ListenerZipFile.java. The result like :

Why i can't run my program?

A: you are using a package without telling javac where it is located (jnotify for example).
you'd have to use it like:
javac -classpath "path/to/jnotify-0.94.jar" test.java

A: There are 2 problems here.

*

*Incorrect directory location for compiling packed classes.

*classpath no set correctly.

Consider you have, source_dir = D:\~\~\src, jar_location = D:\~\~\lib and package is com.example then your steps to compile are:

*

*cd to $source_dir

*$source_dir> set classpath=.;jar_location

*$source_dir> javac com\example\Examples1.java or $source_dir> javac com\example\*.java

As per path shared, command to compile should be :
cd C:\ListenerZipfile\src
javac -cp .;C:\ListenerZipfile\lib\*.jar com\sigma\main\ListenerZipFile.java

Command to run java program with above path:
java -cp .;C:\ListenerZipfile\lib\*.jar com.sigma.main.ListenerZipFile

A: if you are using eclipse (from the screen shot i think you do) then
right click on your project->Properties->Java Build Path, click on Libraries tab->click on "Add External JARs" button-> pick your jar and click OK to close all windows.
This should solve your problem, if your problem is jar dependencies


text:
Q: Include root files into header files I want to include files from the root directory of my site within the WordPress "header" file.
Is there any function for including a file from the root folder?

A: If you are talking about the WordPress root, use:
include ABSPATH . "/extra-file.php";

ABSPATH is always the WordPress root, you can see that in your wp-config.php.

A: In your wp-config.php file, add the following line before /* That's all, stop editing! Happy blogging. */:
define( 'ROOT_FOLDER', dirname( __FILE__ ) );

Now you can use the following for including files from your root folder:
include ROOT_FOLDER . '/filename.php';

A: If you want to "include" some CSS or Javascript (i.e. if you're not talking about PHP include), use the function get_site_url().
Example usage:
<script type="text/javascript" src="<?php echo get_site_url(); ?>/example_javascript.js"></script>

A: Its as simple as this.
include($_SERVER['DOCUMENT_ROOT']."/yourfile.php");

Cheers!!


text:
Q: Как перевернуть выбранную карточку У меня на сайте есть список карточек , я хочу реализовать чтобы при клике на выбранную карточку она переворачивалась.

var card = document.querySelector('.card');

function name() {
  console.log("1")
  card.classList.toggle('is-flipped');
}

{{ task.title }} {% if task.is_active %}
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="15pt" height="15pt" viewBox="0 0 15 15" version="1.1">
                                <g id="surface1">
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(46.666667%,81.960784%,70.196078%);fill-opacity:1;" d="M 2.875 2.210938 C 3.074219 2.121094 3.265625 2.023438 3.433594 1.902344 C 4.039062 1.460938 4.453125 0.601562 5.183594 0.363281 C 5.882812 0.136719 6.722656 0.582031 7.5 0.582031 C 8.277344 0.582031 9.117188 0.136719 9.816406 0.363281 C 10.546875 0.601562 10.960938 1.460938 11.566406 1.902344 C 12.179688 2.347656 13.121094 2.480469 13.566406 3.089844 C 14.007812 3.695312 13.847656 4.632812 14.082031 5.359375 C 14.3125 6.0625 15 6.722656 15 7.5 C 15 8.277344 14.3125 8.9375 14.082031 9.640625 C 13.847656 10.367188 14.007812 11.304688 13.566406 11.910156 C 13.121094 12.519531 12.179688 12.652344 11.566406 13.097656 C 10.960938 13.539062 10.546875 14.398438 9.816406 14.636719 C 9.117188 14.863281 8.277344 14.417969 7.5 14.417969 C 6.722656 14.417969 5.882812 14.863281 5.183594 14.636719 C 4.453125 14.398438 4.039062 13.539062 3.433594 13.097656 C 2.820312 12.652344 1.878906 12.519531 1.433594 11.910156 C 0.992188 11.304688 1.152344 10.367188 0.917969 9.640625 C 0.6875 8.9375 0 8.277344 0 7.5 C 0 6.722656 0.6875 6.0625 0.917969 5.359375 C 1.152344 4.632812 0.992188 3.695312 1.433594 3.089844 C 1.574219 2.898438 1.761719 2.753906 1.976562 2.628906 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(96.078431%,96.078431%,96.078431%);fill-opacity:1;" d="M 13.578125 7.5 C 13.578125 8.128906 13.019531 8.664062 12.835938 9.234375 C 12.644531 9.824219 12.777344 10.582031 12.417969 11.074219 C 12.058594 11.570312 11.292969 11.679688 10.796875 12.039062 C 10.304688 12.394531 9.96875 13.09375 9.378906 13.285156 C 8.808594 13.46875 8.128906 13.109375 7.5 13.109375 C 6.871094 13.109375 6.191406 13.46875 5.621094 13.285156 C 5.03125 13.09375 4.695312 12.394531 4.203125 12.039062 C 3.707031 11.679688 2.941406 11.570312 2.582031 11.074219 C 2.222656 10.582031 2.355469 9.824219 2.164062 9.234375 C 1.980469 8.664062 1.421875 8.128906 1.421875 7.5 C 1.421875 6.871094 1.980469 6.335938 2.164062 5.765625 C 2.355469 5.175781 2.222656 4.417969 2.582031 3.925781 C 2.941406 3.429688 3.707031 3.320312 4.203125 2.960938 C 4.695312 2.605469 5.03125 1.90625 5.621094 1.714844 C 6.191406 1.53125 6.871094 1.890625 7.5 1.890625 C 8.128906 1.890625 8.808594 1.53125 9.378906 1.714844 C 9.96875 1.90625 10.304688 2.605469 10.796875 2.960938 C 11.292969 3.320312 12.058594 3.429688 12.417969 3.925781 C 12.777344 4.417969 12.644531 5.175781 12.835938 5.765625 C 13.019531 6.335938 13.578125 6.871094 13.578125 7.5 Z M 13.578125 7.5 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(40.392157%,70.980392%,62.352941%);fill-opacity:1;" d="M 14.082031 5.359375 C 13.847656 4.632812 14.007812 3.695312 13.566406 3.089844 C 13.121094 2.480469 12.179688 2.347656 11.566406 1.902344 C 10.960938 1.460938 10.546875 0.601562 9.816406 0.363281 C 9.519531 0.269531 9.199219 0.292969 8.867188 0.351562 C 8.882812 0.355469 8.898438 0.359375 8.914062 0.363281 C 9.640625 0.601562 10.054688 1.460938 10.660156 1.902344 C 11.273438 2.347656 12.21875 2.480469 12.664062 3.089844 C 13.101562 3.695312 12.941406 4.632812 13.175781 5.359375 C 13.40625 6.0625 14.09375 6.722656 14.09375 7.5 C 14.09375 8.277344 13.40625 8.9375 13.175781 9.640625 C 12.941406 10.367188 13.101562 11.304688 12.664062 11.910156 C 12.21875 12.519531 11.273438 12.652344 10.660156 13.097656 C 10.054688 13.539062 9.640625 14.398438 8.914062 14.636719 C 8.898438 14.640625 8.882812 14.644531 8.867188 14.648438 C 9.199219 14.707031 9.519531 14.730469 9.816406 14.636719 C 10.546875 14.398438 10.960938 13.539062 11.566406 13.097656 C 12.179688 12.652344 13.121094 12.519531 13.566406 11.910156 C 14.007812 11.304688 13.847656 10.367188 14.082031 9.640625 C 14.3125 8.9375 15 8.277344 15 7.5 C 15 6.722656 14.3125 6.0625 14.082031 5.359375 Z M 14.082031 5.359375 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(93.72549%,91.372549%,94.509804%);fill-opacity:1;" d="M 12.835938 5.765625 C 12.644531 5.175781 12.777344 4.417969 12.417969 3.925781 C 12.058594 3.429688 11.292969 3.320312 10.796875 2.960938 C 10.304688 2.605469 9.96875 1.90625 9.378906 1.714844 C 9.105469 1.628906 8.808594 1.664062 8.5 1.726562 C 9.074219 1.929688 9.410156 2.609375 9.890625 2.960938 C 10.386719 3.320312 11.152344 3.429688 11.511719 3.925781 C 11.871094 4.417969 11.738281 5.175781 11.929688 5.765625 C 12.117188 6.335938 12.675781 6.871094 12.675781 7.5 C 12.675781 8.128906 12.117188 8.664062 11.929688 9.234375 C 11.738281 9.824219 11.871094 10.582031 11.511719 11.074219 C 11.152344 11.570312 10.386719 11.679688 9.890625 12.039062 C 9.410156 12.390625 9.074219 13.070312 8.5 13.273438 C 8.808594 13.335938 9.105469 13.371094 9.378906 13.285156 C 9.96875 13.09375 10.304688 12.394531 10.796875 12.039062 C 11.292969 11.679688 12.058594 11.570312 12.417969 11.074219 C 12.777344 10.582031 12.644531 9.824219 12.835938 9.234375 C 13.019531 8.664062 13.578125 8.128906 13.578125 7.5 C 13.578125 6.871094 13.019531 6.335938 12.835938 5.765625 Z M 12.835938 5.765625 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(57.254902%,87.843137%,76.862745%);fill-opacity:1;" d="M 5.957031 9.933594 L 4.832031 8.582031 C 4.664062 8.375 4.691406 8.074219 4.894531 7.902344 L 5.210938 7.640625 C 5.414062 7.472656 5.714844 7.5 5.886719 7.703125 L 6.453125 8.386719 C 6.585938 8.546875 6.835938 8.558594 6.980469 8.402344 L 9.875 5.578125 C 10.058594 5.386719 10.363281 5.378906 10.554688 5.5625 L 10.851562 5.84375 C 11.042969 6.027344 11.050781 6.332031 10.867188 6.523438 L 7.371094 9.980469 C 6.980469 10.390625 6.316406 10.367188 5.957031 9.933594 Z M 5.957031 9.933594 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(46.666667%,81.960784%,70.196078%);fill-opacity:1;" d="M 10.851562 5.84375 L 10.554688 5.5625 C 10.363281 5.378906 10.058594 5.386719 9.875 5.578125 L 9.769531 5.679688 L 9.945312 5.84375 C 10.136719 6.027344 10.144531 6.332031 9.960938 6.523438 L 6.464844 9.980469 C 6.394531 10.054688 6.316406 10.113281 6.230469 10.160156 C 6.597656 10.359375 7.066406 10.300781 7.371094 9.980469 L 10.867188 6.523438 C 11.050781 6.332031 11.042969 6.027344 10.851562 5.84375 Z M 10.851562 5.84375 "/>
                                </g>
                                </svg> {% elif task.is_wait %}

        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="15pt" height="15pt" viewBox="0 0 15 15" version="1.1">
                                <g id="surface1">
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;" d="M 12.5 3.015625 L 12.5 1.699219 C 12.871094 1.484375 13.125 1.085938 13.125 0.625 L 13.125 0.3125 C 13.125 0.140625 12.984375 0 12.8125 0 L 2.1875 0 C 2.015625 0 1.875 0.140625 1.875 0.3125 L 1.875 0.625 C 1.875 1.085938 2.128906 1.484375 2.5 1.703125 L 2.5 3.015625 C 2.5 4.253906 3.027344 5.441406 3.949219 6.269531 L 5.316406 7.5 L 3.949219 8.730469 C 3.027344 9.558594 2.5 10.746094 2.5 11.984375 L 2.5 13.296875 C 2.128906 13.515625 1.875 13.914062 1.875 14.375 L 1.875 14.6875 C 1.875 14.859375 2.015625 15 2.1875 15 L 12.8125 15 C 12.984375 15 13.125 14.859375 13.125 14.6875 L 13.125 14.375 C 13.125 13.914062 12.871094 13.515625 12.5 13.296875 L 12.5 11.984375 C 12.5 10.746094 11.972656 9.558594 11.050781 8.730469 L 9.683594 7.5 L 11.050781 6.269531 C 11.972656 5.441406 12.5 4.253906 12.5 3.015625 Z M 10.214844 5.339844 L 8.332031 7.035156 C 8.199219 7.152344 8.125 7.324219 8.125 7.5 C 8.125 7.675781 8.199219 7.847656 8.332031 7.964844 L 10.214844 9.660156 C 10.871094 10.25 11.25 11.097656 11.25 11.984375 L 11.25 13.125 L 10.46875 13.125 L 7.75 9.5 C 7.632812 9.34375 7.367188 9.34375 7.25 9.5 L 4.53125 13.125 L 3.75 13.125 L 3.75 11.984375 C 3.75 11.097656 4.128906 10.25 4.785156 9.660156 L 6.667969 7.964844 C 6.800781 7.847656 6.875 7.675781 6.875 7.5 C 6.875 7.324219 6.800781 7.152344 6.667969 7.035156 L 4.785156 5.339844 C 4.128906 4.75 3.75 3.902344 3.75 3.015625 L 3.75 1.875 L 11.25 1.875 L 11.25 3.015625 C 11.25 3.902344 10.871094 4.75 10.214844 5.339844 Z M 10.214844 5.339844 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;" d="M 9.652344 4.375 L 5.347656 4.375 C 5.222656 4.375 5.109375 4.449219 5.058594 4.5625 C 5.011719 4.675781 5.03125 4.804688 5.113281 4.898438 L 7.289062 6.90625 C 7.351562 6.957031 7.425781 6.984375 7.5 6.984375 C 7.574219 6.984375 7.648438 6.957031 7.710938 6.90625 L 9.886719 4.898438 C 9.96875 4.804688 9.988281 4.675781 9.941406 4.5625 C 9.890625 4.449219 9.777344 4.375 9.652344 4.375 Z M 9.652344 4.375 "/>
                                </g>
                                </svg> {% else %}

        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="15pt" height="15pt" viewBox="0 0 15 15" version="1.1">
                                <g id="surface1">
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(88.627451%,91.372549%,93.333333%);fill-opacity:1;" d="M 14.707031 7.5 C 14.707031 11.480469 11.480469 14.707031 7.5 14.707031 C 3.519531 14.707031 0.292969 11.480469 0.292969 7.5 C 0.292969 3.519531 3.519531 0.292969 7.5 0.292969 C 11.480469 0.292969 14.707031 3.519531 14.707031 7.5 Z M 14.707031 7.5 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,49.019608%,59.215686%);fill-opacity:1;" d="M 13.300781 7.5 C 13.300781 10.703125 10.703125 13.300781 7.5 13.300781 C 4.296875 13.300781 1.699219 10.703125 1.699219 7.5 C 1.699219 4.296875 4.296875 1.699219 7.5 1.699219 C 10.703125 1.699219 13.300781 4.296875 13.300781 7.5 Z M 13.300781 7.5 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(100%,100%,100%);fill-opacity:1;" d="M 3.867188 6.445312 L 11.132812 6.445312 L 11.132812 8.554688 L 3.867188 8.554688 Z M 3.867188 6.445312 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;" d="M 2.402344 2.695312 C 2.328125 2.695312 2.25 2.664062 2.195312 2.609375 C 2.140625 2.554688 2.109375 2.480469 2.109375 2.402344 C 2.109375 2.328125 2.140625 2.25 2.195312 2.195312 C 2.25 2.140625 2.328125 2.109375 2.402344 2.109375 C 2.480469 2.109375 2.554688 2.140625 2.609375 2.195312 C 2.664062 2.25 2.695312 2.328125 2.695312 2.402344 C 2.695312 2.480469 2.664062 2.554688 2.609375 2.609375 C 2.554688 2.664062 2.480469 2.695312 2.402344 2.695312 Z M 2.402344 2.695312 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;" d="M 7.5 15 C 5.496094 15 3.613281 14.21875 2.195312 12.804688 C 0.78125 11.386719 0 9.503906 0 7.5 C 0 5.972656 0.457031 4.503906 1.320312 3.25 C 1.410156 3.117188 1.59375 3.082031 1.726562 3.175781 C 1.859375 3.265625 1.894531 3.449219 1.800781 3.582031 C 1.007812 4.738281 0.585938 6.09375 0.585938 7.5 C 0.585938 11.3125 3.6875 14.414062 7.5 14.414062 C 11.3125 14.414062 14.414062 11.3125 14.414062 7.5 C 14.414062 3.6875 11.3125 0.585938 7.5 0.585938 C 6.09375 0.585938 4.738281 1.007812 3.582031 1.800781 C 3.449219 1.894531 3.265625 1.859375 3.175781 1.726562 C 3.082031 1.59375 3.117188 1.410156 3.25 1.320312 C 4.503906 0.457031 5.972656 0 7.5 0 C 9.503906 0 11.386719 0.78125 12.804688 2.195312 C 14.21875 3.613281 15 5.496094 15 7.5 C 15 9.503906 14.21875 11.386719 12.804688 12.804688 C 11.386719 14.21875 9.503906 15 7.5 15 Z M 7.5 15 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;" d="M 7.5 13.59375 C 4.140625 13.59375 1.40625 10.859375 1.40625 7.5 C 1.40625 4.140625 4.140625 1.40625 7.5 1.40625 C 10.859375 1.40625 13.59375 4.140625 13.59375 7.5 C 13.59375 10.859375 10.859375 13.59375 7.5 13.59375 Z M 7.5 1.992188 C 4.464844 1.992188 1.992188 4.464844 1.992188 7.5 C 1.992188 10.535156 4.464844 13.007812 7.5 13.007812 C 10.535156 13.007812 13.007812 10.535156 13.007812 7.5 C 13.007812 4.464844 10.535156 1.992188 7.5 1.992188 Z M 7.5 1.992188 "/>
                                <path style=" stroke:none;fill-rule:nonzero;fill:rgb(0%,0%,0%);fill-opacity:1;" d="M 11.132812 8.847656 L 3.867188 8.847656 C 3.707031 8.847656 3.574219 8.714844 3.574219 8.554688 L 3.574219 6.445312 C 3.574219 6.285156 3.707031 6.152344 3.867188 6.152344 L 11.132812 6.152344 C 11.292969 6.152344 11.425781 6.285156 11.425781 6.445312 L 11.425781 8.554688 C 11.425781 8.714844 11.292969 8.847656 11.132812 8.847656 Z M 4.160156 8.261719 L 10.839844 8.261719 L 10.839844 6.738281 L 4.160156 6.738281 Z M 4.160156 8.261719 "/>
                                </g>
                                </svg> {% endif %}

{{task.short_description}}...

    Перейти к задаче

123

У меня получается либо перевернуть первую, либо все сразу

A: Или можно так воспользоваться контекстом вызова. Не используя аргумент события.
Воспользовался ответом @Roman.

var card = document.querySelectorAll(".card");

function name() {
  this.classList.toggle("is-flipped")
}

card.forEach(el => el.addEventListener('click', name))
.is-flipped {
  background-color: red;
  transform: rotateY(180deg)
}
div {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: solid 1px red;
  cursor: pointer;
  border-radius: 10px;
  text-align: center;
  line-height: 50px;
  font-size: 20px;
}

1

2

3

4

5

A: Нужно достать все карточки с помощью querySelectorAll, и повесить на каждую свой обработчик, в данном случае addEventListener
В дальнейшем получать доступ к текущей карточке с помощью e.target

var card = document.querySelectorAll(".card");

function name(e) {
  e.target.classList.toggle("is-flipped")
}

card.forEach(el => el.addEventListener('click', name))
.is-flipped {
  background-color: red;
  transform: rotateY(180deg)
}
div {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: solid 1px red;
  cursor: pointer;
  border-radius: 10px;
  text-align: center;
  line-height: 50px;
  font-size: 20px;
}

1

2

3

4

5


text:
Q: Is there a CUDA threadId alike in Jax (google)? I'm trying to understand the behaviour of jax.vmap/pmap, (jax: https://jax.readthedocs.io/). CUDA has threadId to let you know which thread is executing the code, is there a similar concept in jax? (jax.process_id is not)

A: No, there is no real analog to CUDA threadid in JAX. Details about GPU thread assignment are handled at a lower level by the XLA compiler, and I don't know of any straightforward API to plumb this information back to JAX's Python runtime.
One case where JAX does offer higher-level handling of device assignment is when using pmap; in this case you can explicitly pass a set of device IDs to the pmapped function if you want logic that depends on the device on which the mapped code is being executed. For example, I ran the following on an 8-device system:
import jax
import jax.numpy as jnp

num_devices = jax.device_count()

def f(device, data):
  return data + device

device_index = jnp.arange(num_devices)
data = jnp.zeros((num_devices, 10))

jax.pmap(f)(device_index, data)

# ShardedDeviceArray([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
#                     [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
#                     [2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
#                     [3., 3., 3., 3., 3., 3., 3., 3., 3., 3.],
#                     [4., 4., 4., 4., 4., 4., 4., 4., 4., 4.],
#                     [5., 5., 5., 5., 5., 5., 5., 5., 5., 5.],
#                     [6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
#                     [7., 7., 7., 7., 7., 7., 7., 7., 7., 7.]], dtype=float32)


text:
Q: Filling missing values for multiple columns by group I'm guessing this has already been asked on here but I'm having difficulty finding this precise issue. I have a data frame that looks like the following:
A 1 X  9  P
A 2 NA NA NA
A 3 NA NA NA
B 1 NA NA NA
B 2 Y  8  Q
B 3 NA NA NA
C 1 NA NA NA
C 2 NA NA NA
C 3 Z  7  R

In other words, there are groups (A, B, C) that have columns with many missing values. I want to fill those missing values using the existing values in those groups. There's always at least one row in each group that has the values that need to be filled in. The desired output would look like the following:
A 1 X  9  P
A 2 X  9  P
A 3 X  9  P
B 1 Y  8  Q
B 2 Y  8  Q
B 3 Y  8  Q
C 1 Z  7  R
C 2 Z  7  R
C 3 Z  7  R

It's very similar to this person's question (Filling missing value in group) except that I want to fill missing values in many columns rather than just one. In the example here, I've included three columns in which missing values need to be filled, but the actual data frame has many more.
Thanks in advance!

A: You can use fill in multiple columns and in both the directions (up and down) by group.
library(dplyr)

df %>%
  group_by(V1) %>%
  fill(V3:V5, .direction = 'updown') %>%
  ungroup()

#  V1       V2 V3       V4 V5
#  <chr> <int> <chr> <int> <chr>
#1 A         1 X         9 P
#2 A         2 X         9 P
#3 A         3 X         9 P
#4 B         1 Y         8 Q
#5 B         2 Y         8 Q
#6 B         3 Y         8 Q
#7 C         1 Z         7 R
#8 C         2 Z         7 R
#9 C         3 Z         7 R

data
df <- structure(list(V1 = c("A", "A", "A", "B", "B", "B", "C", "C",
"C"), V2 = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), V3 = c("X",
NA, NA, NA, "Y", NA, NA, NA, "Z"), V4 = c(9L, NA, NA, NA, 8L,
NA, NA, NA, 7L), V5 = c("P", NA, NA, NA, "Q", NA, NA, NA, "R")),
class = "data.frame", row.names = c(NA, -9L))

A: The zoo package has a na.locf function and it has a data.frame method so just sort the data first on ever column except V2 (since NA will drop to the bottom) and then fill in:
> dat <- read.table(text=txt)
> dat <- dat[order(dat$V1, dat$V3, dat$V4,dat$V5), ]
> dat2 <- na.locf(dat)
> dat2
  V1 V2 V3 V4 V5
1  A  1  X  9  P
2  A  2  X  9  P
3  A  3  X  9  P
5  B  2  Y  8  Q
4  B  1  Y  8  Q
6  B  3  Y  8  Q
9  C  3  Z  7  R
7  C  1  Z  7  R
8  C  2  Z  7  R

If there are groups with all NA's in one or more columns, then you  need to first do a split or group_by operation. Otherwise there will be  carry over from a prior group.

A: You can also use the following solution. I used coalesce function, assuming that there is only one value to be used to replace NAs. If there are more than one value to be used in each group per value I need to modify this solution:
library(dplyr)

df %>%
  group_by(V1) %>%
  mutate(across(V2:V5, ~ coalesce(.x, .x[!is.na(.x)])))

# A tibble: 9 x 5
# Groups:   V1 [3]
  V1       V2 V3       V4 V5
  <chr> <int> <chr> <int> <chr>
1 A         1 X         9 P
2 A         2 X         9 P
3 A         3 X         9 P
4 B         1 Y         8 Q
5 B         2 Y         8 Q
6 B         3 Y         8 Q
7 C         1 Z         7 R
8 C         2 Z         7 R
9 C         3 Z         7 R


text:
Q: Sorting Singly Linked List I have a singly linked list that needs to be sorted according some criteria. I implemented bubble sort but it does not print all the list, it prints only some of the elements. I can not use Arrays. I have to use bubble sort. I cannot use other sorting algorithms.
class SLLNode implements Comparable<SLLNode> {

    protected int id;
    protected int plata;
    protected SLLNode succ;

    public SLLNode(int id,int plata, SLLNode succ) {
        this.id = id;
        this.plata=plata;
        this.succ = succ;
    }

    @Override
    public int compareTo(SLLNode o) {
        return o.id - this.id;
    }

}

class SLL {

    private SLLNode first;

    public SLL() {
        // Construct an empty SLL
        this.first = null;
    }

    public void deleteList() {
        first = null;
    }

    public int length() {
        int ret;
        if (first != null) {
            SLLNode tmp = first;
            ret = 1;
            while (tmp.succ != null) {
                tmp = tmp.succ;
                ret++;
            }
            return ret;
        } else
            return 0;

    }

    public void insertFirst(int id, int plata) {
        SLLNode ins = new SLLNode(id, plata, first);
        first = ins;
    }

    public void insertLast(int id, int plata) {
        if (first != null) {
            SLLNode tmp = first;
            while (tmp.succ != null)
                tmp = tmp.succ;
            SLLNode ins = new SLLNode(id, plata, null);
            tmp.succ = ins;
        } else {
            insertFirst(id, plata);
        }
    }

    public SLLNode getFirst() {
        return first;
    }

    public void pecati(SLL lista) {
        SLLNode p = lista.first;
        while (p != null) {
            System.out.println(p.id + " " + p.plata);
            p = p.succ;
        }
    }

}

public static void sort(SLL lista){
    SLLNode current;
    boolean check = true;
    while(check) {
        current = lista.getFirst();
        check = false;
        while(current.succ != null) {
            if(current.compareTo(current.succ) > 0) {
                SLLNode temp = current;
                current=current.succ;
                temp.succ=current.succ;
                current.succ=temp;
                check = true;
            }
            current = current.succ;
        }
    }
}

public static void deleteLower(SLL lista, int n){
    SLL newList = new SLL();
    SLLNode temp=lista.getFirst();
    while(temp!=null){
        if(temp.plata >= n){
            newList.insertLast(temp.id, temp.plata);
        }
        temp=temp.succ;
    }
    if(newList.length() == 0){
        System.out.print("no");
        return;
    }
    else{
        sort(newList);
        newList.print(newList);
    }

}


text:
Q: Doownload large files (>300MB) using post method in Angular and Node I am trying to enable a download button using angular and Node. I am using the POST method to do it as I have to take the file name in real time and download that file.
Below is my code
Node Controller :
app.post('/api3',function(req,res,next){
    var selectedFileName = JSON.stringify(req.body);
    var fileName = selectedFileName
    var filePath ='absolute path'
    var downloadFile = filePath+fileName+'.csv';
    res.download(downloadFile,fileName1,function(err){
      if(err){
        console.log("Success");
      }
      else{
        console.log("Something");
      }
    });
  });

Download
Angular Code :
var fileNameJSON = {id1:fileName};

      $http.post('/api3',fileNameJSON)
            .success(function (data)
            {
             if (window.navigator.msSaveOrOpenBlob) {
               var blob = new Blob([data]);
               window.navigator.msSaveBlob(blob, fileName);
              }
              else {
                  var anchor = angular.element('<a/>');
                  anchor.css({display: 'none'}); // Make sure it's not visible
                  angular.element(document.body).append(anchor);

                  anchor.attr({
                      href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
                      target: '_blank',
                      download: fileName
                  })[0].click();
                $timeout(function(){
                  anchor.remove();
                },5000);
                 //remove();
              };
             })
            .error(function (data)
            {
                console.log("Download Error!!");
            });

The above code works fine for small files (upto 2MB) But I need to download larger files.
PS: I am not from web development background


text:
Q: Is $\lim_{x\to \infty} \frac{\ln{x}}{x} =\lim_{x\to \infty}  \frac{\frac{1}{x}}{1}$? In my notes its given
$$\lim_{x\to \infty} \frac{\ln{x}}{x} = \lim_{x\to \infty} \frac{\frac{1}{x}}{1}$$
Is that correct? How do I get that?
I think another example is also related
$$x^{\frac{1}{x}} = e^{\frac{\ln{x}}{x}}$$

A: Both of your example are correct.
Please note that $\ln x\to\infty$ as $x\to\infty$. Therefore,
 $$\lim_{x\to\infty}=\frac{\ln x}{x}\equiv\frac{\infty}{\infty},$$
an indeterminate form. Hence by L' Hospital rule,  $$\lim_{x\to\infty}=\frac{\ln x}{x}=\frac{\frac{d}{dx}(\ln x)}{\frac{d}{dx}(x)}=\frac{\frac{1}{x}}{1}$$
Your second example: we have $x^{\frac{1}{x}} = e^{\ln x^\frac{1}{x}}=e^{\frac{\ln x}{x}}$.


text:
Q: How to create popup alert with several copy to clipboard buttons? I came across this popup window and was wondering how I can create it with js. Can anybody give me a hint? Could not find a comparable solution here on stack...

A: For copying to clipboard you can use this code. First you select the element "The text area" then use select() function and finally use exec command to copy

function copyLink(id){
  var copyText = document.getElementById(id);
  copyText.select();
  document.execCommand("copy");
}
 <textarea id="firstTextArea">www.google.com</textarea>
 <button onclick="copyLink('firstTextArea')">Copy</button>


text:
Q: Point of sale products load and add to cart or html table in asp.net C# Jquery I want to develop the POS System, I need to load products and add
    it to html table or cart. in server side i Loaded the products but for adding
    a product to html table I am using Jquery. please help me in this.
This is Markup

                Recent Products

                <%
                    if (products_list.Count > 0)
                    {
                        foreach (var prod in products_list)
                        {
                %>

                            <img class="img-responsive" src="<%=prod.img %>" alt="" />

                                <%=prod.name%>

                                <%=prod.price%>

                             Add To Cart</a

                               <button id="btnAdd" class="btn btn-sm btn-primary">
                                Add To List
                            </button>

                <%}
                    }
                    else
                    {

                %>

                    No Products Available!

                <%} %>

                        Select

Jquery function: this is function that I am using it for adding product to html table or cart.
       $(function () {

            $('#btnAdd').click(function (e) {
                e.preventDefault();
                    var ItemName = $('#ItemName').html();
                    var Price = $('.item_price').html();

                    var markup = "
" + ItemName + "	" + Price + "
";

                    $("#tbl tbody").append(markup);

            });
       });

Products List

A: Your question is very unclear. But there's a problem I noticed in your template. The id of the button "Add to List" is getting duplicated.
<button id="btnAdd" class="btn btn-sm btn-primary">

You cannot have multiple elements with the same id on a page. It will broke processing of the $("#btnAdd").click handler.
To fix this, remove the id for the button, you don't need it. Use class instead. Something like this:
<button class="btn btn-sm btn-primary btn-add">
...
$('.btn-add').click(function (e) {
    ...
}


text:
Q: Layout for Android Application on TV I am designing an application for TV. When I load my application to TV screen, I see it still has the sizes of a smartphone. I have been playing with different dpi's but not working. Spent a day on this.
What are the steps to design the layout so that it will fit the TV screen?
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:background="#FFFFFF"
    android:gravity="center" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/logimgdesc"
        android:src="@drawable/logo" />

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="36dp"
        android:text="@string/start" />

    <Button
        android:id="@+id/btnDownload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="36dp"
        android:text="@string/download" />

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/spyonme"
        android:layout_alignBottom="@+id/spyonme"
        android:layout_alignLeft="@+id/btnLoadFP"
        android:text="@string/stop" />

</RelativeLayout>

A: There are many different ways to implement support for multiple-screen sizes. I'd suggest you read the Supporting Multiple Screens guide on the Android developer site.


text:
Q: Kotlin.math package not importing I'm trying to use kotlin.math.abs in a util.kt file, but the following code results in an "unused import" warning on the import statement and an unresolved reference where I use abs in the code.
import kotlin.math.abs

fun fuzzyEquals(a: Double, b:Double, epsilon: Double= 0.001) = abs(a-b) < epsilon

I'm using IntelliJ and gradle to organize the project. I'm on Intellij 2018.2.5 with Kotlin 1.3.0.
The folling code does work, so I don't think it's a problem with Kotlin as a whole
import kotlin.sequences.find

fun test() = listOf(1,2).find{it==1}

A: The functions from kotlin.math package can be unresolved by one of the following reasons:

*

*you don't have the kotlin standard library in dependencies (it doesn't seem so from your question), or the version of that dependency is lower than that, where this package was introduced, namely 1.2. Check the dependencies block of your build file.

*apiVersion compiler option, which limits visible API to only available in the specified version, can be set. Check whether you have this option in Gradle build file and also check the effective version in the Kotlin facet of your module in IntelliJ project structure.


text:
Q: Overriding keypress I know this may be an easy answer to some of you but i dont know how to properly do this. Ive created a text editor, that also has a docking window that will display functions. I have it set up in the menu that F8 is the shortcut key for showing the function window. I would also like to catch the F8 keypress event to parse the current data for the functions in the program but I cant get this to happen..

A: Capture your Text Editors KeyPressed Event and check the KeyEventArgs that are coming in, then mark the not handled as false which will cause the event to be passed up to the parent control:
Example
KeyPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F8) DoSomething();
    e.Handled = false;
}

In response to the comment that you added to your question. You may need to set the controls KeyPreview to True. I think that KeyPreview may be available at only the form level, but I'm not sure.

A: Set up an event handler for the OnKeyPress (or OnKeyDown or OnKeyUp) event, and check which key was pressed (it will be in the event arguments). Then, you can do whatever you want.

A: I don't think the tagged answer is correct.  The KeyPress event handler won't handle the Function keys; you need to use KeyUp event handler or ProcessDialogKey method.

A: I'm not sure to understand everything, but can't you use the KeyPress Event available in any Control ?


text:
Q: Cannot get a program to compile in command line but worked on Eclipse? I have two classes: I cannot get either of them to compile in command line: I'm using the javac SodaCan.java prompt but it still wont compile, it says stuff like: "error: Class, interface, or enum expected" for double, sodaCan, getvolume etc.
public SodaCan{
    private double sArea;
    private double volume;

    public SodaCan(double height, double radius){
        getSurfaceArea(height);
        getVolume(radius);
    }

    public double getSurfaceArea(double height, double radius){
        sArea = 2*Math.PI * Math.pow(radius, 2) + 2 * Math.PI * radius * height;

        return sArea;
    }

    public double getVolume(double height, double radius){
        volume = Math.PI * Math.pow(radius, 2) * height;
    }
}

and
import java.util.*;

public class testSodaCan{
    public static void main(String[] args){
        double height, radius;
        Scanner s = new Scanner(System.in);
        System.out.println("Please  input the height of the can: ");
        height = s.nextDouble();
        System.out.println("Please  input the width of the can: ");
        radius = s.nextDouble();
        SodaCan  can = new SodaCan(height, radius);
    }
}

A: Add the class keyword
public class SodaCan {


text:
Q: how to protect url string which is created by GET in php for a filemanagement i want to make an anchor for scanning a specific directory.
I use this echo for it:
echo   "
"
."open dir"
."
";

The dirname and basename give me the the right path to the directory.
this is the normal "root" directory for the users:
$dir = 'uploads/sfm/'.$UserID;

When i user created a folder in his root, he must be able to see the files in that folder.To change the directory and show  all the files in that directory, i use this
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$strArr = explode("=",$actual_link);
$CurrentPath = $strArr[1];

if(isset($_GET['dir'])) {
$dir = $CurrentPath;

}

So i read the dir from the url and the variable $dir changes
The problem: the url shows me a string like this:
sfm?dir=uploads/sfm/c4ca4238a0b923820dcc509a6f75849b/folder
When i type now in the url:
sfm?dir=uploads/
he shows me the files in uploads folder. This must be protected!
Nobody should be able to see this.
And also this must be protected from view:
sfm?dir=uploads/sfm/
How can i achieve that?
By the way: the hash in the url is because i have the var $UserID md5 hashed
md5($UserID)

A: A sample solution is to grab the md5 directory using a regular expression.
Something like this:
$res = preg_match('/uploads\/sfm\/([a-f0-9]{32}).*/', $dir, $matches);

if (!$res || $matches[1] != md5($UserID)) {
   // user requested a directory he has no access to. Take additional
   // actions, e.g. return HTTP status 403
   exit('No access here');
}

A: $protectedDirectories = array(
                            array( 'uploads', 'sfm', $userId )
                        );

$directory = str_replace('\\','',$_GET['dir']);

$directory = trim($directory,'/');

$directory = preg_replace('#[\/]{1,}#','/',$directory);

$stats = false; // True = Protected , False = Cannot enter this directory.

$seperate = explode('/',$directory);

$cntSeperate = count( $seperate );

foreach($protectedDirectories as $pattern ){

    if( count( $pattern ) > $cntSeperate ){

        continue;

    }

    $innerStats = true;

    foreach( $pattern as $key => $val ){

        if( $seperate[ $key ] !== $val ){

            $innerStats = false;

            break;

        }

    }

    if( $innerStats == false ){

        continue;

    }

    $stats = true;

    break;

}

if( $stats == true ){

    // Access Granted

}else{

    // Access Not Granted

}

Now you can dynamically use your directory access grants. Each array means a pattern. Each array's value is a directory inside directories ( For example : array('uploads', 'sfm') means uploads/sfm )


text:
Q: How to extend LinqKit and use a custom method within a linq query? I would like to leverage LinqKit's AsExpandable feature to be able to translate my custom methods inside of my linq query.
I can achieve this by implementing my own expression visitor which will translate my custom methods to expression that EF provider can understand.
After digging a bit into the LinqKit source code, it seems to me that LinqKit was not designed to support such scenario even if it says so on its home page (see capture).
How can one plug a custom visitor into the LinqKit's pipeline ? Any ideas or advices ?
Thanks a lot !
Riana
From

A: I think they are just referring to this overload of AsExpandable:
public static IQueryable<T> AsExpandable<T>(this IQueryable<T> query, Func<Expression, Expression> queryOptimizer)

Although the parameter is named "queryOptimizer", you can really pass in any Func<Expression, Expression> and that will be invoked immediately before the Expression is passed into the query provider:
    IQueryable<TElement> IQueryProvider.CreateQuery<TElement>(Expression expression)
    {
        var expanded = expression.Expand();
        var optimized = _queryOptimizer(expanded);
        return _query.InnerQuery.Provider.CreateQuery<TElement>(optimized).AsExpandable();
    }

By default, _queryOptimizer just ends up being an ID function.  It's named as such because LinqKit is also affiliated with this project: https://github.com/Thorium/Linq.Expression.Optimizer.


text:
Q: XLST Transform only specific tag value nodes I want to transform XML, but will choose only specific records with given value. How can i do that?
Here is the sample XML. I only want to get the records which have CURRENCY value equals to USD. I want to eliminate products with TL currency.
<PRODUCTS>
 <PRODUCT ID="9563">
   <![CDATA[72127]]>
   <NAME><![CDATA[SAMPLE PRODUCT NAME]]></NAME>
   <PRICE><![CDATA[57.90]]></PRICE>
   <PRICE_DISCOUNT><![CDATA[48.50]]></PRICE_DISCOUNT>
   <CURRENCY>USD</CURRENCY>
 </PRODUCT>
 <PRODUCT ID="9564">
   <![CDATA[72128]]>
   <NAME><![CDATA[SAMPLE ANOTHER PRODUCT NAME ]]></NAME>
   <PRICE><![CDATA[67.90]]></PRICE>
   <PRICE_DISCOUNT><![CDATA[58.50]]></PRICE_DISCOUNT>
   <CURRENCY>TL</CURRENCY>
 </PRODUCT>
<PRODUCTS>

A: You need to think about the problem the other way around - start with an identity transformation (that copies the input to the output unchanged, you can find hundreds of examples of this in other questions) and then override it to ignore the elements you don't want to keep
<xsl:template match="PRODUCT[not(CURRENCY = 'USD')]" />


text:
Q: Renaming and Zipping Files Python - FileNotFoundError Just getting back into Python and am trying to build a script that will match file names, rename, zip them, and then ultimately build a control file off them (this I haven't written yet). It works on the files placed in the directory, but at the end I get the error: FileNotFoundError: [WinError 2] The system cannot find the file specified: 'A20190331.txt' -> 'B20190530.txt'. Is it rerunning my txt_files for loop in the beginning after renaming? Code is probably not optimal at this point.
import os
import zipfile

try:
    import zlib
    compression = zipfile.ZIP_DEFLATED
except:
    compression = zipfile.ZIP_STORED

path = 'mypath'

txt_files = []
for root, dirs, files in os.walk(path):
    for file in files:
        txt_files.append(file)

def create_zip(data_dt):
    for files in txt_files:
        if '.py' in files:
            continue
        elif 'A' in files:
            file_name = 'A' + data_dt + '.txt'
            name_full_path = path +'\\'+ file_name
            os.rename(files, file_name)
            zf = zipfile.ZipFile('A' + data_dt+ '.zip', mode='w')
            zf.write(name_full_path, file_name, compress_type=compression)
            zf.close()
        elif 'B' or 'C' in files:
            file_name = 'B' + data_dt + '.txt'
            name_full_path = path +'\\'+ file_name
            os.rename(files, file_name)
            zf = zipfile.ZipFile('B' + data_dt +'.zip', mode='w')
            zf.write(name_full_path, file_name, compress_type=compression)
            zf.close()
        else:
            break

create_zip('20190530')

A: Christopher.
I see your problem immediately:
txt_files = []
for root, dirs, files in os.walk(path):
for file in files:
    txt_files.append(file)

I believe you want to keep the path:
for root, dirs, files in os.walk(path):
    for file in files:
        txt_files.append(os.path.join(os.path.get_cwd(), file))

Let os.path handle the path for you -- it is portable across platforms and less error prone.
hth

A: i did some modification, can you try this please , but using your way, the code will overwrite the files.
so try this script, and tell me if you want to overwrite or  just rename and zip
def create_zipe(data_dt):
    for files in txt_files:
        if '.py' in files:
            continue
        elif 'ASS' in files:
            file_name = 'A' + data_dt + '.txt'
            name_full_path = path +'/'+ file_name
            os.rename(files, file_name)
            zf = zipfile.ZipFile('A' + data_dt+ '.zip', mode='w')
            zf.write(name_full_path, file_name, compress_type=compression)
            zf.close()
        elif 'C' in files or 'B' in files:
            file_name = 'B' + data_dt + '.txt'
            print(file_name)
            name_full_path = path +'/'+ file_name
            print(name_full_path)
            os.rename(files, file_name)
            zf = zipfile.ZipFile('B' + data_dt+ '.zip', mode='w')
            zf.write(name_full_path, file_name, compress_type=compression)
            zf.close()


text:
Q: python2.7 error: UnboundLocalError: local variable 'i' referenced before assignment I get an error when I run this python script.
def thousandthPrime():
    count=0
    candidate=5 #candidates for prime no. these are all odd no.s Since starts at 5 therefore we find 998th prime no. as 2 and 3 are already prime no.s
    while(True):
        #print 'Checking =',candidate
        for i in range(2,candidate/2): #if any number from 2 to candidate/2 can divide candidate with remainder = 0 then candidate is not a prime no.
            if(candidate%i==0):
                break
        if i==(candidate/2)-1: # If none divide it perfectly, i will reach candidate/2-1 eventually. So, this is a prime number.
            count+=1
            print 'No. of prime no.s found excluding 2 and 3 =',count, '--->',candidate
        if(count==998):
            print 'The thousandth prime is',candidate
            break
        candidate+=2 # to go to the next odd number.

I get this error:
File "/home/.../xxx.py", line 19, in thousandthPrime
    if i==(candidate/2)-1: # If none divide it perfectly, i will reach candidate/2-1 eventually. So, this is a prime number.
UnboundLocalError: local variable 'i' referenced before assignment

But if I replace, candidate/2 with just candidate, I get no errors, although it increases some unnecessary calculations.

A: You're declaring candidate as an integer. Thus candidate/2 is also an integer, specifically 2. Then your range(2, candidate/2) is range(2, 2) which is nothing, so i is never initialized. You'll need to set candidate=5.0 to make it a float and all should be well.
EDIT
As pointed out in the comments, simply re-defining candidate will give you a type error, but it should be enough to get you on track. Note, range(x, y) expects integers, you you may have to convert to an integer again after the division or limiting calculation using int(). Also, you may want to look into why the math.sqrt function was mentioned related to primality testing

A: The problem is simple if you step through it:
>>> candidate=5
>>> candidate/2
2
>>> range(2, 2)
[]
>>> for i in []: print(i)
>>> i
NameError: name 'i' is not defined

Your loop is empty, so you never step into it, so i never gets defined.
As pointed out in comments elsewhere, you really only need to check up to int(sqrt(candidate)), not candidate/2. But you'll still have the same problem if you do that: int(sqrt(5)) is still 2.

This means this test:
if i==(candidate/2)-1:

… is trying to access a variable that hasn't been defined.
But if you step back and think about what you're really testing, in pseudocode, it's this:
if I finished the loop without break:

And Python has a built-in way to say that: the else clause on loops.
In fact, the tutorial section break and continue Statements, and else Clauses on Loops which introduces this feature has an example very similar to yours:
>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'

The else clause will be executed if you finish looping without a break—which includes the case where the loop iterator was empty.

So, in your code:
while(True):
    #print 'Checking =',candidate
    for i in range(2,candidate/2): #if any number from 2 to candidate/2 can divide candidate with remainder = 0 then candidate is not a prime no.
        if(candidate%i==0):
            break
    else: # If none divide it perfectly, i will reach candidate/2-1 eventually. So, this is a prime number.
        count+=1
        print 'No. of prime no.s found excluding 2 and 3 =',count, '--->',candidate

If you want more detail on exactly how else works than the tutorial gives, see the reference docs on while and for.

A: Scope of a variable
That's not a problem in this code, which even if it's unpretty to use the variable i outside its intended scope (inside the for construct), i should remain defined after finishing the for loop, provided...
Checking edge cases
... the for loop should run at least once to declare the name i for some variable.
As this doesn't happen, you are getting an UnboundLocalError.
Quick fix
You can fix this by declaring the i variable just before the for loop, in case it doesn't ever run (a simple i = 2)
Recommended steps
As the Python Zen itself says that explicit is better than implicit, by using  different variable for the result you want to keep after the break you're making this value explicit instead of implicit to the i variable after the loop.
Example:
def thousandthPrime():
    count = 0
    candidate = 5 # candidates for prime no. these are all odd no.s Since starts at 5 therefore we find 998th prime no. as 2 and 3 are already prime no.s
    while(True):
        # print 'Checking =',candidate
        useful_divider = 2
        for i in range(2, candidate / 2): # if any number from 2 to candidate/2 can divide candidate with remainder = 0 then candidate is not a prime no.
            if candidate % i == 0:
                useful_divider = i
                break
            if useful_divider == (candidate / 2) - 1: # If none divide it perfectly, useful_divider will reach candidate/2-1 eventually. So, this is a prime number.
            count+=1
            print 'No. of prime no.s found excluding 2 and 3 =',count, '--->',candidate
        # And so on...
        # ... and so on :)


text:
Q: Using 'several' and 'some' What is the difference between these two?

Ann has some nieces.
  Ann has several nieces.

OALD defines some as:

3) a large number or amount of something
  4) a small amount or number of something

and several as:

more than two but not very many

Does this mean that some is more than several? How can I use them correctly?
The question asks " does Annie have any nephews or nieces ?

A: You use several with countable nouns, which means nouns that can be made plural... for example dogs, cats, cars...
I have several cars. I drink several cups of coffee in the morning.
You use some with non-countable nouns... nouns that are always singular.
For example: coffee, sand, money. It means a small amount
I have some money in the bank.
I usually drink some coffee in the morning.


text:
Q: CSGO: laggy gameplay on Dell E6510 Problem
Laggy gameplay in CSGO in offline mode with bots (9 bots + 1 human) with video settings set to low.

Hardware

*

*Dell Latitude E6510

*Core i5 1st Gen 2.67GHz

*8 GB RAM

*NVIDIA NVS 3100M 512MB gDDR3

*Windows 10 Home

Game Minimum Requirements

*

*Windows 7/Vista/XP

*Core 2 Duo E6600 or AMD Phenom™ X3 8750 processor or better

*2 GB RAM

*Video card must be 256 MB or more and should be a DirectX 9-compatible with support for Pixel Shader 3.0

*DirectX 9.0c

Questions

*

*I want to run CSGO at the lowest video setting possible so that gameplay is smooth. Which settings should I enable/disable?

Thank you for your help.

A: Sorry, but no chance. Your laptop is a business device, which is not made for gaming. The primary purpose of that thing is low power consumption to gain better battery life. Also it's already 10 years old.
With that video card you won't get decent results regardless of your config settings. It's simply not made for gaming and it sucks at 3D (which games usually are).
I've run a few benchmarks and they show an average of 20 to 40 FPS in CS:GO with lowest settings. Even tweaking it further down with custom settings won't help much.


text:
Q: How to convert the UTC time to Shanghai +8 timezone time in template? From the database, I query out the created_date and put in the template:

You see, it is UTC time, how can I in the template shows the +8 timezone time?
I tried use the custom template-filter to change, but failed:
from django import template
from django.template.defaultfilters import stringfilter
import datetime, time

register = template.Library()

### function

def utc2local(utc_st):
   """UTC时间转本地时间(+8:00)"""
   now_stamp = time.time()
   local_time = datetime.datetime.fromtimestamp(now_stamp)
   utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
   offset = local_time - utc_time
   local_st = utc_st + offset

   return local_st

@register.filter
def convert_utc_to_shanghai(value):
    """
    UTC->Shanghai
    :param value:
    :return:
    """

    local_time = utc2local(value)

    print local_time.strftime("% Y - % m - % d % H: % M: % S")

    return local_time.strftime

A: my solution is does not save utc time to db,set this in settings.py:
# Chinese Shanghai
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
# db does not use utc time
USE_TZ = False

A: Solution 1: timezone.localtime
settings.py
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = True

$ ./manage.py shell
Python 3.6.5 (default, Apr  1 2018, 05:46:30)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from django.utils import timezone

In [2]: timezone.now()
Out[2]: datetime.datetime(2018, 7, 24, 12, 57, 8, 32455, tzinfo=<UTC>)

In [3]: timezone.localtime(timezone.now())
Out[3]: datetime.datetime(2018, 7, 24, 20, 57, 18, 743225, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

templatetags
@register.filter
def convert_utc_to_shanghai(value):
    return f'{timezone.localtime(value):% Y - % m - % d % H: % M: % S}'

solution 2:  pytz
from datetime import datetime
from typing import Optional

import pytz

def beijing_time(dt: Optional[datetime], fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
    """将datetime类型转化为北京时间的字符串,精确到秒
    Example::
        >>> from datetime import datetime; from django.utils import timezone
        >>> beijing_time(datetime.now())
        '2021-06-30 16:37:40'
        >>> beijing_time(datetime.utcnow())
        '2021-06-30 16:38:18'
        >>> now = timezone.now()
        >>> print(now)
        2021-06-30 08:42:49.838529+00:00
        >>> beijing_time(now)
        '2021-06-30 16:42:49'

    """
    if dt is None:
        return ""
    return f"{dt.astimezone(pytz.timezone('Asia/Shanghai')):{fmt}}"

templatetags
@register.filter
def convert_utc_to_shanghai(value):
    return beijing_time(value)


text:
Q: How to pass Serial object by reference to my class in Arduino? I have been reading up a couple of days now about pointers, references and dereferences in C/C++ targeted for the Arduino and can't fully udnerstand what I am missing.
I have my sketch which has a setup of
Serial.begin(9600);   //Just for logging.
Serial1.begin(9600);  //Arduino Mega-> Other Device

I use a wrapper class to send BYTE's over Serial1 by calling a simple function like getStatus().
The issue I am having is I would like to make my class more dynamic, so I would like my class to use Serial1, Serial2, Serial3 or even the base Serial - but I do not know how to build my .h and .cpp files to use these as references.
At the moment my class has a static Serial1 but if somebody would like to use my class they would have to rename everything to Serial if they use Arduino Uno.
In myclass.h I have something like
myClass(HardwareSerial *serial);

and in myClass.cpp (constructor):
myClass::myClass(HardwareSerial &serial) {
     _HardSerial = serial;
 ..
}

But the compiler keeps on moaning about ) expected before &  or *.
I have tried various ways and always get the same error- except when I reference my class to the Serial object-- but it says Serial was not defined..
I can't find any tutorials, except Pointer Resource for Arduino.

Declaration and Creation
#include "Print.h"
//datatype* variablename = ⌖
Print* printer = &Serial; Usage

Usage
//this is the equivalent of Serial.print
printer->print("print using the Serial object"); //notice the -> as opposed to .
//change target address (or which address to point to)
printer = &Serial2;
//this is the equivalent of Serial2.print
printer->print("print using the Serial2 object");

Which is exactly what I want - but it seems I do not understand it. I did what they did there, and it does not work for me.
EDIT 1
Thanks, I did it the reference way because it is better yet. I still get these errors, though:
:88: error: 'HardwareSerial' has not been declared

Line 88 from .h:
uint8_t Init(long BaudRate, HardwareSerial& serial);

.h:136: error: ISO C++ forbids declaration of 'HardwareSerial' with no type
.h:136: error: expected ';' before '&' token

Line 136 from .h (this keeps on happening- I don't know what to use, Serial.write? / Serial?):
private:
HardwareSerial& _HardSerial;

EDIT 2
So, basically because I import the HardWareserial.h file in file myClass.h which is imported in my sketch to use all myClasses stuff - it kills the references in the sketch and wants me to redefine the Serial instances.  It seems like the inheritance is the wrong way around…annoying. What's the default constructor used in the sketch?
It's like it's asking me to do this:
HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1);

Really? Again I don't understand...

A: On the Arduino Leonardo, I believe Serial is not actually an instance of HardwareSerial, but rather of Serial_, due to it being a virtual USB link and not a normal USART.
However, both of these classes are subclasses of Stream.
So maybe you can declare Stream* instead of HardwareSerial*.

A: You're mixing C++ references and pointers. It looks from that example snippet that you should be using pointers, so I have made my answer follow that style. References would probably be a better choice though.
Your code should look something like this:
myclass.h
myClass(HardwareSerial *serial); // ctor
HardwareSerial * _HardSerial; // member within class

myclass.cpp
// Constructor takes address of serial port
myClass::myClass(HardwareSerial *serial) {
 _HardSerial = serial;
...
}

calling code:
// Gets the address of "Serial1" and passes that to the constructor
myClass(&Serial1);

If you wanted to do it as references it would look something like this:
myclass.h
myClass(HardwareSerial& serial); // ctor taking reference
HardwareSerial& _HardSerial; // reference member within class

myclass.cpp
// Constructor takes reference to a serial port object
myClass::myClass(HardwareSerial& serial) :
    _HardSerial(serial) // Need to initialise references before body
{
    ...
}

calling code:
myClass(Serial1); // Compiler automatically uses reference

A: I have one improvement on Mr Murdoch's code (thanks a lot by the way, following your example on how to initialize a serial object made me a happier, less compiler frustrated individual).
His method will let you pass any hardware serial object to his class.
Mine by default will let you pass (and configure) a hardware object to the class, but will also let you switch in a software serial object later if you are interested.
Almost the exact same as his code, except I replace his instance of the HardwareSerial object in his class with the Stream object.
myclass.h
myClass(HardwareSerial& serial, int baud, int config); // Constructor taking reference
Stream& _s; // reference member within class

myclass.cpp
// Constructor takes reference to a serial port object
myClass::myClass(HardwareSerial& serial = Serial, int baud = 9600, int config = SERIAL_8N1) :
_s(serial) // Need to initialise references before body
{
    serial.begin(baud, config);  //We guarantee a hardware interface at first
    this->_s = serial;           //The constructor uses the hardware serial class
                             //but we can replace it with a virtual hardware
                             //class if we have to thanks to stream
}


text:
Q: Heading h2 changes to make it stand out a little less I feel that the h2-headings with their CSS properties make them stand out a little bit too much in questions and answers. Many users seem to prefer using bold text for headings – possibly because the current h2-headings look too big. Could something be done to make it feel more acceptable to layout the structure of a post using headings instead of bolded text headings?
There's also a bit more specific discussion going into the subject of heading sizes.
Possible solutions
I played around with the margin-bottom property, and a value of 0.5em somehow looked more right from my point of view – at least on my own questions and answers, which try to conform heavily on the semantically correct use of heading tags.


text:
Q: Detecting process crashes with New Relic in NodeJS How do you get New Relic to log errors which crash the process using their New Relic application monitoring? The key things I'm trying to accomplish are to have errors which crash the process still get logged and some way to filter to these errors on the dashboard.
Here's my understanding so far:

*

*New Relic transmits data to their cloud every minute. In the event a uncaughtException occurs, this will result in all of the data currently waiting to be transmitted to be lost.

*There is a newrelic.noticeError() which is supposed to take a second argument allowing you to pass custom parameters with an error. New relic gets the error, but not the custom parameters.
Simple Example:
var newrelic = require("newrelic");
var express = require("express");
var app = express();

app.get("/softFail/", function(req, res) {
    res.send(500, "softFail");
});

app.get("/hardFail/", function(req, res) {
    setImmediate(function() {
        throw new Error("I failed");
    });
});

app.listen(80);

process.on("uncaughtException", function(err) {
    console.error("Uncaught Exception");
    console.error(err.stack);
    newrelic.addCustomParameter("crash", "true");
    newrelic.noticeError(err);
    console.log("sending errors to New Relic");
    newrelic.agent.harvest(function() {
        console.log("send complete, crashing process");
        process.exit(1);
    });
});

Using that block of code if I call /hardFail/ I'm able to get New Relic to at least log the error. Without the uncaughtException handler I don't get anything to New Relic. The issue is that I can't differentiate between the errors which crash the process, and normal HTTP 500 errors.
Here's something things I've tried:

*

*If I attempt to add { crash : true } to the noticeError call it doesn't seem to have any affect.

*I've tried to do domain instead of process.on, that doesn't change the situation.

*If I attempt to alter the name of the error, such as err.name = "CrashError" then the error doesn't get transmitted at all.

*If I create a custom error type, and then new that, and copy the stack trace on to it, it still reports as type Error rather than the prototype.name of my new error type.


text:
Q: Transform rows from a SQL result into columns in an array I would like to take the result from an SQL that looks like this
id    name    kg     date
1     ABC     3      2017-09-14
1     ABC     2      2017-09-15
2     DEF     2      2017-09-14
2     DEF     5      2017-09-15
2     DEF     5      2017-09-16
2     DEF     3      2017-09-17
3     GHI     3      2017-09-15
3     GHI     6      2017-09-17

And put it into an array (or something else that I can loop through) so it looks like this
id    name    2017-09-10    2017-09-11    2017-09-12    2017-09-13    2017-09-14    2017-09-15    2017-09-16    2017-09-17
1     ABC     3 kg          2 kg
2     DEF     2 kg          5 kg          5 kg          3 kg
3     GHI                   3 kg                        6 kg

It will only hold dates from last sunday until this sunday (Active week).
I haven't worked with arrays before, but of what I have read so far I think I have to create an array inside another array to achive this? I am thinking that from the SQL result I will go through each row and push the values into right row depending if the id already exists. One id could only have unique dates.
while ($row = odbc_fetch_row($resultSQL)){
    Create an array with the columns above and push the result from the SQl
    into the array on a new row or an existing column if the ID is
    already in the array.
}

Anyone have any ideas how to achieve this? Thanks.
EDIT:
Solution: I have now done like this which achives the result I wanted.
//create two arrays
$items=array();
$dates=array();

//loop through the SQL result and put it into the arrays
while ($row = odbc_fetch_row($resultSQL)){
$ITEMNO=odbc_result($resultSQL,"id");
$ITEMNAME=odbc_result($resultSQL,"name");
$RecQtyDay=odbc_result($resultSQL,"kg");

$items[$ITEMNO] = $ITEMNAME;
$dates[$REGDATE][$ITEMNO] = $RecQtyDay;
}

//sort the dates array
ksort($dates);

//loop through and print out dates array within the item array
foreach ($items as $ITEMNO => $ITEMNAME) {
echo "$ITEMNO $ITEMNAME ";
foreach ($dates as $REGDATE => $values) {
    if (isset($values[$ITEMNO])) echo "$REGDATE $values[$ITEMNO]";
}
echo"<BR>";
}

A: As you fetch your query results, build two arrays, one with all the items, and another that's grouped by date with values for any items that have records for each date.
while ($row = odbc_fetch_row($resultSQL)) {
    $items[$row['id']] = $row['name'];
    $dates[$row['date']][$row['id']] = $row['kg'];
}

Sort the dates/values array by key (date)
ksort($dates);

Then loop over your array of items to generate the rows. Within each row, loop over the array of dates and output the value for that id and date.
foreach ($items as $id => $name) {
    echo "$id   $name";
    foreach ($dates as $date => $values) {
        if (isset($values[$id])) echo "$value kg";
    }
}

This output won't be neatly formatted, but I don't know exactly how you're planning to output this, so I'll leave that up to you.


text:
Q: how to check variable type in javascript i need to check a variable whether it is an integer or a decimal one.
if integer just have to showing the integer if is not show the decimal point up 2.
i just used the
toFixed(2)

but it will show the integer number also with two decimal points

A: One simple way could be to use parseInt function to obtain the integer value and check if it is the same as the original. If it is, then value is an integer, otherwise it is a decimal.
function func(value) {
    var integer = parseInt(value);
    if(integer === value) {
        // value is an integer
    } else {
        // value is a decimal
    }
}

function showResult() {
  var num = document.getElementById("num").value;
  if(num) {
      func(num);
  }
}

function func(value) {
    var integer = parseInt(value);
    if(integer == value) {
        document.getElementById("result").value = integer;
    } else {
        document.getElementById("result").value = parseFloat(value).toFixed(2);
    }
}
<input id="num" type="text" placeholder="Enter number here">
<button onclick="showResult();">Show Result</button>

Result
<input id="result" type="text" readonly>

A: isInteger = function(input) {
  if (typeof input === "number")
    return input % 1 === 0;
}

This will return whether the input is an int or not.
Test:
isInteger(1);      // true
isInteger(1.01);   // false
isInteger("2");    // false
isInteger("2.02"); // false


text:
Q: Can I iterate through a dictionary using all items in a comboBox? I tried asking the question earlier but didn't explain well enough. I will try again, I have a dictionary that gets and sets string for an image and List the gets string. The dictionary items are stored in a listBox, when I double click an item it sets to another comboBox. I want to click a button that will iterate through the dictionary and if they match anything in the dictionary it will store in a listView. I don't want the images though just the string name and price, here is the class and dictionary:
    class BookTitle
    {
        public string ImageTitle { get; set; }
        public List<string> Prices { get; }

        public BookTitle(string imageTitle, params string[] prices)
        {
            ImageTitle = imageTitle;
            Prices = new List<string>(prices.Length);
            Prices.AddRange(prices);
        }
    }

    private Dictionary<string, BookTitle> prices = new Dictionary<string, BookTitle>
    {
        { "Visual Basic", new BookTitle("vb.png", "$55") },
        { "Java", new BookTitle("java.png", "$45") },
        { "C#", new BookTitle("c#.png", "$75") },
        { "LAN Networks", new BookTitle("lan.png", "$68") },
        { "Windows Networking", new BookTitle("windows.png", "$49") },
        { "More About Networking", new BookTitle("more.png", "$54") },
        { "Web Programming", new BookTitle("web.png", "$67") },
        { "JavaScript", new BookTitle("javascript.png", "$64") },
        { "ASP", new BookTitle("asp.png", "$50") }
    };

Do you guys think I should just make a new class? I have tried this among many others:
    private void finalizeButton_Click(object sender, EventArgs e)
    {
        string cartItems = cartComboBox.Items.ToString();

        if (prices.Keys.Contains(cartItems))
        {
            BookTitle bt = prices[cartItems];
            ListViewItem list = cartListView.Items.Add(cartItems);
            list.SubItems.Add(cartItems);
        }

    }

A: You can do this way,
    private void finalizeButton_Click(object sender, EventArgs e)
        {
            foreach (var cmbObj in cartComboBox.Items)
            {
                if (prices.Keys.Contains(cmbObj.ToString()))
                {
                     BookTitle tempOut;
                     ListViewItem list =
                     cartListView.Items.Add(cmbObj.ToString());
                    if (prices.TryGetValue(cmbObj.ToString(), out tempOut))
                        list.SubItems.Add(tempOut.Prices[0].ToString());

                }
            }

        }

A: @Sajeetharan I will accept your answer because it was very helpful and got me on the right track.I ended up doing this:
    private void finalizeButton_Click(object sender, EventArgs e)
    {
        foreach (var comboItem in cartComboBox.Items)
        {
            if (prices.Keys.Contains(comboItem.ToString()))
            {
                BookTitle bt = prices[comboItem.ToString()];
                ListViewItem list = cartListView.Items.Add(comboItem.ToString());
                foreach (var p in bt.Prices)
                {
                    list.SubItems.Add(p);
                }
            }
        }
    }


text:
Q: Product of a sequence in NumPy I need to implement this following function with NumPy -

where F_l(x) are N number of arrays that I need to calculate, which are dependent on an array G(x), that I am given, and A_j are N coefficients that are also given. I would like to implement it in NumPy as I would have to calculate F_l(x) for every iteration of my program. The dummy way to do this is by for loops and ifs:
import numpy as np
A = np.arange(1.,5.,1)
G = np.array([[1.,2.],[3.,4.]])

def calcF(G,A):
    N = A.size
    print A
    print N
    F = []
    for l in range(N):
        F.append(G/A[l])
        print F[l]
        for j in range(N):
            if j != l:
                F[l]*=((G - A[l])/(G + A[j]))*((A[l] - A[j])/(A[l] + A[j]))
    return F

F= calcF(G,A)
print F

As for loops and if statements are relatively slow, I am looking for a NumPy witty way to do the same thing. Anyone has an idea?

A: Listed in this post is a vectorized solution making heavy usage of NumPy's powerful broadcasting feature after extending dimensions of input arrays to 3D and 4D cases with np.newaxis/None at various places according to the computation involved. Here's the implementation -
# Get size of A
N = A.size

# Perform "(G - A[l])/(G + A[j]))" in a vectorized manner
p1 = (G - A[:,None,None,None])/(G + A[:,None,None])

# Perform "((A[l] - A[j])/(A[l] + A[j]))" in a vectorized manner
p2 = ((A[:,None] - A)/(A[:,None] + A))

# Elementwise multiplications between the previously calculated parts
p3 = p1*p2[...,None,None]

# Set the escaped portion "j != l" output as "G/A[l]"
p3[np.eye(N,dtype=bool)] = G/A[:,None,None]
Fout = p3.prod(1)

# If you need separate arrays just like in the question, split it
Fout_split = np.array_split(Fout,N)

Sample run -
In [284]: # Original inputs
     ...: A = np.arange(1.,5.,1)
     ...: G = np.array([[1.,2.],[3.,4.]])
     ...:

In [285]: calcF(G,A)
Out[285]:
[array([[-0.        , -0.00166667],
        [-0.01142857, -0.03214286]]), array([[-0.00027778,  0.        ],
        [ 0.00019841,  0.00126984]]), array([[  1.26984127e-03,   1.32275132e-04],
        [ -0.00000000e+00,  -7.93650794e-05]]), array([[-0.00803571, -0.00190476],
        [-0.00017857,  0.        ]])]

In [286]: vectorized_calcF(G,A) # Posted solution
Out[286]:
[array([[[-0.        , -0.00166667],
         [-0.01142857, -0.03214286]]]), array([[[-0.00027778,  0.        ],
         [ 0.00019841,  0.00126984]]]), array([[[  1.26984127e-03,   1.32275132e-04],
         [ -0.00000000e+00,  -7.93650794e-05]]]), array([[[-0.00803571, -0.00190476],
         [-0.00017857,  0.        ]]])]

Runtime test -
In [289]: # Larger inputs
     ...: A = np.random.randint(1,500,(400))
     ...: G = np.random.randint(1,400,(20,20))
     ...:

In [290]: %timeit calcF(G,A)
1 loops, best of 3: 4.46 s per loop

In [291]: %timeit vectorized_calcF(G,A)  # Posted solution
1 loops, best of 3: 1.87 s per loop

Vectorization with NumPy/MATLAB : General approach
Felt like I could throw in my two cents on my general approach and I would think others follow similar strategies when trying to vectorize codes, especially in a high level platform like NumPy or MATLAB. So, here's a quick check-list of things that could be considered for Vectorization -
Idea about extending the dimensions : Dimensions are to be extended for the input arrays such that the new dimensions hold results that would have otherwise gotten generated iteratively within the nested loops.
Where to start vectorizing from? Start from the deepest (that loop where the code is iterating the most) stage of computation and see how inputs could be extended and the relevant computation could be brought in. Take good care of tracing the iterators involved and extend dimensions accordingly. Move outwards onto outer loops, until you are satisfied with the vectorization done.
How to take care of conditional statements? For simple cases, brute force compute everything and see how the IF/ELSE parts could be taken care of later on. This would be highly context specific.
Are there dependencies? If so, see if the dependencies could be traced and implemented accordingly. This could form another topic for discussion, but here are few examples I got myself involved with.


text:
Q: Div Overflow and scroll left I've got a div that has a fixed height of 500px. Contained in the div is images. I've got them stacking and overflowing the way I like currently but instead of when the visible div becomes full filling to the bottom and scrolling down, how do I force the div to scroll on the x axis. Here is my current HTML and SCSS

.gallery {
      clear: both;
      margin: 0 0 0 15px;
      max-height: 500px;
      width: 100%;
      overflow-x: scroll;
      display: block;
      img {
        float: left;
        padding: 3px;
      }
}

A: Updated: Made a mistake not using scss in fiddle, which revealed how float:left ripped your images from the text flow.
.gallery {
    clear: both;
    margin: 0 0 0 15px;
    max-height: 500px;
    width: 100%;
    overflow-x: scroll;
    display: block;
    white-space: nowrap;
    img {
        padding: 3px;
    }
}

jsfiddle.

A: .gallery {
      clear: both;
      margin: 0 0 0 15px;
      max-height: 500px;
      width: 100%;
      overflow-x: scroll;
      display: block;
}

img {
      float: left;
      padding: 3px;
}

Try this please
or this:
overflow-x: auto;


text:
Q: Call Objective C method from Swift I keep getting this error:
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254

What I am trying to do:
Sign in with facebook. I have the objective C code for logging in (from their sample projects) but I am using Swift as I do not know Objective C.
How can I call the objective C method from swift?
here is my objective C code:
// If the session state is any of the two "open" states when the button is clicked
    if (FBSession.activeSession.state == FBSessionStateOpen
        || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {

        // Close the session and remove the access token from the cache
        // The session state handler (in the app delegate) will be called automatically
        [FBSession.activeSession closeAndClearTokenInformation];

        // If the session state is not any of the two "open" states when the button is clicked
    } else {
        // Open a session showing the user the login UI
        // You must ALWAYS ask for public_profile permissions when opening a session
        [FBSession openActiveSessionWithReadPermissions:@[@"public_profile"]
                                           allowLoginUI:YES
                                      completionHandler:
         ^(FBSession *session, FBSessionState state, NSError *error) {

             // Retrieve the app delegate
             AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
             // Call the app delegate's sessionStateChanged:state:error method to handle session state changes
             [appDelegate sessionStateChanged:session state:state error:error];
         }];
    }

And my swift code:
var bridgeForFacebook: Bridge = Bridge()

@IBAction func fbSubmit(sender: AnyObject) {
    bridgeForFacebook.signIn();
}

A: Could be that the code files don't quite see one another correctly, and thus can't play nicely.
When you use Objective-C code from within a Swift file you need to bridge the header from your Objective-C class into Swift. Normally this is done automatically when you create a new Objective-C file.
You need to create an Objective-C heading file called (your project name)-Bridging-Header.h. In that file, write a #import statement and import the heading file for any Objective-C classes you want access to in Swift.
Now head over to your project build settings and find the "Objective-C Bridging Header" field under the "Swift Compiler - Code Generation" section. In there, fill out the relative path to your new bridging file (should be (project name)/(project name)-Bridging-Header.h).
Then your classes and method calls should work as expected.
Source: Swift with Cocoa, Swift and Objective-C in the Same Project


text:
Q:  is hiding part of text which is visible in same  (Chromium) I'm creating a sign language lexicon (for Swedish Sign Languale) centered around the transcription system usually used by researchers here in Sweden. The transcription is implemented as a Unicode font, which makes use of diacritics.

I have an HTML input element where the user types in a search query. Now, if the user starts by entering a diacritic mark, I'd like to be able to display that to the user, and if a diacritic it written without a preceding base character in front of it it will be placed a bit off to the left – and I'd thought I'd just add some padding-left to my text input element to make sure the first character would be visible even if it's a diacritic... However, Chromium doesn't like that.

Below is an image of what it looks like in Chromium. To the left is a (yellow) input element, and to the right is (purple) textarea element (both containing the same string). The textarea shows the desired result, while the input element truncates the diacritics at the top and to the left.

If one inspects the elements, one sees the following. (The text is truncated in the padding area of the input element, but not in the textarea.)

I would prefer to use an input element if I can.

Is there any way I could style the input element so that it won't truncate my text in the padding region?

This problem does not appear in Firefox, where both the textarea an input elements look the same, with no truncating going on.

The following snippet also shows the problem (at least if you're running Chromium).

@font-face {
  font-family: "FreeSans-SWL";
  src: url("https://zrajm.github.io/teckentranskription/freesans-swl.ttf");
}
input, textarea {
  font-family: "FreeSans-SWL";

  /* make textarea & input look the same */
  vertical-align: top;
  border: .25em inset #888;
  padding: .25em .5em;
}
<input value="">
<textarea rows=1></textarea>


text:
Q: adding a value to body onload in xsl I have an xsl which i am converting to html on client side.As i need to wait for the entire javascript to load hence I have given:
         <body onload="setTimeout(MyInitializeFunction, 1000);"

This works fine with other browser but IE doesnt support setTimeout.So After googling i found the solution is to wrap it inside function like this:
        <body onload= "setTimeout(function(){MyInitializeFunction();}, 1000);"

Error:Now it says MyInitializeFunction is an Unknown XSLT function.
Note:I have tried reading from an xml file after enclosing it in CDATA,but with no use.
body onload='<xsl:value-of select="teststrings/MyInitializeFunctionVariable" disable-output-escaping="yes" /&gt'

It should be simple but what is that i am missing??????Plz help folks.....

A: You need to double the braces: <body onload= "setTimeout(function(){{MyInitializeFunction();}}, 1000);">, that should fix the problem with XSLT. Why you think that in IE with Javascript setTimeout(MyInitializeFunction, 1000) would not work while setTimeout(function() {MyInitializeFunction();}, 1000) should work I am not sure, both calls pass a function object to setTimeout. In very old browsers you could only pass in a string with code, as in setTimeout('MyInitializerFunction();', 1000), so that might be more likely to fix any Javascript errors.


text:
Q: LAMP server - one command? I've been reading around the last couple of days to figure out virtual machines and LAMP/WAMP/XAMP and everything else....and wanted to ask one question regarding when it comes to installing the apache/SQL/PHP applications - I've just come across the following command:
sudo apt-get install lamp-server^
...does this do the same thing as this whole walk-through that I've been been through a few times (as I'm trying to get Symfony set up)?
https://help.ubuntu.com/community/ApacheMySQLPHP
Thanks!
Ben

A: Quoted from the website you have provided:
To install the default LAMP stack in Ubuntu 10.04 and above:
$ sudo apt-get update

$ sudo apt-get install lamp-server^

So, yes. That does the trick.
The rest of the website is when you wish to install just apache2 for example. Or want to setup LAMP in specific ways.


text:
Q: PHP show more system I have got this HTML

  View more comments

                        <img src="../users/<?php echo $CommenterPicture[0];?>">
                        <?php echo $CommenterName[0]; ?>
                        <?php echo $CommentRow[1]; ?>

And this Jquery/AJAX
$(".V_CPp").click(function(event) {
    var numItems = $(this).siblings('.F_W_comments').children().children().length;
    var i=$(this).siblings(".c_jq").children(".Likes").attr("data-i");
    $.ajax({
        url: '../connect.php',
        type: 'GET',
        cache: false,
        contentType: false,
        processData: false,
        data:"VMC="+i+"&NI="+numItems,
        success: function(data)
        {
             $("body").html(data);
        }
    });
});

And this php(connect.php)
if (isset($_GET['VMC'])) {
    $RandS=$_GET['VMC'];
    $From=$_GET['NI'];
    $To=$From+4;
    $query=$con->query("SELECT id FROM uploads WHERE Rand='$RandS'");
    $Id=$query->fetch_row();
    $Commentsq=$con->query("SELECT * FROM (SELECT * FROM comments WHERE Post_id='$Id[0]' ORDER BY `DATE` DESC LIMIT $From,$To) AS sub ORDER BY `DATE` ASC");
    while($COMM=$Commentsq->fetch_row())
    {
        echo $COMM[1]."
";
    }
}

So  when i have lets say 13 comments in order from 1 to 13
It only shows 10-13 and when i click

It shows me all comments from 2 to 9 instead of 6-9

A: Did you try with
                        <?php echo $CommentRow[0]; ?>

instead
                        <?php echo $CommentRow[1]; ?>

Try and comment please, maybe this is the issue.
Best of lucks,