text:
Q: Python return statement Includes brackets I have just started coding and have cleared most of my basics but I still have a problem understanding 'return' statements and None type variables in python.
def celtofar(x):
    far= (x*9/5) + 32
    if x<-273.15:
        return("The Value Of Celsius Entered is too low ")
    else:
        return ("Temperature in Fahrenheit Shall Be: ", far)
try :
    cel=int(input("Enter Temperature in celsius: "))
    print(celtofar(cel))
except ValueError :
    print("Please Enter an Integral Value")

I want the output without brackets and quotes but the terminal is giving me the following result:
PS C:\Users\welcome\Desktop\Work> python .\program1.py

Enter Temperature in celsius: 30
('Temperature in Fahrenheit Shall Be: ', 86.0)

I don't want the brackets and the quotes to be included.

A: Convert the far to a str and concatenate it with the result:
def celtofar(x):
   far = (x * 9 / 5) + 32
   if x < -273.15:
      return "The Value Of Celsius Entered is too low"
   else:
      return "Temperature in Fahrenheit Shall Be: " + str(far)

try:
    cel = int(input("Enter Temperature in celsius: "))
    print(celtofar(cel))
except ValueError:
    print("Please Enter an Integral Value")

OUTPUT:
Enter Temperature in celsius: 30
Temperature in Fahrenheit Shall Be: 86.0

Process finished with exit code 0

EDIT:
However, I'd recommend using str.format():
def celtofar(x):
    far = (x * 9 / 5) + 32
    if x < -273.15:
        return "The Value Of Celsius Entered is too low"
    else:
        return "Temperature in Fahrenheit Shall Be: {}".format(far)

def main():
    try:
         cel = int(input("Enter Temperature in celsius: "))
         print(celtofar(cel))
    except ValueError:
         print("Please Enter an Integral Value")

if __name__ == "__main__":
     main()

A: This is cause your print is a tuple. Use this example to format the string in your print
    return ("Temperature in Fahrenheit Shall Be: %s" %far)


text:
Q: Get last entry in database I'm new to Android and am trying to make an app that allows me to insert text and save it.
Once it is saved to the database, when I click the button "Display" it will display that text I entered.
My problem is I don't know how to get the last entry in database.
Here is where I query the database:
public String getIDNotifPM() {
    // TODO Auto-generated method stub
    String[] columns = new String[]{KEY_ROWIDPM, NOTIFPM};
    Cursor c = ourDatabase.query(TABLE_NOTIFPM, columns, null, null, null, null, null);

    c.moveToFirst();
    String notifIDPM = c.getString(0);
    return notifIDPM;
}

