text:
Q: Why Magento 2 `addForeignKey` function does not have `onUpdate` and how to add it while adding foreign key I have started with Magento 2 setup scripts and I found one small change with Magento's addForeignKey function parameters.
In Magento 1, the arguments for the function is like,
public function addForeignKey($fkName, $column, $refTable, $refColumn, $onDelete = null, $onUpdate = null)

There is an option for defining what to do on update of referenced table row,

While in Magento 2, the arguments for the same function is like,
public function addForeignKey($fkName, $column, $refTable, $refColumn, $onDelete = null)

They have remove onUpdate argument.
Does anyone have any idea about why they did that??
Also can anyone guide me what to do if I want to add onUpdate action for foreign key?

A: According to this acknowledged Github issue, this is actually by design:

Hi, this is deliberate restriction, to achieve better compliance with other possible database engines.
  But you can implement actions like "ON UPDATE" on application level. In this case your code will be compatible with Magento SPI ( events, interceptors, e.t.c).


text:
Q: How to set Time out to AutodiscoverUrl call using EWS in C#? I am working on Mail Application. I want to set time out for server call of log in using EWS. I have already set 15 seconds for time out but sometimes it takes 1 minutes or more.
System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
System.Net.ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.TraceEnabled = true;
service.Credentials = new WebCredentials(email, Pwd);
service.Timeout = 15000;
service.AutodiscoverUrl(email, RedirectionCallback);
//some times it takes 1 minutes to call (1 minute to reach next statement)
EWS_URL = service.Url.ToString();

//check for certificate
private static bool CertificateValidationCallBack(
        object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    if ((sslPolicyErrors == System.Net.Security.SslPolicyErrors.None))
    {
        entityExchangeServer.isValid = true;
        return true;
    }

    // If there are errors in the certificate chain, look at each error to determine the cause.
    if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
    {
        if (chain != null && chain.ChainStatus != null)
        {
            foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
            {
                if ((certificate.Subject == certificate.Issuer) &&
                   (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                {
                    // Self-signed certificates with an untrusted root are valid.
                    return true;
                }
                else
                {
                    if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                    {
                        // If there are any other errors in the certificate chain, the certificate is invalid,
                        // so the method returns false.
                        return false;
                    }
                }
            }
        }
        // When processing reaches this line, the only errors in the certificate chain are
        // untrusted root errors for self-signed certificates. These certificates are valid
        // for default Exchange server installations, so return true.
        return true;
    }
    else
    {
        // In all other cases, return false.
        return false;
    }
}

static bool RedirectionCallback(string url)
{
    return true;
}

I have already set 15 seconds for time out but sometimes it takes 1 minutes or more.
Can anybody please suggest how to set time out here?

redpajama_set_name: RedPajamaStackExchange


text:
Q: setsockopt does not work in C++ (timeout set to 1s, it waits longer) I want to build a simple port scanner in C++. However, setting the timeout of the socket to 1s, the program waits much longer before testing the next port. Am I doing something wrong?
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <fstream>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>

int main()
{
    int socketFileDescriptor;
    struct sockaddr_in server_address;

    for (int i=3000; i<65535; i++)
    {
        std::cout<<i<<std::endl;

        socketFileDescriptor = socket(AF_INET,SOCK_STREAM, 0);

        struct timeval tv;
        tv.tv_sec = 1;

        if (setsockopt(socketFileDescriptor, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
        {
            perror("Error");
        }

        server_address.sin_family = AF_INET;
        server_address.sin_port = htons(i);
        inet_pton(AF_INET,"212.182.24.27", &(server_address.sin_addr));

        int result = connect(socketFileDescriptor,
                             (struct sockaddr*)&server_address,sizeof(struct sockaddr));
        if (result != -1)
        {
            std::cout<<"Port: "<<i<<std::endl;
        }
        close(socketFileDescriptor);
    }
}

A: SO_RCVTIMEO, as its name should suggest to you, sets a receive timeout, not a connect timeout.
To get a connect timeout, you have to use non-blocking mode and select().


text:
Q: Display Random Posts with thumbnail instead of just a title of the post This code works really well. It displays the title of the post randomly with permalink but my objective is to display the thumbnail and/or featured image instead.
Any help would be appreciated.
<?php function wpb_rand_posts() {
    $args = array(
    'post_type' => 'post',
    'orderby'   => 'rand',
    'posts_per_page' => 5,

    );
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) {
    $string = '
';
        while ( $the_query->have_posts() ) {
        $the_query->the_post();

        $string .= '
'. get_the_title() .'
';

        }
        $string .= '
';

    /* Restore original Post Data */
    wp_reset_postdata();
    } else {
    $string .= 'no posts found';
    }
    return $string;
}
add_shortcode('random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode');  ?>

A: You can get the post thumbnail HTML using the function get_the_post_thumbnail(), so you just need to replace get_the_title() with that function:
$string .= '
'. get_the_post_thumbnail() .'
';

By default the image will be the size defined by your theme, but you use any of the other available sizes by passing the size name as the 2nd argument of the function:
$string .= '
'. get_the_post_thumbnail( null, 'large' ) .'
';

A: Replace this line
$string .= '
'. get_the_title() .'
';

WITH
$string .= '
'. get_the_post_thumbnail( get_the_ID(), 'thumbnail' ) .'
';

get_the_post_thumbnail function is showing the featured image at front end.
Here is the full code:
<?php

function wpb_rand_posts() {
    $args = array(
        'post_type' => 'post',
        'orderby'   => 'rand',
        'posts_per_page' => 5
    );

    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) {
        $string = '
';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();

            $string .= '
'. get_the_post_thumbnail( get_the_ID(), 'thumbnail' ) .'
';
        }

        $string .= '
';

        /* Restore original Post Data */
        wp_reset_postdata();
    } else {
        $string .= 'no posts found';
    }

    return $string;
}
add_shortcode('random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode');

?>

I added the CSS class name into the UL tag.
You will add this CSS into your style.css file
ul.wpb-rand-posts {
    list-style-type: none;
    margin: 20px 0;
    padding: 0;
}

.wpb-rand-posts li {
    display: inline-block;
    float: left;
    margin-left: 10px;
    width: calc( ( 100% - 40px ) / 5 );
}

.wpb-rand-posts li:first-child {
    margin-left: 0;
}


text:
Q: How download url with extension while renaming on curl? I am new at coding and i need help. I use curl -o "$filename.$e" for downloading many file. All work good, but litle bit slow because $e variable determined by if command system
 if [[  url =~ ^.*gif.*$ ]]; then
 e=gif
 elif [[ url =~ ^.*jpg.*$ ]];then
 e=jpg
elif [[ url =~ ^.*png.*$ ]]; then
  e=png
 else echo Corrupted link!!!
 fi

which take time to response. How i can get extension while downloading like
curl -o "$filename.*$"


text:
Q: Pandas DataFrame: Assign values from a column to a subset of original dataframe without copying I want to assign the values of a column in a DataFrame to a subset of another column in the same original DataFrame. Consider the following example:
df = pd.DataFrame(np.random.randn(8, 4), index=[0,1,1,2,1,3,4,5], columns=['A', 'B', 'C', 'D'])
df['str'] = ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
df.loc[1, 'B'] = df.loc[1, 'A']

For all values where the index is 1, I want to assign the value of column 'A' to column 'B'. This operation is to be applied to the original DataFrame and not a copy.
The above example fails with the following error
ValueError                                Traceback (most recent call last)
<ipython-input-144-29c8017817b2> in <module>()
      2 df['str'] = ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
      3 display(df)
----> 4 df.loc[1, 'B'] = df.loc[1, 'A']
      5 display(df)

~/anaconda/envs/snakes36/lib/python3.6/site-packages/pandas/core/indexing.py in __setitem__(self, key, value)
    177             key = com._apply_if_callable(key, self.obj)
    178         indexer = self._get_setitem_indexer(key)
--> 179         self._setitem_with_indexer(indexer, value)
    180
    181     def _has_valid_type(self, k, axis):

~/anaconda/envs/snakes36/lib/python3.6/site-packages/pandas/core/indexing.py in _setitem_with_indexer(self, indexer, value)
    577
    578                     if len(labels) != len(value):
--> 579                         raise ValueError('Must have equal len keys and value '
    580                                          'when setting with an iterable')
    581

ValueError: Must have equal len keys and value when setting with an iterable

The problem seems to be column str which is of different type than the other float64 columns. If I remove column str, the code above works perfectly. Which I do not understand as I assumed my .loc operations only select columns A and B.
The problem is: My DataFrame consists of ~50 columns with different types.
Is there a better approach to solve this?

A: Option 1 :
Use a conditional to match the index i.e
df.loc[df.index==1,'B'] =df.loc[1,'A']

Option 2 :
or with np.where i.e
df['B'] = np.where(df['B'].index==1,df['A'],df['B'])

Option 3 :
or with df.where
df['B']  = df['B'].where(~(df['B'].index==1),df['A'])

Output:

          A         B         C         D str
0 -0.549047 -0.608938 -0.355242  1.362221   a
1  0.298822  0.298822  1.591475  0.146636   a
1 -0.292439 -0.292439  0.425860  0.117091   a
2 -1.715484 -0.343491 -1.448902  1.394756   a
1  0.657651  0.657651 -0.002407  1.317446   a
3 -0.698070 -0.740400 -1.348418 -0.800586   a
4 -1.043036 -0.161858  1.110410  0.275207   a
5  0.050947 -1.424375  0.260261 -1.058468   a


text:
Q: Why polarization in Torelli theorem? Are there two non-isomorphic compact Riemann surfaces with isomorphic integral Hodge structure on $H^1(-,\mathbb{Z})$?
Recall Torelli theorem for Riemann surface: For two compact Riemann surfaces $X,Y$, if there is an isomorphism $H^1(X,\mathbb{Z})\to H^1(Y,\mathbb{Z})$ preserving the intersection pairing, then $X,Y$ are biholomorphic.
I'm wondering what if we ignore the intersection pairing.


text:
Q: Define type for PHPUnit's mock objects I was wondering if its possible to use phpdoc to define some object in specific scope (inside a method only) as PHPUni's Mock, so in that method i can take advantage of type-hints, such as ->expected, ->methods and so on, just like when you just create the mock without addressing it to its real class.
here is an demonstration:

class someTest extends PHPUnit
{
    // here, usually we define the real class (SomeClass in this example)
    /** @var SomeClass */
    private $someMock;

    public function setUp()
    {
        $this->someMock = $this->getMock(SomeClass::class);
    }

    public function testSomethingInSomeClass()
    {
        // here i expect the type hint i defined in the beginning of this test class and its fine
        $a = $this->someMock->someMethodFromSomeClass();
    }

    private function setSomeMethodOnMock()
    {
        // but here i would like to have the type-hint for phpunit's mock object
        // e.g. ->expects,  ->method() , ->willReturn() , etc.
        // if i don't define the mock alias the class type i get will be something like Mock_SomeClass_9873432
        $this->someMock->....
    }
}

A: /**
 * @var SomeClass|\PHPUnit_Framework_MockObject_MockObject
 */
private $someMock;

You can do the same thing with methods:
/**
 * @return SomeClass|\PHPUnit_Framework_MockObject_MockObject
 */
private function getSomeMock()
{
    //....
}


text:
Q: Need help using Object.fromEntries to reorganize an array of objects. The fun stuff delimma I have a form that accepts user selections from groups of options.
This is just an example of the objects I get from the db for the options.
let optiongroups = [
       {
        groupname : "exactly1",
        grouplimit : 1,
        id : 123,
        rules : "exactly",
        rulesnumber : {number :0, minimum : 0, maximum : 0 },
        optionitems : [
          {
            name : "One",
            price : 1
          },
          {
            name : "Two",
            price : 2
          }
        ]

       },
       {
        groupname : "exactly2",
        grouplimit : 2,
        id : 369,
        rules : "exactly",
        rulesnumber : {number :0, minimum : 0, maximum : 0 },
        optionitems : [
          {
            name : "2-One",
            price : 22
          },
          {
            name : "2-Two",
            price : 44
          }
        ]

       }]

I used Object.fromEntries to turn it to this:
finalgroupit = Object.fromEntries(optiongroups.map(g => [g.groupheader,  []]));

So now I have an object that group them like this
{"groupname1" : [], "groupname2" :[] }
That was good till I realized I need to validate user selection against the rules and rulesnumber before I submit the selection. That is my question. How to add rules and rulesnumber to my output in finalgroupit = Object.fromEntries()
I struggled with reduce() so after reading and researching I came accross the Object.fromEntries and using it with map() made really sense to me and I was able to reconstruct my data but I'm stuck with how to add rules and rulesnumber to the output for each group. Something like {"groupname" : [], grouprules : "", rulesnumber :""}
This whole thing with how to reconstruct the data to fit specific scenario is new to me and hopefully someone willing to help.
How do I do that?

A:

let optiongroups = [
       {
        groupname : "exactly1",
        grouplimit : 1,
        id : 123,
        rules : "exactly",
        rulesnumber : {number :0, minimum : 0, maximum : 0 },
        optionitems : [
          {
            name : "One",
            price : 1
          },
          {
            name : "Two",
            price : 2
          }
        ]

       },
       {
        groupname : "exactly2",
        grouplimit : 2,
        id : 369,
        rules : "exactly",
        rulesnumber : {number :0, minimum : 0, maximum : 0 },
        optionitems : [
          {
            name : "2-One",
            price : 22
          },
          {
            name : "2-Two",
            price : 44
          }
        ]

       }];

const final = optiongroups.reduce((res, obj) => {
  res[obj.groupname] = {
    [obj.groupname]: [],
    "rules": obj.rules,
    "rulesnumber": obj.rulesnumber
  };

  return res;
}, {})
console.log(final);

let optiongroups = [
       {
        groupname : "exactly1",
        grouplimit : 1,
        id : 123,
        rules : "exactly",
        rulesnumber : {number :0, minimum : 0, maximum : 0 },
        optionitems : [
          {
            name : "One",
            price : 1
          },
          {
            name : "Two",
            price : 2
          }
        ]

       },
       {
        groupname : "exactly2",
        grouplimit : 2,
        id : 369,
        rules : "exactly",
        rulesnumber : {number :0, minimum : 0, maximum : 0 },
        optionitems : [
          {
            name : "2-One",
            price : 22
          },
          {
            name : "2-Two",
            price : 44
          }
        ]

       }];

const final = Object.fromEntries(optiongroups.map(g => {
  return [g.groupname,
          {
            [g.groupname]: [],
            "rules": g.rules,
            "rulesnumber": g.rulesnumber
          }];
}));
console.log(final);

A: You can use Object.fromEntries, and with destructuring and sort ES6 object literal syntax, it becomes like this:

const optiongroups = [{groupname : "exactly1",grouplimit : 1,id : 123,rules : "exactly",rulesnumber : {number :0, minimum : 0, maximum : 0 },optionitems : [{name : "One",price : 1},{name : "Two",price : 2}]},{groupname : "exactly2",grouplimit : 2,id : 369,rules : "exactly",rulesnumber : {number :0, minimum : 0, maximum : 0 },optionitems : [{name : "2-One",price : 22},{name : "2-Two",price : 44}]}];

const result = Object.fromEntries(
    optiongroups.map(({groupname, rules, rulesnumber}) =>
        [groupname, { rules, rulesnumber, userSelections: [] }]
    )
);

console.log(result);


text:
Q: Obtening reactions in discord js 13 not working I am trying to create a bot for my-self that count reactions but when i try using this code to obtain all reactions it doesnt work at all. If any of you have an idea.
client.on('messageReactionAdd', (reaction, user) => {
    console.log(reaction.emoji.name);
})

I tried placing emojis and all but it never printed anything.


text:
Q: How to randomize the columns in a selected row in PHP The selected id will select the row and randomize. However, it could randomize the same elements.
For example:
 'I like to play the piano.'
The output I'm expecting is randomized to eg. ' Play the like to I piano '
But what I receives sometimes turns out to be ' I piano piano like to piano'
This words comes from the database(phpmyadmin). How do I make it such that the data will all appear but not repeat?
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";

$x = rand(1,4);
echo "$x";
$y = rand(1,4);
echo "$y";
$z = rand(1,4);
echo "$z";
$c = rand(1,4);
echo "$c";

$rs = mysql_query($strSQL);

// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {

    // Write the data of the person
    echo "
Sentence:

" . $row["$x"] . " " . $row["$y"] . " " . $row["$z"] . " " . $row["$c"] ."
";
}

A: You can do:
//create an array with numbers 1-4
$order = array(1,2,3,4);

//shuffle them in random order
shuffle($order);

$rs = mysql_query($strSQL);

// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
    // Write the data of the person
    //Display all the array values from 0-3 (array index starts from 0)
    echo "
Sentence:

" . $row[$order[0]] . " " . $row[$order[1]] . " " . $row[$order[2]] . " " . $row[$order[3]] ."
";
}

Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

A: Try using the shuffle() function.
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";

// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {

    shuffle($row);

    // Write the data of the person
    echo "
Sentence:

" . implode(' ', $row) . "
";
}

Unrelated: mysql_* are deprecated as of php 5.5 and will be removed in the future. Use mysqli or PDO instead.


text:
Q: Javascript - What is wrong with this function and loop? I started learning to code just a couple days ago, and I'm almost finished with my first program. However, I have ran into a problem now at the end, and I can't seem to figure out what's wrong myself.
The program is supposed to help me sort a bunch of dates by week day and time of day. The dates are written "YYMMDD-" and then the time of the day (only hour), e.g. "170109-06".
I have all the dates I want to sort in an array (time), and the following function and loop are supposed to delete all the dates that's not matching a specific year.
Variable clarification:
time - array consisting of dates and time (all the same months but different years. ( e.g. ["161102-03", "151127-11"]
yearDate - the first 4 numbers of the dates that's going to stay in the array.
function checkDate (date) {
    var yearMonth = date.slice(0, 4);
    var index = time.indexOf(date)
    if (yearMonth != yearDate) {
        time.splice(index, index + 1);
    }
    else {
    }
}

for (var i = 0; i <= time.length; i++) {
    checkDate(time[i]);
}

This code seems to work occasionally, but sometimes a few strings from the array stay there when they're supposed to be deleted, so there's clearly something wrong with the code.
I hope that you'll be able to understand what I mean. I do realize that this post ended up kind of wooly.

A: Standard mistake. You are deleting items from array while iterating over it. Every time an item is deleted, incrementing the iterator will jump you over the next element, adjacent to the deleted.
Go backwards:
for (var i = time.length - 1; i >= 0; i--) {
    checkDate(time[i]);
}


text:
Q: Nuxtjs /Vuex is not working with complex objects I am receiving the following message when I try to change the value in my form, works for simple object though.
[vuex] do not mutate vuex store state outside mutation handlers.
I have a list and I need to update a register in this list, so pops up a dialogue modal populated and a need to change or not the fields and I click and save summit the alterations and in case I close the modal without save the changes, the values must be the same as before.
My form
<v-layout wrap>
 <v-flex xs12 sm6 md4>
 <v-text-field  v-model="editedItem.personnel.name" label="Name"></v-text-field>
</v-flex>
<v-flex xs12 sm6 md4>
<v-text-field v-model="editedItem.personnel.email" label="Email"></v-text-field>
</v-flex>

export default {
  name: "TheDealerPersonnel",
  components: { TheContentTitle },

  data: () => ({
    title: "Dealer Personnel",
    dialog: false,
    options: [],
    editedItem: {
      perosonneldealershipid: Number,
      dealerID: Number,
      personnelID: Number,
      dealer: Object,
      personnel: {
        personnelID: Number,
        name: String,
        email: String,
        companyID: Number,
        roleiD: Number,
        company: Object,
        role: {
          roleiD: Number,
          description: String,
          ranking: Number
        }
      }```

A: This error happens not because the object is complex, rather because you are trying to change the vuex state not in mutations,
I'm not sure if its the form that is causing the problem but I'm guessing you are in somewhere in your app you are changing a vuex state....
to change vuex state you must create mutations and commit the change
export const mutations = {
    SET_CHANGE: (state,change)=>{
       state.item = change
    }
}

which can be called by commit('SET_CHANGE')


text:
Q: Exchange mail filter problems Python I have a script to list emails from exchange account and it takes too long to get a response, and other times I get errors like.
EXCEPTION IN (<string>, L_203 ""): HTTPSConnectionPool(host='outlook.office365.com', port=443): Read timed out.

or
requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(10054, 'Se ha forzado la interrupción de una conexión existente por el host remoto', None, 10054, None)", ConnectionResetError(10054, 'Se ha forzado la interrupción de una conexión existente por el host remoto', None, 10054, None))

I don't understand why it takes so long. Will it be a problem with my account? sometimes it takes up to 2 minutes before giving an error
This is a part of my code:
class ExchangeModule:
    def __init__(self, user_, pwd, server_, mail_):
        self.pwd = pwd
        self.mail = mail_
        self.server = server_
        self.user = user_
        self.credentials = None
        self.config = None

    def init(self):
        from exchangelib import Credentials, Configuration
        self.credentials = Credentials(username=self.user, password=self.pwd)
        self.config = Configuration(server=self.server, credentials=self.credentials)
        return self.config

if module == "exchange":
    user = GetParams('user')
    password = GetParams('pass')
    server = GetParams('server')
    address = GetParams('address')
    print('USUARIO', user)
    exchange_module = ExchangeModule(user, password, server, address)
    config = exchange_module.init()

if module == "get_new_mail":

    if exchange_module.config is not None:
        config = exchange_module.config
    else:
        raise Exception("Execute Email Configuration command")
    address = exchange_module.mail
    a = Account(primary_smtp_address=address, config=config,
                access_type=DELEGATE, autodiscover=False)

    var = GetParams('var')
    filter_type= GetParams('tipo_filtro')
    filtro = GetParams('filtro')
    id_ = []

    if filtro:
        if filter_type== 'author':
            for m in a.inbox.all():
                if not m.is_read and filtro in m.author.email_address:
                    id_.append(m.id)

        if tipo_filtro == 'subject':
            mails_filters = a.inbox.filter(subject__contains=filtro)
            for m in mails_filters:
                if not m.is_read:
                    id_.append(m.id)
                    # print('FOR',m.id)

    else:
        id_ = [m.id for m in a.inbox.all() if not m.is_read]

    SetVar(var, id_)

A: If you enable debug logging in exchangelib (see https://ecederstrand.github.io/exchangelib/#troubleshooting) you can see exactly what is going on.
Your script is fetching all item fields, even though it only really needs the id field. That is very heavy since you're also fetching the full body, attachments, etc. Additionally, it is filtering items client-side that might as well be filtered server-side, giving you much less data to transfer. Instead of:
for m in a.inbox.all():
    if not m.is_read and filtro in m.author.email_address:
        id_.append(m.id)

do
for m in a.inbox.filter(is_read=True, author__contains=filtro).only('id'):
    id_.append(m.id)

And instead of:
mails_filters = a.inbox.filter(subject__contains=filtro)
for m in mails_filters:
    if not m.is_read:
        id_.append(m.id)

do
for m in a.inbox.filter(subject__contains=filtro, is_read=True).only('id'):
    id_.append(m.id)

Apart from that, you may just have a slow Internet connection. You can configure fault tolerance (https://ecederstrand.github.io/exchangelib/#fault-tolerance) if you want to hide these errors and let your script try again.


text:
Q: PHP Contact Form Blank Data & Unknown Sender Hello I have made a contact form on my website but even if the user doesn't type in any of the details and presses the submit button it sends me a blank email with nothing in it from Unknown Sender.
Anyone know why this is happening? I have added form validation so it shouldn't be sending anything.
HTML Code:
<form action="mail.php" method="POST">
* Name <input type="text" name="name" required>
* Phone <input type="text" name="phone" required>
* Email <input type="text" name="email" required>
* Message <input type="text" name="message" placeholder="I am looking for..." required>

<input type="image" src="images/Landing_Pages/submit.png" border="0" alt="Submit" />
</form>

PHP Code:
<?php $name = $_POST['name'];
    $phone = $_POST['phone'];
    $preferred = $_POST['preferred'];
    $email = $_POST['email'];
    $formcontent="From: $name \n Phone: $phone \n Email: $email \n Message: $message \n Preferred Contact: $preferred \n Email: $email";
    $recipient = "bwebb@webbmaster.com.au";
    $subject = "New Request Southbank";
    $mailheader = "From: $email \r\n";
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    ?>

A: You have to check if post data is not empty
 if (!empty($name) && !empty($phone) && !empty($preferred) && !empty($email)) {
      mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
 }

Edit
<?php
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $preferred = $_POST['preferred'];
    $email = $_POST['email'];
    $formcontent="From: $name \n Phone: $phone \n Email: $email \n Message: $message \n Preferred Contact: $preferred \n Email: $email";
    $recipient = "bwebb@webbmaster.com.au";
    $subject = "New Request Southbank";
    $mailheader = "From: $email \r\n";
    if (!empty($name) && !empty($phone) && !empty($message) && !empty($preferred) && !empty($email)) {
        mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    }
?>

A: Do something like :
$errorflag = 0 ;
if(empty($name)){$errorflag = 1 ;$error = "Input your Name plz!"; };
if(empty($phone)){$errorflag = 1 ;$error = "Input phone"; }
...
if(!$errorflag) {
    @mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
}

check every input you need and then send


text:
Q: Plot of ACF & PACF There are 96 observations of energy consumption per day from 01/05/2016 - 31/05/2017. I am trying an ARIMA model in R to be fitted to these time series observations. I have chosen the frequency of time series as 96. In total, there are 38016 observations.
I have cleaned the series using tsclean command in R to remove the outliers.
timeseries <- ts(full$consumption, frequency = 96)

Cleansed time series:
timeseries <- tsclean(timeseries)

I have then differenced the series:
diffts <- diff(timeseries)

I have then decomposed the series to obtain the seasonal component from it. Subtracted the seasonal component from it to deseasonalize it.
difftscomponent <- decompose(diffts)
adjusted_diffts <- diffts - difftscomponent$seasonal

The ACF plot of final time series:
acf(adjusted_diffts)

The PACF of the final time series:
pacf(adjusted_diffts)

There are three questions:

*

*Normally, the X-axis of ACF and the PACF plot of the time series will show lag order from 1 to ... . There will be integer values indicating the number of lags. Then why in my case there are decimal values from 0.1.... ? What does that indicate? What to do to get number of lags?

*What will be the probable order of AR and MA in my case by looking at ACF and PACF plot?
3.I have transformed the original time series i.e. made it stationary and deseasonalized it in order to fit an ARIMA model. By looking at the final adjusted time series, can it be said that it is fit to be modelled OR will it require any further transformation?

A: *

*This is the result of formatting your data.frame as time.series. I can't test it right now since I don't have access to R right now but going back to a simple data.frame should do the job, something along (there probably is a more elegant way):
acf(data.frame(adjusted_diffts)

*While the plotted ACF/PACF gives you an indication which lags need to be corrected the selection of the ARIMA-Order should be done by e. g. checking multiple combinations of ARIMA(p,d,q) and choose the one with the best (lowest) AIC. Here is an article + code example to test for different orders.

*This I can't answer with certainty. I would use the data you have and after, fitting an ARIMA model, check the residuals for any remaining structure. If there still is structure in the residuals you might need need to adjust your data/model.
Edit: formatting


text:
Q: @Transactional(isolation = Isolation.SERIALIZABLE) how to lock only few rows I have a method like:
@Transactional(isolation = Isolation.SERIALIZABLE)
public default Student doSomething(Student student) {
  School sch = student.getSchool(); // @JoinColumn's
  List students = sch.getAllStudents();
  List names = getAllNames(students); // stream.map to names or something similar.
  if(!names.contains(student.name)) {
    save(student);
}
}

As we can see from the code snippet here we have a student. From the student we get the school and then all the students from that school. Then we get their names and if the student is not there we are adding it - otherwise not.
From that code I expect serializable exception only when 2 threads are adding for the same school. But I am having the "cant serialize access" even if we add students for 2 different schools. Isn't spring/hibernate locking mechanism dealing with such cases? :( Shouldn't it lock only the lines from the table that were used during the method? Please help on that specific case. Thanks in advance.

A: I'm not 100% sure, but isn't the Isolation.SERIALIZABLE locking all tables and prevents you to add the student ?


text:
Q: Question on non-atomic measures Let $(X,\Sigma,\mu)$ be a finite measure space.  Call $\mu$ nonatomic if for any $A\in\Sigma$ with $\mu(A)>0$ there exists $B\in\Sigma$ with $B\subset A$ and $0<\mu(B)<\mu(A)$.

Suppose that $\mathcal S$ be the algebra that generates  $\Sigma$. I am asking to what is the relation between nonatomicity of $\mu$ and $\mu|_\mathcal S$.

A: I'm no measure theory wizard, so check my argument well for errors!
Consider the collection of sets $\mathcal A\subset\Sigma$ defined by: $A\in\mathcal A$ if and only if the following two conditions both hold

*

*$\mu(A)=0$ or $\exists B\in\Sigma:0<\mu(B)<\mu(A)$.

*$\mu(A^c)=0$ or $\exists B\in\Sigma:0<\mu(B)<\mu(A^c)$.

If we assume that $\mu|_\mathcal S$ is 'nonatomic', then $\mathcal A$ is a Dynkin class containing $\mathcal S$ (check this! I found the second definition found on Wikipedia to be simplest to work with). Since $\mathcal S$ is clearly stable under finite intersections, it follows from Dynkin's Lemma that $\Sigma\subset \mathcal A$.

A: **Fact **. If  $\mu$ is non-atomic then so is $\mu|_{S}$.
Proof. Assume the contrary and let $\mu|_{S}$ is atomic. Then there will be a set(atom)
$A \in S$ with $\mu(A)>0$ such that for each element of the $S$ with $B \subseteq A$ we have $\mu|_{S}(B)=0$ or $\mu|_{S}(B)=\mu|_{S}(A)$. Since $\mu$ is non-atomic and extension of $\mu|_{S}$ by the condition $\mu(A)=\mu|_{S}(A)$ we claim that there is $B_0 \in \sum$ such that $0<\mu(B_0)<\mu(A)$. By the Charatheodory measure extension theorem from the algebra to the minimal algebra we have
$
\mu(B_0)= \inf \{\sum_{k=1}^{\infty} \mu|_{S}(A_k) : A_k \in S \& k \in N \&
$
$
B_0 \subseteq \cup_{k =1}^{\infty}A_k \in S\}.
$
For $\epsilon=((\mu(A)-\mu(B_0))/2$ there is a sequence $\{ A_k \in S:k \in N\}$ such that  $B_0 \subseteq \cup_{k =1}^{\infty}A_k \in S$ and $\sum_{k=1}^{\infty}\mu(A_k)<\mu(B_0)+\epsilon$. Then we have:
(i) $\cup_{k=1}^{\infty}A_k\cap A \in S$;
(ii) $\mu|_{S}(\cup_{k =1}^{\infty}A_k\cap A)=\mu(\cup_{k =1}^{\infty}A_k\cap A) \le \sum_{k=1}^{\infty}\mu(A_k)<\mu(B_0)+\epsilon < \mu(A)=\mu|_{S}(A)$;
(iii)  $\mu|_{S}(\cup_{k =1}^{\infty}A_k\cap A)=\mu(\cup_{k =1}^{\infty}A_k\cap A)\ge \mu(B_0)>0$;
So The conditions (i)-(iii) contradicts to the our assumption that $A$ is atom for $\mu|_{S}$.
**Example( The converse of the Fact above is not valid). We have to show there is $S$ and $\mu$ such that $\mu|_{S}$ is non-atomic but  $\mu$ is atomic. Indeed, let consider $E=Q\cap[0,1]$ where $Q$ is a set of all rational numbers; $\sum=\{A:A\subseteq E\}$. Let $(q_k)_{k \in N}$ be  a numeration of the $E$; Let $m_k$ be a sequence of positive numbers with $\sum_{k=1}^{\infty}m_k=1$. For $A \in \sum$ we set $\mu(A)=\sum_{q_k \in A}m_k$.
Let $S$ be a class of subsets of $E$ which can be presented in the form
 $\sum_{k=1}^n[a_k,b_k[\cap Q , (n\in N)$, where $\{[a_k,b_k[:1 \le k \le n\}$ is a sequence of pairwise disjoint intervals closed from the left and open from the right. Then it is not hard to show that
(j)  $S$ is an algebra of subsets of $E$ which generates $\sum$;
(jj) $\mu$ is atomic measure on $\sum$;
(jjj) $\mu|_{S}$ is non-atomic measure on $S$.


text:
Q: Is there a cheatsheet for linux commands to save your system? I've recently lost my window options, had to somehow manipulate my way to Xchat and ask some people how do I get it back (it was metacity --replace, and after I decided to stop the command and run it in background the X was completely useless so I had to do killall -u user).
And that was after the internet connection stopped working for some reason (might've been the ISP).
The thing is, after using linux a long time, I still get the feeling
that on dire situations, I don't know the good tricks (stuff like metacity --replace).
I feel like a really need like a "rescue" cheatsheet for things like:

*

*how to save the X no matter what without pressing reset

*how to reset the system to "normal state"

*how to connect to the internet through the command line

*how to monitor what the X is doing
(using ubuntu linux 10.04 btw)

A: X
If it's working: Ctrl-Alt-Backspace.
Ctrl-Alt-F[1-6] go to terminal.
Ctrl-Alt-F7 - go to X
Restart XDM in most distros:
/etc/init.d/xdm restart

Or find X processes PIDs
ps aux|grep "[Xx]"

and kill them. Then start new X
startx

X logs: /var/log/Xorg.0.log
Internet
Using dhcp:
dhclient interface

Interface could be eth0.
Without
ifconfig ...

or
ip

(see man for more)
Not sure how Ubuntu works, but i think you can restart your network connecting using some kind of /etc/init.d script.
Check server guide. Not sure, but I think that works for desktop edition too.
Other stuff
Useful terminal programs:

*

*lynx,links - internet browsers

*irssi - IRC client

*mc - file manager

*mcedit - simplest file editor ever

*GNU and system utils - basic like: cat, tail, head, cp, rm, mv - must know!

*top, ps - display Linux tasks

*free - memory usage (but remember to look at buffors table, not mem)

*man :)

Magic Resq Key
Wikibooks Freezes

A: I'm a programmer, so I use git daily.
I have found git very useful for monitoring changes (and eventually restoring in emergency cases) changes in config files.
Edit:
On my Ubuntu 10.04 LTS I do:
sudo /etc/init.d/network-manager restart

or
sudo service network-manager restart

A: I know this isn't exactly what your looking for, but I found this .pdf to be a good resource for figuring out ubuntu. (Plus its free...which is always nice.)
http://ubuntu-manual.org/


text:
Q: Meaning of $\geqslant$, $\leqslant$, $\eqslantgtr$, $\eqslantless$ What do slanted inequality signs mean? Specifically, these are $\geqslant$, $\leqslant$; and the variation: $\eqslantgtr$, $\eqslantless$.
Is there any place I can look this up? I've searched Wikipedia and the web and can't find anything about them. The last two were found when looking up the first two.

A: I haven't seen $\eqslantless$ or $\eqslantgtr$ used.  A Google search for "eqslantless" turned up
http://www.mathnet.ru/php/archive.phtml?wshow=paper&jrnid=tmf&paperid=3775&option_lang=eng
but the actual paper (both the Russian original and the English translation) used $\leqslant$.

A: In France too, we use $\geqslant$ and $\leqslant$, at least in high school teaching.
The $\geq$ and $\leq$ signs are understandable though, and used by pocket calculators.

A: $\geqslant$ is an alternative to $\geq$ and means the same: $a \geqslant b$ = "$a$ is greater than or equal to $b$".
Likewise, $\leqslant$ is an alternative notation for $\leq$, with $a \leqslant b$ = "$a$ is less than or equal to $b$".
I haven't encountered $\eqslantgtr$ or $\eqslantless$, but given that the former is formatted eqslantgtr and the latter eqslantless, I would venture to guess that they likewise denote "greater than or equal to" and "less than or equal to", respectively.  Perhaps with these symbols, where the emphasis appears to be on the "equals" component, they are read as "equal to or greater than" and "equal to or less than", respectively.

A: Since people agreed with $\leq$ vs $\leqslant$ is a style issue. I checked a list of books from various disciplines,
the "$\leq$" group:
R. Shankar, Principle of Quantum Mechanics.
O.C. Zienkiewicz, et al. The Finite Element Method.
J. Munkres, Topology.
S. Boyd, et al. Convex Optimization.
S.M. Carroll, Spacetime and Geometry
R.W. Hamming, Numerical Methods for Scientists and Engineers
T. Sauer, Numerical Analysis.
R.A. Horn, et al. Matrix Analysis
G.H. Golub, et al. Matrix Computations
W. Fulton, et al. Representation Theory
T.W. Hungerford, Algebra
N. Jacobson, Basic Algebra
I. Goodfellow, Deep Learning
the "$\leqslant$" group:
D.V. Hutton, Fundamentals of Finite Element Analysis.
S.J. Farlow, Partial Differential Equations for Scientistes and Engineers
R.L. Graham, Concrete Mathematics
C.M. Bishop, Pattern Recognition and Machine Learning
It seems that most gurus preferred "$\leq$".

A: In Russia $\geqslant$ and $\leqslant$ are used instead of $\geq$ and $\leq$.
We don't use $\geq$ and $\leq$ at all.
But I've never seen $\eqslantgtr$ and $\eqslantless$ in Russian math texts.
P.S.
1. There are more interesting distinctions between Russian and English math notations.
For example, we occasionally using $\ n\vdots d\ $ instead of $\ d|n$.
2. There are a lot of strange math symbols exists: see here and here.

A: As other answers have remarked, $\eqslantless$ and $\eqslantgtr$ are rarely seen, and the difference between $\leqslant$ and $\leq$, and similarly between $\geqslant$ and $\geq$, is just a matter of style. I would like to add that  $\leqslant$ and $\geqslant$ were the preferred standard of many publishers in the UK and the US until recent decades when the direct setting of authors' LaTeX files took over in books and journals. In LaTeX, the default characters are $\leq$ and $\geq$, the slanted versions requiring an extra five keystrokes each for the author to type.
Personally, I prefer the aesthetics of the slanted version, to the extent that I am willing to type the extra letters.


text:
Q: No windows identity for DOMAIN\USER In my SharePoint 2013 environment (1 WFE, 1 APP, NTLM, Nintex Workflow, Claims to Windows NT Token Service (c2WTS) is standard with local system) are lots of (Every seconds a few) claims authentication errors in the ULS log.
Any ideas where the problem come from?
Any ideas how I can fix the problem?
Thank you in advance!
ULS Log
Claims Authentication Medium:

> SPSecurityContext: Could not retrieve a valid windows identity for
> username 'DOMAIN\USER' with UPN 'USER@DOMAIN.DE'. UPN is required when
> Kerberos constrained delegation is used. Exception:
> System.ServiceModel.FaultException
> 1[System.ServiceModel.ExceptionDetail]: WTS0003: The caller is not
> authorized to access the service. (Fault Detail is equal to An
> ExceptionDetail, likely created by
> IncludeExceptionDetailInFaults=true, whose value is:
> System.UnauthorizedAccessException: WTS0003: The caller is not
> authorized to access the service.     at
> Microsoft.IdentityModel.WindowsTokenService.CallerSecurity.CheckCaller(WindowsIdentity
> callerIdentity)      at
> Microsoft.IdentityModel.WindowsTokenService.S4UServiceContract.PerformLogon(Func
> 1 logonOperation, Int32 pid)      at SyncInvokeUpnLogon(Object ,
> Object[] , Object[] )      at
> System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
> instance, Object[] inputs, Object[]& outputs)      at
> System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
> rpc)      at
> System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&
> rpc)      at
> System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&
> rpc)      at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
> isOperationContextSet))..

Claims Authentication Unexpected:

No windows identity for DOMAIN\USER.

A: As i mentioned in the comment, This error is typically due to issue with Claims to token Service.Please make sure following things

*

*from central admin > manager services on server make sure CTS is running on all server in the farm.

*if not running start it.

*If running then restart them.


text:
Q: Stop AVPlayer video when a new UITableViewCell is selected I want to show a video accordingly to the selected cell in my tableview. I want to show the video in a view in my vc.
The following code is showing the correct videos when the cells are tapped but whenever i select a new cell the audio from the old video is still there. How can i remove it ?
Setting up the view in my vc:
    func setupView(for url: URL) {
        let player = AVPlayer(url: url)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.videoView.bounds
        self.videoView.layer.addSublayer(playerLayer)
        player.play()
    }

didSelectRow code:
 let selectedExercise = exercises[indexPath.row]
        setupView(for: URL(string: selectedExercise.videoUrl)!)

My guess is that i should pause/stop the previous video before showing the new one. But i don't know how to.
Thanks a lot!

A: It's happend because you create new instance of AVPlayer every tap.
To solve your problem, you need to move
let player = AVPlayer(url: url)
outside of setupView() and call it only once. You could move it in init() for example.
For updating asset (video url) in setupView() you could use
player.replaceCurrentItem(with: AVPlayerItem(url: url))
.


text:
Q: Build a proper dataframe from a matrix list after importing .xlsx file Implemented:
I am importing a .xlsx file into R.
This file consists of three sheets.
I am binding all the sheets into a list.
Need to Implement
Now I want to combine this matrix lists into a single data.frame. With the header being the --> names(dataset).
I tried using the as.data.frame with read.xlsx as given in the help but it did not work.
I explicitly tried with as.data.frame(as.table(dataset)) but still it generates a long list of data.frame but nothing that I want.
I want to have a structure like
header = names and the values below that, just like how the read.table imports the data.
This is the code I am using:
    xlfile <- list.files(pattern = "*.xlsx")
    wb <- loadWorkbook(xlfile)
    sheet_ct <- wb$getNumberOfSheets()
    b <- rbind(list(lapply(1:sheet_ct, function(x) {
             res <- read.xlsx(xlfile, x, as.data.frame = TRUE, header = TRUE)
})))
    b <- b [-c(1),] # Just want to remove the second header

I want to have the data arrangement something like below.
Ei  Mi  hours   Nphy    Cphy    CHLphy  Nhet    Chet    Ndet    Cdet    DON DOC DIN DIC AT  dCCHO   TEPC    Ncocco  Ccocco  CHLcocco    PICcocco    par Temp    Sal co2atm  u10 dicfl   co2ppm  co2mol  pH
1   1   1   1   0.1023488   0.6534707   0.1053458   0.04994161  0.3308593   0.04991916  0.3307085   0.05042275  49.76304    14.99330000 2050.132    2150.007    0.9642220   0.1339044   0.1040715   0.6500288   0.1087667   0.1000664   0.0000000   9.900000    31.31000    370 0.01    -2.963256000    565.1855    0.02562326  7.879427
2   1   1   2   0.1045240   0.6448216   0.1103250   0.04988347  0.3304699   0.04984045  0.3301691   0.05085697  49.52745    14.98729000 2050.264    2150.007    0.9308690   0.1652179   0.1076058   0.6386706   0.1164099   0.1001396   0.0000000   9.900000    31.31000    370 0.01    -2.971632000    565.7373    0.02564828  7.879042
3   1   1   3   0.1064772   0.6369597   0.1148174   0.04982555  0.3300819   0.04976363  0.3296314   0.05130091  49.29323    14.98221000 2050.396    2150.007    0.8997098   0.1941872   0.1104229   0.6291149   0.1225822   0.1007908   0.8695131   9.900000    31.31000    370 0.01    -2.980446000    566.3179    0.02567460  7.878636
4   1   1   4   0.1081702   0.6299084   0.1187672   0.04976784  0.3296952   0.04968840  0.3290949   0.05175249  49.06034    14.97810000 2050.524    2150.007    0.8705440   0.2210289   0.1125141   0.6213265   0.1273103   0.1018360   1.5513170   9.900000    31.31000    370 0.01    -2.989259000    566.8983    0.02570091  7.878231
5   1   1   5   0.1095905   0.6239005   0.1221460   0.04971029  0.3293089   0.04961446  0.3285598   0.05220978  48.82878    14.97485000 2050.641    2150.007    0.8431960   0.2459341   0.1140222   0.6152447   0.1308843   0.1034179   2.7777070   9.900000

Please dont suggest me to have all data on a single sheet and also convert .xlsx to .csv or simple text format. I am trying really hard to have a proper dataframe from a .xlsx file.
Following is the file
And this is the post following : Followup
This is what resulted:
str(full_data)
'data.frame':   0 obs. of  19 variables:
 $ Experiment : Factor w/ 2 levels "#","1":
 $ Mesocosm   : Factor w/ 10 levels "#","1","2","3",..:
 $ Exp.day    : Factor w/ 24 levels "1","10","11",..:
 $ Hour       : Factor w/ 24 levels "108","12","132",..:
 $ Temperature: Factor w/ 125 levels "10","10.01","10.02",..:
 $ Salinity   : num
 $ pH         : num
 $ DIC        : Factor w/ 205 levels "1582.2925","1588.6475",..:
 $ TA         : Factor w/ 117 levels "1813","1826",..:
 $ DIN        : Factor w/ 66 levels "0.2","0.3","0.4",..:
 $ Chl.a      : Factor w/ 156 levels "0.171","0.22",..:
 $ PIC        : Factor w/ 194 levels "-0.47","-0.96",..:
 $ POC        : Factor w/ 199 levels "-0.046","1.733",..:
 $ PON        : Factor w/ 151 levels "1.675","1.723",..:
 $ POP        : Factor w/ 110 levels "0.032","0.034",..:
 $ DOC        : Factor w/ 93 levels "100.1","100.4",..:
 $ DON        : Factor w/ 1 level "µmol/L":
 $ DOP        : Factor w/ 1 level "µmol/L":
 $ TEP        : Factor w/ 100 levels "10.4934","11.0053",..:

  [Note: Above is the structure after reading from .xlsx file......the levels makes the calculation and manipulation part tedious and messy.]

This is what I want to achieve:

str(a)

'data.frame':   9936 obs. of  29 variables:
 $ Ei      : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Mi      : int  1 1 1 1 1 1 1 1 1 1 ...
 $ hours   : int  1 2 3 4 5 6 7 8 9 10 ...
 $ Cphy    : num  0.653 0.645 0.637 0.63 0.624 ...
 $ CHLphy  : num  0.105 0.11 0.115 0.119 0.122 ...
 $ Nhet    : num  0.0499 0.0499 0.0498 0.0498 0.0497 ...
 $ Chet    : num  0.331 0.33 0.33 0.33 0.329 ...
 $ Ndet    : num  0.0499 0.0498 0.0498 0.0497 0.0496 ...
 $ Cdet    : num  0.331 0.33 0.33 0.329 0.329 ...
 $ DON     : num  0.0504 0.0509 0.0513 0.0518 0.0522 ...
 $ DOC     : num  49.8 49.5 49.3 49.1 48.8 ...
 $ DIN     : num  15 15 15 15 15 ...
 $ DIC     : num  2050 2050 2050 2051 2051 ...
 $ AT      : num  2150 2150 2150 2150 2150 ...
 $ dCCHO   : num  0.964 0.931 0.9 0.871 0.843 ...
 $ TEPC    : num  0.134 0.165 0.194 0.221 0.246 ...
 $ Ncocco  : num  0.104 0.108 0.11 0.113 0.114 ...
 $ Ccocco  : num  0.65 0.639 0.629 0.621 0.615 ...
 $ CHLcocco: num  0.109 0.116 0.123 0.127 0.131 ...
 $ PICcocco: num  0.1 0.1 0.101 0.102 0.103 ...
 $ par     : num  0 0 0.87 1.55 2.78 ...
 $ Temp    : num  9.9 9.9 9.9 9.9 9.9 9.9 9.9 9.9 9.9 9.9 ...
 $ Sal     : num  31.3 31.3 31.3 31.3 31.3 ...
 $ co2atm  : num  370 370 370 370 370 370 370 370 370 370 ...
 $ u10     : num  0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 0.01 ...
 $ dicfl   : num  -2.96 -2.97 -2.98 -2.99 -3 ...
 $ co2ppm  : num  565 566 566 567 567 ...
 $ co2mol  : num  0.0256 0.0256 0.0257 0.0257 0.0257 ...
 $ pH      : num  7.88 7.88 7.88 7.88 7.88 ...

[Note: sorry for the extra columns, this is another dataset (simple text), which I am reading from read.table]
With NA's handled:
> unique(mydf_1$Exp.num)
[1] # 1
Levels: # 1
> unique(mydf_2$Exp.num)
[1] # 2
Levels: # 2
> unique(mydf_3$Exp.num)
[1] # 3
Levels: # 3
> unique(full_data$Exp.num)
[1] 2 3 4

Without handling NA's:
> unique(full_data$Exp.num)
[1]  1 NA  2  3
> unique(full_data$Mesocosm)
 [1]  1  2  3  4  5  6  7  8  9 NA

A: I think this is what you need. I add a few comments on what I am doing:
xlfile <- list.files(pattern = "*.xlsx")
wb <- loadWorkbook(xlfile)
sheet_ct <- wb$getNumberOfSheets()
for( i in 1:sheet_ct) {    #read the sheets into 3 separate dataframes (mydf_1, mydf_2, mydf3)
  print(i)
  variable_name <- sprintf('mydf_%s',i)
  assign(variable_name, read.xlsx(xlfile, sheetIndex=i,startRow=1, endRow=209)) #using this you don't need to use my formula to eliminate NAs. but you need to specify the first and last rows.
}

colnames(mydf_1) <- names(mydf_2) #this here was unclear. I chose the second sheet's
# names as column names but you can chose whichever you want using the same (second and third column had the same names).

#some of the sheets were loaded with a few blank rows (full of NAs) which I remove
#with the following function according to the first column which is always populated
#according to what I see
remove_na_rows <- function(x) {
  x <- x[!is.na(x)]
  a <- length(x==TRUE)
}

mydf_1 <- mydf_1[1:remove_na_rows(mydf_1$Exp.num),]
mydf_2 <- mydf_2[1:remove_na_rows(mydf_2$Exp.num),]
mydf_3 <- mydf_3[1:remove_na_rows(mydf_3$Exp.num),]

full_data <- rbind(mydf_1[-1,],mydf_2[-1,],mydf_3[-1,]) #making one dataframe here
full_data <- lapply(full_data,function(x) as.numeric(x)) #convert fields to numeric
full_data2$Ei <- as.integer(full_data[['Ei']]) #use this to convert any column to integer
full_data2$Mi <- as.integer(full_data[['Mi']])
full_data2$hours <- as.integer(full_data[['hours']])

#*********code to use for removing NA rows *****************
#so if you rbind not caring about the NA rows you can use the below to get rid of them
#I just tested it and it seems to be working

n_row <- NULL
for ( i in 1:nrow(full_data)) {
  x <- full_data[i,]
  if ( all(is.na(x)) ) {
    n_row <- append(n_row,i)
  }
}

full_data <- full_data[-n_row,]

I think now this is what you need


text:
Q: Is there a way that I can auto filter a table in VBA based on a cell value? I have a cell V2 which has a number. I want to filter a column in my table so that the values in that column are equal or greater to that value. So if cell V2 contains 5, then the rows in the specific column will all have value 5 or greater.
My current VBA code only seems to filter for exact values, not greater than values. I've tried adding ">=" under the criteria in different places but each time, the syntax is wrong.
Worksheets("Scores").ListObjects("MyDatabase").Range.AutoFilter Field:=19, Criteria1:= _
Worksheets("Scores").Range("V2").Value

A: You can use:
Worksheets("Scores").ListObjects("MyDatabase").Range.AutoFilter Field:=19, Criteria1:= _
">=" & Worksheets("Scores").Range("V2").Value


text:
Q: Android application Online and offline I have to create an android application which shows some reports and images in Recycler view using json volley request   it works when internet is available    i also need to show the once loaded data in recycler view when internet is not available  here is the code i used to select data when internet is available
 JsonObjectRequest jsObjRequest = new JsonObjectRequest
                    (Request.Method.GET, Config.DATA_URL, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                String str = response.toString();

                                                               loading.hide();
                                JSONArray arr =     response.getJSONArray("Stock_Report");

                                parseData(arr);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            // now you have the array. in this array you have the jsonObjects
                            // iterate on this array using a for loop and parse like you did before
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub

                        }
                    });

            //Creating request queue
            RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());

            //Adding request to the queue
            requestQueue.add(jsObjRequest);
        }

please help me to find better solution to show this data when internet is not available also thanks in advance


text:
Q: Elasticsearch: Intuitive Date Search I have a dt_birth property of type date. I would like to be able to search for a date in different ways. For example 1/13/1992, 01/13/1992, 1-13-1992, January 13, 1992. How could I go about this? Currently I can only search by the format I have implemented bellow:
dt_birth: {
  type: 'date',
  format: 'strict_date_optional_time||epoch_millis'
},

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
UPDATE: I am having a few issues comprehending this.
for the dt_birth format:
dt_birth: {
  type: 'date',
  format: 'strict_date_optional_time||epoch_millis'
}

How does the format specified above 'strict_date_optional_time||epoch_millis' effect the query format specified below:
{
  "query": {
    "range": {
      "dt_birth": {
        "gte": "01/13/1992",
        "lte": "1-13-1992",
        "format": "d/MM/yyyy||dd/MM/yyyy||d-MM-yyyy||dd-MM-yyyy"
      }
    }
  }
}

Also, I'm a bit confused when you say add the date formats you need to support. How does the format correspond to the LTE and GTE? For example I would like to accept the date format January 15, 2000 - 1/15/2000 - 01/15/200 - 1-15-2000 - 01-15-2000. If I have 5 different formats I wish to support would that mean I would need 5 GTE/LTE? These last two questions are the most confusing. I appreciate any help :)

A: The definition of your dt_birth field contains the date format that ES expects to find in your document when you index it, so that it can retrieve the number of milliseconds (as a long) and index that.
At query time, you have the option to search by date by specifying any other date format using the format property of the range query:
{
  "query": {
    "range": {
      "dt_birth": {
        "gte": "01/13/1992",
        "lte": "1-13-1992",
        "format": "d/MM/yyyy||dd/MM/yyyy||d-MM-yyyy||dd-MM-yyyy"
      }
    }
  }
}

or
{
  "query": {
    "range": {
      "dt_birth": {
        "gte": "1/13/1992",
        "lte": "January 13, 1992",
        "format": "d/MM/yyyy||MMMM dd, yyyy"
      }
    }
  }
}

You can simply add all the date formats you need to support at query time in the format property and then simply fill the gte and lte properties with the appropriate dates. ES will happily parse them.


text:
Q: Dynamically set visibility of Controls in asp:repeater I have 3 tables in database
students_login,
interview_events,
interested_students,
student_login has unique :- student_id,
interview_events has unique :- id,
interested_students has unique :- id,  student_id, interview_id.
so on an interview.aspx page am showing the interviews. just like this mdl-card. which have a button(yes am going). so clicking on this button i want to update the interested_student table by storing student_id and interview_id.And also after click the Button should hide and a message appears "success".
If a student again came on interview.aspx page then the button on the card should not be visible.
I tried so many things but not getting to work
my aspx.cs page
<asp:Repeater ID="Repeater1" runat="server">
  <ItemTemplate>
     <asp:Label ID="lbl_company_name" runat="server" Text='<%# Eval("company_name") %>'></asp:Label>
     <asp:Label ID="lbl_description" runat="server" Text='<%# Eval("description") %>'></asp:Label></b>
     <asp:Label ID="lbl_event_date" runat="server" Text='<%# "Date :"+Convert.ToDateTime(Eval("event_date")).ToString("dd/MMM/yyyy") %>'></asp:Label>
     <asp:Label ID="lbl_min_Ty" runat="server" Text=<%#"Minimum Aggregate of All Sems :"+ Eval("min_ty_per")+" %" %>></asp:Label>
     <asp:Label ID="lbl_min_hsc" runat="server" Text=<%#"Minimum Hsc Percentage : "+ Eval("min_hsc_per")+" %" %>></asp:Label>
     <asp:Label ID="lbl_min_ssc" runat="server" Text=<%#"Minumum SSC Percentage : "+ Eval("min_ssc_per")+" %" %>></asp:Label>
     <asp:Label ID="lbl_backlogs" runat="server" Text='<%#"Allowed Live Backlogs : "+ Eval("backlogs") %>'></asp:Label>
     <asp:HiddenField ID="hf_event_id" runat="server" Value=<%# Eval("id") %>></asp:HiddenField>
     <asp:HiddenField ID="hf_intreseted" runat="server" Value=<%# Eval("intrested") %>></asp:HiddenField>
     <asp:Label ID="lbl_already_intrested" runat="server" Text="You are Going To This Interview"></asp:Label>
     <asp:Button Text="Yes am Going" runat='server' ID="btn_intrested" OnClick="btn_Intrested_Click"></asp:Button>
     <asp:Label ID="lbl_status" runat="server" Text=""></asp:Label>
     <asp:Label ID="Label1" runat="server" Text=<%#Eval("intrested") %>></asp:Label>
  </ItemTemplate>
</asp:Repeater>

.cs page:
public partial class InterviewDetails : System.Web.UI.Page
{
    //List<int> intrested_event = new List<int>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["student_username"] != null)
            {
                fetchInterviews();
            }
            else {
                Response.Redirect("studentLogin.aspx");
            }
        }
    }

    private void fetchInterviews()
    {
        //fetch both the tables interviews as well as interested
        DataSet ds = DataAccessLayer.fetchInterviewsEvents(Session["student_username"].ToString());
        DataTable dt_interview = ds.Tables[0];//interview table
        dt_interview.Columns.Add("intrested",typeof(bool));//added a column

        DataTable dt_intrested = ds.Tables[1];//interested table

        //this code is to insert true or false in the column we have created above
        if (dt_intrested.Rows.Count > 0)//check if the student have not interested in any interview or coming for first time
        {
            foreach (DataRow dr_intrested in dt_intrested.Rows)
            {
                //interested_event.Add(Convert.ToInt32(dr_intrested.ItemArray[1]));
                foreach (DataRow dr_interview in dt_interview.Rows)
                {
                    //check if the interested table has the interiew_id
                    if (Convert.ToInt32(dr_intrested["interview_id"]) == Convert.ToInt32(dr_interview["id"]))
                    {
                        dr_interview["intrested"] = true;//student is intereseted
                    }
                    else
                    {
                        dr_interview["intrested"] = false;//student is not interested
                    }
                }
            }
        }
        else {
            foreach (DataRow dr_interview in dt_interview.Rows)
            {
                dr_interview["intrested"] = false;//make all value false if he is coming first time or not interested in avy interview
            }
        }
        Repeater1.DataSource = ds.Tables[0];
        Repeater1.DataBind();
    }

    protected void btn_Intrested_Click(object sender, EventArgs e)
    {
        var button = (Button)sender;
        var item = (RepeaterItem)button.NamingContainer;
        HiddenField hf_event_id = (HiddenField)item.FindControl("hf_event_id");
        int event_id = Convert.ToInt32(hf_event_id.Value);
        Label lbl_company_name = (Label)item.FindControl("lbl_company_name");
        Label lbl_description = (Label)item.FindControl("lbl_description");
        Label lbl_event_date = (Label)item.FindControl("lbl_event_date");
        Label lbl_min_Ty = (Label)item.FindControl("lbl_min_Ty");
        Label lbl_min_hsc = (Label)item.FindControl("lbl_min_hsc");
        Label lbl_min_ssc = (Label)item.FindControl("lbl_min_ssc");
        Label lbl_backlogs = (Label)item.FindControl("lbl_backlogs");
        Label lbl_status = (Label)item.FindControl("lbl_status");
        string error;
        //Label2.Text = event_id.ToString() +" "+ lbl_company_name.Text + " " + lbl_description.Text + " " + lbl_event_date.Text + " " + lbl_min_Ty.Text + " " + lbl_min_hsc.Text + " " + lbl_min_ssc.Text + " " + lbl_backlogs.Text;
        //submitting data to database
        if (DataAccessLayer.addStudentToIntrested(Session["student_username"].ToString(), event_id, out error))
        {
            if (error == null)
            {
                button.Visible = false;
                lbl_status.Text = "You are Going To This Interview";
            }
            else
            {
                lbl_status.Text = error;
            }
        }
        else
        {
            lbl_status.Text = "Some Error Occured";
        }
    }

    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item)
        {
            Button btn_intrested = (Button)e.Item.FindControl("btn_intrested");
            Label lbl_already_intrested = (Label)e.Item.FindControl("lbl_already_intrested");
            //HiddenField hf_event_id = (HiddenField)e.Item.FindControl("hf_event_id");
            HiddenField hf_intrested = (HiddenField)e.Item.FindControl("hf_event_id");
            //int event_id = Convert.ToInt32(hf_event_id.Value);
            bool intrested = Convert.ToBoolean(hf_intrested.Value);
            if (intrested == true)
            {
                btn_intrested.Visible = false;
                lbl_already_intrested.Visible = true;
            }
            else
            {
                btn_intrested.Visible = true;
                lbl_already_intrested.Visible = false;
            }

        }
    }
}


text:
Q: having issue while trying to use model route binding with laravel By using this code I'm trying to return the post from posts table which has the same id by {post}.
Route::model('posts', 'Posts');
Route::get('post/{post}', function(Posts $post){
    return $post;
});

But It returns:
Argument 1 passed to {closure}() must be an instance of Posts, string given

What's the problem? (I'm a beginner)

A: The name in Route::model needs to match the parameter in your route:
Route::model('post', 'Posts');
Route::get('post/{post}', function(Posts $post){
    return $post;
});


text:
Q: #define EXIT_SUCCESS 0 I was looking at a program that calculates the average of 3 numbers and came across
#define EXIT_SUCCESS 0

to make return EXIT_SUCCESS; work without an error (right under the include header). What is the purpose of using #define EXIT_SUCCESS 0 and return EXIT_SUCCESS; and is there any alternative to this? Is it like return 0;? Thank you for your time.
Here is the code for the program I was looking at:
#include <iostream>
#define EXIT_SUCCESS 0
using namespace std;

int main()
{
// prototypes:

float add_and_div(float, float, float);

// variables:

float x, y, z;
float result;

cout << "Enter three floats: ";
cin >> x >> y >> z;

// continue the program here

result = add_and_div( x, y, z );
cout<< "Average is \n" << result;

return EXIT_SUCCESS;
}

// function definition:

float add_and_div(float n1, float n2, float n3)
{

// continue the program here
return ( n1 + n2 + n3 ) / 3;
}

A: The macros EXIT_SUCCESS and EXIT_FAILURE expand into integral expressions that either indicate successful or unsuccessful execution of the program. They're part of the C standard and can be found in stdlib.h or rather cstdlib.
In your case it will expand to 0, so return EXIT_SUCCESS is the same as return 0. However, the macro is already defined in the standard library, so you should use that one instead of defining your own. Note that returning or using EXIT_SUCCESS in exit will have the same behavior as using 0 at those occurrences, so it's up to you what you want to use.

A: As others have noted, EXIT_SUCCESS is defined in <cstdlib>. Presumably the author was simply unaware of this. Moreover it is not guaranteed to be zero, but an "integer constant expression that can be used as the argument to the exit function to return … successful termination status … to the host environment." (C11 §7.22/3) Therefore the compiler can complain about the custom #define conflicting with the macro definition in <cstdlib>.
In practice, it is always zero though. Even if it's not, zero is also guaranteed to mean success.
It's a matter of style, but most prefer to write no return statement at all at the end of main. In both C++ and recent editions of C, a return 0; is added automatically in this case.

A: Yes it is the same. #define basically tells the compiler to switch,when they are referred, with it's value.
Example:
Code:
#define HELLO 0
#define WORLD "WORLD"

cout << HELLO;
cout << WORLD;

The compiler will then change it to:
cout << 0;
cout << "WORLD";

It's much more safe to use defines because you can easily change one value that changes the whole program than changing the whole program directly.
Also, defines are constant values. It also does not matter if it's an integer value, float, string or even a structure reference. And, because of being constant, defines can never be changed after the program execution (like in functions).

A: As per C++11 3.6.1 Main function /5:

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument.

In 18.5 Start and termination /8, it states, with regards to exit:

If status is _zero or EXIT_SUCCESS,_ an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

In other words, returning either 0 or EXIT_SUCCESS has the same effect here so you would be better off returning the literal 0, which every competent C or C++ coder knows indicates a successful termination of the program.
If you really want to use EXIT_SUCCESS, you should be including the one in <cstdlib> rather than creating your own. The standard specifically disallows otherwise, as per 17.6.4.3.1 Macro names /1:

A translation unit that includes a standard library header shall not #define or #undef names declared in any standard library header.

The fact that you're including a standard header file iostream means that you are not permitted to define EXIT_SUCCESS yourself.


text:
Q: Android Parsing Same variable object name in retrofit I had seen many examples regarding retrofit.And I had Done too most of like listview but this is something new which I am not finding easily.I am using retrofit2.Here it has same name details first is simple object and other have nested object and I am bit confuse how to parse it.It is alogin form First it checks details if it is one then it goes further.
[
 {
"title": "success",
"details": "1"
},
{
"title": "data",
"details": {
  "EMPLOYEE_ID": 5,
  "FIRST_NAME": "ABHISHEK",
  "LAST_NAME": "BARDOLIA"

  }
 }
]

Here is the Interface used in login purpose.
  public interface LoginInterface {
  @GET("Login")
  Call<List<ClsLogin>> Login(@Query("username") String username
        , @Query("password") String password
        , @Query("imei") String imei);
}

Model Class:
     public class ClsLogin {
@SerializedName("title")
String title;

@SerializedName("details")
String details;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDetails() {
    return details;
}

public void setDetails(String details) {
    this.details = details;
 }
}

Response Code:
public static void login(final LoginCallback logincallback, ClsLogin ObjLogin) {
    LoginInterface apiLoginService = ApiClient.getClient().create(LoginInterface.class);

    Call<List<ClsLogin>> call = apiLoginService.Login(
            ObjLogin.getUsername(),
            ObjLogin.getPassword(),
            ObjLogin.getImei());
    Log.e("response", String.valueOf(call.request().url()));

call.enqueue(new Callback<List<ClsLogin>>() {
    @Override
    public void onResponse(Call<List<ClsLogin>> call, Response<List<ClsLogin>> response) {
        Log.e("response", "onResponse ");
    }

    @Override
    public void onFailure(Call<List<ClsLogin>> call, Throwable t) {
        Log.e("response", t.getLocalizedMessage());
    }
});

}

A: you can see how GsonConverterFactory parsing data:
  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
  Retrofit retrofit) {
     TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
     return new GsonResponseBodyConverter<>(adapter);
}

how GsonResponseBodyConverter works:
    @Override public T convert(ResponseBody value) throws IOException {
    try {
      return adapter.fromJson(value.charStream());
    } finally {
      value.close();
    }
  }

so you can write your own ResponseBodyConverter to differentiate between data and the status code,you just have to override the convert method.
because,GsonConverterFactory and GsonRequestBodyConverter are finnal class,you should copy them in your project.And you should code your Custom GsonResponseBodyConverter:
 final class CusGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final TypeAdapter<T> adapter;
    private final Gson gson;

    CusGsonResponseBodyConverter(TypeAdapter<T> adapter) {
        this.adapter = adapter;
        this.gson = new Gson();
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        //get the response string data
        String response = value.string();

        //in there,you can check your data
        // for exp,you can catch the exception and return the entity with error flag
        //or just return the gson entity,like this:
        MediaType contentType = value.contentType();
        Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
        InputStream inputStream = new ByteArrayInputStream(response.getBytes());
        Reader reader = new InputStreamReader(inputStream, charset);
        JsonReader jsonReader = gson.newJsonReader(reader);

        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}


text:
Q: Is there a way to combine parameters to the HttpGet method into an object? I have the following method in my controller.
[HttpGet]
public ActionResult MyGetMethod(string address, string zip, int width) {...}

It's called via http://foo.com/home/MyGetMethod?address=234MainSt&zip=90210&width=123
Is there a way to combine the parameters address, zip and width into an object and have object be passed in to the method in the following manner?
[HttpGet]
public ActionResult MyGetMethod(Foo myParam) {...}

public class Foo {
   public string Address {get; set;}
   public string Zip {get; set;}
   public int Width {get; set;}
}

There is a vaguely related question for the old ASP.NET MVC that seems to suggest that this is impossible for that technology.
Is it possible with the .NET Core 2.x?

A: your data in queryString so you need provider[FromQuery]

[FromQuery]

[HttpGet]
public ActionResult MyGetMethod([FromQuery]Foo myParam) {...}

public class Foo {
   public string Address {get; set;}
   public string Zip {get; set;}
   public int Width {get; set;}
}


text:
Q: Showing that $f(x) \leq 0$ on an interval Let $m \in (0,1)$ and $k \in \mathbb{N}$, and consider
$$f(x) = \frac{1}{k^{m+1}} \frac{1-m}{2(m+1)} - \frac{1-m}{m}\frac{1}{k^m}x.$$
Is there any easy way to show that $f(x) \leq 0$ when $x \in (\frac{1}{k}, k)$?
I can just about do it by graphing but it is painful!!

A: Since $x>\frac{1}{k}$ you have
$$f(x) < \frac{1}{k^{m+1}} \frac{1-m}{2m+2} - \frac{1-m}{m} \frac{1}{k^m} \frac{1}{k} \\
= \frac{\frac{1-m}{2m+2} - \frac{1-m}{m}}{k^{m+1}}$$
because $f$ is decreasing (it has a negative slope).
Now you just need to show that the numerator is negative. You can prove this formally by getting a common denominator in the big numerator. Intuitively it should be true because you have the same (positive) numerators in the big numerator, so the first fraction is smaller than the second because it has the larger denominator.

A: You have $f(x)=ax+b$.
If $a<0$ then $f(x)\le0$ whenever $x\ge\dfrac{-b}a$.
If $a>0$ then $f(x)\le0$ whenever $x\le\dfrac{-b}a$.

A: This is just algebra really. Let's just make the expression more palatable.
$$f(x) = \frac{1}{2}\frac{1}{k^{m+1}}\frac{1-m}{m+1} - \frac{1}{k^m}\frac{1-m}{m}x$$
Since $k > 0$ we may multiply by $k^m$ without affecting the sign.
$$\frac{1}{2k}\frac{1-m}{m+1} - \frac{1-m}{m}x$$
And $1-m > 0$ so similarly you can cancel this without affecting the sign.
$$\frac{1}{2k}\frac{1}{m+1} - \frac{1}{m}x$$
Can you show that expression is nonpositive? I would multiply out the denominator (which is positive) next.

A: You can simplify:
$$f(x) = \frac{1-m}{k^m}\left(\frac{1}{2k(m+1)} - \frac{x}{m}\right)$$
or
$$f(x) = \frac{1-m}{k^m}\frac{m - 2k(m+1)x}{2km(m+1)}.$$
The first term is always positive, and so is the denominator in the second term. So this is negative exactly when
$$2k(m+1)x > m$$
or
$$x > \frac{1}{2k}\frac{m}{m+1}.$$
Since $\frac 1 k > \frac 1 2 \frac{m}{m+1} \frac 1 k$,
this always holds in the given interval $\left(\frac 1 k, k\right)$.


text:
Q: C# Event Handlers How can I check in C# if button.Click event has any handlers associated?
If (button.Click != null) throws compile error.

A: You can't. Events just expose "add a handler" and "remove a handler" - that's all. (In fact in the CLR you can also have metadata to associate a method with "fire the event" but the C# compiler never generates that.) Some event publishers may offer additional means to check whether or not there are any subscribers (or indeed let you see those subscribers) but it's not part of the event pattern itself.
See my article about events for more information, or look at the events tag (which I'm about to add to this question).

A: Why do you need this? What is the context? Maybe there's a better way to achieve the result
The button is an external object and what you're trying to do is check is its internal list of subscribers without asking it. It's violating encapsulation..
You should always let the object manage the subscribers for the events it exposes. If it wanted clients to be aware, it would have exposed a method HasClientsRegistered. Don't break in.

A: I think you can if you are in the class that raises the event.
You can define the handler and enumerate each.
e.g.  If your event is defined as
event System.EventHandler NewEvent;

Then on the raise event method you might create you can do...
    EventHandler handler = NewEvent;
    if(handler != null)
    {
      handler(this, e);
    }

That will give you the handler and from that you can get the Invocation List.

A: EventDescriptor e = TypeDescriptor.GetEvents(yourObject).Find("yourEventName", true);


text:
Q: View in areas cannot be located - Visual Studio 2015, C#, ASP.NET MVC 5 I've found many topic and suggestions on this and I think I've tried all of the combinations.
I had a working application that is going to grow larger so I decided to make use of areas. I sloughed through that and can access the controllers but then the application fails when it tries to return data to a view. I created a test data context, classes, etc. then to be sure that it wasn't something that I did wrong when moving into areas.
It's probably best to work through the somewhat smaller test situation and then apply what works to the larger actual application.
My link from _Layout.cshtml:

@Html.ActionLink("Test", "Index", "testclasses")

My model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Tracking.Areas.test.Models
{
    public class testclass
    {
        public int ID { get; set; }
    }
}

My testAreaRegistration:
using System.Web.Mvc;

namespace Tracking.Areas.test
{
    public class testAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "test";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "test_default",
                //"test/{controller}/{action}/{id}",
                "test/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

My test controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tracking.Areas.test.Models;
using Tracking.DAL.Test;

namespace Tracking.Areas.test.Controllers
{
    [RouteArea("test")]
    public class testclassesController : Controller
    {
        private testcontext db = new testcontext();

        // GET: test/testclasses
        public async Task<ActionResult> Index()
        {
            return View(await db.spas.ToListAsync());
        }

        // GET: test/testclasses/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            testclass testclass = await db.spas.FindAsync(id);
            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // GET: test/testclasses/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: test/testclasses/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "ID")] testclass testclass)
        {
            if (ModelState.IsValid)
            {
                db.spas.Add(testclass);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(testclass);
        }

        // GET: test/testclasses/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            testclass testclass = await db.spas.FindAsync(id);
            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // POST: test/testclasses/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "ID")] testclass testclass)
        {
            if (ModelState.IsValid)
            {
                db.Entry(testclass).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(testclass);
        }

        // GET: test/testclasses/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            testclass testclass = await db.spas.FindAsync(id);

            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // POST: test/testclasses/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            testclass testclass = await db.spas.FindAsync(id);
            db.spas.Remove(testclass);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

My RouteConfig file
namespace Tracking
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

My Global.asax.cs file
namespace Tracking
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

I've tried with and without [RouteArea("test")] in the controller; I've tried multiple options with adding a controller to the area registration file, removing the area name from in front of controller in the area registration file, and many other combinations.
The code finds the controller and model as I put breakpoints in those and reach them - when it attempts to return the view I get the error message about the index view not being found in the standard locations - it doesn't search within the areas at all.
Thanks!

A: I think you have an inconsistence in your "convention over configuration" setup. Might be helpful to add the error message and your solution structure. You should check, for example, that the Index.cshtml is found in the Areas\test\Views\testclasses folder. The only thing that I see at a first glance is that you didn't modify your action link to include the area. You should try:
@Html.ActionLink("Test", "Index", "testclasses", new { Area = "test" }, new{})

P.S.> I would recommend using camel case notation for the class names and areas... you know, for the clean code sake. Not to mention that you never know when you might stumble upon a case sensitive convention....


text:
Q: I need any app or any website by the help of that i can easily download the mp3 or video songs or movie from Youtube.com Looking for a app for ubuntu 14.04
I need a app to download the songs and video from  youtube.com.
Is there any way to get the sign of download on youtube while watching any favourite songs or videoes?
In my friends computer the download option comes on youtube while watching any movie or song on youtube.com,  he was using Windows7. But I am using Ubuntu 14.04 LTS.
By clicking on download, he was able to download that songs from youtube directly?
I need a best app or website in Ubuntu to download the songs from youtube.com

A: If you are using Firefox as your browser then there is an extension you can install.
Download YouTube Videos as MP4 what i use however for mp3 they also have,
Youtube MP3 Downloader using youtube.
Hope this helps.

A: Using youtube-dl and a youtube-dlg
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install youtube-dl
sudo apt-get install youtube-dlg

to download videos and mp3 via GUI or command line.
The PPA is updated more frequently so that one is the preferred source.

More details here and here.


text:
Q: How to set strong parameter for many to many relationship I have a model Word that has many to many relation Translation through junction table word_to_words.
The Translation is Word class itself.
These are source code for it.
app/models/word.rb
class Word < ApplicationRecord
  has_many :word_to_words
  has_many :translations, through: :word_to_words
end

app/models/word_to_word.rb
class WordToWord < ApplicationRecord
  belongs_to :word
  belongs_to :translation, class_name: 'Word'
end

app/views/words/_form.html.erb
<%= form_for(word) do |f| %>
  <%= f.text_field :name %>
  <%= f.fields_for :translations, word.translations.build do |q| -%>
    <%= q.text_field :name %>
  <% end -%>
  <%= f.submit %>
<% end %>

app/controllers/words_controller.rb
def word_params
  params.require(:word).permit(:name, :pronunciation,
                               word_to_words_attributes: [:word_id, :translation_id],
                               translations_attributes: [:id, :name]
  )
end

When I create a new word, the translation variable are rejected with error Unpermitted parameter.
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx", "word"=>{"name"=>"foo", "translations"=>{"name"=>"bar"}}, "commit"=>"Create Word"}
Unpermitted parameter: translations

I think this is because my strong parameter configuration is wrong.
How should I set the strong parameter?

A: you should use nested_attributes.
class Word < ApplicationRecord
  has_many :word_to_words
  has_many :translations, through: :word_to_words
  accepts_nested_attributes_for :translations
end

And the migration canbe:
class CreateWordToWords < ActiveRecord::Migration[5.0]
  def change
    create_table :word_to_words do |t|
      t.belongs_to :word, index: true, foreign_key: true
      t.belongs_to :translation, index: true, foreign_key: true

      t.timestamps
    end
  end
end


text:
Q: How to search exact index (not index pattern) in elasticsearch eland? I am calling elasticsearch data using eland. The documentation is simple and I am able to implement it, but when searching the index it search using es_index_pattern which is basically a wildcard index-string.
from elasticsearch import ElasticSearch
import eland as ed

es = Elasticsearch(hosts="myhost", "port":0000)

search_body={
    "bool":{
            "filter":[
                {"exists": {"field": "customer_name"}},
                {"match_phrase": {"city": "chicago"}},
                ]
        }

    }

# I am able to get the results if I search the index through "elasticsearch" api. Tried this repetitively and it works every time
results = es.search(index="my_index", body=search_body)

# But, I do not get results (but ReadTimeoutError) if I connect to 'my_index' index via localhost Elasticsearch node using Eland
df = ed.DataFrame(es_client=es, es_index_pattern = 'my_index')

I have to hand type the error message becasue I cannot copy the error outside the environment I am using. Also, my host and port would be different
...
  File ".../elasticsearch/transport.py", line 458, in perform_request
    raise e
  File "......elasticsearch/transport.py", line 419, in perform_request
  File "..... /elasticsearch/connection/http_urllib3.py", line 275, in perform_request
    raise ConnectionTimeout("TIMEOUT", str(e), e)
elasticsearch.exceptions.ConnectionTimeout: ConnctionTimeout caused by - ReadTimeoutError(HTTPSConnectionPool(host=myhost', port=0000): Read timed out. (read timeout=10)

I think that elasticsearch is able to get results bc it's calling the exact index name and hence not running into timedout.
But, Eland is rather using es_index_pattern thereby using my_index as wildcard i.e *my_index, therefore I must be running into ReadTimeOutError.
I looked inside the source code to see if there was anything I could do, so it did not search the index as a pattern but exact match. But, I see no option for searching the exact index both in the documentation and source code.
How do I search for exact index string in Eland?
Sources:

*

*https://www.elastic.co/guide/en/elasticsearch/client/eland/current/overview.html

*https://www.elastic.co/guide/en/elasticsearch/client/eland/current/overview.html

*https://github.com/elastic/eland/blob/main/eland/ndframe.py

*https://github.com/elastic/eland/blob/main/eland/dataframe.py

A: Regardless of whether you use a wildcard or not in your index pattern the way Eland communicates with Elasticsearch is identical. So that leads me to think that your requests are timing out either due to connectivity or the request being too large to process in time on Elasticsearch (do you have a complete traceback of your timeout error?)
Perhaps increasing your request_timeout value on the Elasticsearch client constructor would help here?
(Disclaimer: I'm the maintainer of Eland and work for Elastic)


text:
Q: Rails how to render JSON as UTF-8? In my controller I have:
def index
    @title = 'asdsadas'
    @kategoris = Tag.where("name like ?", "%#{params[:q]}%")
    respond_to do |format|
    format.html
    format.json { render :json => @kategoris.map(&:attributes) }
    end
end

I created a monkey patch as the answer to this question:
JSON encoding wrongly escaped (Rails 3, Ruby 1.9.2)
But the JSON has still not the correct encoding example:
Delta i t��vlingar f��r biljetter

A: I am pretty sure that you could fix this with your database but the quick fix may be:
new_kategoris = @kategoris.map {|v| v.force_encoding('UTF-8') }
format.json { render :json => new_kategoris.map(&:attributes) }


text:
Q: Read data from Firebase database when I have multiple unique ids I'm having trouble writing in my database because I have multiple unique ids that I don't know how to access.
I know that for writing I need to use something like this:
DatabaseReference ref=database.getReference().child("Children")
ChildData data = new ChildData(fullName,age);
ref.push().setValue(data);

My database looks like this:
  {
  "Children" : {
    "55hxObZjRLY9PSZxZxGgSTRKzpc2" : {
      "-MzUih5e40OsWPF_Dj0q" : {
        "age" : "22",
        "fullName" : "Cristina "
      },
      "plays" : {
        "-MznnNih5fItYf2usXB4" : {
          "centiseconds" : "70",
          "currentDate" : "01.04.2022",
          "currentHour" : "04:23:30",
          "numberOfFails" : "5",
          "seconds" : "2"
        }
      }
    }
  },
  "Data" : {
    "id1" : {
      "centiseconds" : "70",
      "currentDate" : "01.04.2022",
      "currentHour" : "04:23:30",
      "numberOfFails" : "5",
      "seconds" : "2"
    }
  }
}

I need the "plays" child to be under "fullName" in "-MzUih5e40OsWPF_Dj0q", not as a separated child. How can I access the path without hardcoding it like this ref.child("MzUih5e40OsWPF_Dj0q").child("plays").push().setValue(data)? I will have multiple children in "Children" with different ids, I won't be able to harcode them.
Is there any function that returns the path for the unique id?
Here is the entire function:
public void writeNewData
            (String fullName,String age) {
    DatabaseReference reference = database.getReference().child("Data");
    DatabaseReference ref=myRef.push();
    ChildData data = new ChildData(fullName,age);
    ref.push().setValue(data);
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot ds : snapshot.getChildren()) {
                DatabaseReference playRef=ref.child("plays");
                DatabaseData databaseData = ds.getValue(DatabaseData.class);
                playRef.push().setValue(databaseData);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

Edit: This is my desired schema:
{
  "Children" : {
    "55hxObZjRLY9PSZxZxGgSTRKzpc2" : {
      "-MzUih5e40OsWPF_Dj0q" : {
        "age" : "22",
        "fullName" : "Cristina ",
        "plays" : {
          "-MznnNih5fItYf2usXB4" : {
            "centiseconds" : "70",
            "currentDate" : "01.04.2022",
            "currentHour" : "04:23:30",
            "numberOfFails" : "5",
            "seconds" : "2"
          }
        }
      },
    }
  },
  "Data" : {
    "id1" : {
      "centiseconds" : "70",
      "currentDate" : "01.04.2022",
      "currentHour" : "04:23:30",
      "numberOfFails" : "5",
      "seconds" : "2"
    }
  }
}

A: If you want the plays information to be a sibling of the age and fullName properties, then you will need to have a plays field/property in your ChildData class.
You'll need two classes, one to represent a "play" and one to represent a "child". At its minimum these will look like:
public class Play {
  public String centiseconds, currentDate, currentHour, numberOfFails, seconds;
}

public class Child {
  public String age, fullName;
  public Map<String, Play> plays = new HashMap<>();
}

If you read/write this class, you will get plays nested under the child's data.