text:
Q: Forbid explicit type parameters or constrain union type parameters for more type safety The following Typescript code works fine, when the getValues() function is invoked without explicit type parameters. However when it is called with explicit type parameters, it can lead to errors (see invocation getValues<'a' | 'b' | 'c' >(store, 'a', 'b') below).
type Store = Record<string, string>;

function getValues<T extends string>(
    store: Store, ...keys: T[]
): {[P in T]: string} {
    const values = {} as {[P in T]: string};

    keys.forEach((p) => {
        const value = store[p];
        if (value) {
            values[p] = value;
        } else {
            values[p] = 'no value';
        }
    });

    return values;
}

// Usage / requirements:

const store: Store = {}; // assume it is filled with arbitrary values

// in the following line values1 is inferred to be of type
// {a: string, b: string}, which is the required behavior
const values1 = getValues(store, 'a', 'b');

// the following line does not compile, which is the required behavior
// Argument of type 'b' is not assignable to parameter of type 'a' | 'c'
const values2 = getValues<'a' | 'c'>(store, 'a', 'b');

// in the following line values3 is inferred to be of type
// {a: string, b: string, c: string}, which is NOT the required behavior
// the required behavior would be to forbid this situation, similar to
// how values2 declaration was forbidden by the compiler.
const values3 = getValues<'a' | 'b' | 'c' >(store, 'a', 'b');

// now values3.c can be accessed
// values3.c cannot have a value and will cause an error when used

Is there a way to prevent the caller from providing explicit type parameters or any other way to make this code more type-safe without making the return type of the getValues function partial or making its return type's properties optional.
The following ideas come to my mind, for which I don't know whether or how they are possible in Typescript:
Idea 1: prevent explicit type parameters to be provided
Idea 2: remove getValues' value arguments and access the provided type arguments at runtime
Idea 3: enforce all provided type arguments to be used as value arguments also. That is, the declaration of values3 constant above will lead to a compile error.
I am aware that the problem is caused by the unsafe type assertion as {[P in T]: string}. I am looking for a way to make this type-safe.

A: This might be more trouble than it's worth; the level of complexity involved in trying to get such guarantees from the type system is unfortunately high, and should be weighed against the likelihood of people manually specifying too-wide type parameters.  Perhaps you can just document the function (/** hey, let the compiler infer T, thanks **/) instead of trying to make the compiler enforce this for you.

First, there's no way to prevent explicit type parameters from being specified. Even if you could it might not help you much, since type inference could still result in the wider types you are trying to avoid:
const aOrB = Math.random() < 0.5 ? "a" : "b";
getValues(store, aOrB); // {a: string, b: string} again

You also can't access type parameters at runtime because they, like the rest of the static type system, are erased upon transpilation to JavaScript.

From looking around, I think TS folks have run into this when trying to deal with computed property keys, which have a similar problem.  The solution proposed (but not implemented in the language, see microsoft/TypeScript#21030 and linked issues for discussion) seems to be something called Unionize in which you'd get {a: string} | {b: string} if you didn't know if the key is "a" or "b".

I think I could imagine using a type like Unionize in concert with taking an programmatic intersection of these types for each key passed in.  That implies you want your generic parameter not to be a union of key types, but a rest tuple of key types:
type UnionizeRecord<K, V> = K extends PropertyKey ? { [P in K]: V } : never;
type Expand<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
type UnionizeRecordTupleKeys<K extends PropertyKey[], V> = Expand<
    { [I in keyof K]: (x: UnionizeRecord<K[I], V>) => void }[number] extends
    ((x: infer R) => void) ? R : never
>;

The UnionizeRecord<K,V> type is like Record<K, V> but produces a union of types, one for each key in K.  The Expand<T> type just helps with IntelliSense output; it turns an intersection like {a: string} & {bar: number} into an equivalent single object type like {a: string, bar: number}.  And UnionizeRecordTupleKeys<K, V> is, well, ugly.  What it does is walks through each index I of the K tuple and produces a UnionizeRecord<K[I], V>.  It then intersects them together and expands them.  The specifics for how that all works are explained via distributive conditional types and inference in conditional types.
Your getValues() function then looks something like this:
function getValues<K extends (number extends K['length'] ? [string] : string[])>(
    store: Store, ...keys: [...K]
): UnionizeRecordTupleKeys<K, string> {
    const values = {} as any; // not worried about impl safety here

    keys.forEach((p) => {
        const value = store[p];
        if (value) {
            values[p] = value;
        } else {
            values[p] = 'no value';
        }
    });

    return values;
}

I'm not bothering trying to make the compiler understand that it can assign things to a value of type UnionizeRecordTupleKeys<K, string> when K is an unspecified generic type parameter, so I used any inside the implementation.  The other wrinkle is that I constrained the K type to be a tuple assignable to string[]; I want to prevent a non-tuple like Array<"a" | "b">.  It's not really necessary to prevent this, since the output type would just be wider than you like, but I wanted to forestall an objection about someone manually specifying something weird.  You can use similar tricks to prevent other specific things.

Let's see how it works.  This still behaves how you want:
const values1 = getValues(store, 'a', 'b');
/*const values1: {
    a: string;
    b: string;
} */

If you manually specify a type parameter, it needs to be a tuple:
const values2 = getValues<["a", "b"]>(store, 'a', 'b');
/* const values2: {
    a: string;
    b: string;
} */

If you specify the wrong tuple, you get an error:
const values3 = getValues<["a", "b", "c"]>(store, 'a', 'b'); // error!
// -----------> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Expected 4 arguments, but got 3.

If you specify or pass-in a union for one of the tuple elements, you get the union of object types out:
const aOrB = Math.random() < 0.5 ? "a" : "b";
const values4 = getValues(store, aOrB);
/* const values4: {
    a: string;
} | {
    b: string;
} */

which can become a fun union of lots of things:
const cOrD = Math.random() < 0.5 ? "c" : "d";
const values5 = getValues(store, aOrB, cOrD);
/* const values5: {
    a: string;
    c: string;
} | {
    a: string;
    d: string;
} | {
    b: string;
    c: string;
} | {
    b: string;
    d: string;
} */

So that all works!  There are probably plenty of edge cases I haven't considered, though... and even if it works it's clunky and complicated.  So again, I'd probably just recommend documenting your original function so that callers are aware of the limitations of the compiler.  But it's neat to see how close you can get to the "correct" output type!
Playground link to code


text:
Q: Creating a form with unknown fields and storing those fields into a serialized filed in my model I have a form that will have both a dynamic set and a known set of fields. I need a way of storing the dynamic fields in the database and I have decided on storing them in a serialized field, as I will not need to search on the data, and I just need it stored and recalled when needed.
class MyApplication < ActiveRecord::Base
    has_one :applicant
    belongs_to :member

    serialize :additional_fields, Hash

    accepts_nested_attributes_for :applicant, :additional_fields

I was thinking of having the form return the fields as an additional_fields_attributes and somehow have the model look after storying the hash into the additional_fields section. Im not sure if I have to go as far as using something like method missing to look after this, or if I should scrap the accepts_nested_attributes_for and handle it on my own.
Does anyone have any thoughts?
Thanks! Ryan

A: I just tested what you suggest.
You don't need: accepts_nested_attributes_for :additional_fields
Just add in your form html like:
<input name="my_application[additional_fields][first]" type="text" />
<input name="my_application[additional_fields][second]" type="text" />

it will save a Hash with keys: first and second
You could put in your model an array of fields, say in your User model:
FIELDS= ["item1", "item2"]

In your view:
<% User::FIELDS.each do |field|%>
     <input name="my_application[additional_fields][<%= field %>]" type="text" />
<% end %>

A: I ended up using this tutorial http://www.kalzumeus.com/2009/11/17/practical-metaprogramming-with-ruby-storing-preferences/ which worked really well.
Thanks for your help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot connect SAS OnDemand for Academic - SASpy I follow the site:
enter link description here
My sascfg_personal.py
SAS_config_names=['oda']
oda = {'java' : 'C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath\\java.exe',
#US Home Region 1
'iomhost' : ['odaws01-usw2.oda.sas.com','odaws02-usw2.oda.sas.com','odaws03-usw2.oda.sas.com','odaws04-usw2.oda.sas.com'],
'iomport' : 8591,
'authkey' : 'oda',
'encoding' : 'utf-8'
}

My _authinfo
oda user q***g@gmail.com password ****

When I enter:
import saspy
sas = saspy.SASsession()

It returns:
Using SAS Config named: oda
We failed in getConnection
The application could not log on to the server "odaws04-usw2.oda.sas.com:8591". The load balancing object spawner timed out.

SAS process has terminated unexpectedly. RC from wait was: 4294967290
SAS Connection failed. No connection established. Double check your settings in sascfg_personal.py file.

Attempted to run program C:\Program Files (x86)\Common Files\Oracle\Java\javapath\java.exe with the following parameters:['C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath\\java.exe', '-classpath', 'C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\saspyiom.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\log4j-1.2-api-2.12.4.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\log4j-api-2.12.4.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\log4j-core-2.12.4.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\sas.security.sspi.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\sas.core.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\sas.svc.connection.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\sas.rutil.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\sas.rutil.nls.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\iomclient\\sastpj.rutil.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\thirdparty\\glassfish-corba-internal-api.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\thirdparty\\glassfish-corba-omgapi.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\thirdparty\\glassfish-corba-orb.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\thirdparty\\pfl-basic.jar;C:\\Users\\PHAN\\anaconda3\\lib\\site-packages\\saspy\\java\\thirdparty\\pfl-tf.jar', 'pyiom.saspy2j', '-host', 'localhost', '-stdinport', '64138', '-stdoutport', '64139', '-stderrport', '64140', '-iomhost', 'odaws01-usw2.oda.sas.com;odaws02-usw2.oda.sas.com;odaws03-usw2.oda.sas.com;odaws04-usw2.oda.sas.com', '-iomport', '8591', '-user', 'quocphantruong@gmail.com', '-lrecl', '1048576', '']

No SAS process attached. SAS process has terminated unexpectedly.
Invalid response from SAS on inital submission. printing the SASLOG as diagnostic

---------------------------------------------------------------------------
SASIOConnectionError                      Traceback (most recent call last)
Input In [17], in <cell line: 1>()
----> 1 sas = saspy.SASsession()

File ~\anaconda3\lib\site-packages\saspy\sasbase.py:606, in SASsession.__init__(self, **kwargs)
    603    pass
    605 if failed:
--> 606    raise SASIOConnectionError(res)
    608 if self.pyenc is not None:
    609    if self._io.sascfg.encoding != '':

SASIOConnectionError: Failure establishing SASsession.
 No SAS process attached. SAS process has terminated unexpectedly.

Does anyone know how to fix this?
Thank you

A: Make sure that your sascfg_personal.py file in the right directory that is shown by the result the code below.
import saspy, os
print(saspy.__file__.replace('__init__.py', 'sascfg_personal.py'))


text:
Q: Implement Rewrite Module to have ApplicationName with querystring How can I rewrite the URL to have application name + querystring? For example I have a web application with the following querystring
mywebsite/default.aspx?UserName=xyz

How can I have URL with the folllowing
mywebsite?xyz

I have managed to implement RewriteModule using HttpApplication on Begin_request event and currently I can use this query
http://mywebsite/?xyz

Is there a way to have the url without /?

A: try,
rewrite ^/default\.aspx\?UserName=(.*)$ /?$1 last;


text:
Q: Copying dataframes through variables vs copying through variables for columns I have been playing with python and understanding the concept of copying a dataframe through the .copy function as opposed to just reassigning it to a variable.
Let's say we have the following data frame:
dfx:
   Name        Score1   Score2  Score3        Score4
0  Jack            10  Perfect      10       Perfect
1  Jill            10       10      10  Not Finished
2  Jane            20       10      10             5
3   Tom  Not Finished       15      10             5

dfx2 = dfx.drop("Score1",axis = 1)

dfx2:
   Name   Score2  Score3        Score4
0  Jack  Perfect      10       Perfect
1  Jill       10      10  Not Finished
2  Jane       10      10             5
3   Tom       15      10             5

running dfx again still returns the original dataframe
   Name        Score1   Score2  Score3        Score4
0  Jack            10  Perfect      10       Perfect
1  Jill            10       10      10  Not Finished
2  Jane            20       10      10             5
3   Tom  Not Finished       15      10             5

Shouldn't the reassignment cause the column "Score1" be dropped from the original dataset as well?
However, running the following:
dfx3 = dfx

dfx3

   Name        Score1   Score2  Score3        Score4
0  Jack            10  Perfect      10       Perfect
1  Jill            10       10      10  Not Finished
2  Jane            20       10      10             5
3   Tom  Not Finished       15      10             5

dfx3.loc[0,"Score4"] = "BAD"

dfx3

   Name        Score1   Score2  Score3        Score4
0  Jack            10  Perfect      10           BAD
1  Jill            10       10      10  Not Finished
2  Jane            20       10      10             5
3   Tom  Not Finished       15      10             5

dfx
   Name        Score1   Score2  Score3        Score4
0  Jack            10  Perfect      10           BAD
1  Jill            10       10      10  Not Finished
2  Jane            20       10      10             5
3   Tom  Not Finished       15      10             5

does cause the original dataset to be modified.
Any explanation why a column drop does not modify the original dataset but an element change does change the original? and seems like any change to a column name in an assigned dataset also modifies the original dataset.

A: You are referencing dfx3 and dfx to one DataFrame, if you want to do manipulations on dfx3with columns similar to that dfx's then you should make a copy of dfx on dfx3 not reference them both to the same DataFrame.
dfx3 = dfx.copy()


text:
Q: Laravel 4 - Filter results and caching I am creating an ecommerce system. I have a getCategories() function in a controller. This function works but I tried to extend its functionality so that it would return the appropriate view according to a filter.
Lets say the user is viewing a specific category. Each category contains products and I tried to create a filter for the products based on their brand. For example if the user is in the category 'Guitars' he should be able to filter its products based on an existing brand 'Gibson'.
So I implemented the above scenario but I am not sure if that's very efficient. I've created a link:
@foreach($brand as $key => $value)
  slug}}?brand={{$value->slug}}">{{$value->name}}
@foreach

As you can see I am passing the parameter brand through the url and this link calls the getCategories() function, where inside that function I am checking if the link contains the parameter like so:
if (Input::has('brand')) {
    $brandflag = true;
    $brand_input = Input::get('brand');
    $brandfilter = array('type'=>'Brand', 'name' => ucfirst($brand_input));
}

$brandflag is initially set to false and if it exists it changes its value to true. Also another if to return a different data to the view if the $brandflag changed to true.
if ($brandflag == true) {
    $b = Brand::whereSlug($brand_input)->first();
    $products = Product::where('brand_id','=', $b->id)->whereIn('category_id', $children->lists('id'));
    return View::make('store.categories')
        ->with('products', $products->paginate(6))
        ->with('ranges', $ranges)
        ->with('brandfilter', $brandfilter)
        ->with('category', $main)
        ->with('brands', $brands)
        ->with('children', $children_array)
        ->with('seo', $seo);
}

All of the above works, however when I am caching the categories route none of this would work because it would cache the view and it will refer to that cached file. Anything passed after the ? gets ignored.
Route::get('categories/{slug}', array(
    'as' => 'store.categories',
    'uses' => 'StoreController@getCategories'
))->where('slug', '(.*)?')->before('cache.fetch')->after('cache.put');

How should I clean up/fix my code to get this functionality working and be able to cache the categories?

A: I am assuming that the cache.put and cache.fetch filters are based on this article.
In his example, the author uses $request->url() to build the cache key. The API docs state that this method does not include the query string.
In order for the caching to work with the query parameters you'll have to replace the call to url() with either fullUrl(), or a combination of url() and query().


text:
Q: How to use Google oAuth with Node.js backend and Angular frontend? I am using Node.js on backend and creates a token for a user each time logins. angularx-social-login package makes it very easy to integrate Google OAuth with Angular but how to use it with API? After successful login the Google returns user information with token. I was thinking to send this information to backend and login the user but for that I need to create a route which accepts email address and logins user. And this will return JWT token which is not secure. By secure I mean, anyone can access the route without Google Authentication and generate token.
I am looking for ideas how developers achieved this.

A: I found google-auth-library client package for Node.js managed by Google.
Here is the follow:

*

*Login user with Angular

*Send the idToken to backend

*Validate token and response to Angular

Node.js:
exports.googleLogin = function(req, res, next) {
  //verify the token using google client
  return googleClient
    .verifyIdToken({
      idToken: req.body.token,
      audience: config.google.clientID
    })
    .then(login => {
      //if verification is ok, google returns a jwt
      var payload = login.getPayload();
      var userid = payload['sub'];

      //check if the jwt is issued for our client
      var audience = payload.aud;
      if (audience !== config.google.clientID) {
        throw new Error(
          'error while authenticating google user: audience mismatch: wanted [' +
            config.google.clientID +
            '] but was [' +
            audience +
            ']'
        );
      }
      //promise the creation of a user
      return {
        name: payload['name'], //profile name
        pic: payload['picture'], //profile pic
        id: payload['sub'], //google id
        email_verified: payload['email_verified'],
        email: payload['email']
      };
    })
    .then(user => {
      return res.status(200).json(user);
    })
    .catch(err => {
      //throw an error if something gos wrong
      throw new Error(
        'error while authenticating google user: ' + JSON.stringify(err)
      );
    });
};


text:
Q: MediaElement: PosterSource, where are you? I am using MediaElement in my program.
<MediaElement x:Name="media" Source="MyVideo.mp4" Height="480" Width="640" HorizontalAlignment="Left" VerticalAlignment="Top" LoadedBehavior="Manual" Stretch="Fill" />

In various articles I see the possibility of using the PosterSource property in this element.
<MediaElement PosterSource="imageUri" />

This property is missing in my media. Where could there be a mistake?
P.S. I use Visual Studio Enterprise 2015. The version of .NET Framework is 4.7.2.

A: This function is available only in UWP applications.


text:
Q: Can't get radio buttons to work in PHPmailer First off, I'm not a programming expert by any means. I had a company set PHPmailer for me and they created a simple form and the php code that makes it work. They didn't include radio buttons in the example and I haven't been able to figure out how to make them work.
I believe it's something simple but still over my head.
The link to the webpage: https://rappahannockfoundation.org/pages/opinion.php
Form code:
<form method="post" action="frmCode_opinion.php">

Which concert did you attend? Click only one.

    <input name="concert" type="radio" value="Face 2 Face">
    Face 2 Face

    <input type="radio" name="concert" ivalue="Capitol Steps">
    Capitol Steps

    <input type="radio" name="concert" value="Russian String Orchestra">
    Russian String Orchestra

    <input type="radio" name="concert" value="Motones vs. Jerseys">
    Motones vs. Jerseys

    <input type="radio" name="concert" value="Leahy">
    Leahy

Would you like to see them for a return performance?

<input name="return" type="radio"  value="YES"> Yes
  <input name="return" type="radio"  value="NO"> No

Please rate this program. 1 is poor 5 is excellent.

    <input type="radio" name="rate" value="1">1
    <input type="radio" name="rate" value="2">2
    <input type="radio" name="rate" value="3">3
    <input type="radio" name="rate" value="4">4
    <input type="radio" name="rate" value="5">5

Please provide comments or suggestions for future performances.

    <textarea style="margin-left:20px;" name="comments" cols="70" rows="5" id="comments"></textarea>

 <input type="submit" name="submit" id="submit" value="Submit">

    </form>

PHP code:
<?php

/**
 * This example shows how to handle a simple contact form using PHPMailer.
 */

//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

$msg = '';
//Don't run this unless we're handling a form submission
if (array_key_exists('email', $_POST)) {
    date_default_timezone_set('Etc/UTC');

    // the below files are required in order to perform SMTP authentication using the PHPMailer library. If your page/script is under a subdirectory, rather than at the root of the Website directory, then you will need to update the paths here accordingly. For example, if your contact form is located under "/contact/form.php" then you should use a format like: "../phpmailer/src/PHPMailer.php"
    require 'phpmailer/src/PHPMailer.php';
    require 'phpmailer/src/SMTP.php';
    require 'phpmailer/src/Exception.php';

    //Create a new PHPMailer instance, the following lines will remain the same for all sites on your Plesk server
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->Host = 'secure.emailsrvr.com';
    $mail->Port = 465;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'ssl';
    //$mail->SMTPAutoTLS = true;

    //CAPTCHA CODE
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
 }
if(!$captcha){  $err = "1";
}
$secretKey = "6LcXnhUUAAAAACRJ2RZ4A2CJmCFdNVxDfV4EbLPx";
 $ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
$err = "1";
}

    // This will send information from the web server if form doesn't work
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->SMTPDebug = SMTP::DEBUG_CONNECTION;
    $mail->SMTPDebug = 3; //this one is best

    // The below parameters must be updated per Website:
    // Username (address) and Password to use for SMTP authentication
    $mail->Username = 'dave@lmarketing.com';
    $mail->Password = 'Cr0ssT0ur!';

    //Use the same "Username" fixed address in your own domain as the from address
    $mail->setFrom('info@lmarketing.com', 'Dave Lipscombe');
    //Set the recipient for this email (any email address and name)
    $mail->addAddress('dave@lmarketing.com', 'Dave Lipscombe');
    $mail->addBCC('lurbanna@gmail.com', 'Dave Lipscombe');

    //Put the submitter's address in a reply-to header
    //This will fail if the address provided is invalid,
    //in which case we should ignore the whole request
    if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
        $mail->Subject = 'Submission from RFA Website';
        $mail->isHTML(true);
        //Build HTML message body
        $emailMessage = "";
        $emailMessage .= "
Concert: {$_POST['concert']}
";
        $emailMessage .= "
Return performance: {$_POST['return']}
";
        $emailMessage .= "
Program rating: {$_POST['rate']}
";
        $emailMessage .= "
Comments: {$_POST['comments']}
";

        // store the complete message string in the email body
        $mail->Body = $emailMessage;

        //set non-html message text for fallback in non-html compatible email software
        //Build a simple message body
        $mail->AltBody = <<<EOT
Concert: {$_POST['concert']}
Return Performance: {$_POST['return']}
Program rating: {$_POST['rate']}
Program rating: {$_POST['rate']}
Comments: {$_POST['comments']}
EOT;
        //Send the message, check for errors
        if (!$mail->send()) {
            //If you need to debug an error sending, the reason for failing to send will be in $mail->ErrorInfo. Uncomment the below line to enable detailed error reporting, but be warned, this will display detailed error messages to anyone who uses the form while enabled!
            print_r($mail->ErrorInfo); //comment this line when not in-use
            //but you shouldn't display the details of those errors to users, so only this generic message will display publicly
            $msg = 'Sorry, something went wrong. Please try again later.';
        } else {
            header("Location: thanks.php");
        }
    } else {
        $msg = 'Invalid email address, message ignored.';
    }
}
// Below you will find an example form, which includes the basic fields being sent in the email body above.
?>


text:
Q: 1/F distribution equality significance level A question about equality
$$F_{r_{1},r_{2},\alpha}=\frac{1}{F_{r_{2},r_{1},1-\alpha}}$$
We know if $X\sim\chi^{2}\left(  r_{1}\right)  ,~Y\sim\chi^{2}\left(
r_{2}\right)  $ and $X,~Y$ independent then
$$\frac{X/r_{1}}{Y/r_{2}}=F\implies\frac{Y/r_{2}}{X/r_{1}}=\frac{1}{F}$$
distributed. But how can we get $1-\alpha$ instead of $\alpha$. Do i have to get
this result using probability density function and transformations or is there
another sensible explanation?


text:
Q: alternative to wp_is_mobile() I would like to show a different image depending on whether you are on mobile or desktop.
I figured I could do this with the wp_is_mobile function, but Wordpress says it should not be used for styling purposes.
Real-life testing also shows that indeed it does not always work, and sometimes the desktop images is showed on mobile devices. My current code below. Where the div refers to a css class where I load the image.
I initially used @media only screen and (max-width) in my css, but then it always loads both images. What would you recommend doing as the best solution?
<?php if ( wp_is_mobile() ) : ?>

<?php else : ?>

<?php endif; ?>

css part to load image from sprite
#webwinkelkeur-desktop{
    position:fixed;
    right:0px;
    top:45%;
    z-index:999;
    width:50px;
    height:100px;
    background: url('/webwinkelkeur-sprite.png') 0 0;
}
#webwinkelkeur-mobile{
    position:fixed;
    bottom:0px;
    z-index:999;
    width:80px;
    height:40px;
    background: url('/webwinkelkeur-sprite.png') 80px 40px;
}

A: Thank you for your feedback.
I realized you can use the media queries and the sprites in one go.
The code then becomes:
In my footer.php

And in my style.css
@media only screen and (min-width: 691px){
#webwinkelkeur-float{
position:fixed;
right:0px;
top:45%;
z-index:999;
width:50px;
height:100px;
background: url('webwinkelkeur-sprite.png') 0 0;
}}

@media only screen and (max-width: 691px){
#webwinkelkeur-float{
position:fixed;
bottom:0px;
z-index:999;
width:80px;
height:40px;
background: url('webwinkelkeur-sprite.png') 80px 40px;
}}


text:
Q: The SELECT permission was denied My query:
update sc
set grade = 80
where grade = 90

results in this error:

Msg 229, Level 14, State 5, Line 1
  The SELECT permission was denied on the object 'sc', database 'student', schema 'dbo'.

I have typed this, and it get worked
grant UPDATE (grade) on sc to MyUserName

A: I figured it out.
My query:
update sc
set grade = 80
where grade = 90

I need permission  to update and select, so I need to modify to
update sc
set grate = 80

or
grant UPDATE,SELECT (grade) on sc to MyUserName


text:
Q: MobaXterm right mouse button double click Recently I have updated/upgraded to version 10.2, free personal edition. I think right after the upgrade, the right-mouse-button behaviors changed.
I am a long time unix user, I always high light a selection in the term, and then double click the right-mouse-button to paste the selection in the place where the mouse cursor is.
But now, the context menu pops up when clicking the RMB regardless one-clicking or double clicking, and I have select the paste from the menu to paste the selection.
I don't see the reason why MobaXterm should change the behave in such a way that is annoying and inconvenient.
How can I change it back to the way before like any other Xterm apps?

A: I found the setting:
Settings | Terminal
The check box Paste using right-click is default to unchecked.
check this box, and restart MobaXterm, the RMB double click will paste the selection without the context menu popping up.

A: *

*Go to Settings tab on the Top Panel

*Select Settings->Configuration.

*Under the Terminal Tab, inside the  "Terminal Features" Panel. Toggle "Paste using right-click" to ☑ ( toggle : yes).


text:
Q: "variable" is read only I have the following code and I am getting error of "count" is read-only:
import React, {useState} from 'react';
import {View, Text, StyleSheet, Button} from 'react-native';

const CounterScreen = () => {
  const [count, setCount] = useState(0);

  return (
    <View>
      <Button onPress={() => setCount(count++)} title="Increase" />
      <Button onPress={() => setCount(count--)} title="Decrease" />
      <Text>Current Counter: {count}</Text>
    </View>
  );
};

const styles = StyleSheet.create({});
export default CounterScreen;

But if I use setCount(count + 1) instead of setCount(count++), it works perfectly. What is the difference here between count + 1 and count++

A: The important thing to remember is that you can change the value of a variable declared as a const, but you cannot reassign it. Here is a good blog post about this:
https://mathiasbynens.be/notes/es6-const
setCount(count+1) is taking the current value of the variable count, adding 1 to it and then passing this to our setter function, 'setCount' to update our state. We are in no way reassigning the 'count' variable. React is updating the value of 'count' under the hood using the setter function.
What you are doing with count++ is attempting to re-assign the count variable, not just change the value of the 'count' variable.

A: count++ is shorthand for count = count + 1; you are actually changing the value of a variable. not just reading its value.

A: count++ is similar as count = count + 1
means it's changing the variable itself
and you know const are read-only after initialization that is why you doing setCount() to update the value.
and count + 1 is not updating itself.

A: const [count, setCount] = useState(0);

Your count in here ↑ is read only, if you want to change it's value have to call setCount()
Like setCount(num)
so if num= 10 then equal to setCount(10)
So that setCount(count + 1) could work, count+1 is a number
But why setCount(count++) couldn't work is because
count++

Equal to
count=count+1; //It is changing the value of count directly!

setCount(count++)

setCount(count=count+1) //So count++ is changing the value of count directly, not through setCount, couldn't work.

It couldn't work and may error for "count" is read-only
This is try to change count value without calling setCount in setCount


text:
Q: Issue to determine a currently downloading file size? I have an interesting problem. I need to do a progress bar from an asycronusly php file downloading. I thought the best way to do it is before the download starts the script is making a txt file which is including the file name and the original file size as well.
Now we have an ajax function which calling a php script what is intended to check the local file size. I have 2 main problems.

*

*files are bigger then 2GB so filesize() function is out of business

*i tried to find a different way to determine the local file size like this:

.
  function getSize($filename) {

       $a = fopen($filename, 'r');
       fseek($a, 0, SEEK_END);
       $filesize = ftell($a);
       fclose($a);
       return $filesize;
  }

Unfortunately the second way giving me a tons of error assuming that i cannot open a file which is currently downloading.
Is there any way i can check a size of a file which is currently downloading and the file size will be bigger then 2 GB?
Any help is greatly appreciated.

A: I found the solution by using an exec() function:
exec("ls -s -k /path/to/your/file/".$file_name,$out);

A: Just change your OS and PHP to support 64 bit computing. and you can still use filesize().
From filesize() manual:

Return Values
Returns the size of the file in bytes, or FALSE (and generates an
  error of level E_WARNING) in case of an error.
Note: Because PHP's integer type is signed and many platforms use
  32bit integers, some filesystem functions may return unexpected
  results for files which are larger than 2GB.


text:
Q: postgresql does no restart after changing postgres.conf or pg_hba.conf. This incident happened while i was trying to setup the postgresql BDR I am not able to login to postgresql after restarting postgresql DB after configuring pg_hba.conf and postgresql.conf file. The snapshot of the error is attached for referral postgresql.conf / pg_hba.conf. This incident happened while i was trying to setup the postgresql Bi Directional replication. After this I need to restart the database to take the configuration changes into effect. But when I restart the database the configuration files go missing.

A: i had the issue that a syntax error in the config file was the problem; i did not get an error or warning (maybe yes but i didn't find it),
so double check your config file and do only one change at one time,
Is "sudo systemctl start postgresql" getting more information?
Or sudo service postgresql status
best,
Bodo


text:
Q: laravel - post function not working through db @extends('layouts.master')
@section('content')

Laravel Blog

              The php framework for web artisans

          @foreach($posts as $post)

                {{$post->title}}

Posted by
              {{$post->user->name}}
              on {{$post->created_at}}

          @endforeach

            Older Posts

@endsection

controller code:
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PublicController extends Controller
{
    public function index(){
      $posts= Post::all();
      return view('welcome', compact( 'posts'));
    }
    public function singlePost($id){
      return view('singlePost');
    }
    public function about(){
      return view('about');
    }
    public function contact(){
      return view('contact');
    }
    public function contactPost(){

    }
}

I have been revising my code for more than 24 hours still cant figure out why the posts are not being displayed on my homepage. the routes are okay they are working correctly just the information when passing the posts are not being displayed could anyone assist pls


text:
Q: How did Tarski show that some propositions are neither true nor false? I'm not a logician, and I'm something of an amateur or beginner here, so please bear with me.
I was just reading Mike Nahas' tutorial on the Coq proof assistant, and I saw this paragraph, about an eighth of the way through the tutorial:

IT IS VITALLY IMPORTANT THAT YOU DO NOT THINK OF A Prop AS BEING EITHER "TRUE" OR "FALSE". A Prop either has a proof or it does not have a proof. Godel shattered mathematics by showing that some true propositions can never proven. Tarski went further and showed that some propositions cannot even said be to be true or false!!! Coq deals with these obstacles in modern mathematics by restricting Prop to being either proven or unproven, rather than true or false.

This, I think, is telling us that Coq uses a constructivist approach like Brouwer's. I more or less understand what Gödel did, at least at some level, but this is the first time I've heard of Tarski going further. Just what did Tarski do here, how did he do it, and what were its implications for mathematics and logic?

A: I can't really say what the author means here.  Tarski accomplished an enormous amount in logic:

*

*Tarski developed the T-schema as part of his goal to understand what does it mean for a proposition to be true.  The T-schema gives a kind of recursive definition of truth.

*Tarski's theorem on the undefinability of truth shows that it is impossible to define, in formal systems of arithmetic, what it means for a formula to be true.
But Tarski did not directly show that there are propositions that "cannot be said to be true or false". Indeed, throughout the history of mathematics most mathematicians have thought classically, writing and speaking as if each proposition is true or false, although we may not know which of these is the case or even know whether a given proposition is provable.
Now, to give the author some credit, it is almost certainly correct that, in order to work effectively in Coq, it is better to think constructively ("Is this propositional provable? Is it disprovable?") than to think classically ("Is this proposition true?").   I think this is really the point of the quoted paragraph, and it is an important one.
However, the entire logic of Coq can be interpreted into set theory (see this MathOverflow question and its answers for how much set theory is needed).   Under that interpretation, each proposition $P$ in the language of Coq is just as true or false as the proposition of set theory that is used to represent $P$.  Of course, there are many philosophical issues with set theoretic truth, but if someone accepts that each set theoretic proposition is true or false in some sense, they will see that the interpretation of each proposition of Coq is true or false in the same sense.


text:
Q: AttributeError: 'module' object has no attribute 'kill' Here is my code:
def cmdoutput(cmd1, flag):
    finish = time.time() + 50
    p = subprocess.Popen(cmd1, stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
    while p.poll() is None:
        time.sleep(1)
        if finish < time.time():
            os.kill(p.pid, signal.SIGTERM)
            print "timed out and killed child, collecting what output exists so far"
        if (flag == "1"):#To enable container
            out, err = p.communicate(input='container\nzone1')
    else:
        out, err = p.communicate()
    print (out)
    return out

When I run this script, I get
Attribute Error: 'module' object has no attribute 'kill'.

What's wrong with my code?

A: I think you have your own os.py.
Put print os.__file__ before os.kill(...) line, and you will see what's going on.

UPDATE
os.kill is only available in unix in jython
Instead of os.kill(...), use p.kill().
UPDATE
p.kill() not work. (At least in Windows + Jython 2.5.2, 2.5.3).
p.pid is None.
http://bugs.jython.org/issue1898

A: Change your code as follow. Change CPYTHON_EXECUTABLE_PATH, CMDOUTPUT_SCRIPT_PATH.
CPYTHON_EXECUTABLE_PATH = r'c:\python27\python.exe' # Change path to python.exe
CMDOUTPUT_SCRIPT_PATH = r'c:\users\falsetru\cmdoutput.py' # Change path to the script

def cmdoutput(cmd1, flag):
    return subprocess.check_output([CPYTHON_EXECUTABLE_PATH, CMDOUTPUT_SCRIPT_PATH, flag])

Save following code as cmdoutput.py
import subprocess
import sys

def cmdoutput(cmd1, flag):
    finish = time.time() + 50
    p = subprocess.Popen(cmd1, stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
    while p.poll() is None:
        time.sleep(1)
        if finish < time.time():
            p.kill()
            return '<<timeout>>'
        if flag == "1":
            out, err = p.communicate('container\nzone1')
    else:
        out, err = p.communicate()
    return out

if __name__ == '__main__':
    cmd, flag = sys.argv[1:3]
    print(cmdoutput(cmd, flag))


text:
Q: Merge a two way relation in the same table in SQL Server Current Data
ID      | Name1      | Name2
<guid1> | XMind      | MindNode
<guid2> | MindNode   | XMind
<guid3> | avast      | Hitman Pro
<guid4> | Hitman Pro | avast
<guid5> | PPLive     | Hola!
<guid6> | ZenMate    | Hola!
<guid7> | Hola!      | PPLive
<guid8> | Hola!      | ZenMate

Required Output
ID1       | ID2       | Name1  | Name2
<guid1>   | <guid2>   | XMind  | MindNode
<guid3>   | <guid4>   | avast  | Hitman Pro
<guid5>   | <guid7>   | PPLive | Hola!
<guid6>   | <guid8>   | Hola!  | ZenMate

These are relations between apps. I want to show that Avast and Hitman has a relation but in this view i do not need to show in what "direction" they have an relation. It's a given in this view that the relation goes both ways.
EDIT: Seems like my example was to simple. The solution doesn't work with more data.
DECLARE @a TABLE (ID INT, Name1 VARCHAR(50), Name2 VARCHAR(50))
INSERT  INTO @a VALUES  ( 1, 'XMind', 'MindNode' )
INSERT  INTO @a VALUES  ( 2, 'MindNode', 'XMind' )
INSERT  INTO @a VALUES  ( 3, 'avast', 'Hitman Pro' )
INSERT  INTO @a VALUES  ( 4, 'Hitman Pro', 'avast' )
INSERT  INTO @a VALUES  ( 5, 'PPLive Video Accelerator', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( 6, 'ZenMate', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( 7, 'Hola! Better Internet', 'PPLive Video Accelerator' )
INSERT  INTO @a VALUES  ( 8, 'Hola! Better Internet', 'ZenMate' )

SELECT  a1.ID AS ID1 ,
        a2.ID AS ID2 ,
        a1.Name1 ,
        a2.Name1 AS Name2
FROM    @a a1
JOIN @a a2 ON a1.Name1 = a2.Name2
        AND a1.ID < a2.ID -- avoid duplicates

This works however so i guess it's the Guid that is messing with me.
EDIT AGAIN:
I haven't looked at this for a while and i thought it worked but i just realized it does not. I've struggled all morning with this but i must admit that SQL is not really my strong suite. The thing is this.
DECLARE @a TABLE (ID int, Name1 VARCHAR(50), Name2 VARCHAR(50))
INSERT  INTO @a VALUES  ( 1, 'XMind', 'MindNode' )
INSERT  INTO @a VALUES  ( 2, 'MindNode', 'XMind' )
INSERT  INTO @a VALUES  ( 3, 'avast', 'Hitman Pro' )
INSERT  INTO @a VALUES  ( 4, 'PPLive Video Accelerator', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( 5, 'ZenMate', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( 6, 'Hitman Pro', 'avast' )
INSERT  INTO @a VALUES  ( 7, 'Hola! Better Internet', 'PPLive Video Accelerator' )
INSERT  INTO @a VALUES  ( 8, 'Hola! Better Internet', 'ZenMate' )
INSERT  INTO @a VALUES  ( 9, 'XX', 'A' )
INSERT  INTO @a VALUES  ( 10, 'XX', 'BB' )
INSERT  INTO @a VALUES  ( 11, 'BB', 'XX' )
INSERT  INTO @a VALUES  ( 12, 'A', 'XX' )
INSERT  INTO @a VALUES  ( 13, 'XX', 'CC' )
INSERT  INTO @a VALUES  ( 14, 'CC', 'XX' )

;With CTE as
(
SELECT  a1.ID AS ID1 ,
        a2.ID AS ID2 ,
        a1.Name1 ,
        a2.Name1 AS Name2,
        CheckSum(Case when a1.Name1>a2.Name1 then a2.Name1+a1.Name1 else a1.Name1+a2.Name1 end) ck, -- just for display
        Row_Number() over (Partition by CheckSum(Case when a1.Name1>a2.Name1 then a2.Name1+a1.Name1 else a1.Name1+a2.Name1 end)
                           order by CheckSum(Case when a1.Name1>a2.Name1 then a2.Name1+a1.Name1 else a1.Name1+a2.Name1 end)) as rn

FROM    @a a1
JOIN @a a2 ON a1.Name1 = a2.Name2
)
Select ID1, ID2,Name1, Name2
from CTE C1
where rn=1

When i use this code it sure works fine with the names but it doesn't match the ID's correctly.
The result is
ID1       | ID2       | Name1  | Name2
12        | 9         | A      | X (Correct)
7         | 5         | Hola!  | ZenMate (Not Correct)
[..]

I've pulled my hair all morning but i can't figure this out. I still use Guid's as ID's and just use Int's here to make it a bit more readable.

A: DECLARE @a TABLE (ID INT, Name1 VARCHAR(50), Name2 VARCHAR(50))
INSERT  INTO @a VALUES  ( 1, 'XMind', 'MindNode' )
INSERT  INTO @a VALUES  ( 2, 'MindNode', 'XMind' )
INSERT  INTO @a VALUES  ( 3, 'avast', 'Hitman Pro' )
INSERT  INTO @a VALUES  ( 4, 'Hitman Pro', 'avast' )

SELECT  a1.ID AS ID1 ,
        a2.ID AS ID2 ,
        a1.Name1 ,
        a2.Name1 AS Name2
FROM    @a a1
JOIN @a a2 ON a1.Name1 = a2.Name2
        AND a1.ID < a2.ID -- avoid duplicates

Referring to the amendment and extension of your question, a more complicated solution is required.
We form a CHECKSUM on a1.Name1,a2.Name (to get an identical we exchanged on size).
Using this we generate with ROW_NUMBER (Transact-SQL) a number and use only rows from the result with number 1.
DECLARE @a TABLE (ID uniqueIdentifier, Name1 VARCHAR(50), Name2 VARCHAR(50))
INSERT  INTO @a VALUES  ( NewID(), 'XMind', 'MindNode' )
INSERT  INTO @a VALUES  ( NewID(), 'MindNode', 'XMind' )
INSERT  INTO @a VALUES  ( NewID(), 'avast', 'Hitman Pro' )
INSERT  INTO @a VALUES  ( NewID(), 'Hitman Pro', 'avast' )
INSERT  INTO @a VALUES  ( NewID(), 'PPLive Video Accelerator', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( NewID(), 'ZenMate', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( NewID(), 'Hola! Better Internet', 'PPLive Video Accelerator' )
INSERT  INTO @a VALUES  ( NewID(), 'Hola! Better Internet', 'ZenMate' )
INSERT  INTO @a VALUES  ( NewID(), 'XX', 'A' )
INSERT  INTO @a VALUES  ( NewID(), 'A', 'XX' )
INSERT  INTO @a VALUES  ( NewID(), 'XX', 'BB' )
INSERT  INTO @a VALUES  ( NewID(), 'BB', 'XX' )
INSERT  INTO @a VALUES  ( NewID(), 'XX', 'CC' )
INSERT  INTO @a VALUES  ( NewID(), 'CC', 'XX' )

;With CTE as
(
SELECT  a1.ID AS ID1 ,
        a2.ID AS ID2 ,
        a1.Name1 ,
        a2.Name1 AS Name2,
        CheckSum(Case when a1.Name1>a2.Name1 then a2.Name1+a1.Name1 else a1.Name1+a2.Name1 end) ck, -- just for display
        Row_Number() over (Partition by CheckSum(Case when a1.Name1>a2.Name1 then a2.Name1+a1.Name1 else a1.Name1+a2.Name1 end)
                           order by CheckSum(Case when a1.Name1>a2.Name1 then a2.Name1+a1.Name1 else a1.Name1+a2.Name1 end)) as rn

FROM    @a a1
JOIN @a a2 ON a1.Name1 = a2.Name2
)
Select *
from CTE C1
where rn=1

Edit:
If you only want to get those where both fields are fitting the needed query would simply be:
SELECT a1.ID AS ID1 , a2.ID AS ID2 , a1.Name1 , a2.Name1 AS Name2
FROM @a a1
JOIN @a a2 ON a1.Name1 = a2.Name2 and a1.Name2 = a2.Name1 AND a1.ID < a2.ID

A: If the output should contain only two-way relations ('XX' + 'A') AND ('A' + 'XX'), try this:
;
WITH m    (ID1, ID2, Name1, Name2) AS (
    SELECT ID1, ID2, Name1, Name2
    FROM (
        SELECT a1.ID AS ID1
              ,a2.ID AS ID2
              ,a1.Name1 AS Name1
              ,a2.Name1 AS Name2
              ,ROW_NUMBER() OVER (PARTITION BY a1.Name1, a2.Name1 ORDER BY (SELECT 1)) AS n
        FROM @a AS a1
        JOIN @a AS a2
            ON a1.Name1 = a2.Name2
                AND a1.Name2 = a2.Name1
    ) AS T
    WHERE n = 1
)
SELECT DISTINCT *
FROM (
    SELECT ID1, ID2, Name1, Name2
    FROM m
    WHERE ID1 <= ID2

    UNION ALL

    SELECT ID2, ID1, Name2, Name1
    FROM m
    WHERE ID1 > ID2
) AS dm

It produces the output as follows:
+------+-----+--------------------------+-----------------------+
| ID1  | ID2 | Name1                    | Name2                 |
+------+-----+--------------------------+-----------------------+
|    1 |   2 | XMind                    | MindNode              |
|    3 |   6 | avast                    | Hitman Pro            |
|    4 |   7 | PPLive Video Accelerator | Hola! Better Internet |
|    5 |   8 | ZenMate                  | Hola! Better Internet |
|    9 |  12 | XX                       | A                     |
|   10 |  11 | XX                       | BB                    |
|   13 |  14 | XX                       | CC                    |
+------+-----+--------------------------+-----------------------+

A: Just rank your rows with ROW_NUMBER function and use this rank in join instead of original ID column:
DECLARE @a TABLE (ID UNIQUEIDENTIFIER, Name1 VARCHAR(50), Name2 VARCHAR(50))
INSERT  INTO @a VALUES  ( NEWID(), 'XMind', 'MindNode' )
INSERT  INTO @a VALUES  ( NEWID(), 'MindNode', 'XMind' )
INSERT  INTO @a VALUES  ( NEWID(), 'avast', 'Hitman Pro' )
INSERT  INTO @a VALUES  ( NEWID(), 'Hitman Pro', 'avast' )
INSERT  INTO @a VALUES  ( NEWID(), 'PPLive Video Accelerator', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( NEWID(), 'ZenMate', 'Hola! Better Internet' )
INSERT  INTO @a VALUES  ( NEWID(), 'Hola! Better Internet', 'PPLive Video Accelerator' )
INSERT  INTO @a VALUES  ( NEWID(), 'Hola! Better Internet', 'ZenMate' )

;WITH cte AS(SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) rn FROM @a)
SELECT  a1.ID AS ID1 ,
        a2.ID AS ID2 ,
        a1.Name1 ,
        a2.Name1 AS Name2
FROM    cte a1
JOIN cte a2 ON a1.Name1 = a2.Name2 AND
               a2.Name1 = a1.Name2 AND
               a1.rn < a2.rn

Output:
ID1     ID2     Name1                       Name2
Guid    Guid    XMind                       MindNode
Guid    Guid    avast                       Hitman Pro
Guid    Guid    PPLive Video Accelerator    Hola! Better Internet
Guid    Guid    ZenMate                     Hola! Better Internet

A: I suggest you to use this simple way:
SELECT
    t2.ID, t3.ID ID2,
    t1.Name1,t1.Name2
FROM (
    SELECT DISTINCT
        CASE WHEN Name1 <= Name2 THEN Name1 ELSE Name2 END AS Name1,
        CASE WHEN Name1 <= Name2 THEN Name2 ELSE Name1 END AS Name2
    FROM
        @a) t1
    JOIN
    @a t2 ON t1.Name1+t1.Name2 = t2.Name1+t2.Name2
    JOIN
    @a t3 ON t1.Name1+t1.Name2 = t3.Name2+t3.Name1

For this:
ID  | ID2 | Name1                 | Name2
----+-----+-----------------------+---------------------------
12  | 9   | A                     | XX
3   | 4   | avast                 | Hitman Pro
11  | 10  | BB                    | XX
14  | 13  | CC                    | XX
7   | 5   | Hola! Better Internet | PPLive Video Accelerator
8   | 6   | Hola! Better Internet | ZenMate
2   | 1   | MindNode              | XMind

A: You can solve this using a CROSS APPLY
SELECT a2.ID ID_1,a1.ID ID_2, a2.Name1 , a2.Name2
FROM @a a1
CROSS APPLY
(
    SELECT ID, Name2, Name1
    FROM @a aa
    WHERE aa.Name1 = a1.Name2 AND a1.Name1 = aa.Name2 AND a1.ID > aa.ID
) a2

A: You can try also:
select min(ID) ID1,
       max(ID) ID2,
       Name1,
       Name2
from ( -- Here I get all the IDs and each couple sorted
       -- Change > to < if you don't like the order
       select ID,
              case
                  when Name1 > Name2 then Name1
                  else Name2
              end Name1,
              case
                  when Name1 > Name2 then Name2
                  else Name1
              end Name2
       from table1
      ) as t
group by Name1,
         Name2

You can even tansform this in a simgle query, without the inner one, but I think in this way it's more readable and you can understand better my approach.


text:
Q: Python executable with pyinstaller and Pmw I am trying to create an executable in windows using pyinstaller, but I get an error when running the executable if I import Pmw.
I am using the following code to create a sample GUI
import tkinter as tk
from tkinter import ttk
import Pmw

class Test():
    def __init__(self):
        self.mainwindow = tk.Tk()
        self.mainwindow.title("Main Window")
        self.mainwindow.geometry("600x300")
        self.mainwindow.configure(background='light sea green')
        self.textInfo = tk.Text(self.mainwindow, width=60, height=30)
        self.textInfo.pack(side=tk.TOP)

        self.labelWelcome = ttk.Label(self.mainwindow, text="Welcome to the Ribadesella Guest House Platform!")
        self.labelWelcome.place(x = 160, y = 80, width = 280, height = 30)

        self.buttonHello = ttk.Button(self.mainwindow, text="Hello", command=self.hello)
        self.textHello = tk.Text(self.mainwindow)

        self.buttonHello.place(x = 80, y = 200, width = 150, height = 35)
        self.textHello.place(x = 230, y = 200, width = 150, height = 35)

        self.mainwindow.mainloop()

    def hello(self):
        self.textHello.insert(tk.END,'Hello world')

start = Test()

It compiles and runs well if I omit the line import Pmw, but if I include it, I get the error:
Traceback (most recent call last):
  File "test.py", line 10, in <module>
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "c:\anaconda3\lib\site-packages\Pmw\__init__.py", line 34, in <module>
    _loader = 'Pmw.' + _instdirs[0] + '.lib.PmwLoader'
IndexError: list index out of range

I understand it has something to do with the package lazy importer, but I have no clue how to fix it (or what a lazy importer is, for that matter)
A few more details bellow:

*

*I have not included the use of Pmv in the code yet, but I will in the future.

*The error does not appear when I run the .py directly in python

*Pmw version 2.0.1

*pyinstaller version 4.2

*Python version 3.6.5

*To create the executable I am using: pyinstaller --onefile --debug=all test.py

A: There is a working solution here. The link in the answer is not working (that's the reason why I posted this question), but there is a working one in the comments of said answer.


text:
Q: ASP.net how to design this best On my pages I sometimes have a tab menu with the following HTML:

Home

Create New

Help!

Different groups of pages have different tabs obviously.  But what is the best way to write these tabs onto a page without manually doing it with HTML each time, so that if I want to add a tab I don't have to go through each page ensuring they are all the same?
Should I make my own control?  What is the best way to load these tabs in a modularised way?  Should I have a class which holds all the tab groups and builds the HTML?
Thanks for any help!

A: You can either make a custom control or use a master page.

A: If they are static controls you are best off creating the Html in custom ascx controls and load them dynamically on the page. Once they are created you should look at using the OutputCache directive which will speed up the page rendering.

A: Maybe a usercontrol like :
public partial class TabControl : System.Web.UI.UserControl
{
    public List<TabObject> TabObjects { get; set; }

    public override void RenderControl(HtmlTextWriter writer)
    {
        writer.Write("
");
        foreach (var item in TabObjects)
        {
            writer.Write("
{2}
", (item.Selected) ? " tabSelected" : "", item.Link, item.Name);
        }
        writer.Write("

");
        writer.Write("
");

        base.RenderControl(writer);
    }
}

The TabObject class :
public class TabObject
{
    public string Name { get; set; }
    public string Link { get; set; }
    public bool Selected { get; set; }
}

And in your page :
        UcTabControl.TabObjects = new List<TabObject>()
        {
            new TabObject(){
                Link = "artworkHome.aspx",
                Name = "Home",
                Selected = true
            },
            new TabObject(){
                Link = "#",
                Name = "Create New",
                Selected = false
            },
            new TabObject(){
                Link = "#",
                Name = "Help!",
                Selected = false
            },
        };

The output will be :

Home

Create New

Help!


text:
Q: Django admin download reportlab PDF I use this guide(https://docs.djangoproject.com/en/4.1/howto/outputting-pdf/) to download PDF. It works on regular public page. But I am trying to get it working in the admin for a specific model and have model data on the PDF.
In my admin I have:
cakes/models.py
from django.db import models

class Cake(models.Model):
    date = models.DateField("Date ordered")
    name = models.CharField()

    def pdf_link(self):
        from django.utils.html import format_html
        return format_html("Download PDF" % self.pk)

Dislay the PDF link in the django admin. The link is showing up in admin, it just doesn't link to the PDF yet(pass pdf_link)...
cakes/admin.py
from django.contrib import admin
from .models import Cake

@admin.register(Cake)
class CakeAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'customer',
        'date',
        'pdf_link',
    )

On my cakes.views.py I have the generate_pdf function from the django docs.
How do I connect/link my view function(generate_pdf) with the pdf_link function in my model?
I can download the PDF outside the admin. I'm just not sure how to tie it all together in the admin.


text:
Q: running docker compose on swarm I have a compose file:
docker-compose.yml
openjdk-6b36-jdk:
  image: java:openjdk-6b36-jdk
  volumes:
   - ./src:/src
   - ./build/openjdk-6b36-jdk:/build
  command: /src/compileAndTest

openjdk-7u79-jdk:
  image: java:openjdk-7u79-jdk
  volumes:
   - ./src:/src
   - ./build/openjdk-7u79-jdk:/build
  command: /src/compileAndTest

openjdk-8u66-jdk:
  image: java:openjdk-8u66-jdk
  volumes:
   - ./src:/src
   - ./build/openjdk-8u66-jdk:/build
  command: /src/compileAndTest

it runs fine:
-bash-4.2$ docker-compose up
Starting compose_openjdk-7u79-jdk_1
Starting compose_openjdk-8u66-jdk_1
Starting compose_openjdk-6b36-jdk_1
Attaching to compose_openjdk-8u66-jdk_1, compose_openjdk-7u79-jdk_1, compose_openjdk-6b36-jdk_1
openjdk-7u79-jdk_1  | Hello, World
openjdk-8u66-jdk_1  | Hello, World
openjdk-6b36-jdk_1  | Hello, World
compose_openjdk-7u79-jdk_1 exited with code 0
compose_openjdk-8u66-jdk_1 exited with code 0
compose_openjdk-6b36-jdk_1 exited with code 0

i would like to run this across swarm cluster
What would be the command to do so?
would it be something like docker -H :4000 run <something>?
because that the command i used to run images on swarm nodes
I can run docker -H :4000 run hello-world fine but those are docker images. how do you run docker compose across swarm cluster?
i.e. i want compose_openjdk-7u79-jdk_1 to go to one node and compose_openjdk-8u66-jdk_1 to go to another node and so forth?

A: According to the documentation you can add contraints to services:
https://docs.docker.com/compose/swarm/#/manual-scheduling
I have not tested it myself.


text:
Q: Somewhere to be dead or somewhere to die? Which is the correct sentence? Somewhere to be Dead or Somewhere to Die?
But what if I use "Somewhere to be dead" instead? I would like to use this for my video game title

A: Dead is an adjective: it describes something which is not alive. It is a state or condition. Typical places to be dead include cemeteries.
Die is a verb: it is the action of becoming dead. Typical places to die include hospital beds, wars, wrecked cars, etc.


text:
Q: Possible With WebStorm and JavaScript to extract a class compponent to separate file? I have a class component in react that I refactored out of the render method and it looks like the following inside my index.js file.
    class speakerCard extends Component {
        render() {
            return

                <img className="card-img-top" src={`/static/speakers/Speaker-${this.props.speaker.id}.jpg`}/>

                    Details

{this.props.speaker.firstName} {this.props.speaker.lastName}

{this.props.speaker.bioShort}

;
        }
    }

Is there any nice refactoring in WebStorm that let's me pull this out directly to it's own file? (SpeakerCard.js).

A: On class name, hit F6 (or choose Refactor > Move... from right-click menu), specify a file to move the class to:


text:
Q: Why doesnt javascript check object's local scope first? Why doesnt the outer scope get accessed in the inner scope ?
I am coming from C++ world where any reference to an unqualified variable inside a class's method is attempted to be resolved first within the object's scope and then in the outer scope. And this happens without having to use "this" keyword.
For ex:
#include <iostream>
using namespace std;

std::string name = "Global::name";

class MyClass {
    private:
        string name = "MyClass::name";
    public:
        void printName() {
            // No need to use 'this' keyword to refer to the variables in the
            // object's scope, unless there is an ambiguity to resolve
            cout << "Name from inside printName is: " << name << "\n";
        }
};

int main()
{
    MyClass obj;
    cout << "Name from inside main is: " << name << "\n";
    obj.printName();
    return 0;
}

prints
Name from inside main is: Global::name
Name from inside printName is: MyClass::name

But in javascript, the following code snippet
function fn() {
    let name1 = "fnB";
    console.log("Inside fn() name is : ", name1);
}

var obj = {
    name1: "objA",
    objFn: function() {
        console.log("Inside objFn() name is : ", name1); // ERROR !!
        // console.log("Inside objFn() name is : ", this.name1); // OK !
    }
}

fn();
obj.objFn();

results in
Uncaught ReferenceError: name1 is not defined
    at Object.objFn (my.js:10)

What is the reason javascript doesnt want to refer to the "name1" variable in the scope of "obj" object, without requiring "this" keyword to refer to it ? What is the problem that is being solved by forcing the use of "this" keyword in this context ?

A: Every language is different and makes different tradeoffs. An obvious difference between C++ and JavaScript wrt class/object methods:

*

*In JavaScript, every function is a standalone object. It doesn't strongly belong to anything.

*

*In C++, class methods belongs the class. They cannot be invoked without it.

*In JavaScript, every function is a closure, i.e. it has access to free variables defined in a "higher" lexical scope.

*

*In C++, methods are not closures.

Why does this matter? Consider the following example:
var name = 42;

var obj = {
    name: "objA",
    objFn: function() {
        console.log("Inside objFn() name is : ", name);
    }
}

Which name should objFn access according to your expectation?
As it is now, the function would log 42, because that's how lexical scoping + closures work. In order to access the object's name property I have to write this.name.
Now lets assume it was the other way round, that object properties would be accessed before the outer scope. Then in order to explicitly access the outer scope's variables, i.e. 42, we would need some new API, e.g. getVariableFromScope('name'). This is worse than always requiring this for a simple reason: It makes it more difficult to reason about the code. By always requiring this, the rules are very simply:

*

*Want to access a property on the object? this.<property>

*Want to access a variable in scope? <variable>
In your case it would be:

*

*Want to access a variable in scope? <variable>, but only if the object doesn't have a property with the same name, otherwise getVariableFromScope('<variable>').

*Want to access a property on the object? <property>, but only if there is not a local variable with the same name, otherwise this.<property>.

One possible tradeoff here is consistency vs convenience.
Also consider the following example:
var foo = 42;
function bar() {
  console.log(foo);
}

Calling bar() will log 42. Now lets assume I pass the function to some third-party code someOtherFunction(foo) which does:
function someOtherFunction(func) {
  var obj = createObject();
  obj.func = func;
  obj.func();
}

Do you see the problem? The result of calling bar now depends on whether obj has a name property or not. To resolve this, either someOtherFunction needs to know which free variables bar contains or bar needs to know that someOtherFunction assigns it to some object and has to account for that. Either way, the code would be tightly coupled.
Doing what C++ or Java does would basically mean to introduce dynamic scope, and I assume there is a reason why very few languages use it.
(Someone might argue that this is also like dynamic scope. Well, this is a single keyword. It's easier to reason about that than to reason about the space of all possible variable names that could be overwritten.)

There are probably more reason why the behavior you are describing is not desirable in JavaScript. But again, programming language design is all about tradeoffs.

A: The this keyword behaves quite differently in javascript from how it does in many other languages. The value of this is not figured out until the function is invoked, and may not have anything to do with the object you think its associated with.
For example, consider the following code:

const obj = {
  name: 'bob',
  sayName: function () {
    console.log(this.name);
  }
}

const verbalize = obj.sayName; // Make another way to reference the function

console.log(verbalize === obj.sayName); // They're literally the same function

// And yet they log very different things
obj.sayName();  // logs 'bob'
verbalize();  // for me, it logs 1d7dcb5e-0fde-4726-8875-4bdcd636c6eb

Why does verbalize produce such a weird result? Well, since i'm invoking the function without specifying what this should be equal to, this defaults to the global window object, and so i end up logging window.name, which for me happens to be "1d7dcb5e-0fde-4726-8875-4bdcd636c6eb".
So if the language was set up to check this before checking other scopes, the actual result would be (in some cases) to check for global variables before local variables, which is the exact opposite of what we'd like to happen. Thus, this has to be done explicitly.
(ps: while this can be set to the window object in some cases, it can also be set to undefined if you're in strict mode)


text:
Q: GET request to multiple pages of URL and 400 bad request I am to get the data from this url: http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057 with a parameter page from 1 to 10 choosing the appropriate method from GET, POST, DELETE, PUT, OPTIONS. Tried this code to access the first page, but it didn't work:
import requests as rq
data_1 = rq.get('http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057/?page=1', params={'page': '1'})
data_1

whatever I've tried - always getting 400 bad request in response.

A: Your passing the GET parameters twice, which is likely resulting in a malformed URL. Try running
import requests as rq
data_1 = rq.get(
    'http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057/',
    params={'page': '1'},
)


text:
Q: How to use XPath in Odoo I having some problem in Odoo
<record id="lunch_order_view_form" model="ir.ui.view">
<field name="name">lunch.order.form</field>
<field name="model">lunch.order</field>
<field name="arch" type="xml">
    <form string='Orders Form' class="o_lunch">
    <header>
        <button name="%(action_lunch_order_line_lucky)d" type="action" string="Feeling Lucky" class="oe_highlight"/>
         <!-- HERE THAT I WANT TO ADD  -->

And then I use
<record id="lunch_order_view_form" model="ir.ui.view">
    <xpath expr="/lunch/views/lunch_views/field[@name='arch']" position="after">
        <button name="%(action_lunch_order_line_favorite)d" type="action" string="Favorite Menu" />
        hello
    </xpath>
</record>

but it now works how to define it?

A: If header is already define in your parent form view , you can inherit it as below:
<record id="lunch_order_view_form_inherit" model="ir.ui.view">
    <field name="name">lunch.order.form.inherit</field>
    <field name="model">lunch.order</field>
    <field name="inherit_id" ref="parent_form_module_name.lunch_order_view_form"/>
    <field name="arch" type="xml">
        <xpath expr="//header" position="inside">
            <button name="%(action_lunch_order_line_favorite)d" type="action" string="Favorite Menu" />
        </xpath>
    </field>
</record>

You can replace parent_form_module_name with actual module name where you have define parent form.


text:
Q: How to work with Migrations on rider? I tried to add-migration and other migration operations on Rider with Entity Framework 6 project.
I tried two approaches.

*

*Using inline tool from menu
Tried this - https://blog.jetbrains.com/dotnet/2018/04/06/entity-framework-support-rider-2018-1/
I am using SQL Server LocalDB and no tool appears in Tools menu. If I using standard SQL Server with EF, the menu appears.

*Using migrate.exe.
I tried this approach - https://msdn.microsoft.com/en-us/library/jj618307(v=vs.113).aspx ,
I can execute migrate.exe, but there is no any command like add-migration.
UPDATED:
1) I use up menu trying to get access to EF Tools, see screenshot.
2) EntityFramework 6.2.0
3) My web.config file is this
<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyProg.mdf;Initial Catalog=MyProg;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <globalization culture="ru-RU" uiCulture="ru" />
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <anonymousIdentification enabled="true" />
    <sessionState mode="InProc" timeout="30" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <contexts>
      <context type="MyProg.ApplicationDbContext, MyProg">
        <databaseInitializer type="MyProg.DBDropCreateInitializer, MyProg" />
      </context>
    </contexts>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.6.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.6.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>

4) I use Rider 2018.1.3
And EF Tools menu has strange behavior, some times I saw this menu with all items disabled, but I can't reproduce it, I did not find any logic in when it appears. Most other times no menu at all.


text:
Q: document.createElement('a').click() not working in firefox I have a function that retrieves arraybuffer data from my API, creates a temporary anchor on the page and then clicks it in order to download the file.
The function works as expected in Chrome.
@action
  async loadVoucher(id, fiscalId) {
    const pdf = await this.httpClient.get(...);

    console.log("load Voucher: ", pdf);

    const blob = new Blob([pdf.data], { type: "application/pdf" });
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "Dossier_" + new Date() + ".pdf";

    console.log("before link click");

    link.click();
    link.remove();
  }

The @action decorator comes from mobx. In firefox the second console.log - before click link gets logged to the browser console (the first log also logs my data correctly), but the download does not start.
What am I doing wrong?

A: In Firefox, you need to add the created element to the DOM and it will work:

Create File

    $('body').on('click', '#test', function(event) {
        var link = document.createElement('a');
        // Add the element to the DOM
        document.body.appendChild(link);
        link.setAttribute("type", "hidden"); // make it hidden if needed
        link.download = 'test.xls';
        link.href = 'data:application/vnd.ms-excel;utf-8,test';
        link.click();
    });

codepen - http://jsfiddle.net/b40af6rm/


text:
Q: Re-axis the Matplotlib plot interval with np.arange does not work I have a plot (left hand one) which y axis has 10 values. I try to re-axis from the default which is 0-9, interval = 2 to be 1-10, interval = 1. Normally, I use np.arange which works well except this one.
(default)

I ran
plt.yticks(np.arange(0, 9, 2), np.arange(1, 10, 1))

and
plt.yticks(np.arange(0, 10, 2), np.arange(1, 11, 1))

and many another number, they did not work. Both of the above .ytick show

Why the interval does not change to 1? How to fix this?

A: You need to set the ticks as [0,1,2,...,9] and the ticklabels to your liking, e.g. [1,2,3,..,10].
plt.yticks(np.arange(0, 10), np.arange(1, 11))


text:
Q: Filter different data frame and merge the results I have different DataFrames, they have a common column (id), as the data is huge, I want to filter all DataFrames on a list of values defined in (lis) and then merge all the newly built DataFrames on a common column.
I implemented it, as follows, it is slow and have many duplicate.I am not sure if my answer is correct, can someone help me to optimize the code?
My Merge result is so bigger than dataframes size, I dont know how to find a correct merge for my data.
from functools import reduce
import functools as ft

df_list = [df1,df2,df3,df4,df5,df6]
lis = ["PT08"]
dfs = []

for df in df_list:
    dfs.append(df[df['id'].isin(lis)])

df = df_list[0]
for df_ in dfs[1:]:
    dfall= df.merge(df_, on='id')

dfall

A: just you can use from multi processing in python. after filtering
Parallel process for below merges
df1 df2 - df3 df4 - df5 df6
(Select the order based on you dataframes, hard merging must place this part)
then merge 3 datafrme
It can a little improve your speed


text:
Q: Translation in .yml with optional parameter I want to make a translation my_translation with an optional parameter. For example:
> I18n.t('my_translation')
=> "This is my translation"
> I18n.t('my_translation', parameter: 1)
=> "This is my translation with an optional parameter which value is 1"

Is this possible?

A: Yes, definitely. You just write the translations like this:
my_translation: This is my translation with an optional parameter which value is %{parameter}

Is the parameter really optional? In above translation, you have to provide all parameters.
UPDATE: Sorry, I answered too soon. I don't think it's easy to do. Maybe the easiest way is like this:
> I18n.t('my_translation1')
=> "This is my translation"
> I18n.t('my_translation2', parameter: 1)
=> "This is my translation with an optional parameter which value is 1"

A: This is the way i did it!

*

*First set my translation
I18n.t('my_translation', parameter: optional_parameter)

*Check if value is nil
optional_parameter = value.nil? "" : "with an optional parameter which value is #{value}"
I18n.t('my_translation', parameter: optional_parameter)

*

*if value is nil   =>"This is my translation"

*if value is 1 => "This is my translation with an optional parameter which value is 1"

A: I would say it is possible, though not recommended.  You have two completely separate strings, based on your comments in @Yanhao's answer, and I would say they should be two separate entries in your yaml file:
report_name: My report
report_name_with_date: My report on %{date}

Since the existence of the date determines which string to display, you could perhaps test for its existence in in the params hash in a controller method, assign the title to a variable, and then use it in a view.  Perhaps something like:
report_date = params[:report_date]
if report_date && report_date.is_a?(Date)
  @report_name = I18n.t('report_name_with_date', date: report_date.to_s)
else
  @report_name = I18n.t('report_name')
end

If you want behaviour exactly as you have described, you'd need two yaml entries anyway, and you'd have extra convolution, and you'd be doing a I18n no-no by creating a string by concatenating two strings together, which assumes a fixed grammatical sentence structure (not to mention this drives translators up the wall):
report_name_with_date: My report%{on_date}
on_date: on %{date}

with code something like this:
report_date = params[:report_date]
if report_date && report_date.is_a?(Date)
  on_date = I18n.t('on_date', date: report_date.to_s)
  @report_name = I18n.t('report_name_with_date', on_date: " #{on_date}")
else
  @report_name = I18n.t('report_name_with_date', on_date: nil)
end

So, in summary, I'd say go with two separate whole strings, like in the first example.

A: If you're using a number as an optional argument, Rails provides a better way to handle it.
e.g.
  invoice:
    zero: "Great! You have no pending invoices."
    one: "You have only 1 pending invoice."
    other: "You have %{count} pending invoices."

  >> t("invoice", count: 0)
  => Great! You have no pending invoices.

  >> t("invoice", count: 1)
  => You have only 1 pending invoice.

  >> t("invoice", count: 5)
  => You have 5 pending invoices.


text:
Q: How to write file with data is Uint8Array? I have some problems write file ( image ) to folder.
my script I get Uint8Array() from image
var arrayBuffer = event.target.result
var byteArray = new Uint8Array(arrayBuffer);

Then, I used "json.dumps", objData['imagedata'] is "var byteArray "
print(objData['imagedata'])
print("=========================================================================")
user_encode_data = json.dumps(objData['imagedata']).encode('utf-8')
print(user_encode_data)

Example image is print(user_encode_data) then I saved it in mysql with data type as longblob.
read_blob(1,"./MainArchives/images/data.png")

def read_blob(author_id, filename):
   query = *my syntax query*
   ...
   photo = cursor.fetchone()[0] // "photo" is "user_encode_data" when I get back from mysql => as mentioned above *
   write_file(photo, filename)

And Finally is function "write_file"
def write_file(data, filename):
   with open(filename, 'wb') as f:
       f.write(data)

And i get error as: ==>
TypeError: a bytes-like object is required, not 'str'

A: You opened the file in wb mode which means write binary data to the file whereas ur data is in str format. Try changing your data to binary format or if you dont want that you can simply do it by
def write_file(data, filename):
   with open(filename, 'w') as f:
       f.write(data)


text:
Q: Strange error with template literal adding *{} to string I am facing a weird error where copying svelte code into a template literal is adding *{} to the string. I tried replicating this in a REPL to share, but the error didn't occur there. Does anyone know what might be causing this?
Example:
+page.svelte
  let svelteCode = `

These styles...

<Nested/>

In the last line *{} was added for some reason and I can't figure out where it's coming from, since I'm just printing the string without making any adjustments to it.
When I remove the  block the *{} disappears or when I just remove style from the <> tags, but I can't figure out why this happens. I'm a bit lost. Any ideas on what is causing this?
I expect the string output to be the same as the defined string.
Screenshot:

A: The parser has issues with tags in code. I cannot tell why it specifically generates *{} but I would recommend doing something like </${''}style> or <\/style> to work around the problem.


text:
Q: how to insert wait between block of codes I want to implement something like this : I am creating snapshots of volume ( using amazon ec2 tools ) and I am storing the details of latest snapshots in a file.
#Create snapshots of all attached volumes

echo "Create snapshots of all attached volumes"
read -rsp $'Press enter to continue...\n'
awk '{print $2, $3}' "$EC2_HOME/ActiveVolumes_$today_date" | while read vol_id inst_id; do
    awk '{print $3, $5}' "$EC2_HOME/Instances_$today_date" | while read inst_id2 name; do
        if test "$inst_id" = "$inst_id2"; then
            echo ec2-create-snapshot "$vol_id" -d "$today_date: Daily Backup for $inst_id (VolID:$vol_id InstID:$inst_id)"
             ec2-create-snapshot "$vol_id" -d "$today_date: Daily Backup for $inst_id (VolID:$vol_id InstID:$inst_id)"
        fi
    done
done

#Create a file with all latest snapshots

echo "Create a file with all latest snapshots"
read -rsp $'Press enter to continue...\n'
latestdate=$(ec2-describe-snapshots | grep ^SNAPSHOT | sort -rk 5 | awk '{print substr($5, 1, 10); exit}')
ec2-describe-snapshots | grep "^SNAPSHOT.*$latestdate" > "$EC2_HOME/SnapshotsLatest_$today_date"

i want to do one thing. I want to put a wait between two block of codes based on one condition. I want to put a wait after the first block of code is executed. i Want to check if status of is completed then execute next block of code.
SNAPSHOT    snap-7749   vol-86d0    pending 2013-12-11T04:17:57+0000    100%    109030037527    35  EBS_Automated_Snapshot_12-10-2013-20:20:13
SNAPSHOT    snap-e2f3dc vol-80  completed   2013-12-11T04:16:49+0000    100%    109030037527    35  EBS_Automated_Snapshot_12-10-2013-20:19:05

A:
To check if status of is completed then execute next block of code.

You can also use one of "; && ||" The ; just separates one command from another. The && says only run the following command if the previous was successful" || - if it was not successful. Examples
If it is not enough there is sleep and wait command:

*

*Wait: wait, waitpid, waitid - wait for process to change state

*Sleep: delay for a specified amount of time

To put a wait after the first block of code is executed. Just use sleep num.

echo "hello"
# wait 5 seconds
sleep 5
echo  "Bye"

More info: man sleep.


text:
Q: spring boot reactive mongo health check doe not show up (reactive mongo) I am using spring boot 2.0.2 with the reactive mongo driver
As per Auto-configured HealthIndicators the mongo health indicator must be autoconfigured. I see rabbit health indicator got autoconfigured
However when I invoke my health actuator the mongo details do not show up.
Here is a snippet of my application.yml
management:
    context-path: /acaf/v1
    security:
        enabled: false
    endpoint:
      health:
        show-details: always
    health:
      defaults:
        enabled: true
      mongo:
        enabled: true

Here is the output from my actuator:
{
    "status": "UP",
    "details": {
        "rabbit": {
            "status": "UP",
            "details": {
                "version": "3.7.5"
            }
        },
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 250685575168,
                "free": 192069795840,
                "threshold": 10485760
            }
        }
    }
}

A: Apparently the MongoReactiveHealthIndicator was added only in Spring Boot 2.0.4 release, hence my options were:

*

*Upgrade to 2.0.4 or

*Write my own health indicator (I chose this which was just a copy paste of 2.0.4 code)


text:
Q: Shop Category Pages missing s My website is using Future Life theme and Woo Commerce. On the shop product category pages, it doesn't display the category name and there are no <h1>'s ../nothing to make a <h1>.
Does anyone know how I can get the product category to show on the each product category page and make it each shop pages <h1>?
Any help would be great. Cheers, Guy.


text:
Q: A generic error has occurred in GDI+ I know this has been asked a million times but I think I need to make it a million and one.
I am getting "A generic error has occurred in GDI+" when trying to save a new bitmap.
I have completely stripped down to the most basic lines of code and I still get the error with the following method:
public class HomeController : Controller
{
  public ActionResult Index()
  {
    return this.View();
  }

  public void CreatePicture()
  {
    try
    {
      // THIS WORKS
      System.IO.File.Copy("C:\\copyTest.bmp", "C:\\test folder\\copyTest2.bmp");

      // THIS WORKS
      System.IO.File.Delete("C:\\test folder\\deleteTest.bmp");

      using (Bitmap newBitmap = new Bitmap(120, 120))
      {
        // THIS FAILS
        newBitmap.Save("C:\\test folder\\test.bmp", ImageFormat.Bmp);
      }
    }
    catch (Exception ex)
    {
      throw ex;
    }
  }
}

The code is called from an html link on a blank page within an MVC 3.0 website using anonymous login.
View:
@Html.ActionLink("Create Picture", "CreatePicture", "Home", new { })

I have checked the folder permissions of "test folder" and have given full access to the following:

*

*ASPNET

*NETWORK SERVICE

*IUSR

I still get the error...  what have I missed / done wrong ?

A: It may be caused by another reason but in this case it seems you haven't specified image type.
So try : newBitmap.Save("C:\\test folder\\test.bmp",System.Drawing.Imaging.ImageFormat.Bmp );

A: I've finally solved the problem after over 4 hours.
My computer started grinding itself to a halt so I decided to restart it.
After reboot (no updates installed by the way) magically everything is now working!!!


text:
Q: Electron window not showing up after successfull build This week I got into electron and I have built my own simple project. I want to build it into an executable file. I have followed this video with building an electron project. The build goes as it should.
    loaded configuration  file=package.json ("build" field)
    description is missed in the package.json  appPackageFile=C:\Users\evalo\Desktop\Desktop\electron\02-nekton\package.json
    writing effective config  file=dist\builder-effective-config.yaml
    packaging       platform=win32 arch=x64 electron=16.0.5 appOutDir=dist\win-unpacked
    building        target=nsis file=dist\nekton Setup 1.0.1.exe archs=x64 oneClick=false perMachine=false
    building block map  blockMapFile=dist\nekton Setup 1.0.1.exe.blockmap

After that, I ran the installer and installed the app without any problem and launched the shortcut, which had been generated on the desktop. The main window didn't show up but in Task Manager I could see that the application is running (3 times actually after one launch, don't know why)

Content of my package.json file, if it helps:
{
  "name": "nekton",
  "produktName": "nekton",
  "version": "1.0.1",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "electron .",
    "build": "electron-builder"
  },
  "build": {
    "asar": true,
    "appId": "nekton",
    "win": {
      "target": [
        "nsis"
      ],
      "icon": "nekton.ico"
    },
    "nsis": {
      "oneClick": false,
      "installerIcon": "nekton.ico",
      "uninstallerIcon": "nekton.ico",
      "uninstallDisplayName": "Nekton-uninstaller",
      "license": "license.md",
      "allowToChangeInstallationDirectory": true
    }
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "electron-store": "^8.0.1",
    "wallpaper": "^6.0.0"
  },
  "devDependencies": {
    "electron": "^16.0.5",
    "electron-builder": "^22.14.5"
  }
}

One thing, which might affect this behaviour is that I hadn't saved electron as dev dependency before I started working on the app. I just installed it: npm i electron. When I tried to build it gave my error with a hint to move electron into dev dependencies. So I ran:
npm uninstall electron
npm i --save-dev electron

Tried to launch the app with: npm start and all worked flawlessly. So I assumed that this didn't affect the project.
**Edit:**
-----------------
I made and build an app to show static HTML files in the main window with the same build configuration. All worked flawlessly. The app launched and behaved as expected. So I have manually created a new project and copied the content of each file to the project which has been built before without error. I have encountered the same problem. The app works fine with npm start, builds, installs. After installation is complete the app 'runs' but without a window. I think there might be a run error, which would be logged into the terminal in vscode at the start and the application is halted. Is there a way I can see the terminal for my app after it has been installed?


text:
Q: What's the best way of excluding specific @Bean from @WebMvcTest What's the best way of excluding javax.servlet.Filters from specific @WebMvcTests in a granular way when they're defined via @Bean instead of @Component?
More information:
@WebMvcTest excludeFilters works fine for excluding beans defined via component scanning (i.e. @Component). However, excluding beans defined via @Bean from specific @WebMvcTests is not as easy. Instead of excluding those beans on my test classes I have to make sure that they're not picked up by the slicing and then include them manually. One way of doing this is to group beans into different @Configuration classes based on how I will need to include or exclude them in the tests. However, I'm starting to compromise project structure, by creating unneeded @Configuration classes that maybe don't make a lot of sense, due to testing framework limitations.
What about mocking?
In some situations, like the one described in the top of this question, mocking is not appropriate. Mocking a javax.servlet.Filter doesn't make a lot of sense since you need to call the rest of the chain filter.

A: You need to manage your dependency injection well. All dependencies for a Component or a Bean should be injected via Constructor object. By doing this, in your test cases when you create an object of the testing class, it will expect you to pass all beans that is needed for that class. You can then pass in a mocked class or a null value based on your logic.