Here is my OnClickListener:
bViewNotifPM = (Button) findViewById(R.id.bViewNotifPM);
bViewNotifPM.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        try {
            DatabasePM w = new DatabasePM(this);
            w.open();
            String s = w.getIDNotifPM();
            w.close();
            long l = Long.parseLong(s);
            DatabasePM amem = new DatabasePM(this);
            amem.open();
            String returnedName = amem.getNotif(l);
            amem.close();

            Dialog d = new Dialog(this);
            d.setTitle("Notification!");
            TextView tv = new TextView(this);
            tv.setText("" + returnedName);
            d.setContentView(tv);
            d.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A: Try this one
cursor.moveToLast();
String notifIDPM = cursor.getString(0);

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF combo box, adding an all options item, when binding to an Observable Collection So I've got an object that has an observable collection. Most places I bind to this collection I only want the user to select a single item. But in one place I want the combobox to include an all items option.
Is the way to do this simply with xaml converter?
It seems like doing it in the view model would be a good idea, but it's really a lot dependency object goop to basically wire up an collection that is two objects deep for an on change event, where as the xaml converter just works.
But I always feel like xaml converters should be generic and reusable, where in this instance, the xaml converter would be more of a one off.
Of course the third option would be to create one off list for UI in the object that contains the standard observable collection.  But this seems to be mixing the logic and presentation in a way that makes me uncomfortable.

A: Take a look at CompositeCollection. It lets you concatenate multiple collections into a single collection -- sort of the XAML equivalent of the LINQ Concat. It implements INotifyCollectionChanged, so it should be able to react to changes if some of its inner collections are ObservableCollections.
CompositeCollection also lets you add individual elements, so you wouldn't even need to wrap your "All Items" in a collection of its own. (Instead, you have to wrap collections in a CollectionContainer. See the examples on the CompositeCollection doc page.)

A: I had a similar need, and ended up using the solution discussed in this article: How To Select Null/None in a ComboBox/ListBox/ListView.
You can replace the "(None)" string on line 98 with "All" or something similar. Then just add logic in your ViewModel to treat a null value as "All" in whatever manner is appropriate. It's a little annoying to have an extra class lying around but it makes the code a lot cleaner if you do need this in several places.


text:
Q: What is the maximum size in MB of a batch write to Firestore I am interested to know if the maximum size for a Firestore batch write is 10MB which is the Maximum API request size, or it's per Document eg 1MB leading up to 500MB. Or does this not matter?

A: As far as I can tell (using the nodejs SDK), a call to commit a batch will result in a single call to a CommitRequest API call, passing all documents in that call.  If that's the case, then I imagine the 10MB limit for the entire API call will apply.


text:
Q: Can we configure simple-xml to let it ignore unknown nodes When using simple-xml, is there a way to let it ignore the nodes it does not recognize?

A: Yes. If you annotate your class with @Root(strict=false) it will ignore any elements that are not mapped. See the documentation for additional details:
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#loosemap
On a related note, you can also handle optional elements using @Element(required=false).
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#optional

A: Discliamer: If simple-xml means anything but a simple XML then the following answer is irrelevant
First, look at: http://www.w3.org/TR/xmlschema-1/#element-any
An example schema allowing such any elements is:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="Root">
        <xs:complexType>
            <xs:all>
                <xs:element name="Element">
                <xs:complexType>
                    <xs:sequence minOccurs="0">
                        <xs:any processContents="lax" maxOccurs="unbounded"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
            </xs:all>
        </xs:complexType>
    </xs:element>
</xs:schema>

And an example xml validating to the above is:
<?xml version="1.0" encoding="UTF-8"?>
<Root xsi:noNamespaceSchemaLocation="Any.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Element>
    <Root>
        <Element><Node1><SubElement/></Node1><Node2/></Element>
    </Root>
    </Element>
</Root>


text:
Q: Scala Currying Function I have two methods,  nTimes and nTimesBetter. Both functions perform an operation on a function passed as a parameter n times.
The method nTimes takes a function f, the number of times it has to be called n and the initial value for the function to work on x
def nTimes(f:Int=>Int,n:Int,x:Int):Int =
  if (n <= 0) x
  else
    nTimes(f, n-1, f(x))

The following is what happens when the method is called with some function f, n = 3 and x = 1:
// nTimes(f,3,1)
// nTimes(f,2,f(1))
// nTimes(f,1,f(f(1)))
// nTimes(f,0,f(f(f(1))))

The method nTimesBetter method does not take initial value, but only a function f and the number of times n the function should be called
def nTimesBetter(f:Int=>Int,n:Int):(Int=>Int)=
  if (n <= 0) x => x
  else
   x => nTimesBetter(f, n-1)(f(x))

nTimesBetter returns a function that can be applied to an initial value
println(nTimes((x:Int)=>x+1,10,1))

val plus10 = nTimesBetter((x:Int)=>x+1,10)
println(plus10(1))

Can someone explain nTimesBetter with a stack of execution and use of (x:Int) => nTimesBetter(f,n-1)(f(x))? Why (f(x)) is called like this.

A: The main difference between these two is that the former returns a value and the latter returns a function Int => Int. The stack is far less readable than the one from nTimes but here it is:
  // nTimesBetter(f, 3)
  // x => nTimesBetter(f, 2)(f(x))
  // x => (x => nTimesBetter(f, 1)(f(x)))(f(x))
  // x => (x => (x => (x => x)(f(x)))(f(x)))(f(x))

Why (f(x)) is called like this?

Because nTimesBetter returns a function that needs an argument. You can rewrite nTimesBetter as:
def nTimesBetter(f: Int => Int, n: Int): Int => Int =
  if (n <= 0) x => x
  else {
    val function: Int => Int = nTimesBetter(f, n - 1) // Creates a function
    x => function(f(x))                               // Uses f(x) as an argument
  }

PS. nTimesBetter is not that better because nTimes is tail recursive.


text:
Q: how to show forum page as default home page in moodle 2.8 i am working on moodle 2.8 and essential theme now i want to set my home page to show the forum topics . from frontpage.php in render folder i can see that they used get_setting funtion to render items but i cant find where and how to use this function to show the forum page in home page by the way i duplicated the code which renders the home page but i guess that my argomans are not true so this get setting is not working and now showing any thing
ty in advance
`
if ($showfrontcontent) { ?>

                <?php
                echo $OUTPUT->get_setting('frontcontentarea', 'format_html');
                echo $OUTPUT->get_setting('mod_forum', 'format_html');
                echo $OUTPUT->essential_edit_button('theme_essential_frontpage');
                ?>

`

A: An easy way to do this, and should be created as a default in Moodle in my humble opinion, is to create a centre region in the frontpage layout.
Then when you add a block (with your forum topics code) to the front page, just move it to the centre region.
Here is how to create the region :
in /theme/themename/config.php add 'center-post' to regions for the frontpage.
 'frontpage' => array(
     'file' => 'default.php',
     'regions' => array('side-pre', 'side-post', 'center-post'),
     'defaultregion' => 'side-pre',
     'options' => array('langmenu'=>true),
 ),

in /theme/themename/lang/en/theme_themename.php add a string for the region name
$string['region-center-post'] = 'Center Bottom';

in /theme/themename/layout/default.php add the $hasscenterpost line:
$hassidepost = (empty($PAGE->layout_options['noblocks']) && $PAGE->blocks->region_has_content('side-post', $OUTPUT));
// Add this line.
$hascenterpost = (empty($PAGE->layout_options['noblocks']) && $PAGE->blocks->region_has_content('center-post', $OUTPUT));
$haslogininfo = (empty($PAGE->layout_options['nologininfo']));

Then after the region-content div, add the if ($hascenterpost) code:

        <?php echo $coursecontentheader; ?>
        <?php echo $OUTPUT->main_content() ?>
        <?php echo $coursecontentfooter; ?>

    <?php if ($hascenterpost) { ?>

                <?php echo $OUTPUT->blocks_for_region('center-post'); ?>

    <?php } ?>

You will probably need to increment the version number in /theme/themename/version.php too.


text:
Q: Find GPS accuracy of track using gpx data I have a bunch of gpx files, where tracks of around 500 (+/- 50) meters were saved. I compared the tracks to the measuring wheel distance and have calculated the relative error through them.
Now, out of 50 tracks, around 10 have a distance error (sum of Vincenty distance between each (lon,lat) recorded) > 5% (up to 16%) and i want to find possible causes for the error using only the gpx data.
My goal is to see, if it is possible to determine gps distance accuracy through the gpx data i have, without comparing to the measuring wheel.
I have heard of Dilution of Precision etc. but i don't know how many satellites are being used each time or the distance to the location etc.
Any possibilities? I can't find similarities in these track, that lower error tracks don't also have.
I'm also using python.
Approaches: check elevation inaccuracy compared to kalman filtered elevation, smooth track using moving average and compare to kalman filtered track (makes a difference, but the curvier the track, the worse it performs), find correlations between filtered and raw data... doesn't show much of a difference to 1% error tracks. I have also used speed recordings of each point to use distance = speed*time but the distance was overestimated by more than a 100 m.


text:
Q: A coin is flipped six times. In how many possible outcomes are the number of heads and tails not equal? This is an example question from my Discrete Mathematics course textbook. I'd like help on whether I'm approaching it correctly and how to continue from where I am, that is if I'm right so far.
A coin is flipped six times where each flip comes up either heads or tails. In how many possible outcomes are the number of heads and tails not equal?
I've figured out that order doesn't matter, indicating I'll use combination and that there are 64 possible outcomes (26=64) and that for the number of heads and tails not to be equal any outcome is possible apart from 3 heads and 3 tails.
I'm fairly new to this so I'm not sure how to proceed from here.
Thanks!

A: The order of the flips does matter, for the reason that N.F.Taussig has mentioned in the comments: the sequence $\mathrm{HHHHTT}$ is a different outcome to $\mathrm{HTHTHH}$. Moreover, if you neglect the order, then there are not $64$ possible outcomes, but rather $7$. Can you see why?
The simplest way to solve this problem is as follows: let $p$ equal the number of ways of getting the same number of heads as tails (where the order is taken into account); and let $p'$ equal the number of ways of not getting the same number of heads as tails. Clearly, $p+p'=2^6=64$, meaning that $p'=64-p$. There are $\binom{6}{3}$ ways of getting exactly $3$ heads and $3$ tails, and
$$
\binom{6}{3}=\frac{6\cdot5\cdot 4}{3\cdot 2\cdot 1}=20 \, .
$$
Therefore, $p'=44$.


text:
Q: Genetic algorithm based feature selection in R I am attempting to write a Genetic Algorithm for feature selection problem using the Caret package of R.
I tested the code below (using Random forest as a fitness fucntion). It works.
What can i change to make it work with other models (SVM or LDA) ?
library(dplyr)
library(doParallel)
library(randomForest)

ga_ctrl <- gafsControl(functions = rfGA, # Assess fitness with RF
                       method = "cv",   # 10 fold cross validation
                       genParallel=TRUE, # Use parallel programming
                       allowParallel = TRUE
)

lev <- c("0", "1")     # Set the levels

set.seed(27)
system.time( model_1 <- gafs(x = hill_train, y = hill_train$class,
                             iters = 100, # generations of algorithm
                             popSize = 50, # population size for each generation
                             pcrossover = 0.8,
                             pmutation = 0.001,
                             levels = lev,
                             gafsControl = ga_ctrl))
plot(model_1) # Plot mean fitness (AUC) by generation

mm_hill <- model_1$ga$final


text: Q: Custom CSS in SharePoint Modern site I have created a SPFx app customizer to hide the AppBar and SuiteNav. Basically, it injects CSS to the 'head' element. It works fine, but when I first load the page, for a second it shows these two items and then hides it. Is there any way to achieve this more efficiently without seeing the jump?


text:
Q: How to use unauthorizedRedirect to redirect user of different role to their respective page? In my app I have a user with 3 different roles and each one with their own respective page that they can visit. I would like to redirect them to their own respective home page when they try to access any pages that they should not be viewing, but are unable to do so.
I found the below thread with a very similar problem, but after modifying and putting the code in AppController::beforefilter, I am unable to get the desired result.
How to redirect each type of user to a different page when access is denied?
Updated with code from the thread above:
public function beforeFilter(Event $event)
{
    $user_role = $this->Auth->user('role');

    if ($user_role == "admin")
    {
        $redirectController = 'Pages';
        $redirectMethod     = 'adminhome';
    }
    elseif ($user_role == "teacher")
    {
        $redirectController = 'Pages';
        $redirectMethod     = 'teacherhome';
    }
    elseif ($user_role == "studentparent")
    {
        $redirectController = 'Pages';
        $redirectMethod     = 'parenthome';
    }

    $this->Auth->unauthorizedRedirect = array(
        'controller' => $redirectController,
        'action'     => $redirectMethod,
        'prefix'     => false
    );

}


text:
Q: Regex: Exclude replacing matches based on prefixes Note: I'm using JavaScript in the case that changes the proposed solutions.
When looking through multiple files and changing a property/parameter like the word "count" (e.g. count, register.count, function(count), getCount, incrementCount) I run into a issue of changing a word like "discount", "recount", or "encounter".
I realize that for my small use case* this error can be avoided by using simple heuristic - looking for known character groupings that prefix "count" and excluding them from replacement.
Question
Is there any way to use a regular expression to look for all instances
of "count" but ignore replacing if known prefix grouping of characters are found?
Just to clarify*
I know my "prefix heuristic" breaks down if you tried to generalize for other words besides "count" in a large unknown search space but it'll suffice for now.

A: You can handle the regex this way:
\b(get)?(count|Count)\b

You should apply the case insensitive switch.
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
1st Capturing group (get)?
    Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
    Note: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data
    get matches the characters get literally (case sensitive)
2nd Capturing group (count|Count)
    1st Alternative: count
        count matches the characters count literally (case sensitive)
    2nd Alternative: Count
        Count matches the characters Count literally (case sensitive)
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

A: I don't think that it's possible to go the exclusion route, given the lack of lookbehinds in javascript.
Wouldn't it be easier anyway for your "known" prefixes be the ones that are allowed? You cannot, after all, list every single regular word that has "count" somewhere in it. Allow for your known legal prefixes, and let \b take care of the rest:

*

*pattern: (get|increment)count|\bcount\b //case insensitive

*replace: $1FOO
demo


text:
Q: @keyframe animation issue in css I tried an animation in CSS but got an issue that its not working.
Here is my fiddle
ul {
    display: block;
}
ul>li {
    list-style-type: none;
    transition: all 0.5s ease-out;
}
ul>li:nth-child(1) {
    height:100px;
    width: 100px;
    background: transparent;
    border-radius: 100%;
    border:solid 5px #00f;
    border-right: transparent;
    border-left: transparent;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left:0;
    margin: auto;
    animation: spin 1s infinite ease-out;
}
ul>li:nth-child(2) {
    height:75px;
    width: 75px;
    background: transparent;
    border-radius: 100%;
    border:solid 5px #0f0;
    border-top: transparent;
    border-bottom: transparent;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left:0;
    margin: auto;
    animation: spin2 1s infinite ease-out;
}
ul>li:nth-child(3) {
    height:50px;
    width: 50px;
    background: transparent;
    border-radius: 100%;
    border:solid 5px #f00;
    border-left: transparent;
    border-right: transparent;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left:0;
    margin: auto;
    animation: spin3 1s infinite ease-out;
}
@keyframes spin1 {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
@keyframes spin2 {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
@keyframes spin3 {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

A: Add the browser prefixes and also you are using animation name spin for the first li which doesn't exist.

    ul {
        display: block;
        width: 200px;
        height: 200px;
        margin: 0 auto;
    }
    ul>li {
        list-style-type: none;
    }
    ul>li:nth-child(1) {
        height:100px;
        width: 100px;
        background: transparent;
        border-radius: 100%;
        border:solid 5px #00f;
        border-right: transparent;
        border-left: transparent;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left:0;
        margin: auto;
        -webkit-animation: spin1 5s infinite ease-out;
        animation: spin1 5s infinite ease-out;
    }
    ul>li:nth-child(2) {
        height:75px;
        width: 75px;
        background: transparent;
        border-radius: 100%;
        border:solid 5px #0f0;
        border-top: transparent;
        border-bottom: transparent;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left:0;
        margin: auto;
        -webkit-animation: spin2 5s infinite ease-out;
        animation: spin2 5s infinite ease-out;
    }
    ul>li:nth-child(3) {
        height:50px;
        width: 50px;
        background: transparent;
        border-radius: 100%;
        border:solid 5px #f00;
        border-left: transparent;
        border-right: transparent;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left:0;
        margin: auto;
        -webkit-animation: spin3 5s infinite ease-out;
        animation: spin3 5s infinite ease-out;
    }
    @-webkit-keyframes spin1 {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
    @-webkit-keyframes spin2 {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
    @-webkit-keyframes spin3 {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
    @keyframes spin1 {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
    @keyframes spin2 {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
    @keyframes spin3 {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }


text:
Q: Get selected radio button value in javascript I have dynamically created radio buttons and have assigned them ids. Now when i try,
function updateAO(id2) {
    var status = $('input[name=id2]:checked').val();
    alert(status);
}

It prints undefined. Can anyone please tell how to get this value.
Thanks in advance!!

A: You're not using your parameter correctly.
var status = $('input[name="' + id2 + '"]:checked').val();

A: The :checked selector will only select inputs currently checked, if the passed input isnt checked at the time, status will remain unset, try changing your JS to:
function updateAO(id2) {
    var status = $('input[name='+id2+']').val();
    alert(status);
}

A: To get the selected radio button value use
function updateAO(id2) {
    var status = $('input[name=id2]:checked').val();
    alert(status);
}

To select normal radio button use
function updateAO(id2) {
    var status = $('input[name=id2]').val();
    alert(status);
}


text:
Q: PHPMAiler DKIM signature working in command line (but not in browser) I have just installed PHPMailer 6.1 and managed to send a test e-mail through a simple php file using command line (php my_email_file.php). I was even able to sign it with DKIM so that Gmail flag it as signed by my domain.
However, when I run the very same file through the browser (www.mydomain.com/my_email_file.php), the e-mail is sent but the DKIM signature no longer works. Debug info does not contain any hints, it simply ignores de DKIM part.
I am assuming either php versions are different or there is any permissions issue. I could not validate any of the two hypotheses and could not find any similar questions here or elsewhere.
Any ideas?
Thank you very much in advance.
UPDATING with more details:
For reference, this is the code I am using both in CLI and web (php file located in /var/www/mywebsite/web):
<?php
/**
 * This example shows making an SMTP connection without using authentication.
 */

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

$direccion = "xxx@gmail.com";
$titulo = "DKIM Test";
$mensaje = "DKIM signed message";
$replyto = "info@mydomain.com";
$replytoname = "MyName";

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Europe/Madrid');

require 'new_mail/vendor/autoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// SMTP::DEBUG_OFF = off (for production use)
// SMTP::DEBUG_CLIENT = client messages
// SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
//Set the hostname of the mail server
$mail->Host = 'localhost';
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
$mail->SMTPAutoTLS = false;
$mail->CharSet = 'utf-8';
$mail->setLanguage('es', 'PHPMailer/language');
//We don't need to set this as it's the default value
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = 'info@mydomain.com';
//Password to use for SMTP authentication
$mail->Password = 'mypassword';
//Set who the message is to be sent from
$mail->setFrom('info@mydomain.com', 'MyName');
//Set an alternative reply-to address
$mail->AddReplyTo($replyto, $replytoname);
//Set who the message is to be sent to
$mail->addAddress($direccion);
//Set the subject line
$mail->Subject    = "=?UTF-8?B?".base64_encode($titulo)."?=";
//Replace the plain text body with one created manually
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';

//This should be the same as the domain of your From address
$mail->DKIM_domain = 'mydomain.com';
//See the DKIM_gen_keys.phps script for making a key pair -
//here we assume you've already done that.
//Path to your private key:
$mail->DKIM_private = '/var/lib/amavis/dkim/mydomain.com.private';
//Set this to your own selector
$mail->DKIM_selector = 'mail';
//Put your private key's passphrase in here if it has one
$mail->DKIM_passphrase = '';
//The identity you're signing as - usually your From address
$mail->DKIM_identity = $mail->From;
//Suppress listing signed header fields in signature, defaults to true for debugging purpose
$mail->DKIM_copyHeaderFields = false;

$privatekey = $mail->DKIM_private;
echo $privatekey;
if (file_exists($privatekey))
{
    echo "Has access";
}
else
{
    echo "No access";
}

//send the message, check for errors
if (!$mail->send()) {
    echo 'Mailer Error: '. $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}

This is what I get in CLI:
Has access
08:05:49       SERVER -> CLIENT: 220 myserver ESMTP
08:05:49     CLIENT -> SERVER: EHLO myserver
08:05:49     SERVER -> CLIENT: 250-myserver
                                          250-PIPELINING
                                          250-SIZE 20480000
                                          250-ETRN
                                          250-STARTTLS
                                          250-AUTH PLAIN LOGIN
                                          250-AUTH=PLAIN LOGIN
                                          250-ENHANCEDSTATUSCODES
                                          250-8BITMIME
                                          250 DSN
08:05:49     CLIENT -> SERVER: AUTH LOGIN
08:05:49     SERVER -> CLIENT: 334 VXNlcm5hbWU6
08:05:49     CLIENT -> SERVER: [credentials hidden]
08:05:49     SERVER -> CLIENT: 334 UGFzc3dvcmQ6
08:05:49     CLIENT -> SERVER: [credentials hidden]
08:05:49     SERVER -> CLIENT: 235 2.7.0 Authentication successful
08:05:49     CLIENT -> SERVER: MAIL FROM:<info@mydomain.com>
08:05:49     SERVER -> CLIENT: 250 2.1.0 Ok
08:05:49     CLIENT -> SERVER: RCPT TO:<xxx@gmail.com>
08:05:49     SERVER -> CLIENT: 250 2.1.5 Ok
08:05:49     CLIENT -> SERVER: DATA
08:05:49     SERVER -> CLIENT: 354 End data with <CR><LF>.<CR><LF>
08:05:49     CLIENT -> SERVER: Date: Sat, 25 Jul 2020 10:05:49 +0200
08:05:49     CLIENT -> SERVER: To: xxx@gmail.com
08:05:49     CLIENT -> SERVER: From: MyName <info@mydomain.com>
08:05:49     CLIENT -> SERVER: Reply-To: MyName <info@mydomain.com>
08:05:49     CLIENT -> SERVER: Subject: =?UTF-8?B?SG9sYSBES0lN?=
08:05:49     CLIENT -> SERVER: Message-ID: <FbCdgC7Q8GcnzAXbC81d7aR8dGYXMjaHTPcJufflp1Y@ns300543>
08:05:49     CLIENT -> SERVER: X-Mailer: PHPMailer 6.1.7 (https://github.com/PHPMailer/PHPMailer)
08:05:49     CLIENT -> SERVER: MIME-Version: 1.0
08:05:49     CLIENT -> SERVER: Content-Type: multipart/alternative;
08:05:49     CLIENT -> SERVER:  boundary="b1_FbCdgC7Q8GcnzAXbC81d7aR8dGYXMjaHTPcJufflp1Y"
08:05:49     CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
08:05:49     CLIENT -> SERVER: DKIM-Signature: v=1; d=mydomain.com; s=mail;
08:05:49     CLIENT -> SERVER:  a=rsa-sha256; q=dns/txt; t=1595664349; c=relaxed/simple;
08:05:49     CLIENT -> SERVER:  h=Date:To:From:Reply-To:Subject:Message-ID:X-Mailer:MIME-Version:Content-Type;
08:05:49     CLIENT -> SERVER:  i=info@mydomain.com;
08:05:49     CLIENT -> SERVER:  bh=quH/vtvt3pX5+MdRVXNLdXO5/96jjoTSgctYgk2xZJI=;
08:05:49     CLIENT -> SERVER:  b=KLNeiShgq2uE2FkMqDDNuNn4w0C0ZmD9hcuhNMzE07xenka3a+Ech4i7+9+SLnOXTv30H8tq5
08:05:49     CLIENT -> SERVER:  NiUjLCU4c6BsYZxfeD4MH/qKHAD02yzZHfECCj2C3T2HaQb+qbSrzkhAYfYnfRDxNhtPI34sE
08:05:49     CLIENT -> SERVER:  dNHXVb6fL9ptKvv9cIBj0xUEk=
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER: This is a multi-part message in MIME format.
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER: --b1_FbCdgC7Q8GcnzAXbC81d7aR8dGYXMjaHTPcJufflp1Y
08:05:49     CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER: To view the message, please use an HTML compatible email viewer!
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER: --b1_FbCdgC7Q8GcnzAXbC81d7aR8dGYXMjaHTPcJufflp1Y
08:05:49     CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER: DKIM test
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER: --b1_FbCdgC7Q8GcnzAXbC81d7aR8dGYXMjaHTPcJufflp1Y--
08:05:49     CLIENT -> SERVER:
08:05:49     CLIENT -> SERVER: .
08:05:49     SERVER -> CLIENT: 250 2.0.0 Ok: queued as 500561A80068
08:05:49     CLIENT -> SERVER: QUIT
08:05:49     SERVER -> CLIENT: 221 2.0.0 Bye

And this one, what I get after running the very same php file through browser
No access
08:06:29 SERVER -> CLIENT: 220 myserver ESMTP
08:06:29 CLIENT -> SERVER: EHLO mydomain.com
08:06:29 SERVER -> CLIENT: 250-ns300543.ip-91-121-64.eu250-PIPELINING250-SIZE 20480000250-ETRN250-STARTTLS250-AUTH PLAIN LOGIN250-AUTH=PLAIN LOGIN250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
08:06:29 CLIENT -> SERVER: AUTH LOGIN
08:06:29 SERVER -> CLIENT: 334 VXNlcm5hbWU6
08:06:29 CLIENT -> SERVER: [credentials hidden]
08:06:29 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
08:06:29 CLIENT -> SERVER: [credentials hidden]
08:06:29 SERVER -> CLIENT: 235 2.7.0 Authentication successful
08:06:29 CLIENT -> SERVER: MAIL FROM:<info@mydomain.com>
08:06:29 SERVER -> CLIENT: 250 2.1.0 Ok
08:06:29 CLIENT -> SERVER: RCPT TO:<xxx@gmail.com>
08:06:29 SERVER -> CLIENT: 250 2.1.5 Ok
08:06:29 CLIENT -> SERVER: DATA
08:06:29 SERVER -> CLIENT: 354 End data with <CR><LF>.<CR><LF>
08:06:29 CLIENT -> SERVER: Date: Sat, 25 Jul 2020 10:06:29 +0200
08:06:29 CLIENT -> SERVER: To: xxx@gmail.com
08:06:29 CLIENT -> SERVER: From: MyName <info@mydomain.com>
08:06:29 CLIENT -> SERVER: Reply-To: MyName <info@mydomain.com>
08:06:29 CLIENT -> SERVER: Subject: =?UTF-8?B?SG9sYSBES0lN?=
08:06:29 CLIENT -> SERVER: Message-ID: <4neYS87UPhdjVyQOEiztiLiXfL6Z0XZZgTPT0tr0@mydomain.com>
08:06:29 CLIENT -> SERVER: X-Mailer: PHPMailer 6.1.7 (https://github.com/PHPMailer/PHPMailer)
08:06:29 CLIENT -> SERVER: MIME-Version: 1.0
08:06:29 CLIENT -> SERVER: Content-Type: multipart/alternative;
08:06:29 CLIENT -> SERVER: boundary="b1_4neYS87UPhdjVyQOEiztiLiXfL6Z0XZZgTPT0tr0"
08:06:29 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER: This is a multi-part message in MIME format.
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER: --b1_4neYS87UPhdjVyQOEiztiLiXfL6Z0XZZgTPT0tr0
08:06:29 CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER: To view the message, please use an HTML compatible email viewer!
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER: --b1_4neYS87UPhdjVyQOEiztiLiXfL6Z0XZZgTPT0tr0
08:06:29 CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER: DKIM test
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER: --b1_4neYS87UPhdjVyQOEiztiLiXfL6Z0XZZgTPT0tr0--
08:06:29 CLIENT -> SERVER:
08:06:29 CLIENT -> SERVER: .
08:06:29 SERVER -> CLIENT: 250 2.0.0 Ok: queued as 725A21A80068
08:06:29 CLIENT -> SERVER: QUIT
08:06:29 SERVER -> CLIENT: 221 2.0.0 Bye
Message sent!

So, as you can see, the message is sent in both cases and authentication works as well. The key difference is that the instance run through browser does not get access to the private key file and, hence, cannot sign the message, while the CLI one can access and can sign.


text:
Q: VBA to edit excel column of data I have a requirement to edit a column of data where each cell has to be edited to remove all non-numeric characters.  The only data that I need are actual numbers and a decimal point if one was there originally.  I found a piece of code that removes everything with the exception of a "%" character.  If someone could look at the code below and let me know how to modify it I would be appreciative.  Examples of the type of data I am editing are as follows Complete cell contents enclosed in quotes). "3"  "2.5%"  "17 nks" "3.00 %" "4 VNS"
Here's the code I have used;
Sub RemoveAlphas()
'' Remove alpha characters from a string.
Dim intI As Integer
Dim rngR As Range, rngRR As Range
Dim strNotNum As String, strTemp As String

Set rngRR = Selection.SpecialCells(xlCellTypeConstants, _
xlTextValues)

For Each rngR In rngRR
    strTemp = ""
    For intI = 1 To Len(rngR.Value)
        If Mid(rngR.Value, intI, 1) Like "[0-9,.]" Then
            strNotNum = Mid(rngR.Value, intI, 1)
        Else: strNotNum = ""
        End If
        strTemp = strTemp & strNotNum
    Next intI
    rngR.Value = strTemp
Next rngR

End Sub

Thanks.

A: This can be done using Regex as shown below- Have tested with your exact sample data and works for me:
Sub RemoveAlphas()
'' Remove alpha characters from a string.
Dim intI As Integer
Dim rngR As Range, rngRR As Range
Dim strNotNum As String, strTemp As String
Dim RegEx As Object

   Set rngRR = Selection.SpecialCells(xlCellTypeConstants, _
   xlTextValues)
   Set RegEx = CreateObject("VBScript.RegExp")
   RegEx.Global = True
   RegEx.Pattern = "[^\d.]+"
   For Each rngR In rngRR
      rngR.Value = RegEx.Replace(rngR.Value, "")
   Next rngR
End Sub

A: If you are getting the results you need with the exception of a percent sign, you can insert into this part of your code a Replace function:
    Next intI
    strTemp = Replace(strTemp, "%", "")   'Remove the % sign and replace with nothing.
    rngR.Value = strTemp
Next rngR

A: Try the RexExp below which builds on my code from Remove non-numeric characters from a range of cells, and uses variant arrays for speed.
The RegExp pattern is [^\d\.]+
Sub KillNonNumbers()
    Dim rng1 As Range
    Dim rngArea As Range
    Dim lngRow As Long
    Dim lngCol As Long
    Dim lngCalc As Long
    Dim objReg As Object
    Dim X()

    On Error Resume Next
    Set rng1 = Selection.SpecialCells(xlCellTypeConstants, xlTextValues)
    If rng1 Is Nothing Then Exit Sub
    On Error GoTo 0

    'See Patrick Matthews excellent article on using Regular Expressions with VBA
    Set objReg = CreateObject("vbscript.regexp")
    objReg.Pattern = "[^\d\.]+"
    objReg.Global = True

   'Speed up the code by turning off screenupdating and setting calculation to manual
   'Disable any code events that may occur when writing to cells
    With Application
        lngCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .EnableEvents = False
    End With

    'Test each area in the user selected range

    'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on
    For Each rngArea In rng1.Areas
        'The most common outcome is used for the True outcome to optimise code speed
        If rngArea.Cells.Count > 1 Then
           'If there is more than once cell then set the variant array to the dimensions of the range area
           'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks
            X = rngArea.Value2
            For lngRow = 1 To rngArea.Rows.Count
                For lngCol = 1 To rngArea.Columns.Count
                    'replace the leading zeroes
                    X(lngRow, lngCol) = objReg.Replace(X(lngRow, lngCol), vbNullString)
                Next lngCol
            Next lngRow
            'Dump the updated array sans leading zeroes back over the initial range
            rngArea.Value2 = X
        Else
            'caters for a single cell range area. No variant array required
            rngArea.Value = objReg.Replace(rngArea.Value, vbNullString)
        End If
    Next rngArea

    'cleanup the Application settings
    With Application
        .ScreenUpdating = True
        .Calculation = lngCalc
        .EnableEvents = True
    End With

    Set objReg = Nothing
End Sub


text:
Q: Android HTML to docx Docx4j issues I am trying to convert html string to docx using the below code as per
github code recommended on previous stackoverflow questions.
I added the following libraries other than the ones used for Android docx to HTML by docx4j:
1. docx4j-importXHTML-3.2.2.jar
2. itext-2.1.7.jar
3. xml-renderer-3.0.0.jar
4. xalan-2.7.0.jar
The following is the android version of code in XhtmlToDocxAndBack.java :
       try {
                String html = "<title>Import me</title>
Hello World!
";

                WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

                XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
                XHTMLImporter.setDivHandler(new DivToSdt());

                wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert(html, null));

                System.out.println(XmlUtils.marshaltoString(wordMLPackage
                        .getMainDocumentPart().getJaxbElement(), true, true));

                wordMLPackage.save(new File("/sdcard/OUT_from_XHTML.docx"));

            } catch (Docx4JException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

Error I receive:
Error:(166, 34) error: cannot access XHTMLImporter
class file for org.docx4j.convert.in.xhtml.XHTMLImporter not found

Error I receive if I comment out XHTMLImporter.setDivHandler(new DivToSdt()):
Error:(168, 34) error: cannot access XHTMLImporter
class file for org.docx4j.convert.in.xhtml.XHTMLImporter not found

Error I receive if I comment out wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert(html, null)); as well:
Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'.
> java.util.zip.ZipException: duplicate entry: org/docx4j/convert/in/xhtml/ListHelper.class

I should mention docx to html is working fine in Android studio but the above error is buggy. Please tell me how to fix it.
Thanks in advance.


text:
Q: A doubt in a proof that if an entire function dominates another entire function then one of them is a constant multiple of the other I have seen some proofs of the fact that if $f,g$ are entire functions such that $|f(z)| \le |g(z)|, \forall z \in \mathbb C$ then $f(z)=cg(z) , \forall z \in \mathbb C$ for some $c \in \mathbb C$ . In all the proofs, it is proceeded like : Assume w.l.o.g. , $g$ is not identically zero . $|f(z)/g(z)| \le 1 $ for all $z$ for which $g(z)\ne 0$ ; now the set of zeroes of $g$ is isolated , and as $f/g$ is bounded in a neighbourhood of each such zero , each zero of $g$ is a removable singularity of $f/g$ , then it can be extended to a function holomorphic on $\mathbb C$ which is bounded .
Now  I have one question with this proof . I agree that in some neighbourhood of each zero of $g$ , $f/g$ is bounded . So individually one by one we can holomorphically extend $f/g$ to incorporate each zero of $g$ .  But $g$ can have infinitely many zeroes .  How can we then extend $f/g$ holomorphically to whole complex plane ? The step by step procedure won't work . Is there any other way or any thing obvious I am missing ? Please help . Thanks in advance

A: I am not really sure about the meaning of your expression "step by step procedure". Let $Z=\{z\in\mathbb{C}\,|\,g(z)=0\}$. Define$$\begin{array}{rccc}h\colon&\mathbb C&\longrightarrow&\mathbb C\\&z&\mapsto&\begin{cases}\frac{f(z)}{g(z)}&\text{ if }z\notin Z\\\lim_{w\to z}\frac{f(w)}{g(w)}&\text{ if }z\in Z.\end{cases}\end{array}$$This definition makes sense because the singularities of $\frac fg$ are removable. And it is easy to prove that $h$ is analytic. Since it is a bounded entire function, it is constant.


text:
Q: Simplest way to calculate the width of a segment of a convex shape A convex shape $C$ is cut using a a chord. What is the width of the resulting segment? This is the length of the green thick short line in the figure below:

Here is my current solution:

*

*Mark the endpoints of the chord by:

$$A_1 = (x_1,y_1) = (x(t_1), y(t_1))$$
$$A_2 = (x_2,y_2) = (x(t_2), y(t_2))$$

*Calculate the slope of the chord:

$$s = (y_2 - y_1) / (x_2 - x_1)$$

*Find the point $T$ on the curve in which the tangent is paralle to the chord (the slope is equal to $s$), i.e. find the value of $t$ for which:

$$y'(t)/x'(t) = s$$
And then let:
$$T = (x_T,y_T) = (x(t),y(t))$$

*Calculate the distance between the point $T$ and the chord according to the formula of the distance between a line and a point:

$$\operatorname{distance} = \frac{|(y_2-y_1)x_T-(x_2-x_1)y_T+(x_2 y_1-y_2 x_1)|}{\sqrt{(y_2-y_1)^2+(x_2-x_1)^2}}. $$
Is this calculation correct?
Is there a simpler way to calculate the distance?
In particular, the most difficult step here is step 3, which requires to solve a non-linear equation. Is there a way that does not require to find the point $T$ as in step 3?


text:
Q: Why everytime that I run jest this error EADDRINUSE pops up? Using supertest and jest Im learning to make test in restfull application
const app = require("../app");
const request = require("supertest")(app);

describe("Test API", () => {

    it("Buscar CPF que possui uma conexão apenas", async () => {
        const res = await request.get('/pessoas/buscar/13123213213123')

        const body = res.body;
        if (body.hasOwnProperty('message')) {
            expect(res.body.message).toBe("Person not found")
            expect(res.status).toBe(404)
        } else {
            expect(res.body).toEqual([{
                blabla:  "aahahah"
            }])
            expect(res.status).toBe(200)
        }
    });

});

I ran the jest with --watch:

listen EADDRINUSE: address already in use :::3030

Also, I do not know, if this test is correct, when I receive a Object inside array [ { } ], I should use toEqual?
Trying this eaddrinuse-127-0-0-15858-during-jest-test-debugging does not work.


text:
Q: How to create a php script which make function run in background? I want to create a function which runs in the background. An example would be deleting a session from database (id,session_token, session_identifier, expired_time). Once it's expire the current page will automatically redirect user back to the login page (login.php).
UPDATE
The expired time is stored in database.

A: Php Cronjob will be better approach for this. Cronjob is a way to run scheduled task in background.
Please have a look at the following link:
http://www.thesitewizard.com/general/set-cron-job.shtml

A: You can do this by using jquery Ajax and setInterval function
 function check_login() {
            $.ajax({
                type: 'get',
                url: "http://stackoverflow.com", /*Where you will check user is logged in or not means session is expired or not*/
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                },
                success: function(response) {
                    /*ajax call will return "Still login" (or any other response) if login*/
                    if (response == 'Still login') {
                        return true;
                    } else if (response == 'not login') {
                        window.location.replace("http://domain.com/login.php");
                    }
                }
            });
        }

        setInterval(check_login, 100);


text:
Q: How to print "\123" as "\123" in Java I am getting a string as "\123" from input and since \ with number is a valid syntax, java is converting it to ASCII. But I want to treat it as "\123". I was trying to search for raw strings as python but could not find anything. Also tried to check escape-utils but it is also not giving the expected output.
Any pointers to resolve the issue are appreciated.

A: You have to escape it. Try printing "\\123"


text:
Q: fetch function doesn't called with react-redux I want to call a rest api with react-redux but my fetch doesn't called at all.
My actions:
restActions.js file:

export const customerbyidGetAction = (data) => ({ type: types.customerbyidGetAction, data });

My reducer:
restReducer.js file:

import { Map, fromJS } from 'immutable';
import * as types from '../constants/restConstants';

const initialState = {};
const initialImmutableState = fromJS(initialState);
export default function reducer(state = initialImmutableState, action) {
    switch(action.type) {
        case types.customerbyidGetAction:
            return {
                ...state,
                data: action.payload
            }
        break;

        default:
            // the dispatched action is not in this reducer, return the state unchanged
            return state;
    }
}

restApi.js file:
import {customerbyidGetAction} from '../../redux/actions/restActions'

const URL = "https://***"

export default  function customerbyidGet() {

    return dispatch => {
        console.log("not called")
        dispatch(customerbyidGetAction());
        fetch(URL + 'customer/byid/Get',{
            method:'POST',
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'token':1234
            },
            body: JSON.stringify({'customerId': 1})
        })
        .then(res => {
            const r = res.json();
            return r;
        })
        .then(res => {
            if(res.error) {
                throw(res.error);
            }
            dispatch(customerbyidGetAction(res));
            return res;
        })
        .catch(error => {
            dispatch(customerbyidGetAction(error));
        })
    }
}

export default apis;

inside my Component:
import React from 'react';
import { Helmet } from 'react-helmet';
import Grid from '@material-ui/core/Grid';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import {
  Help, InsertDriveFile,
  MonetizationOn,
  Person,
  PersonPin,
  RemoveRedEye
} from '@material-ui/icons';

import { Link } from 'react-router-dom';
import CounterWidget from '../../../components/Counter/CounterWidget';
import colorfull from '../../../api/palette/colorfull';
import styles from '../../../components/Widget/widget-jss';
import PapperBlock from '../../../components/PapperBlock/PapperBlock';
import {customerbyidGetAction} from '../../../redux/actions/restActions';

class Panelclass extends React.Component {

  componentDidMount(){
    const {customerbyidGet} = this.props;
   customerbyidGet()
  }

  render() {
    const { classes } = this.props;

    return (
      <div>
 Hi
      </div>
    );
  }
}

Panelclass.propTypes = {
  classes: PropTypes.object.isRequired,
  customerbyidGet: PropTypes.func.isRequired,
};

// const mapStateToProps = state => ({
//   customers: customerbyidGet(state),
// })

const mapDispatchToProps = dispatch => bindActionCreators({
  customerbyidGet: customerbyidGetAction
}, dispatch)

const Panel = connect(
  //mapStateToProps,
  null,
  mapDispatchToProps
)(Panelclass);

export default withStyles(styles)(Panel);

A: Your reducer expects payload property in action:
function reducer(state = initialImmutableState, action) {
  switch (action.type) {
    case types.customerbyidGetAction:
      return {
        ...state,
        data: action.payload, // Here
      };
  }
}

So, you need to have that property in action creator:
const customerbyidGetAction = (data) => ({
  type: types.customerbyidGetAction,
  payload: data, // Here
});

Also, you need to fix the correct action import in component:
import { customerbyidGet } from "../path-to/restApi";

const mapDispatchToProps = (dispatch) =>
  bindActionCreators(
    {
      customerbyidGet,
    },
    dispatch
  );

PS: Today, you should use the Redux Toolkit library which reduces lots of boilerplate code.

A: First of all define your rest api function like below
export default  function customerbyidGet(dispatch) {

    return () => {
        console.log("not called")
        dispatch(customerbyidGetAction());
        fetch(URL + 'customer/byid/Get',{
            method:'POST',
            headers:{
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'token':1234
            },
            body: JSON.stringify({'customerId': 1})
        })
        .then(res => {
            const r = res.json();
            return r;
        })
        .then(res => {
            if(res.error) {
                throw(res.error);
            }
            dispatch(customerbyidGetAction(res));
            return res;
        })
        .catch(error => {
            dispatch(customerbyidGetAction(error));
        })
    }
}

Then pass it to your mapDispatchToProps function
const mapDispatchToProps = dispatch => bindActionCreators({
  customerbyidGetData: customerbyidGet(dispatch)
}, dispatch)

And finally`invoke it in mapDispatchToProps
componentDidMount(){
 const {customerbyidGetData} = this.props;
 customerbyidGetData()
}

A: The other two answers are pointing out good points, but missing something very crucial: That ; there is a typo.

    const {customerbyidGet} = this.props;
   customerbyidGet()

should be

    const {customerbyidGet} = this.props.customerbyidGet()


text:
Q: How do I merge two SELECT queries with different WHERE clauses I'm trying to write query on two different selects with different WHERE clause and using GROUP BY.
I browsed for examples but mine is different since I have multiple fields for SELECT.
Here is example data:
--    drop table #temp_counts;
create table #temp_counts(
report_date smalldatetime not null,
Emp_id varchar(10) not null,
source_system varchar(10) not null
)

Insert into #temp_counts values ('2021-05-02 00:00:00', '12411', 'ABC');
Insert into #temp_counts values ('2021-05-02 00:00:00', '56421', 'ABC');
Insert into #temp_counts values ('2021-05-02 00:00:00', '45411', 'ABC');
Insert into #temp_counts values ('2021-05-02 00:00:00', '75411', 'ABC');
Insert into #temp_counts values ('2021-05-02 00:00:00', '13245', 'XYZ');
Insert into #temp_counts values ('2021-05-02 00:00:00', '66245', 'XYZ');
Insert into #temp_counts values ('2021-05-02 00:00:00', '77245', 'XYZ');
Insert into #temp_counts values ('2021-05-02 00:00:00', '98245', 'XYZ');
Insert into #temp_counts values ('2021-05-02 00:00:00', '34245', 'XYZ');
Insert into #temp_counts values ('2021-05-02 00:00:00', '29245', 'XYZ');

Insert into #temp_counts values ('2021-05-03 00:00:00', '14524', 'ABC');
Insert into #temp_counts values ('2021-05-03 00:00:00', '17824', 'ABC');
Insert into #temp_counts values ('2021-05-03 00:00:00', '32524', 'ABC');
Insert into #temp_counts values ('2021-05-03 00:00:00', '16724', 'XYZ');
Insert into #temp_counts values ('2021-05-03 00:00:00', '19924', 'XYZ');
Insert into #temp_counts values ('2021-05-03 00:00:00', '89424', 'XYZ');
Insert into #temp_counts values ('2021-05-03 00:00:00', '48324', 'XYZ');
Insert into #temp_counts values ('2021-05-03 00:00:00', '16000', 'XYZ');

Insert into #temp_counts values ('2021-05-04 00:00:00', '18724', 'ABC');
Insert into #temp_counts values ('2021-05-04 00:00:00', '12904', 'XYZ');

Insert into #temp_counts values ('2021-05-05 00:00:00', '12074', 'ABC');
Insert into #temp_counts values ('2021-05-05 00:00:00', '12784', 'XYZ');
Insert into #temp_counts values ('2021-05-05 00:00:00', '12324', 'XYZ');
Insert into #temp_counts values ('2021-05-05 00:00:00', '75124', 'XYZ');

These are the queries I would like to merge:
select count(*) emp_count,  report_date , 'ABC' source_system from #temp_counts
where  source_system = 'ABC'
group by report_date
order by report_date

select count(*) emp_count,  report_date , 'XYZ' source_system from #temp_counts
where  source_system = 'XYZ'
group by report_date
order by report_date

I tried 2 methods as under:
--Method 1
select fir.emp_count, fir.report_date, fir.source_system from
(select count(*) emp_count,  report_date , 'ABC' source_system from #temp_counts
where  source_system = 'ABC') as fir
inner join
(select count(*) emp_count,  report_date , 'XYZ' source_system from #temp_counts
where  source_system = 'XYZ') as sec
on fir.report_date = sec.report_date
group by fir.report_date
order by fir.report_date
--Method 2
select count(*) emp_count,  report_date , 'ABC' source_system from #temp_counts
where  source_system = 'ABC'
UNION ALL
select count(*) emp_count,  report_date , 'XYZ' source_system from #temp_counts
where  source_system = 'XYZ'
group by report_date
order by report_date

Both give Error:
Msg 8120, Level 16, State 1, Line 61
Column '#temp_counts.report_date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Please guide

A: seems like you just want to group by report_date and source_system:
select count(*) emp_count,  report_date , source_system
FROM #temp_counts
group by report_date, source_system
order by source_system,report_date

if you want to have result for specific source systems then you can combine conditions:
select count(*) emp_count,  report_date , source_system
FROM #temp_counts
where  source_system in ('ABC', 'XYZ')
group by report_date, source_system
order by source_system,report_date

you can change order by to show rows in the order you want to show
just to illustrate how to use union :
select count(*) emp_count,  report_date , source_system from #temp_counts
where  source_system = 'ABC'
group by report_date

union all

select count(*) emp_count,  report_date , source_system from #temp_counts
where  source_system = 'XYZ'
group by report_date
order by source_system, report_date


text:
Q: SQL keep only the last X rows I have a table in which the id is constantly increasing. The Id does not always increase by the same value and it is not an auto_increment due to a api, but it increases permanently. Example:

Id
other content

501
xxx

500
yyy

365
qqq

...
...

Now I just want to keep the last X rows, remove rows with lower ids. I was able to find a similar but not a working solution for myself to this problem.
I thought that something like that would work, but there is an error:
DELETE FROM `games` WHERE `matchId` NOT IN(SELECT `matchId` FROM `games` ORDER BY `matchId` DESC LIMIT X)

#1235 - This version of MySQL doesn't yet support 'LIMIT &
IN/ALL/ANY/SOME subquery'

Im running the mysql version 8.0.27 on a phpmyadmin 5.1.1 web interface.
Is there a way to keep the newest x rows without triggering this error?

A: WITH cte AS (
 SELECT id, ROW_NUMBER() OVER (ORDER BY id DESC) AS rownum FROM games
)
DELETE games FROM games JOIN cte USING (id) WHERE rownum > 2;

A: You can use a CTE instead:
with u as
(select Id from table_name order by Id desc limit 5)
delete from table_name
where Id not in(select Id from u)


text:
Q: Ruby on Rails Tutorial chapter 9.4 (add admin user) Please help with error
Error:
SyntaxError in UsersController#index

app/views/users/_user.html.erb:4: syntax error, unexpected ')', expecting keyword_then or ';' or '\n' ...dmin? && !current_user?(user) );@output_buffer.safe_append=' ... ^

app/views/users/_user.html.erb:7: syntax error, unexpected keyword_end '.freeze;@output_buffer.append=( end );@output_buffer.safe_append=' ^

/app/views/users/_user.html.erb:10: syntax error, unexpected keyword_ensure, expecting ')'

/app/views/users/_user.html.erb:12: syntax error, unexpected keyword_end, expecting ')'

My /app/controllers/users_controller.rb:
  class UsersController < ApplicationController
  before_action :signed_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy

  def new
    @user = User.new
  end

  def index
    # @users = User.paginate(:page => params[:page])
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
    if @user.save
      sign_in @user
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    # @user = User.find(params[:id])
  end

  def update
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash.now[:success] = "User deleted."
    redirect_to users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

    #Before filters

    def signed_in_user
      redirect_to signin_url, notice: "Please sign in." unless signed_in?
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
end

app/views/users/_user.html.erb

  <%= gravatar_for user, size: 52 %>
  <%= link_to user.name, user %>
  <%= if current_user.admin? && !current_user?(user) %>
    | <%= link_to 'delete', user, method: :delete,
                                  data: { confirm: "You sure?" } %>
  <%= end %>

A: Change your app/views/users/_user.html.erb code to the following:

  <%= gravatar_for user, size: 52 %>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user) %>
      <%= link_to 'delete', user, method: :delete,
                    data: { confirm: "You sure?" } %>
  <% end %>


text:
Q: Is it possible to use #define inside a function? For example, I saw source code like the following. Can we use #define in a function? How does it work? (more information: this code is what I copied from openvswitch source code):
void *
ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
{
switch (code) {
case OFPUTIL_ACTION_INVALID:

#define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) case OFPUTIL_##ENUM:
#include "ofp-util.def"
    OVS_NOT_REACHED();

#define OFPAT10_ACTION(ENUM, STRUCT, NAME)                  \
case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
#define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)      \
case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
#define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
#include "ofp-util.def"
}
OVS_NOT_REACHED();
}

#define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
void                                                        \
ofputil_init_##ENUM(struct STRUCT *s)                       \
{                                                           \
    memset(s, 0, sizeof *s);                                \
    s->type = htons(ENUM);                                  \
    s->len = htons(sizeof *s);                              \
}                                                           \
                                                            \
struct STRUCT *                                             \
ofputil_put_##ENUM(struct ofpbuf *buf)                      \
{                                                           \
    struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
    ofputil_init_##ENUM(s);                                 \
    return s;                                               \
}
#define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
OFPAT10_ACTION(ENUM, STRUCT, NAME)
#define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
OFPAT10_ACTION(ENUM, STRUCT, NAME)
#define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
void                                                        \
ofputil_init_##ENUM(struct STRUCT *s)                       \
{                                                           \
    memset(s, 0, sizeof *s);                                \
    s->type = htons(OFPAT10_VENDOR);                        \
    s->len = htons(sizeof *s);                              \
    s->vendor = htonl(NX_VENDOR_ID);                        \
    s->subtype = htons(ENUM);                               \
}                                                           \
                                                            \
struct STRUCT *                                             \
ofputil_put_##ENUM(struct ofpbuf *buf)                      \
{                                                           \
    struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
    ofputil_init_##ENUM(s);                                 \
    return s;                                               \
}
#include "ofp-util.def"

A: You can use it inside a function, but it is not scoped to the function.  So, in your example, the second definitions of a macro will be a redefinition and generate an error.  You need to use #undef to clear them first.

A: #define is a preprocessor directive: it is used to generate the eventual C++ code before it is handled to the compiler that will generate an executable. Therefore code like:
for(int i = 0; i < 54; i++) {
  #define BUFFER_SIZE 1024
}

is not executed 54 times (at the preprocessor level): the preprocessor simply runs over the for loop (not knowing what a for loop is), sees a define statement, associates 1024 with BUFFER_SIZE and continues. Until it reaches the bottom of the file.
You can write #define everywhere since the preprocessor is not really aware of the program itself.

A: You can use #define anywhere you want. It has no knowledge of functions and is not bound by their scope. As the preprocessor scans the file from top-to-bottom it processes #defines as it sees them. Do not be misled (by silly code like this!) into thinking that the #define is somehow processed only when the function is called; it's not.

A: How does it work? All C/C++ files are first processed by... the preprocessor.
It doesn't know anything about C nor C++ syntax. It simply replaces THIS_THING with ANOTHER THING. That's why you can place a #define in functions as well.

A: Sure.   #define is handled by the preprocessor which occurs well before the compiler has any sense of lines of code being inside functions, inside parameters lists, inside data structures, etc.
Since the preprocessor has no concept of C++ functions, it also means that there is no natural scope to macro definitions.  So if you want to reuse a macro name, you have to #undef NAME to avoid warnings.

A: Sure this is possible. The #define is processed by the preprocessor before the compiler does anything. It is a simple text replacement. The preprocessor doesn't even know if the line of code is inside or outside a function, class or whatever.
By the way, it is generally considered bad style to define preprocessor macros in C++. Most of the things they are used for can be better achieved with templates.


text:
Q: how to transfer more then one string from one activity to another in android i have to transfer more then one string from one activity to another activity in android , i already know how to transfer one string from one to another string in android but for more then one string i can not found ways my code is here ,
 if (long_insert_row_index>0){
                        //Spinner spDepCMPName = (Spinner) findViewById(R.id.spDepCMPName);
                        // String strCMP= spDepCMPName.getSelectedItem().toString();
                        //String strCMP=depositecmpname;

           //startActivity(new Intent(DepositActivity.this, AuditPointDetailsActivity.class).putExtra("insert_row_index",""+long_insert_row_index).putExtra("segment_name", spinner_segment.getSelectedItem().toString()).putExtra("audit_type_name", spinner_audit_type.getSelectedItem().toString()).putExtra("audit_type_id", audit_type_id).putExtra("segment_id", segment_id));

///please see commented section at bottom
                      startActivity(new Intent(DepositActivity.this, DepositeNextActivity.class)
                                .putExtra("insert_row_index",""+long_insert_row_index)
                                .putExtra("CMPName", depositecmpname));
                    }else {
                        Toast.makeText(DepositActivity.this,"Error while inserting data.Please re-enter data.",Toast.LENGTH_LONG).show();
                    }
                }

Now i want to send both string from one activity to another , i dont know how to do that one .

A: you can use code in your first activity like :-
  ArrayList<String> arr = new ArrayList<String>();
    arr.add(long_insert_row_index);
    arr.add( depositecmpname);
    Intent intent = new Intent(firstactivity.this,secondActivity.class);
                intent.putExtra("array_list", arr);
                startActivity(intent);

Now in another class you can use this code saying :-
Bundle extras = getIntent().getExtras();

ArrayList<String> arr = (ArrayList<String>)extras.getStringArrayList("array_list");
          Toast.makeText(getApplicationContext(),""+arr.size(),Toast.LENGTH_LONG).show();

hope it will help

A: Use for open activity:
Intent intent = new Intent(activity, Activity2.class);
            intent.putExtra("String1", "Hello!");
            intent.putExtra("String2", "Hello!2")
            activity.startActivity(intent);

In open activity:
getIntent.getStringExtra("String1");
getIntent.getStringExtra("String2");

Or use
intent.putExtra("StringByteArr", "str".toByteArray());

and:
String.valueOf(getIntent.getByteArrayExtra("StringByteArr"));


text:
Q: Как обновить данные одной строки данными из другой строки? Есть таблица sales с полями model, color, price. Вытаскиваю данные из строки с id='12' и пытаюсь их вставить с id='13':
UPDATE sales SET (model, color, price) =
(SELECT model, color, price FROM sales WHERE id = '12') WHERE id = '13'

Но ничего не получается.
Пытаюсь cделать, основываясь на этом примере.

A: в mysql можно сделать так (объединить таблицу саму с собой):
SQL Fiddle
MySQL 5.6 Schema Setup:
create table sales (id int, model int, color int);
insert into sales values
  (1, 1, 1), (2, 2, 2);

update sales a
  inner join sales b on a.id = 1 and b.id = 2
  set a.model = b.model, a.color = b.color;

Query 1:
select * from sales

Results:
| id | model | color |
|----|-------|-------|
|  1 |     2 |     2 |
|  2 |     2 |     2 |


text:
Q: How can I make this Excel macro loop through only visible filtered data? I have very little experience with VBA and I'm now stumped by what I'm trying to accomplish with a macro. Excel 2010.
I have 3 relevant columns. B, C, and AD. (Columns 2, 3, and 30)
My data is filtered down to about 30 rows, almost none of which are contiguous (about 500 rows total).
I want the following to happen:
A formula is entered in ONLY THE VISIBLE ROWS in column AD, which will look at the value in column B of that same row and check for that value in all of the VISIBLE CELLS in column C. It cannot look at all of the cells in column C, only the visible ones.
If the value from column B in that row is found anywhere in the VISIBLE CELLS in column C, then "True" should be returned in column AD. I don't care about what is returned when the value is not found, as I will be filtering for the "True" values only.
As an added requirement, if the first 3 characters of the value in column B are "010" I need it to return a value of "True" in column AD. I then need this formula copied down column AD for each VISIBLE row.
Right now, I have a formula that will conduct the search in column C for the value in column B. (found on stackoverflow)
=NOT(ISNA(VLOOKUP(B4,C:C,1,0))))

This provides a "True" in column AD when the value from column B is found somewhere in column C. With the "010" constraint, the formula looks like this:
=IF(LEFT(B4,3)="010","True",NOT(ISNA(VLOOKUP(B4,C:C,1,0))))

I am having a problem in that this looks at even the hidden (filtered out) rows. Every one of my values in column B will appear in column C at some point, so I'm only getting "True" for all my entries.
I think there must be a better way to do this than just having a macro paste the formula down (even considering I can't get the formula to work). So, 2 questions:

*

*Is the formula the right way to go in this case, and, if so, can anyone tell me how to get it to only search the visible cells in column C?

*If code is the best way (I'm guessing it is), can anyone show me an example of code that might work?

A: You're almost there. On its own, COUNTIF does not have this capability, but if you throw user-defined functions (UDF functions) into the mix, you have an elegant solution.
Add the following code to a module in your code-behind.
Function Vis(Rin As Range) As Range
    'Returns the subset of Rin that is visible
    Dim Cell As Range
    Application.Volatile
    Set Vis = Nothing
    For Each Cell In Rin
        If Not (Cell.EntireRow.Hidden Or Cell.EntireColumn.Hidden) Then
            If Vis Is Nothing Then
                Set Vis = Cell
            Else
                Set Vis = Union(Vis, Cell)
            End If
        End If
    Next Cell

End Function

Function COUNTIFv(Rin As Range, Condition As Variant) As Long
    'Same as Excel COUNTIF worksheet function, except does not count
    'cells that are hidden
    Dim A As Range
    Dim Csum As Long
    Csum = 0

    For Each A In Vis(Rin).Areas
        Csum = Csum + WorksheetFunction.CountIf(A, Condition)
    Next A

    COUNTIFv = Csum
End Function

Now you can use the new COUNTIFv() function to do the same as count, but only include visible cells. This code example was sampled from Damon Ostrander's answer to a similar question, so you will probably need to tweak it slightly. You can either use the COUNTIFv function in the macro itself, or modify the VLOOKUP function in a similar fashion to use the worksheet function example you have already. Neither method is really better than the other, so either should work for you.


text:
Q: How to call multi block with in one tab in admin edit page in magento I want to call two section/block within one tab. Can anyone help me to how can I get achieve this one?
Please find attached screen-shot to more detail.

Thanks in advance!

A: in tab section write code only for one tab like:
<namespacename>_<modulename>_Block_Adminhtml_<modulename>_Edit_Tabs

$this->addTab('form_section', array(
                   'label' => '<tab lable>',
                   'title' => '<tab title>',
                   'content' => $this->getLayout()
     ->createBlock('<modulename>/adminhtml_<modulename>_edit_tab_form')
     ->toHtml()
         ));

and then write all code related to the two tab in this folder structure file:
<namespacename>_<modulename>_Block_Adminhtml_<modulename>_Edit_Tab_Form


text:
Q: jQuery - How to evaluate two select option values for an if/else statement? I have a continue button with the class "options-btn" on a page (it's a multi-step booking process), with two select fields on the page. One of these dropdown select fields needs to have a value selected by the user before they can click the submit button on the page while also disabling the click event?
Each dropdown field has the default select option 0, with the other choice of "1". How can I write a function to basically say "If neither one of these options has a value of 1 selected - alert message "please select an option" and disable the button.
The two ID's associated with these select fields are:
#extra_units_7 & #extra_units_4
This is what I wrote so far, but it's not working:
jQuery(document).ready(function($) {
$(".options-btn").click(function() {
  if ( $('#extra_units_7').val() === 0  ||  $('#extra_units_4').val() === 0 )
    alert("Please select an option");
    return false;
  } else {
      $('.options-btn').trigger('click');
  }
});

A: jQuery(document).ready(function($) {
    $(".options-btn").click(function(){
        if ( $('#extra_units_7').val() === 0  &&  $('#extra_units_4').val() === 0 )
            alert("Please select an option");
            return false;
        }
        return true;
    });
)}

You should use && instead of ||. You don't need to trigger click event again.

A: you want to check id the condition is respected at every change of the select an basically disable / enable the button, the code was pretty much ok but you had to perform the check at the change event. I've extracted the check function in an external one just to help redability (you missed a { indenting too much the code) and i've introduced a class on the select to perform the check better, you can use the ID's if you like.
<select class="input-select" id="extra_units_4">
  <option value="0">Volvo</option>
  <option value="1">Saab</option>
</select>

<select class="input-select" id="extra_units_7">
  <option value="0">Volvo</option>
  <option value="1">Saab</option>
</select>

<button class="options-btn" disabled="disabled">Submit</button>

The if contition is an AND because you are checking that both the values are 0 and the check must be performed on string because the select value is not an integer.

A: 1st: There is an error for   }); at the end of your code
2nd: use == instead of ===
3rd: no need to use $('.options-btn').trigger('click');
try this .. if you have submit button without form
jQuery(document).ready(function($) {
  $(".options-btn").on('click',function() {
    if( $('#extra_units_4').val() == 0 ){
      alert("Please select an option in extra_units_4");
      //return false;
    }else if($('#extra_units_7').val() == 0 ){
      alert("Please select an option in extra_units_7");
        //$('.options-btn').trigger('click');
    }else{
      alert('extra_units_4 value = '+$('#extra_units_4').val());
      alert('extra_units_7 value = '+$('#extra_units_7').val());
    }
  });
});

Working Demo
or this .. if you have a submit button for a form (you need to use e.preventDefault();  and  window.location.href )
jQuery(document).ready(function($) {
  $(".options-btn").on('click',function(e) {
    e.preventDefault();
    if( $('#extra_units_4').val() == 0 ){
      alert("Please select an option in extra_units_4");
      //return false;
    }else if($('#extra_units_7').val() == 0 ){
      alert("Please select an option in extra_units_7");
        //$('.options-btn').trigger('click');
    }else{
      alert('extra_units_4 value = '+$('#extra_units_4').val());
      alert('extra_units_7 value = '+$('#extra_units_7').val());

      // window.location.href = "type_url_here" // change type_url_here with url you need or with the form action attribute
    }
  });
});

Working Demo

A: Here's an alternative approach, in case you plan to keep adding selects which are mutually exclusive but required (you would need to add the required-select to all of them):
    });

jQuery(document).ready(function($) {

  var hasSelected = function() {
    return $('.required-select option:not([value="0"]):selected').length;
  };

  $('.required-select').change(function() {
    $('.options-btn').prop('disabled', !hasSelected());
  });

  $('form').submit(function(e) {
    if (!hasSelected()) {
      alert("Please select an option");
      e.preventDefault();
    } else {
      alert('submitted');
    }
  });

});

<form method="post" onsubmit="return false;">
  <select id="extra_units_7" class="required-select">
    <option value="0">Select an option</option>
    <option value="1">One</option>
    <option value="2">Two</option>
  </select>
  <select id="extra_units_4" class="required-select">
    <option value="0">Select an option</option>
    <option value="1">One</option>
    <option value="2">Two</option>
  </select>

  <button type="submit" class="options-btn" disabled="disabled">Submit</button>
</form>

I think it's overkill to validate on submit when the button is disabled, and it's not intuitive to allow submit, alert error and then disable the button. I'd take one of the two approaches in the code above (I prefer specifying in writing that the selects are required and not enabling the submit until they are selected).

A: I re-factored your HTML in order to enable you to feedback to the End User without being obtrusive with alert() boxes.

<form id="form_units" action="#" method="post">

      extra_units_4

      <select id="extra_units_4" data-validate="notempty">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>

Please make a selection

    extra_units_7
      <select id="extra_units_7" data-validate="notempty">
        <option value="0">0</option>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>

Please make a selection

    extra_units_8
    <input type="text" id="extra_units_8" data-validate="notempty" />

Please make a selection

  <input type="submit" class="options-btn" value="Submit" />
</form>

Now we have a simple JS which will capture all <input>s with data-validate="notempty".
// Make sure you're specific with your selector for your form
$('#form_units').on('submit',function(e) {
  // Hide all .fielderror elements within the context of 'this' form.
  // This means that the next time we submit error messages are reset
  $('.fielderror', this).hide();
  // Select for all 'not empty' validations
  $('[data-validate="notempty"]').each(function (index, item) {

    // Check if it's an input[type="text"] - future proofing your "not empty" requirements. Expand on this idea for "radio" and "checkbox" inputs if and when required.
    if ($(item).attr('type') === 'text') {

      // Text is empty if the length is less than one char
      if ($(item).val().length < 1) {
        // We've found one that is invalid so stop the from from sending
        e.preventDefault();
        // Show the .fielderror text that is associated with the input being validated
        $(item).siblings('.fielderror').show();
      }
    } else {
        // Selects are empty if val() is less than 1. Be warned, this is dependant on having numerical values - and assumes that zero means no answer.
        if ($(item).val() < 1) {
          // We've found one that is invalid so stop the from from sending
          e.preventDefault();
          // Show the .fielderror text that is associated with the input being validated
          $(item).siblings('.fielderror').show();
        }
      }
  })
});

Lastly, add a little CSS to hide the error messages and style them when they become shown.
.fielderror { display: none; color: red;}

jsFiddle of working example with update to HTML structure and text input - https://jsfiddle.net/likestothink/xLLvzps2/9/


text:
Q: @JsonDeserialize does not work on interface I have an interface for some of my enums with @JsonFormat and @JsonDeserialize:
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@JsonDeserialize(using = JsonEnumDeserializer.class)
public interface JsonEnum {
    @JsonProperty("symbol")
    String getSymbol();

    @JsonProperty("name")
    String name();
}

And I use it for my enums like this:
public enum MyEnum implements JsonEnum {
    VALUE1("v1"), VALUE2("v2"), VALUE3("v3");
    private final String symbol;
}

When I serialize MyEnum I get the correct Object. But when I want to deserialize an object to MyEnum my custom deserializer (JsonEnumDeserializer) does not gets called.
If I add @JsonDeserialize on top of MyEnum then it works fine but I want to have generic deserializer for all of my enums that implements JsonEnum.


text:
Q: get Exception when use webservice(AXIS2) I use axis2 and tomcat to develop my webservices which is used to search my system with Lucene.
I write the server class and test it, and then deploy it with "Axis2 Service Archiver".
There are 2 method in the webservices. I user brower to test it.
[http://localhost:8080/axis2/services/eBook/plus?x=1.1&y=2.2]
This simple method(PLUS) work well, and return 3.3.
But the another one(working with lucene) return some Exception:

    Could not initialize class org.apache.lucene.codecs.Codec

I don't know what make this problem. can someone help? Thanks a lot.
The error message below:
org.apache.axis2.AxisFault: Could not initialize class org.apache.lucene.codecs.Codec
 at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:210)
 at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
 at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
 at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:181)
 at org.apache.axis2.transport.http.util.RESTUtil.invokeAxisEngine(RESTUtil.java:144)
 at org.apache.axis2.transport.http.util.RESTUtil.processURLRequest(RESTUtil.java:139)
 at org.apache.axis2.transport.http.AxisServlet$RestRequestProcessor.processURLRequest(AxisServlet.java:837)
 at org.apache.axis2.transport.http.AxisServlet.doGet(AxisServlet.java:273)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
 at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
 at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1822)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at java.lang.Thread.run(Unknown Source)
 Caused by: java.lang.reflect.InvocationTargetException
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:212)
 at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:117)
 ... 25 more
 Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.lucene.codecs.Codec
 at org.apache.lucene.index.SegmentInfos.read(SegmentInfos.java:299)
 at org.apache.lucene.index.StandardDirectoryReader$1.doBody(StandardDirectoryReader.java:56)
 at org.apache.lucene.index.SegmentInfos$FindSegmentsFile.run(SegmentInfos.java:783)
 at org.apache.lucene.index.StandardDirectoryReader.open(StandardDirectoryReader.java:52)
 at org.apache.lucene.index.DirectoryReader.open(DirectoryReader.java:65)
 at ns.eBook.Search.process2(Search.java:52)
 ... 31 more

A: I have slove the problem.
After trying many way,I got the point.
I put every jar files(lucene) using in the webservices into "WEB-INF\lib", and it work.
Thank goodness.


text:
Q: summarize a list by object with totals, using shell I'm new to sh shell scripting.
How can I write this script in terms of sort and grep?
There is an awk script that sums up all the values of a list by group.
awk '{ arr[$1]+=$2 }
     END {
       for (key in arr) printf("%s\t%s\n", key, arr[key])
     }' "$@" |
sort +0n -1

Suppose the file:
A 8
B 3
A 2
B 4

Output is:
A 10
B 7

All I have now is cat "$1" | sort but how do I get hold of the left and right columns individually without using awk?
I'm stuck on how to get the first column into an array with its values to the right respectively.

A: Assuming you have bash 4.x or a sufficiently recent ksh, you can try:
declare -A sum   # Use typeset -A sum in ksh, which also works in bash
cat <<'EOF' |
A 8
B 3
A 2
B 4
EOF
{
while read key value
do
    ((sum[$key]+=$value))
done
for key in "${!sum[@]}"
do echo "$key ${sum[$key]}"
done
} | sort

The old-style notation +0n -1 is now expressed as -k 1n,1 and means sort the first column (the key values) numerically.  Since the key values are A and B, this is not very helpful, so I've left the sort criteria off.  What would make more sense to me would be -k 2n or -k 2nr to sort by the sum in increasing or decreasing order.
The bash manual recommends declare -A over typeset -A, but both work; ksh requires typeset -A.

A: FILE="input"
eval $(sed '/^$/d;s/\([^ ]*\) \([^ ]*\)/\1=\$((\$\1 + \2))/' $FILE)
eval $(sed '/^$/d;s/ .*$//' $FILE | sort -u | sed 's/.*/echo "& = \$&";/')

The first sed expression creates lines in the form of A=$(($A + 8)). The second one generates echo "A = $A"; expressions.
Gives:
A = 10
B = 7


text:
Q: Show that differentiability at a point implies symmetric differentiability at a point.
Definition Let $c \in (a, b)$ and let $f:(a,b) \rightarrow \mathbb{R}$. Then $f$ is symmetrically differentiable at $c$ if $$\lim_{h \to 0} \frac{f(c + h) - f(c - h)}{2h}$$ exists and is finite.
Problem Show that if $f$ is differentiable at $c$, then $f$ is symmetrically differentiable at $c$, and the derivatives are the same.

I'm not entirely sure where to start. We want to show that, given $f'(c)$ exists, $$\lim_{h \to 0} \frac{f(c + h) - f(c - h)}{2h} = f'(c) = \lim_{h \to 0} \frac{f(c + h) - f(c)}{h}$$
but I'm not sure how to do that. Can anyone provide minimal assistance? This seems like such a simple problem, but I'm stuck nonetheless. Thanks in advance for any response.

A: Hint:
$$\lim_{h\to0}\frac{f(c+h)-f(c-h)}{2h}=\lim_{h\to0}\frac{f(c+h)-f(c)+f(c)-f(c-h)}{2h}=\lim_{h\to0}\frac{\left[f(c+h)-f(c)\right]-\left[f(c-h)-f(c)\right]}{2h}=\frac{1}{2}\lim_{h\to0}\left[\frac{f(c+h)-f(c)}{h}-\frac{f(c-h)-f(c)}{h}\right]$$
and make a change of variable $(-h)\mapsto h$ in the second limit (I mean, in the second fraction).


text:
Q: Apache Wicket 1.6 or higher version does not support visural-wicket As we know, visural-wicket is a light-weight wicket component, loosely coupled and to be easily integrated into any existing Wicket application.
Currently, I am updating wicket 1.5 to a higher version(mostly to wicket 1.8) in my project. And I see visural-wicket is designed for use with Wicket 1.5 or less.
is there any alternative for visural-wicket in the higher version like wicket 1.8 so that all the features of this can be migrated/implemented in up-gradation Or any suggestion on this will be a great help.
Thanks.

A: I would recommend you Wicket JQuery UI. It has both jQuery and KendoUI components.
The other supported library is Wiquery, but it is maintained as much as to compile with newer versions of Wicket. Nothing new has been added to it in the last few years.


text:
Q: Waiting for a backend process response using Spring Boot, Kafka and ReactJS I'm using Spring Boot 2.1.4, Kafka and React as a frontend UI. I have a user registration process from the UI which requires a backend process and it's data before the registration is complete.
The flow is like this:

*

*The frontend UI makes a request to an API which returns a token and puts a message on to a request Kafka queue

*The message is processed by a backend process (which takes approximately 1 minute)

*When the process is finished, a message with the token and data is written to a reply Kafka queue which indicates the process is complete

What I want is the frontend UI to make the initial API request which returns immediately, show a loading screen and display a ready message when the registration process is complete.
I have thought of a couple of options:

*

*Attach a KafkaListener to the reply queue. Once the reply message appears, store the response and token in a datastore (e.g. Redis). Provide an API to the UI which checks the datastore for the token. The UI will poll this API every 10 seconds. If the response is not available after 2 mins, the user will be asked to check back later.

*Use WebSockets with React. I've not used WebSockets before but the only thing I'm unsure of is if I have multiple instances of the registration microservice, will this cause any issues with client/api communication.
Any recommendations or any other options on the best way to handle this?

A:

*

*Attach a KafkaListener to the reply queue. Once the reply message appears, store the response and token in a datastore (e.g. Redis). Provide an API to the UI which checks the datastore for the token. The UI will poll this API every 10 seconds. If the response is not available after 2 mins, the user will be asked to check back later.

This will work. I would use the built in RocksDB for storage though, just for simplicity. Below is the documentation for exposing a state store to be queryable outside of kafka streams.
https://kafka.apache.org/20/documentation/streams/developer-guide/interactive-queries.html

*Use WebSockets with React. I've not used WebSockets before but the only thing I'm unsure of is if I have multiple instances of the registration microservice, will this cause any issues with client/api communication.

It can potentially cause issues. It depends on the implementation of the registration service. You won't know which instance of the registration service a client will establish a connection with. For instance session needs to be managed in a external datasource like Redis or you would have to use a laod balancer that supports sticky sessions (a bit of an archaic solution).


text:
Q: Custom Post Type and taxonomies's labels localization not working after a few hours serching on the net I decided to ask here my problem.
I'm in a multi site environment and I have this custom post type code:
$products_labels = array(
    'name'                => _x( 'Prodotti', 'General post type name', 'textdomain' ),
    'singular_name'       => _x( 'Prodotto', 'General post type name', 'textdomain' ),
    'menu_name'           => _x( 'Prodotti', 'General post type menu label', 'textdomain' ),
    'parent_item_colon'   => __( 'Genitore elemento:', 'textdomain' ),
    'all_items'           => __( 'Tutti gli elementi', 'textdomain' ),
    'view_item'           => __( 'Vedi', 'textdomain' ),
    'add_new_item'        => __( 'Aggiungi nuovo elemento', 'textdomain' ),
    'add_new'             => __( 'Aggiungi nuovo', 'textdomain' ),
    'edit_item'           => __( 'Modifica', 'textdomain' ),
    'update_item'         => __( 'Aggiorna', 'textdomain' ),
    'search_items'        => __( 'Cerca', 'textdomain' ),
    'not_found'           => __( 'Non trovato', 'textdomain' ),
    'not_found_in_trash'  => __( 'Non trovato nel cestino', 'textdomain' ),
);
$products_args = array(
    'label'               => __( 'Prodotti', 'textdomain' ),
    'description'         => __( 'Prodotti', 'textdomain' ),
    'labels'              => $products_labels,
    'supports'            => array( 'title', 'thumbnail', 'editor', 'excerpt', 'revisions', 'page-attributes' ),
    'taxonomies'          => array( 'product_category' ),
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'menu_icon'           => '',
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page',
);

One of my sites is on german language and the backoffice has been set in german as well.
All the strings are correctly translated (the frontend works without problems) and the de_DE.mo file is well loaded but the labels from the admin perspective are not localized and I can't understand why not :(
This is the load text domain
load_theme_textdomain( 'textdomain', THEMEPATH . '/languages' );

pls find the attached image

Hope you can help me :(
UPDATE:
I'noticed that all strings written in functions.php file are not translated.
The only way to translate them is to insert strings in a new function called on init action.
exemple:
NOT TRANSLATED
$str = __('My string','textdomain');

TRANSLATED:
function my_function_name()
{
    $str = __('My string','textdomain');
    echo $str;
}

add_action('init','my_function_name', 0);

UPDATE 2:
SOLVED.
You have to load the load_theme_textdomain not by action but directly written as first line on the file functions.php
Now my custom post type labels are finally translated :)

A: SOLVED. You have to load the load_theme_textdomain not by action but directly written as first line on the file functions.php Now my custom post type labels are finally translated :)

A: According to the documentation after_setup_theme should be used as hook to load translations.
add_action( 'after_setup_theme', 'my_theme_setup' );
function my_theme_setup(){
    load_theme_textdomain( 'my-theme', get_template_directory() . '/languages' );
}


text:
Q: Connect to AWS ElastiCache with In-Transit Encryption + Auth from client other than redis-cli+stunnel I'm trying to use a Ruby redis client and either one of two NodeJS clients (node_redis or ioredis) to connect to an Amazon ElastiCache cluster with in-transit encryption and auth enabled and am having issues. For all three clients, as soon as I connect I get an ECONNRESET error thrown immediately and over and over again when connection retries occur.
I have followed the AWS docs and am able to successfully connect via redis-cli using stunnel, but haven't been able to connect with any other client so far.
From looking at this SO answer, it appears there is no certificate required and we simply need to pass empty options to the TLS config (if applicable), but no matter what I enter I'm unsuccessful. I've also tried passing the default stunnel stunnel.pem private key as the cert in all clients just in case, and it obviously doesn't work either. Any assistance or expertise from others who have used ElastiCache would be helpful!

A: I ran into a similar problem, but instead of ECONNRESET I was getting a timeout. For me, there were a few problems that had to be ironed out

*

*The lambda needs VPC permissions.

*The ElastiCache security group needs an inbound rule from the Lambda security group that allows communication on the Redis port. I thought they could just be in the same security group.

*Because encryption in-transit was turned on, I needed to pass redis.RedisClient(... ssl=True). The redis-py page mentions that ssl_cert_reqs needs to be set to None for use with ElastiCache similar to what was answered, but that didn't seem to be true in my case. I think AWS has updated the ElastiCache certs to have the proper hostname. I did however need to pass ssl=True.

It makes sense that ssl=True needed to be set but the connection was just timing out so I went round and round trying to figure out what the problem with the permissions/VPC/SG setup was.

A: For both clients the default TLS behavior is to verify the server certificate, which we needed to disable. The solution for both clients is as follows:
NodeJS client:
const redis = require('redis')
const client = redis.createClient({host: hostOrIp, port: 6379, auth_pass: 'thePassword', tls: { checkServerIdentity: () => undefined }})

Ruby client:
require "redis"
redis = Redis.new(url: connectionString, ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE })