text:
Q: Why isn't word allowing me to make page 2? I have a document with text boxes, its an inspection report. I would like to add a blank page to add some details. When completed the document will be printed to both sides.
However, it is not giving me the option to insert a new page. I tried to copy and paste the document into a new word file, but it doesn't even keep the formatting as it was originally.
The current page is filled right to the bottom. Hitting Enter to try and bring up a page only creates more tables on the new page. Deleting the tables deletes the whole page.
Why isn't word allowing me to make page 2?

A: Click the very last line in the table, and then press the down arrow key. The cursor should now be outside (after) the table. Press Ctrl-Enter to insert a new page.
If somehow you were still in the table when you pressed Ctrl-Enter, a new table would be created on the next page. You can delete this table without deleting the page.


text:
Q: What is wrong with this code attempting to concatenate strings in C? I am just attempting to concatenate two strings in C and I don't know why but I'm getting segfault errors.  I tracked it down using gdb to the first line in the lines of code below.
  strcat(tempString, "uptime");
  pFile = fopen (tempString,"r");

tempString is = "/proc/".  I just want to append the string "uptime" to the tempString and then attempt to open the file if it exists in the /proc folder.  When memcpy() is called by strcat() is when the actual segfault occurs.

A: You have not shown some code before these lines, but it is likely tempString is assigned using
tempString = "/proc/";

Which makes it a constant (with constant mem size allocation)
The 2nd line strcat will atempt to overwrite the string constant, which puts 6 bytes beyond your buffer into unknown territory (*if it succeeded).
Use strcat responsibly: http://beej.us/guide/bgc/output/html/multipage/strcat.html
* as JeremyP points out, if it points to the text segment, it is read only and will cause the segfault

A: It would help confirm things if you showed us the line that defines tempString.  However, it looks like you've got something like char * tempString = "/proc/";, and are trying to modify that.  Since it's a quoted string, you may or may not be able to modify it, and a segmentation fault is quite likely if you try.  (Moreover, "/proc/" is seven char long, and adding anything to the end would overwrite something or other.)
For a modifiable string, you need to have your own buffer, allocated either on the stack or on the heap, and you need to make sure it's long enough.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting Array not working correctly The sorting of array in alphabetical order is not outputting correctly.
It outputted as:
Demo
qwerty
Demo3
Test1
Test2
New1
Instead of:
Demo
Demo3
New1
qwerty
Test1
Test2
Code:
<?php

$dbresults= array ( "0"  => array ( "id" => "1",
                              "cb_boutiquename1" => "Test1",
                              "cb_boutiquename2" => "Test2",
                              "cb_boutiquename3" => "New1"
                                 ),
              "1" => array ( "id" => "2",
                              "cb_boutiquename1" => "Demo",
                              "cb_boutiquename2" => "qwerty",
                              "cb_boutiquename3" => "Demo3"
                                 )
            );

    function sortarray($a, $b) {
        return strcmp($a["cb_boutiquename$i"], $b["cb_boutiquename$i"]);
    }

    usort($dbresults, "sortarray");

    while (list($key, $value) = each($dbresults)) {
        $results[] = $value ;
    }

    foreach($results as $result) {
        $i = 1;
        while (array_key_exists("cb_boutiquename$i", $result)) {
        if ($result["cb_boutiquename$i"] !='') {
            echo '' . $result["cb_boutiquename$i"] . '
';
        }
        ++$i;
        }
    }
?>

A: Your problem is that in here:
function sortarray($a, $b) {
    return strcmp($a["cb_boutiquename$i"], $b["cb_boutiquename$i"]);
}

$i is undefined so you are basically comparing one undefined array offset with another.
If you want to specify which of the cb_boutiquename fields to specify at runtime then what you probably want to do is include the $i in the function, on php this can be done with a function that returns a closure (PHP 5.3+).
function getSorter($idx){
       return function($a, $b) use ($idx) {
           return strcmp($a["cb_boutiquename$idx"], $b["cb_boutiquename$idx"]);
       };
}

This returns a function that closes over the supplied argument and is appropriate for use as a comparison function for usort. So for your sort call you would use:
usort($dbresults, getSorter(1));

Or for a more general solution that does not assume the cb_boutiquename prefix on the properties  you can change this to
function getSorter($idx){
       return function($a, $b) use ($idx) {
           return strcmp($a[$idx], $b[$idx]);
       };
}
usort($dbresults, getSorter("cb_boutiquename1"));

This will allow you to sort any array of arrays by an one of the indexes.
UPDATE
I completely misunderstood the goal of this exercise. What you want to do is to flatten your array prior to doing any sorting.
    $dbresults= array ( "0"  => array ( "id" => "1",
                          "cb_boutiquename1" => "Test1",
                          "cb_boutiquename2" => "Test2",
                          "cb_boutiquename3" => "New1"
                             ),
          "1" => array ( "id" => "2",
                          "cb_boutiquename1" => "Demo",
                          "cb_boutiquename2" => "qwerty",
                          "cb_boutiquename3" => "Demo3"
                             )
        );

// flatten out the array
$results = array();
foreach($dbresults as $k=>$v){
    foreach ($v as $key=>$value) {
          if (substr($key, 0,15) == "cb_boutiquename"){
              $results[] = array("id"=>$v["id"], "cb_boutiquename"=>$value, "i"=>substr($key, 15));
          }
    }

}

usort($results, function($a, $b){ return strcasecmp($a["cb_boutiquename"], $b["cb_boutiquename"]); });
foreach($results as $result){
    echo '' . $result["cb_boutiquename"] . '
'."\n";
}

A: Instead of your sortarray function, use simply this:
asort($dbresults);
No need to reinvent the wheel. Read about it here


text:
Q: Ordering by username in Cassandra Let's say I have this table:
CREATE TABLE "users" (
    username text,
    created_at timeuuid,
    email text,
    firstname text,
    groups list<text>,
    is_active boolean,
    lastname text,
    "password" text,
    roles list<text>,
    PRIMARY KEY (username, created_at)
)

I want to order users by username, which is not possible as ordering is only possible via the clustering column. How can I order my users by username?
I need to query users by username, so that is the reason, why username is the indexing column.
What is the right approach here?

A: If you absolutely must have the username sorted, and return all usernames in one query then you will need to create another table for this effect:
CREATE TABLE "users" (
field text,
value text,
PRIMARY KEY (field, value)
)

Unfortunately, this will put all the usernames in just one partition, but it's the only way of keeping them sorted. On the other hand, you could expand the table to store different values that you need to retrieve in the same way. So for instance, the partition field="username" would have all the usernames, but you could create another partition field="Surname" to store all the usernames sorted.
Cassandra is NoSQL, so duplication of data can be expected.

A: Cassandra stores the partition key data by hashing the value.
So when the data is returned, the order is done by the hash values and not order of the data itself. Thus, you can't order on the partition key.
Coming back to your question, I'm not sure about what kind of data it is and what kind of query you would want to run. Assuming multiple users per email I'd create the following table:
CREATE TABLE "users" (
username text,
created_at timeuuid,
email text,
firstname text,
groups list<text>,
is_active boolean,
lastname text,
"password" text,
roles list<text>,
PRIMARY KEY (email, username)

)


text:
Q: How to use a variable in the format specifier statement? I can use:
write (*, FMT = "(/, X, 17('-'), /, 2X, A, /, X, 17('-'))") "My Program Name"

to display the following lines on the console window:
-----------------
 My Program Name
-----------------

Now, I want to show a pre-defined character instead of - in the above format. I tried this code with no success:
character, parameter :: Chr = Achar(6)

write (*, FMT = "(/, X, 17(<Chr>), /, 2X, A, /, X, 17(<Chr>))") "My Program Name"

Obviously, there are another ways to display what I am trying to show by means of a variable in the format specifier statement. For instance:
character, parameter :: Chr = Achar(6)
integer :: i, iMax = 17

write (*, FMT = "(/, X, <iMax>A1, /, 2X, A, /, X, <iMax>A1)") (Chr, i = 1, iMax), &
                                                              "My Program Name",  &
                                                              (Chr, i = 1, iMax)

However, I would like to know if there is any way to use a variable or invoke a function in the format specifier statement.

A: The code you are trying to use (<>) is not standard Fortran. It is an extension accepted by some compilers. Just build the format string as a string.
"(/, X, 17(" // Chr // "), /, 2X, A, /, X, 17(" // Chr // "))"

For the the numeric case you have to prepare a string with the value
write(chMax, *) iMax

"(/, X, " // chMax // "A1, /, 2X, A, /, X, " // chMax // "A1)"

or you can use some function, if you have it
"(/, X, " // itoa(iMax) // "A1, /, 2X, A, /, X, " // itoa(iMax) // "A1)"

but it may still be preferable to call it beforehand, to avoid multiple calls.
The function can look like:
function itoa(i) result(res)
  character(:),allocatable :: res
  integer,intent(in) :: i
  character(range(i)+2) :: tmp
  write(tmp,'(i0)') i
  res = trim(tmp)
end function


text:
Q: Setting max execution time causes Laravel to die I am in the midst of deploying a Laravel application I have written.
The app uses Office365 to send emails over SMTP - unfortunately Office365 is awfully slow.
On my local machine I bumped my max execution time up to 60 seconds and this resolved the issue.
The problem I am having now, is that I cannot globally edit the php.ini file in production as the company uses shared hosting.
The host offers the ability to set a php.ini file for the directories so you can edit some of these variables.
As such, I have placed a php.ini file in the public directory of my app with the below contents:
max_execution_time=60

However after doing this, trying to access my app results in the below error:

Fatal error: Uncaught TypeError: Argument 6 passed to
  Symfony\Component\HttpFoundation\Request::createRequestFromFactory()
  must be of the type array, null given, called in
  /home/grainfat/capture_html/Capture/vendor/symfony/http-foundation/Request.php
  on line 315 and defined in
  /home/grainfat/capture_html/Capture/vendor/symfony/http-foundation/Request.php:2014
  Stack trace: #0
  /home/grainfat/capture_html/Capture/vendor/symfony/http-foundation/Request.php(315):
  Symfony\Component\HttpFoundation\Request::createRequestFromFactory(Array,
  Array, Array, Array, Array, NULL) #1
  /home/grainfat/capture_html/Capture/vendor/laravel/framework/src/Illuminate/Http/Request.php(62):
  Symfony\Component\HttpFoundation\Request::createFromGlobals() #2
  /home/grainfat/capture_html/Capture/public/index.php(55):
  Illuminate\Http\Request::capture() #3 {main} thrown in
  /home/grainfat/capture_html/Capture/vendor/symfony/http-foundation/Request.php
  on line 2014

As soon as I remove the php.ini file it goes away.
Any ideas as to why this causes the above error? Or suggestions for an alternative workaround?

A: Try to set your necessary php settings in your .htaccess file.
Ex:

php_value max_execution_time 60

A: Along with max_execution_time, Also add memory_limit at top of your .htaccess file

php_value memory_limit 256M
php_value max_execution_time 60


text:
Q: woocommerce checkout - is it possible to get the functionality of a specific shipping zone for a specific shipping class? The following code will detect the cart if it has shipping class
i got this here (https://isabelcastillo.com/woocommerce-check-shipping-class)
<?php if ( cart_has_product_with_shipping_class('small-items') ): ?>

 Shipping Method 1

<?php elseif ( cart_has_product_with_shipping_class('big-items') ): ?>

 Shipping Method 2

<?php else:?>

 Shipping Method 3

<?php endif;?>

i just want to know if i can get the shipping method for a shipping class so that when i choose the "small-items" it will get the functionality of the shipping method 1


text:
Q: Vb.Net LINQ query nested list I have  list of cPoint objects. Every cPoint has list of cPosition objects.  I have to make query that returns only cPoints whose  cPositions meet the criteria and and every single cPoint must contain only those cPositions that meet the criteria.  Is it possible with LINQ?
'classes
Public Class cPoint
    Private _PointName As String
    Public Positions As colPositions
    '...
End Class

Public Class cPosition
    Private _X As Double
    Private _Y As Double
    Private _Z As Double
    Private _IntervalStart As Long
    '...
End Class

Public Class cPoints
    Inherits System.ComponentModel.BindingList(Of cPoint)
End Class

Public Class cPositions
    Inherits System.ComponentModel.BindingList(Of cPosition)
End Class

The closest thing I did is this query  but it does not return filtered cPoints. Every item in query has two objects: 1. filtered Point (with unfiltered child Positions) and 2. filtered Positions that belong to that Point.
Dim PtList As cPoints
'...
'my query
Dim query = (From pt In PtList
             From pos In pt.Positions
             Where (pos.IntervalStart < 222)
             Select New With {Key .PT = pt,
             Key .PTPOS = (From position In pt.Positions Where (position.IntervalStart < 222)).ToList}).Distinct

A: So you want the points whose positions ALL have interval more than 222? Just use the All Linq method as the follow example:
Module Module1
'classes
Public Class cPoint
    Private _PointName As String
    Public Positions As cPositions

    ''' <summary>
    ''' Needed because we want to construct cPoints object using cPosition list within Linq
    ''' </summary>
    ''' <param name="posList"></param>
    ''' <remarks></remarks>
    Public Sub New(posList As IEnumerable(Of cPosition))
        Positions = New cPositions
        For Each cp As cPosition In posList
            Me.Positions.Add(cp)
        Next
    End Sub

    'default
    Public Sub New()

    End Sub
End Class

Public Class cPosition
    Private _X As Double
    Private _Y As Double
    Private _Z As Double
    Private _IntervalStart As Long

    Public Sub New(x As Double, y As Double, z As Double, iss As long)
        _X = x
        _Y = y
        _Z = z
        _IntervalStart = iss
    End Sub

    ''' <summary>
    ''' Added a property to access from outside class
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property IntervalStart As Long
        Get
            Return _IntervalStart
        End Get
        Set(value As Long)
            _IntervalStart = value
        End Set
    End Property
End Class

Public Class cPoints
    Inherits System.ComponentModel.BindingList(Of cPoint)
End Class

Public Class cPositions
    Inherits System.ComponentModel.BindingList(Of cPosition)
End Class

Sub Main()

    Dim ptlist As cPoints = New cPoints
    Dim point1 = New cPoint
    point1.Positions = New cPositions
    point1.Positions.Add(New cPosition(1, 2, 3, 4))
    point1.Positions.Add(New cPosition(1, 2, 3, 1000))
    point1.Positions.Add(New cPosition(1, 2, 3, 2000))
    point1.Positions.Add(New cPosition(1, 2, 3, 1))

    Dim point2 = New cPoint
    point2.Positions = New cPositions
    point2.Positions.Add(New cPosition(1, 2, 3, 1))
    point2.Positions.Add(New cPosition(1, 2, 3, 2))
    point2.Positions.Add(New cPosition(1, 2, 3, 444))
    point2.Positions.Add(New cPosition(1, 2, 3, 555))

    ptlist.Add(point1)
    ptlist.Add(point2)

    'selects all the points in ptlist that have all their positions with interval start more than 222.
    Dim result = From pt In ptlist
                 Where pt.Positions.All(Function(l As cPosition)
                                            'put whatever condition here.
                                            Return l.IntervalStart > 222
                                        End Function)
                Select pt

    'select all the points. each point, will have all the positions that are less than 222.
    Dim result2 = From pt In ptlist
                  Select New cPoint(pt.Positions.Where(Function(l As cPosition)
                                                           Return l.IntervalStart < 222
                                                       End Function))

    For Each a In result2
        Console.WriteLine(a.Positions.Count)
    Next

End Sub

End Module


text:
Q: PropertyReference Exception in ManyToOne Mapping I am using ManyToOne annotation mapping in my VerticalTask class
@JsonIgnore
@ManyToOne
@JoinColumn(name = "vertical_type_id")
private VerticalType vertical;

I have VerticalType class also where I am mapping the OneToMany annotation since I want vertical task for each company
@OneToMany (mappedBy = "vertical", cascade = CascadeType.ALL,
orphanRemoval = true) private List<VerticalTask> verticalTask;

I also have verticalTaskRepository
public interface VerticalTaskRepository extends CrudRepository<VerticalTask, Long>{

    List<VerticalTask> findByVertical_type_Id(Long aircraft_typeId);
}

I have a column verticalName in VerticalType class  therefore using that I want to get All vertical task associated with one VerticalType record
I have also mentioned a mapping in postgresql (vertical_type_id) -> (id)
But at runtime I am getting Exception::

Unsatisfied dependency expressed through constructor parameter 7;
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'verticalTaskRepository': Invocation of init
  method failed; nested exception is
  org.springframework.data.mapping.PropertyReferenceException: No
  property name found for type VerticalType! Traversed path:
  VerticalTask.vertical.


text:
Q: Get single unicode string from digest::hmac How can I get a single unicode string as the signature below (instead of a character vector (which seems to contain pieces of unicode strings)?
For example
  library(digest)

  raw_key = 'QQrawkeyrawkeyrawkeyrawkey4='
  key = RCurl::base64Decode(raw_key)
  url_test = 'example_url'
  signature <- digest::hmac(key, url_test, algo = "sha1", raw = T)

Returns the character vector
64 d9 cb 13 d3 f9 5c 0a 4c 1d 47 d2 d5 9d ab 24 25 3f f3 20
But I want it to return the single string
'd\xd9\xcb\x13\xd3\xf9\\nL\x1dG\xd2\xd5\x9d\xab$%?\xf3 '
Background:
I am trying to make the R code work the same as the python code below (I am not very experienced with python).
     raw_key = 'QQrawkeyrawkeyrawkeyrawkey4='
     key = base64.urlsafe_b64decode(raw_key)
     url_test = 'example_url'
     hmac.new(key, url_test.encode(), hashlib.sha1).digest()

Additional context is that I need to string to create the signature for a call to the google distance matrix API using a premium account.

A: digest::hmac(.., raw=TRUE) isn't actually returning a character vector, it's returning a "raw" vector in R. To convert this to a string, use
rawToChar(signature)


text:
Q: RAdwords Error in 1:ncol(data) : argument of length 0 Using RAdwords, I can connect and get a token - list reports and list metrics.  But when I try to pull data i get the error below the code - thanks for the help!
body <- statement(select=c('KeywordText','Clicks','Cost','Ctr'),
report="KEYWORDS_PERFORMANCE_REPORT",
where="Clicks > 100",
start="20150101",
end="20150301")

data <- getData(clientCustomerId='949-xxx-xxxx', google_auth=google_auth,
statement=body, transformation = TRUE)

e* upload completely sent off: 130 out of 130 bytes
 HTTP/1.1 400 Bad Request
 Content-Type: text/xml
 Date: Fri, 06 Mar 2015 18:28:30 GMT
 Expires: Fri, 06 Mar 2015 18:28:30 GMT
 Cache-Control: private, max-age=0
 X-Content-Type-Options: nosniff
 X-Frame-Options: SAMEORIGIN
 X-XSS-Protection: 1; mode=block
 Server: GSE
 Accept-Ranges: none
 Vary: Accept-Encoding
 Transfer-Encoding: chunked

*

*Connection #0 to host adwords.google.com left intact
Error in 1:ncol(data) : argument of length 0

A: Update:
There is an update of the package on my github repository which might solve your problem:
https://github.com/jburkhardt/RAdwords
Could you please reinstall the package from github and see if your bug gets fixed?

Austin, referring to the R output you sent me per mail, your problem is:
> data <- getData(clientCustomerId='xxx-xxx-xxxx', google_auth=google_auth, statement=body)
* Hostname was NOT found in DNS cache

Please make sure that you use the Adwords Account Id. The MCC Id will not work!

This is not an error or bug of the RAdwords package per se. The problem rather has something to do with the curl settings on your system.
See here for similiar problems:
Curl Hostname was NOT found in DNS cache error
https://bbs.archlinux.org/viewtopic.php?id=175433


text:
Q: Compare directories but not content of files With
diff -r

I can do this task, however it takes so long because diff checks file's content.
I want something that determine that two files are the same regarding of their size, last modified, etc. But no checking bit by bit the file (for example a video takes sooo long).
Is there any other way?

A: Use the -q (--brief) option with diff -r (diff -qr).  From the info page for GNU diff:

1.6 Summarizing Which Files Differ
When you only want to find out whether files are different, and you
  don't care what the differences are, you can use the summary output
  format.  In this format, instead of showing the differences between
  the files, diff' simply reports whether files differ.  The--brief'
  (`-q') option selects this output format.
This format is especially useful when comparing the contents of two
  directories.  It is also much faster than doing the normal line by
  line comparisons, because `diff' can stop analyzing the files as soon
  as it knows that there are any differences.

This will not compare line by line, but rather the file as a whole, which greatly speeds up the processor (what' you're looking for).

A: I've just discovered tree.
tree old_dir/ > tree_old
tree new_dir/ > tree_new
vimdiff tree_old tree_new

A: rsync, by default, compares only file metadata. that means timestamp, size, and attributes. among others. but not content of files.
rsync -n -a -i --delete source/ target/

explanation:

*

*-n do not actually copy or delete <-- THIS IS IMPORTANT!!1

*-a compare all metadata of file like timestamp and attributes

*-i print one line of information per file

*--delete also report files which are not in source

note: it is important to append the directory names with a slash. this is an rsync thing.
you can shorten the one letter options like this
rsync -nai --delete source/ target/

if you also want to see lines printed for files that are identical then provide -i twice
rsync -naii --delete source/ target/

example output:
*deleting   removedfile   (file in target but not in source)
.d..t...... ./            (directory with different timestamp)
>f.st...... modifiedfile  (file with different size and timestamp)
>f+++++++++ newfile       (file in source but not in target)
.f          samefile      (file that has same metadata. only with -ii)

remember that rsync only compares metadata. that means if the file content changed but metadata stayed the same then rsync will report that file is same. this is an unlikely scenario. so either trust that when metadata is same then data is same, or you have to compare file data bit by bit.
bonus: for progress information see here: Estimate time or work left to finish for rsync?

A: Here's a quick python script that will check that the filenames, mtimes, and file sizes are all the same:
import os
import sys

def getStats(path):
    for pathname, dirnames, filenames in os.walk(path):
        for filename in ( os.path.join(pathname, x) for x in filenames ):
            stat = os.stat(filename)
            yield filename[len(path):], stat.st_mtime, stat.st_size

sys.exit(tuple(getStats(sys.argv[1])) != tuple(getStats(sys.argv[2])))

A: If you only need to know if files from two file system branch are different (without look inside files) you can do something like this:
find /opt/branch1 -type f | sort | xargs -i md5sum {} >/tmp/branch1;
find /opt/branch2 -type f | sort | xargs -i md5sum {} >/tmp/branch2;
diff /tmp/branch1 /tmp/branch2;

HTH

A: If you'd like to compare only a structure and some basic info about files, you can try something like this:
diff <(cd $DIR1 && ls -laR) <(cd $DIR2 && ls -laR)

I didn't test it, so any edits are welcome :)

A: Based on Chris Down's script, this script is a little more "visual". Calling it with two arguments folder1 and folder2, it walks the first folder and for each file searches a corresponding file in the second folder. If it is found, the relative path is printed in green, if they have different modified time or size, it is printed in yellow, and if it is not found then it is printed in red.
#!/usr/bin/env python

import os
import sys
from termcolor import colored

def compare_filestats(file1,file2):
    """
    Compares modified time and size between two files.
    Return:
        -1 if file1 or file2 does not exist
         0 if they exist and compare equal
         1 if they have different modified time, but same size
         2 if they have different size, but same modified time
         3 if they have different size, and different modified time
    """

    if not os.path.exists(file1) or not os.path.exists(file2):
        return -1

    stat1 = os.stat(file1)
    stat2 = os.stat(file2)

    return (stat1.st_mtime != stat2.st_mtime) \
        + 2*(stat1.st_size != stat2.st_size)

def compare_folders(folder1,folder2):
    """
    folder1: serves as reference and will be walked through
    folder2: serves as target and will be querried for each file in folder1

    Prints colored status for each file in folder1:
        missing: file was not found in folder2
        mtime  : modified time is different
        size   : filesize is different
        ok     : found with same filestats
    """
    for dirpath, dirnames, filenames in os.walk(folder1):
        for file1 in ( os.path.join(dirpath, x) for x in filenames ):
            relpath = file1[len(folder1):]
            file2 = os.path.join( folder2, relpath )
            comp = compare_filestats(file1,file2)

            if comp < 0:
                status = colored('[missing]','red')
            elif comp == 1:
                status = colored('[mtime  ]','yellow')
            elif comp >= 2:
                status = colored('[size   ]','yellow')
            else:
                status = colored('[ok     ]','green')

            print status, relpath

if __name__ == '__main__':
    compare_folders(sys.argv[1],sys.argv[2])

Note that this is not sufficient to decide whether the two folders are the same, you would need to run it both ways to make sure. In practice if you just want to know whether the folders are the same, then Chris' script is better. If you want to know what's missing or different from one folder to another, then my script will tell you.
NOTE: you will need termcolor installed, pip install termcolor.

A: Save the next code as: diffm.sh:
# DIFF with Modification date - a .sh (dash; bash; zsh - compatible)
# "diff utility"-like script that can compare files in two directory
# trees by path, size and modification date

# Disclaimer:
# By using this program you are assuming full responsibility (and the
# author of this program shall not be held liable) for any data loss
# or damage that may result from the use or misuse of this program.

Proc1 () {
    new="$line"
    first_remaining_part="${new%"///////"*}"
    time="${first_remaining_part#*"///////"}"
    first_part="${new%%" ///////"*}"
    #last_part="${new##*"///////"}"

    seconds_since_epoch="${new##*" "}"
    #convert seconds_since_epoch to base 10 (remove 0's padding):
    temp="${seconds_since_epoch#"0"*[1-9]}"
    zeros="${seconds_since_epoch%"$temp"}"
    zeros="${zeros%?}" #Remove last non-0 digit
    seconds_since_epoch="${seconds_since_epoch#"$zeros"}"

    time_zone="${time##*" "}"
    time="${time%"."*}"

    new="$first_part ///// $time $time_zone ///// $seconds_since_epoch"

    printf '%s\n' "$new"
}

Proc2 () {
    cd "$dir1" >/dev/null 2>/dev/null

    count_files=0

    {
        IFS="
"
        set -f
        #FilePath / FileType / FileSize / FileTime / SecondsSinceEpoch
        if [ "$OS" = "Linux" -o "$OS" = "Windows" ]; then
            find . -not -type d -printf '%p ///// <_ ///// %s ///////%TY-%Tm-%Td %TT %Tz///////' -exec stat --printf ' %Y\n' {} \; 2>/dev/null|\
            {\
            while read line; do {\
                count_files=$((count_files + 1));\
                PrintJustInTitle "Analyzing file $count_files...";\
                Proc1;\
            }; done;\
            printf "$count_files">$RAMLocation/diffm_count.txt;\
            }
        elif [ "$OS" = "Mac" ]; then
            gfind . -not -type d -printf '%p ///// <_ ///// %s ///////%TY-%Tm-%Td %TT %Tz///////' -exec gstat --printf ' %Y\n' {} \; 2>/dev/null|\
            {\
            while read line; do {\
                count_files=$((count_files + 1));\
                PrintJustInTitle "Analyzing file $count_files...";\
                Proc1;\
            }; done;\
            printf "$count_files">$RAMLocation/diffm_count.txt;\
            }
        fi
        unset IFS
        set +f
    }

    cd "$initial_dir"
}

Proc3 () {
    cd "$dir2" >/dev/null 2>/dev/null

    #Get previous line count value from diffm_count.txt:
    read count_files<"$RAMLocation/diffm_count.txt"
    #Validate count_files as a number:
    count_files=$((count_files))

    {
        IFS="
"
        set -f
        #FilePath / FileType / FileSize / FileTime / SecondsSinceEpoch
        if [ "$OS" = "Linux" -o "$OS" = "Windows" ]; then
            find . -not -type d -printf '%p ///// >_ ///// %s ///////%TY-%Tm-%Td %TT %Tz///////' -exec stat --printf ' %Y\n' {} \; 2>/dev/null|\
            {\
            while read line; do {\
                count_files=$((count_files + 1));\
                PrintJustInTitle "Analyzing file $count_files...";\
                Proc1;\
            }; done;\
            printf "$count_files">$RAMLocation/diffm_count.txt;\
            }
        elif [ "$OS" = "Mac" ]; then
            gfind . -not -type d -printf '%p ///// >_ ///// %s ///////%TY-%Tm-%Td %TT %Tz///////' -exec gstat --printf ' %Y\n' {} \; 2>/dev/null|\
            {\
            while read line; do {\
                count_files=$((count_files + 1));\
                PrintJustInTitle "Analyzing file $count_files...";\
                Proc1;\
            }; done;\
            printf "$count_files">$RAMLocation/diffm_count.txt;\
            }
        fi
        unset IFS
        set +f
    }

    #Get total line count value from diffm_count.txt:
    read count_files<"$RAMLocation/diffm_count.txt"
    #Validate count_files as a number:
    count_files=$((count_files))

    #"." in front of the number is for displaying it as first line after the sort operation:
    printf ".$count_files"

    cd "$initial_dir"
}

GetOS () {
    OS_kernel_name=$(uname -s)

    case "$OS_kernel_name" in
        "Linux")
            eval $1="Linux"
        ;;
        "Darwin")
            eval $1="Mac"
        ;;
        "CYGWIN"*|"MSYS"*|"MINGW"*)
            eval $1="Windows"
        ;;
        "")
            eval $1="unknown"
        ;;
        *)
            eval $1="other"
        ;;
    esac
}

PrintInTitle () {
    printf "\033]0;%s\007" "$1"
}

PrintJustInTitle () {
    PrintInTitle "$1">/dev/tty
}

trap1 () {
    CleanUp
    printf "\nAborted.\n">/dev/tty
}

CleanUp () {
    #Clear the title:
    PrintJustInTitle ""
    #Restore "INTERRUPT" (CTRL-C) and "TERMINAL STOP" (CTRL-Z) signals:
    trap - INT
    trap - TSTP
}

GetSetRAMLocation () {
    GetOS OS
    if [ "$OS" = "Linux" ]; then
        RAMLocation='/dev/shm'
    elif [ "$OS" = "Mac" ]; then
        RAMLocation='/Volumes/RamDiskDIFFM'
        sizeInMB = "1"
        if [ ! -e "/Volumes/RamDiskDIFFM" ]; then
            diskutil partitionDisk $(hdiutil attach -nomount ram://$((2048*sizeInMB))) 1 GPTFormat APFS 'RamDiskDIFFM' '100%'&&{
                printf "">"$RAMLocation/diffm_count.txt"&&{
                    error="false"
                }||{
                    printf '\n%s\n\n' "Error: Could not write to RAM (\"$RAMLocation/diffm_count.txt\"). Write to current directory instead? [ Yes (=continue) / No (=Enter=abort) ]">/dev/tty
                    read answer
                    case "$answer" in
                        "Y"|"y"|"Yes"|"yes")
                            answer="yes"
                        ;;
                        "N"|"n"|"No"|"no")
                            answer="no"
                        ;;
                        "")
                            answer="no"
                        ;;
                        *)
                            answer="no"
                        ;;
                    esac
                    if [ "$answer" = "yes" ]; then
                        RAMLocation="$initial_dir"
                        error="false"
                    elif [ "$answer" = "no" ]; then
                        printf "\nAborted.\n\n">/dev/tty
                        error="true"
                    fi
                }
            }||{
                printf '\n%s\n\n' "ERROR: Could not create RAM Volume!">/dev/tty
                error="true"
            }
        fi
        if [ "$error" = "true" ]; then
            CleanUp
            exit 1
        fi
    elif [ "$OS" = "Windows" ]; then
        #On Windows, the RAMLocation variable is not currently designed to point to a RAM Drive path:
        RAMLocation="$initial_dir"
    elif [ $OS" = "other ]; then
        #On other operating systems, the RAMLocation variable is not currently designed to point to a RAM Drive path:
        RAMLocation="$initial_dir"
    else
        printf '\n%s\n\n' "ERROR: Could not get OS!">/dev/stderr
        CleanUp
        exit 1
    fi
}

DestroyArray () {
    eval array_len=\$\(\($1\_0\)\)

    j=0;
    while [ "$j" -lt "$array_len" ]; do
        j=$((j+1))
        unset $1\_$j
    done
    unset $1\_0
}

DisplayHelp () {
    printf "\n"
    printf "diffm - DIFF with Modification date\n"
    printf "\n"
    printf "    What it does:\n"
    printf "        - compares the files (recursively) in the two provided directory tree paths (<dir_tree1> and <dir_tree2>) by:\n"
    printf "            1. Path\n"
    printf "            2. Size\n"
    printf "            3. Modification date\n"
    printf "    Syntax:\n"
    printf "        <caller_shell> '/path/to/diffm.sh' <dir_tree1> <dir_tree2> [flags]\n"
    printf "        - where:\n"
    printf "            - <caller_shell> can be any of the shells: dash, bash, zsh, or any other shell compatible with the \"dash\" shell syntax\n"
    printf "            - '/path/to/diffm.sh' represents the path of this script\n"
    printf "            - <dir_tree1> and <dir_tree2> represent the directory trees to be compared\n"
    printf "            - [flags] can be:\n"
    printf "                --help or -h\n"
    printf "                    Displays this help information\n"
    printf "    Output:\n"
    printf "        - lines starting with '<' signify files from <dir_tree1>\n"
    printf "        - lines starting with '>' signify files from <dir_tree2>\n"
    printf "    Notes:\n"
    printf "        - only files in the two provided directory tree paths are compared, not also directories\n"
    printf "\n"
}

##################
### MAIN START ###
##################

GetOS OS

if [ "$OS" = "Linux" -o "$OS" = "Windows" ]; then
    error1="false"
    error2="false"
    error3="false"

    { sort --version-sort --help >/dev/null 2>/dev/null; } || { error1="true"; }
    { stat --help >/dev/null 2>/dev/null; } ||  { error2="true"; }
    { find --help >/dev/null 2>/dev/null; } ||  { error3="true"; }
    if [ "$error1" = "true" -o "$error2" = "true" -o "$error3" = "true" ]; then
        {
        printf "\n"
        if [ "$error1" = "true" ]; then printf '%s' "ERROR: Could not run \"sort --version-sort\" (necessary in order for this script to function correctly)!"; fi
        if [ "$error2" = "true" ]; then printf '%s' "ERROR: Could not run \"stat\" (necessary in order for this script to function correctly)"; fi
        if [ "$error3" = "true" ]; then printf '%s' "ERROR: Could not run \"find\" (necessary in order for this script to function correctly)"; fi
        printf "\n"
        }>/dev/stderr
        exit
    else
        sort_command="sort --version-sort"
    fi
elif [ "$OS" = "Mac" ]; then
    error1="false"
    error2="false"
    error3="false"

    { gsort --version-sort --help >/dev/null 2>/dev/null; } || { error1="true"; }
    { gstat --help >/dev/null 2>/dev/null; } ||  { error2="true"; }
    { gfind --help >/dev/null 2>/dev/null; } ||  { error3="true"; }
    if [ "$error1" = "true" -o "$error2" = "true" -o "$error3" = "true" ]; then
        {
        printf "\n"
        if [ "$error1" = "true" ]; then printf '%s' "ERROR: Could not run \"gsort --version-sort\" (necessary in order for this script to function correctly)!"; fi
        if [ "$error2" = "true" ]; then printf '%s' "ERROR: Could not run \"gstat\" (necessary in order for this script to function correctly)"; fi
        if [ "$error3" = "true" ]; then printf '%s' "ERROR: Could not run \"gfind\" (necessary in order for this script to function correctly)"; fi
        printf "\n"

        printf "\n"
        printf '%s\n' "You can install them by installing \"homebrew\" and then GNU \"coreutils\":"
        printf '%s\n' "sudo ruby -e \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\""
        printf '%s\n' "sudo brew install coreutils"
        }>/dev/stderr

        exit
    else
        sort_command="gsort --version-sort"
    fi
elif [ "$OS" = "unknown" ]; then
    printf '\n%s\n\n' "ERROR: Could not get OS!">/dev/stderr
    CleanUp
    exit 1
elif [ "$OS" = "other" ]; then
    printf '\n%s\n\n' "ERROR: OS currently not supported!">/dev/stderr
    CleanUp
    exit 1
fi

#Get the program parameters into the array "params":
params_count=0
for i; do
    params_count=$((params_count+1))
    eval params_$params_count=\"\$i\"
done
params_0=$((params_count))

if [ "$params_0" = "0" ]; then #if no parameters are provided: display help
    DisplayHelp
    CleanUp && exit 0
fi

#Create a flags array. A flag denotes special parameters:
help_flag="0"
i=1;
j=0;
while [ "$i" -le "$((params_0))" ]; do
    eval params_i=\"\$\{params_$i\}\"
    case "${params_i}" in
    "--help" | "-h" )
        help_flag="1"
    ;;
    * )
        j=$((j+1))
        eval selected_params_$j=\"\$params_i\"
    ;;
    esac

    i=$((i+1))
done

selected_params_0=$j
#Rebuild params array:
DestroyArray params
for i in $(seq 1 $selected_params_0); do
    eval params_$i=\"\$\{selected_params_$i\}\"
done
params_0=$selected_params_0

if [ "$help_flag" = "1" ]; then
    DisplayHelp
else
    #Check program arguments:
    if [ "$params_0" -lt "2" ]; then
        printf '\n%s\n' "ERROR: To few program parameters provided (expected two: <dir_tree1> and <dir_tree2>)!">/dev/stderr
        exit 1
    elif [ "$params_0" -gt "2" ]; then
        printf '\n%s\n' "ERROR: To many program parameters provided (expected two: <dir_tree1> and <dir_tree2>)!">/dev/stderr
        exit 1
    else #two program arguments are provided:
        mask1="$params_1"
        mask2="$params_2"
    fi

    #If two program arguments are provided (<dir_tree1> and <dir_tree2>) proceed to checking them:

    initial_dir="$PWD" #Store initial dir
    error_encountered="false"

    [ -e "$params_1" -a -d "$params_1" ] && cd "$params_1" >/dev/null 2>/dev/null && {
        dir1="$PWD"
        cd "$initial_dir"
    }||{
        printf '\n%s\n' "ERROR: \"$params_1\" does not exist as a directory or is not accessible!">/dev/stderr
        error_encountered="true"
    }

    printf "\n">/dev/tty

    [ -e "$params_2" -a -d "$params_2" ] && cd "$params_2" >/dev/null 2>/dev/null && {
        dir2="$PWD"
        cd "$initial_dir"
    }||{
        printf '%s\n' "ERROR: \"$params_2\" does not exist as a directory or is not accessible!">/dev/stderr
        error_encountered="true"
    }

    if [ "$error_encountered" = "true" ]; then
        printf "\n">/dev/stderr
        exit
    fi

    GetSetRAMLocation

    #Trap "INTERRUPT" (CTRL-C) and "TERMINAL STOP" (CTRL-Z) signals:
    trap 'trap1' INT
    trap 'trap1' TSTP

    #Proceed to <dir_tree1> and <dir_tree2> compare:
    IFS="
"
    set -f
    unset count_total
    unset previous_line
    unset current_line
    unset previous_case
    skip="0"
    count="0"
    found_previous="false"
    found_previous_last_line_case="false"
    for l in $(\
        {\
            PrintJustInTitle "Loading file data, please wait...";\
            Proc2;\
            Proc3;\
            PrintJustInTitle "Sorting results, please wait...";\
        }|eval $sort_command;
    ); do
        if [ -z "$count_total" ]; then
            # #? is for removing the "." in front of the number:
            count_total=$((${l#?}))
        else
            count=$((count + 1))
            PrintJustInTitle "Analyzing file $count of $count_total"
            if [ -z "$current_line" ]; then
                #FilePath / FileType / FileSize / FileTime / SecondsSinceEpoch

                #Get previous FileType = if from <dir_tree1> or <dir_tree2>:
                previous_line_type="${l#*"///// "}"
                #extract first character from $previous_line_type ("<" or ">"):
                previous_line_type_temp="${previous_line_type#?}"
                previous_line_type="${previous_line_type%"$previous_line_type_temp"}"

                #Remove FileType from line:
                previous_line="$l"
                previous_line_file_path="${l%%" /////"*}"
                previous_line_last_part="${previous_line#*"///// ""$previous_line_type""_ ///// "}"
                previous_line="$previous_line_file_path /////$previous_line_last_part"

                previous_line_file_size="${previous_line_last_part%%" /////"*}"
                previous_line_seconds_since_epoch="${l##*" "}"

                previous_line_file_time="${previous_line#*"///// "}"
                previous_line_file_time="${previous_line_file_time%%" /////"*}"

                current_line="$previous_line"
                current_line_file_path="$previous_line_file_path"
                current_line_file_size="$previous_line_file_size"
                current_line_seconds_since_epoch="$previous_line_seconds_since_epoch"

                current_line_type="$previous_line_type"

                current_line_file_time="$previous_line_file_time"
            else
                #FilePath / FileType / FileSize / FileTime / SecondsSinceEpoch

                previous_line="$current_line"
                previous_line_file_path="$current_line_file_path"
                previous_line_file_size="$current_line_file_size"
                previous_line_seconds_since_epoch="$current_line_seconds_since_epoch"

                previous_line_type="$current_line_type"

                previous_line_file_time="$current_line_file_time"

                #Get current FileType = if from <dir_tree1> or <dir_tree2>:
                current_line_type="${l#*"///// "}"
                #extract first character from $current_line_type ("<" or ">"):
                current_line_type_temp="${current_line_type#?}"
                current_line_type="${current_line_type%"$current_line_type_temp"}"

                #Remove FileType from line:
                current_line="$l"
                current_line_file_path="${l%%" /////"*}"
                current_line_last_part="${current_line#*"///// ""$current_line_type""_ ///// "}"
                current_line="$current_line_file_path /////$current_line_last_part"

                current_line_file_size="${current_line_last_part%%" /////"*}"
                current_line_seconds_since_epoch="${l##*" "}"

                current_line_file_time="${current_line#*"///// "}"
                current_line_file_time="${current_line_file_time%%" /////"*}"

                if [ ! "$skip" = "$count"  ]; then
                    if [ "$found_previous" = "false" ]; then
                        seconds_difference=$(($current_line_seconds_since_epoch - $previous_line_seconds_since_epoch))
                        if [ \
                            \( "$current_line" = "$previous_line" \) -o \
                            \( \
                                \( "$current_line_file_path" = "$previous_line_file_path" \) -a \
                                \( "$current_line_file_size" = "$previous_line_file_size" \) -a \
                                \( "$seconds_difference" = "1" -o "$seconds_difference" = "-1" \) \
                            \) \
                        ]; then
                            found_previous="true"
                            found_previous_last_line_case="false"
                            skip=$((count+1))
                        else
                            printf '%s\n' "$previous_line_type $previous_line_file_path - ""Size: ""$previous_line_file_size"" Bytes"" - ""Modified Date: ""$previous_line_file_time"
                            found_previous="false"
                            found_previous_last_line_case="true"
                        fi
                    else
                        printf '%s\n' "$previous_line_type $previous_line_file_path - ""Size: ""$previous_line_file_size"" Bytes"" - ""Modified Date: ""$previous_line_file_time"
                        found_previous="false"
                        found_previous_last_line_case="true"
                    fi
                else
                    found_previous="false"
                    found_previous_last_line_case="true"
                fi
            fi
        fi
    done
    #Treat last case sepparatelly:
    if [ "$found_previous_last_line_case" = "true" ]; then
        printf '%s\n' "$current_line_type $current_line_file_path - ""Size: ""$current_line_file_size"" Bytes"" - ""Modified Date: ""$current_line_file_time"
    fi

    unset IFS
    set +f
fi

CleanUp

*

*How to use it:
Syntax: <caller_shell> '/path/to/diffm.sh' <dir_tree1> <dir_tree2>
 where: <caller_shell> can be any of the shells: dash, bash, zsh, or any other shell compatible with the dash shell syntax.

*What it does: Compares the files (recursively) in the two provided directory tree paths (<dir_tree1> and <dir_tree2>) by:

*

*Path

*Size

*Modification Date

Notes:

*

*This script compares only the files, not also the directories in <dir_tree1> and <dir_tree2>.

*To find out how to use the script, you can call it with the --help flag.

A: If you are open for a GUI-based solution, meld can also perform directory comparisons.

A: Midnight commander (mc in Debian linux) is a two-pane command-line file manager with a Compare Directories function (C-x d; that is, holding the control key, press x, release, then press d). It has three choices: Quick, Size only, and Thorough. Quick or Size only may be helpful to you. It then highlights the files that are different in both panes, so you can do something to one or both sets.
I use the rsync method given above when I have a lot of files and a clear source and destination directory. But I often find I have two directories that each have new files to synchronize and I end up using mc frequently.


text:
Q: pywinauto - how click in text element in grid I need given one click in text inside the grid, and not have click method in this element, how do it?
select_viagem = flight_app.child_window(title="166,80", control_type="Text")
select_viagem.click()

https://github.com/reinaldorossetti/pywinauto/blob/master/exemplo01.py
Traceback (most recent call last):
  File "C:/Users/reinaldo.rossetti/PycharmProjects/pywinauto/exemplo01.py", line 56, in <module>
    select_viagem.click()
  File "C:\Python35\lib\site-packages\pywinauto\application.py", line 171, in __call__
    format(self.criteria[-1]['best_match']))
AttributeError: WindowSpecification class has no 'click' method

    test = {UIAWrapper} <pywinauto.controls.uiawrapper.UIAWrapper object at 0x0000000005BE14E0>
 _abc_cache = {WeakSet} <_weakrefset.WeakSet object at 0x00000000050DF748>
 _abc_negative_cache = {WeakSet} <_weakrefset.WeakSet object at 0x00000000050DF7B8>
 _abc_negative_cache_version = {int} 39
 _abc_registry = {WeakSet} <_weakrefset.WeakSet object at 0x00000000050DF6D8>
 _as_parameter_ = {NoneType} None
 _cache = {dict} {}
 _control_types = {list} <class 'list'>: []
 _element_info = {UIAElementInfo} <pywinauto.uia_element_info.UIAElementInfo object at 0x0000000005BE16A0>
 _needs_image_prop = {bool} False
 actions = {_StandardLogger} <pywinauto.actionlogger._StandardLogger object at 0x0000000005BE1780>
 appdata = {NoneType} None
 backend = {BackEnd} <pywinauto.backend.BackEnd object at 0x00000000050DF828>
 can_be_label = {bool} False
 element_info = {UIAElementInfo} <pywinauto.uia_element_info.UIAElementInfo object at 0x0000000005BE16A0>
 friendlyclassname = {NoneType} None
 handle = {NoneType} None
 has_title = {bool} True
 iface_expand_collapse = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_grid = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_grid_item = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_invoke = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_item_container = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_range_value = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_scroll_item = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_selection = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_selection_item = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_table = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_table_item = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_text = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_toggle = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_value = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_virtualized_item = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 iface_window = {str} 'Traceback (most recent call last):\n  File "C:\\Python35\\lib\\site-packages\\pywinauto\\uia_defines.py", line 217, in get_elem_interface\n    iface = cur_ptrn.QueryInterface(cls_name)\n  File "C:\\Python35\\lib\\site-packages\\comtypes\\__init__.py", line 1
 ref = {NoneType} None
 windowclasses = {list} <class 'list'>: []
 writable_props = {list} <class 'list'>: ['class_name', 'friendly_class_name', 'texts', 'control_id', 'rectangle', 'is_visible', 'is_enabled', 'control_count', 'is_keyboard_focusable', 'has_keyboard_focus']

send this logs.

A: OK, I've tried this app on my machine and it works so (on your locale dot should be replaced with comma):
grid.child_window(title="131.10", control_type="Text").click_input()

The grid elements have no InvokePattern so that method .invoke() will raise NoPatternInterfaceError. Method .click() is just an alias of .invoke() for buttons. But it may have different meaning for other control types. That's why we use .invoke() name only for non-button controls.


text:
Q: How to deny ajax PHP files from browser There is AJAX script on my WS.
Is there a method to deny straight access to ajax php backend?
And to access to it only if it is run from my ajax code

A: The answer is no.
The way your ajax calls access the php scripts is just as direct as any other method.
That said, you can limit the access to your scripts in different ways, such as requiring a valid session which is created only after a login. However, once a user has logged in, accessing the backend via an ajax script or "directly" are both fair game. In other words, you cannot count on being able distinguish an ajax call from some other call at the server side.
The security of your backend needs to depend on somewhere else.

A: You can try heuristics (such as examining X-Requested-With HTTP header) but NOT as any security measure. Any such difference in how the request looks can easily be duplicated by anyone who really wants to.

A: On server-side you can add this to the top of your backend files:
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
  die("You need to use an AJAX request");
}

Edit: As stated by others, this is not reliable as a security measure.


text:
Q: Locked out of logging in through GUI on Ubuntu When I installed Ubuntu on my laptop, I chose "Automatic login" so that I was not asked for a username and password everytime I switched on.
I later wanted to change the settings.
So I went to:

Systems > Administration > Login window > Security

From there I disabled automatic login and rebooted the computer. Now the GUI does not allow me to enter username and password.
The following displays on the login screen:

Authentication failed

Please help me.

A: First off, you can try booting into single user mode.  Interrupt the boot process at the GRUB loader screen by pressing 'enter'.  Then edit the booting line, and put the word 'single' at the end of that kernel line.  Then boot, and it will give you a login prompt.  Plug in your root credentials, and that will give you a shell.
The GUI screen you were modifying makes changes in /etc/gdm/custom.conf.  So check that file once you have access.  You may need to make sure "AllowRoot" is undefined, or set to 'true', so that the root user can login.  There's also "AutomaticLoginEnabled" which is set to 'true' if automatic logins are in use.

A: Press CTRL+ALT+F1 and enter your username and password, it will give you a shell. Then type:
nano /etc/gdm/custom.conf
And replace the content with:
[daemon]
AutomaticLoginEnable=false

Then restart.


text:
Q: influence of bayesian priors: rjags and categorical variables I am a bad statistician and new using Bayesian tools, and I am learning how to make regressions with rjags. While toying, I came across a situation I do not fully understand, and I would need some help from the community.
the example:
library(data.table)
library(ggplot2)
library(rjags)
library(magrittr)

global_slope <- 1
global_intercept <- 1

Npoints_per_group <- 50
N_groups <- 10
pentes <- rnorm(N_groups,-1,.5)

centers_x <- seq(0,10,length = N_groups)
center_y <- global_slope*centers_x + global_intercept

group_spread <- 2
group_names <- sample(LETTERS,N_groups)

df <- lapply(1:N_groups,function(i){
  x <- seq(centers_x[i]-group_spread/2,centers_x[i]+group_spread/2,length = Npoints_per_group)
  y <- pentes[i]*(x- centers_x[i])+center_y[i]+rnorm(Npoints_per_group)
  data.table(x = x,y = y,ID = group_names[i])
}) %>% rbindlist()

It creates a dataset with a classical Simpson paradox:
ggplot(df,aes(x,y,color = as.factor(ID)))+
  geom_point()

I can use mixed effect regression, but in a first step I just wanted to perform a regression adjusted for the ID categorical variable:
lm(y ~ x + ID,data = df) %>% summary()

lm(formula = y ~ x + ID, data = df)

Residuals:
    Min      1Q  Median      3Q     Max
-3.1638 -0.7172 -0.0060  0.6544  2.9827

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  3.32405    0.16884  19.687   <2e-16 ***
x           -0.99256    0.07785 -12.750   <2e-16 ***
IDG         17.79467    0.72174  24.655   <2e-16 ***
IDH          8.88795    0.40220  22.098   <2e-16 ***
IDN         15.26829    0.63928  23.884   <2e-16 ***
IDS         -2.05924    0.22256  -9.252   <2e-16 ***
IDT         11.07778    0.47865  23.144   <2e-16 ***
IDU          2.11935    0.22256   9.522   <2e-16 ***
IDW         13.28410    0.55804  23.805   <2e-16 ***
IDY          4.20289    0.26829  15.665   <2e-16 ***
IDZ          6.61491    0.33074  20.000   <2e-16 ***

Now I want to do the same with rjags. I do the following:
model_code <-
"model
{

  for (i in 1:n) {
    y[i] ~ dnorm(mu[i], sigma^-2)
    mu[i] <- alpha + beta * x[i] + bID[ID[i]]
  }

  # cat distrib
  bID[1] <- 0
  for(j in 2:Nid){
  bID[j] ~ dunif(-5,5)
  }

  # Priors
  alpha ~ dnorm(0, 100^-2)
  beta ~ dnorm(0, 100^-2)
  sigma ~ dunif(0, 10)
}
"

df[,ID_num := as.numeric(as.factor(ID))]
model_data <- list(n = nrow(df),
                   Nid = df[,uniqueN(ID)],
                   ID = df$ID_num,
               y = df$y,
                   x = df$x)

model <- jags.model(textConnection(model_code),
                    data = model_data,
                    n.chains = 2,
                    n.adapt = 1000)
update(model, 1000)

samples <- coda.samples(    model,
    c("alpha", "beta", "sigma","bID"),
    1000)

summary(samples)

This does not give the expected results:
1. Empirical mean and standard deviation for each variable,
   plus standard error of the mean:

            Mean      SD  Naive SE Time-series SE
alpha    2.38553 0.20216 0.0045205       0.023001
bID[1]   0.00000 0.00000 0.0000000       0.000000
bID[2]   4.94015 0.05910 0.0013216       0.003490
bID[3]   2.45937 0.22747 0.0050864       0.009988
bID[4]   4.42102 0.24729 0.0055295       0.012415
bID[5]  -1.11753 0.27499 0.0061490       0.022423
bID[6]   3.17433 0.23565 0.0052692       0.011053
bID[7]   0.09581 0.24132 0.0053960       0.014685
bID[8]   3.90678 0.25029 0.0055967       0.012346
bID[9]   0.71809 0.23663 0.0052912       0.012584
bID[10]  1.66045 0.23142 0.0051747       0.011332
beta     0.33399 0.02955 0.0006607       0.003277
sigma    1.31688 0.04148 0.0009275       0.001146

I realized that it was because the prior I gave for the categorical variable ID is too narrow. If I replace
bID[j] ~ dunif(-5,5)

by
bID[j] ~ dunif(-100,100)

in the JAGS model, then I find results similar to those of the frequentist lm:
1. Empirical mean and standard deviation for each variable,
   plus standard error of the mean:

          Mean      SD  Naive SE Time-series SE
alpha    3.292 0.16957 0.0037918      0.0194214
bID[1]   0.000 0.00000 0.0000000      0.0000000
bID[2]  17.622 0.66571 0.0148857      0.2021913
bID[3]   8.805 0.35826 0.0080109      0.0892269
bID[4]  15.123 0.57542 0.0128667      0.1739097
bID[5]  -2.025 0.22548 0.0050420      0.0194497
bID[6]  10.969 0.43419 0.0097089      0.1219498
bID[7]   2.107 0.21089 0.0047156      0.0170001
bID[8]  13.156 0.51186 0.0114454      0.1450026
bID[9]   4.165 0.24613 0.0055036      0.0381072
bID[10]  6.545 0.29735 0.0066490      0.0548702
beta    -0.972 0.07282 0.0016284      0.0193806
sigma    1.027 0.03268 0.0007307      0.0009942

So the question:
I was expecting that even if the priors are wrong or too narrow (my bID[j] ~ dunif(-5,5)), the model would at the end converge to the expected solution if it has enough iterations, as each step posterior distribution os based on the data. But it seems it does not.
The MCMC seems to have converged (to the wrong result), and increasing the number of burning does not alter the result.
Why is that ? Do the priors constrain the possible results whatever the number of iterations ? Or is there a kind of local minima reached before the actual true result ?

A: If you set as a prior for the ID coefficients a uniform distribution between -5 and 5, this means that these coefficients are assumed to be in the interval $[-5,5]$, other values are impossible. These cannot become possible during the MCMC algorithm, because you have specified these values as a priori impossible. As the frequentist analysis estimates these values outside that interval, the Bayesian analysis will necessarily deviate quite a bit from the frequentist one.
The way you generated the data implies (as confirmed by the frequentist analysis) that there are so big differences between the ID means that $[-5,5]$ is not enough of a range to fit them. In other words, choosing the prior like this actively prevents the Bayesian analysis from finding the "correct" coefficient values. This is no longer the case for a uniform on $[-100,100]$.
By the way, also the priors for alpha and beta look very restrictive, even though the normal distribution at least doesn't make any value totally impossible. In a proper Bayesian analysis you need to choose the priors so that they allow the data to have enough influence to put the parameters anywhere where they could realistically occur. Overprecision in the priors is not good.


text:
Q: Script para remover assinatura BOM dos arquivo UTF-8 Estou com vário problemas de arquivos em UTF-8 com BOM, varios tokens estao sendo gerado no inicio das páginas, isso faz ocorrer varios problemas nas leituras de arquivos json e desindentação dos componentes HTML. Quase impossível de descobrir pois os tokens são invisiveis. Procurei no google uma forma de alterar todos os arquivos para UTF-8 sem BOM e achei um script em perl para remover a assinatura BOM mas não funcionou. Alguem poderia ajudar. Preciso de um script que altere todos os arquivos do projeto.
Mais informções do problema e o script pode ser encontrada aqui
A minha soluçao por enquanto é ficar garimpando os arquivos e salvando em UTF-8 sem BOM, mas são vários arquivos, por isso pensei em um script, mas não tenho idéia de como fazer.
A solução momentanea para os problemas de token do json eu fiz assim para resolver (POG):
1.Recupero a string apartir da primeira chaves { encontrada.
Pois os tokens são gerados antes dessa chave. Isso resolve momentaneamente. Mas é uma gambiarra.
json = json.substring(json.indexOf("{"),json.length);
objeto = $.parseJSON(json);

A: Um arquivo UTF-8 com BOM é simplesmente um arquivo na codificação UTF-8 em que os primeiros 3 bytes são EF BB BF. Identificar o BOM é portanto uma questão de ler os 3 primeiros bytes e ver se eles correspondem a esse formato. E para eliminar o BOM, é só copiar o restante do arquivo pra saída, sem incluir esses 3 bytes.
Um exemplo em Python (3), bem simplificado (Disclaimer: não testei!), seria:
import os, sys

def tem_bom(arq):
    with open(arq, mode="rb") as f:
        bom = f.read(3)
        resto = f.read()
        if bom == b"\xef\xbb\xbf":
            return True, resto
        else:
            return False, bom + resto

def copiar_pasta(origem, destino, copiar_sempre=True):
    for nome in os.listdir(origem):
        path1 = os.path.join(origem, nome)
        path2 = os.path.join(destino, nome)

        if os.path.isfile(path1):
             bom, resto = tem_bom(path1)
             if bom or copiar_sempre:
                 with open(path2, "wb") as f:
                     f.write(resto)
                 if bom:
                     print("Corrigido arquivo {}".format(path1))

        elif os.path.isdir(path1):
            os.mkdir(path2)
            copiar_pasta(path1, path2, copiar_sempre)

if __name__ == "__main__":
    copiar_pasta(sys.argv[1], sys.argv[2])

Esse exemplo pegaria uma pasta de origem e copiaria todos os arquivos para uma pasta de destino, recursivamente. Cada arquivo que tivesse BOM, ele copiaria sem o BOM. Fiz dessa forma (sem alterar nada na pasta original) pra não correr o risco de sobrescrever nada importante, apenas verifique se a pasta de destino é uma nova pasta, vazia. Adapte se necessário.

A: #!/usr/bin/perl -pi
s/^(\xEF\xBB\xBF)//;  ## remove BOM !

Esta versão altera os próprios ficheiros.
Exemplo de uso:
rmbom *.js
ou
perl rmbom file1 file2  *.js  dir/*


text:
Q: How to use minimum layout for complex design in Qt I have complex GUI design and I want minimum usage of QLayout for more readable code.
I had used QGridLayout and QBoxLayout but code is not readable.
Short version of my code please do suggest modification so that code will become more readable
QVBoxLayout *mainLayout   = new QVBoxLayout(this); // Main Layout

// First GroupBox  QGroupBox
QGroupBox *GroupBox1 = new QGroupBox();
QHBoxLayout *Layout1 = new QHBoxLayout(); // Layout1 contains 3 Line edits
GroupBox1->setLayout(Layout1);

// Second Group table Group Box
QGroupBox *GroupBox2 = new QGroupBox("Second Group", this);
//   GroupBox2 contains table Widget and Buttons

QHBoxLayout *tableWrapperLayout = new QHBoxLayout();
QVBoxLayout *TableWidgetLayout1  = new QVBoxLayout();
QVBoxLayout *TableButtonLayout1  = new QVBoxLayout();
GroupBox2->setLayout(tableWrapperLayout);

// Param Table widget
QGroupBox *GroupBox3 = new QGroupBox("Third Group", this); // Same as GroupBox3

QHBoxLayout *TableWrapperLayout1  = new QHBoxLayout();
QVBoxLayout *TableWidgetLayout2 = new QVBoxLayout();
QVBoxLayout *TableButtonLayout2 = new QVBoxLayout();

GroupBox3->setLayout(TableWrapperLayout1);

QHBoxLayout *groupWrapperLayout = new QHBoxLayout();
// This is Wrapper for GroupBox2     and GroupBox3
groupWrapperLayout->addWidget(GroupBox2);
groupWrapperLayout->addWidget(GroupBox3);

// Main Layout contains GroupBox1 and groupWrapper
mainLayout->addWidget(GroupBox1);
mainLayout->addLayout(groupWrapperLayout);

A: I don't know what's so unreadable about it, but here it is with a bit less verbosity. Generally speaking you don't need to use box layouts, a grid layout can do all a box layout can do. You also don't need to set parents for widgets that are managed by layouts.
In real code you of course wouldn't be creating all the buttons/edits on the heap, but simply adding them as members of the Widget class and then adding them to the layouts one-by-one. I used the loops and heap allocation for brevity only.

#include <QApplication>
#include <QGridLayout>
#include <QLineEdit>
#include <QGroupBox>
#include <QTableWidget>
#include <QPushButton>

class Widget : public QWidget {
    QGridLayout m_layout;
    QGroupBox m_group1;
    QGridLayout m_group1Layout;
    QGroupBox m_group2;
    QGridLayout m_group2Layout;
    QGroupBox m_group3;
    QGridLayout m_group3Layout;
public:
    Widget(QWidget * parent = 0) : QWidget(parent),
        m_layout(this),
        m_group1("First Group"),
        m_group1Layout(&m_group1),
        m_group2("Second Group"),
        m_group2Layout(&m_group2),
        m_group3("Third Group"),
        m_group3Layout(&m_group3)
    {
        m_layout.addWidget(&m_group1, 0, 0, 1, 2);
        m_layout.addWidget(&m_group2, 1, 0);
        m_layout.addWidget(&m_group3, 1, 1);

        // Line edits in group 1
        for (int i = 0; i < 3; ++ i)
            m_group1Layout.addWidget(new QLineEdit, 0, i);

        // Table and buttons in group 2
        m_group2Layout.addWidget(new QTableWidget, 0, 0, 4, 1);
        for (int i = 0; i < 4; ++ i)
            m_group2Layout.addWidget(new QPushButton(QString::number(i)), i, 1);

        // Table and buttons in group 3
        m_group3Layout.addWidget(new QTableWidget, 0, 0, 4, 1);
        for (int i = 0; i < 4; ++ i)
            m_group3Layout.addWidget(new QPushButton(QString::number(i)), i, 1);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}


text:
Q: Edit created figure with pylab in MATLAB you can edit, if needed, figure files (.fig) - is there a similar functionality using pylab?
I can create the image I need but it comes out as .png that I have no control over - if I could sligthly edit it (e.g. to move legend to the side, or modify labels) would be great

A: If you want to save your plot and edit it later, you should try the hints given in this
thread
If your plot is still active in a [I]python shell, you can edit all properties and make a redraw. The following example is for moving the legend from default location to right upper corner after examination.
In [51]: import numpy as np

In [52]: import pylab as pl

In [53]: v = np.arange(10)

In [54]: pl.figure(1)
Out[54]: <matplotlib.figure.Figure at 0x253a250>

In [55]: # if needed, use pl.figure(1) again to make it active

In [56]: pl.plot(v)
Out[56]: [<matplotlib.lines.Line2D at 0x456a450>]

In [60]: pl.legend('v')
Out[60]: <matplotlib.legend.Legend at 0x4591150>

In [61]: pl.show(block=False)

In [62]: # keyword block=False to issue further commands

In [63]: pl.legend('v',loc=2)
Out[63]: <matplotlib.legend.Legend at 0x45962d0>

In [64]: pl.show(block=False)

In [67]: # now the legend is in the upper right corner


text:
Q: Fancybox gallery groups I'm using fancybox http://fancyapps.com/fancybox/, and my question is:
Could i group different resources together? I mean images with inline or video in the same gallery (or 'group'). If yes, anyone knows how?
Here an example that doesn't work:
Test

Test Content

fancyinline and fancyimage aren't grouped together, but I need so.
Of course I need different parameters for inlines and images...
Thank you in advance.

A: To group elements for navigation inside the fancybox, you need to set the rel attribute on each on them.
The same rel value will tell fancybox that all of them are to be present to navigation if one gets open.
See this working Fiddle!
GROUP EXAMPLE
HTML

JQUERY
$("a[rel=example_group]").fancybox();

GROUP EXAMPLE ONE VISIBLE, REST HIDDEN
HTML

JQUERY
$("a[rel=group2]").fancybox();

A: I do it like this
$("#fancybox-manual-c").click(function() {
            $.fancybox.open([
                {
                    href : '1_b.jpg',
                    title : 'My title'
                }, {
                    href : '2_b.jpg',
                    title : '2nd title'
                }, {
                    href : '3_b.jpg'
                }
            ], {
                helpers : {
                    thumbs : {
                        width: 75,
                        height: 50
                    }
                }
            });
        });


text:
Q: sockets - UDP Send data via internet I've made a simple chat application in c#.net that sends and receives data between 2 computers.
So, I used this method to send the data:
int port = 11000;
private void send(string data, string ip)
{
    Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    IPEndPoint sending_end_point = null;
    byte[] send_buffer = Encoding.ASCII.GetBytes(data);
    sending_end_point = new IPEndPoint(IPAddress.Parse(ip), port);
    try { sending_socket.SendTo(send_buffer, sending_end_point); }
    catch { }
}

And to receive I used this:
string receiveddata = "";
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    UdpClient listener = new UdpClient(port);
    IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
    byte[] receive_byte_array;

    try
    {
        receive_byte_array = listener.Receive(ref groupEP);
        receiveddata = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
    }
    catch { }
    listener.Close();
}

This works without any problems between 2 computers on a LAN, but I would like to know (if possible) how to do the same thing over the Internet.
From what I've searched on the Internet, it seems that I have to use port-forwarding in order to do that, so I already did that, but I don't know what should I do know.
So my question is, how should I change this code (if I have to) so I could send and receive data (UDP) over the internet, assuming I have port-forwarded correctly already and assuming I know the external IPs of both routers?
Thank you in advance.

A: This should work just fine, as long as your (public) IP-address is correct and the ports are forwarded correctly on your router (meaning, forwarded to the correct private IP, on the correct protocol, in your case UDP).
You are aware that this is UDP though, so it's not reliable data transfer.


text:
Q: Json map in React Js How can map the json in react js
======================
const temp1 = [
       {
          code:"
Hai
",
          img: "",
        },
        {
          code:"
World
",
          img: "",
        }
      ];

============================

A: If you want to map and render the html you can map and use dangerouslySetInnerHTML
const temp1 = [{
    code: "
Hai
",
    img: "",
  },
  {
    code: "
World
",
    img: "",
  }
]

const Component = () => {
  return (
    <>
      temp1.map(el => (
        <div key={el.code} dangerouslySetInnerHTML={{__html: `${el.code}${el.img}`}} />)
      )
    </>
  )
}

A: To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property :
return (

      {temp.map(({code, img}, index) => (

        ))}

A:    import Image1 from "./images/image1.jpg"
   import Image2 from './images/image2.jpg'
   const temp1 = [
    {
      code_content : 'Hello',
      img_src : Image1
    },
    {
      code_content : 'World',
      img_src : Image2
    }
   ]
   const App = () => {
    return

      {temp1.map((item) => {
        <>

{item.code_content}

        </>
      })}

   }


text:
Q: Systemctl cannot run Script command on openvpn It is weird that the /usr/lib/systemd/system/openvpn@.service is a simple task:
[Unit]
Description=OpenVPN Robust And Highly Flexible Tunneling Application On %I
After=network.target

[Service]
Type=notify
PrivateTmp=true
ExecStart=/usr/sbin/openvpn --cd /etc/openvpn/ --config %i.conf

[Install]
WantedBy=multi-user.target

However, when I tried to make a self-start openvpn script like autoinit.service with
ExecStart=/bin/bash /root/setvpn.sh
Where as /root/setvpn.sh:
#!/bin/bash
/usr/sbin/openvpn --config /etc/openvpn/tun0.conf

Then this indirect start encounters a mistake:
# systemctl start autoinit
Warning: autoinit.service changed on disk. Run 'systemctl daemon-reload' to reload units.
# systemctl status autoinit
● autoinit.service - Sets up OpenVPN servers
   Loaded: loaded (/usr/lib/systemd/system/autoinit.service; enabled; vendor preset: disabled)
   Active: deactivating (stop-sigterm) since Fri 2020-05-15 18:54:50 CST; 12s ago
  Process: 10692 ExecStart=/root/setvpn.sh (code=exited, status=0/SUCCESS)
 Main PID: 10692 (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/autoinit.service
           └─10694 /usr/sbin/openvpn --config /etc/openvpn/tun0.conf

Actually if I run systemctl daemon-reload before start this autoinit service, it will halt and cannot start at all.
Of course /root/setvpn.sh has no problem of execution, why is that systemctl cannot run it?


text:
Q: Unable to update google spreadsheet from data entered in sidebar I have created sidebar through google script HTML and when I am trying to append the data entered in Sidebar to Active Google Spreadsheet and I am unable to trace where the code is failing to append the entered data. I am attaching my HTML code and gs code. Request to let me know where my code went wrong.
Also I would like to create a drop down for dependency field which needs to take input from spreadsheet, I have no idea about this can anyone help with the literature. Thank you in advance
function SideBar() {

  var template=HtmlService.createTemplateFromFile('SideBar')
  var html= template.evaluate();
  html.setTitle("New Task");
  var ui=SpreadsheetApp.getUi();
  ui.createMenu("Task Manager")
  .addItem("Add New Task","SideBar")
  .addToUi();
  //.addItem("Update Task","SideBar")
  //.addToUi();
  //.addItem("Re-assign Task", "SideBar")
  //.addToUi();
  ui.showSidebar(html);
  }

function appendData(data){

  //var url= '1S64cYsfHEcddmOfXNfAO6VaCQ9LIFPylx8Sj_6h70e4';
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Task");
  var log= ws.appendRow([data.Task,
                data.TaskDescription,
                data.AssignedTo,
                data.StartDate,
                data.EndDate,
                data.PriorityType,
                data.Dependency]);
  Logger.log(log);

}

/* HTML File code below */
<!DOCTYPE html>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

          assignment
          <input id="Task" type="text" class="validate">
          Task

          description
          <input id="TaskDescription" type="text" class="validate">
          Task Description

          assignment_ind
          <input id="AssignedTo" type="email" class="validate">
          Assigned To

          <input id="StartDate" type="date" class="validate">
          Start Date

          <input id="EndDate" type="date" class="validate">
          End Date

          <input id="PriorityType" type="text" class="validate">
          Priority Type

          <input id="Dependency" type="text" class="validate">
          Dependency

         <button class="btn waves-effect waves-light">Assign
           <input id="btn">
           send
        </button>

A: I simplified your code a lot.  There  were several client side errors in it.  I recommend you spend more time learning about using  your browsers developer tools.  Especially the console.log.
You will probably want to bring some of your styling back in I'd do it slowly so you don't get lost again.
Any way this works now with a similar addRecord function.
Google Script:
function ShowDialog() {
  var userInterface=HtmlService.createHtmlOutputFromFile('aq7');
  var ui=SpreadsheetApp.getUi();
  ui.showSidebar(userInterface);
  }

function appendData(data){
  Logger.log(data);
  SpreadsheetApp.getActive().getSheetByName("Task").appendRow([data.text]);
}

html:
<!DOCTYPE html>

    <input type="text" id="txt" />
    <input type="button" value="Assign" onClick="addRecord();" />

This error took a while to find.  Can you see where it is?
document.getElementbyId("btn").addEventListener("click",addRecord);

A: Thank you Cooper. Your script has helped me and finally it is working when I change the input button outside div and gave Onclick run function directly. Still I am not sure why Event Listener command did not work.
The Codes are as follows:
G code:
   function onOpen() {
      var userInterface=HtmlService.createHtmlOutputFromFile('SideBarBackUp');
      userInterface.setTitle('New Task');
      var ui=SpreadsheetApp.getUi();
      ui.showSidebar(userInterface);
      ui.createMenu("Task Manager")
      .addItem("Add New Task","SideBar")
      .addToUi();
      }

    function appendData1(data){
      Logger.log(data);
      SpreadsheetApp.getActive().getSheetByName("Task").appendRow([data.txt,data.dxt,data.axt,data.sxt,data.ext,data.pxt,data.yxt]);
    }

HTML Code:
<!DOCTYPE html>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

          assignment
          <input id="Task" type="text" class="validate">
          Task

          description
          <input id="TaskDescription" type="text" class="validate">
          Task Description

          assignment_ind
          <input id="AssignedTo" type="email" class="validate">
          Assigned To

          <input id="StartDate" type="date" class="validate">
          Start Date

          <input id="EndDate" type="date" class="validate">
          End Date

          <input id="PriorityType" type="text" class="validate">
          Priority Type

          <input id="Dependency" type="text" class="validate">
          Dependency

       <input id=btn type="button" class="btn waves-effect waves-light" value="Assign" onClick="addRecord();" />

Thank you once again for patience response and as a newbie to coding I would surely work more on my coding skills.


text:
Q: MVC UpdateModel is not updating some of the model properties In my MVC 5 EF Database First project I have been using UpdateModel method in my controller action successfully, but after including some additional fields (previously unused by application) I find that the new fields simply refuse to get values from the UpdateModel method call. The only thing of any significance I can identify is that the fields share part of their name.
Consider this class as an example:
public class Record
{
public int ID {get;set;}
public string Details {get;set;}
public string DetailsFile {get;set;}
...
}

The property/field DetailsFile was previously unused, but now is an optional field on the web form. It is stored in a <input type="hidden" name="DetailsFile" id="DetailsFile /> and is successfully posted to the controller action with the correct value (or empty string).
Within the controller action I handle the update like this:
[HttpPost]
public async Task<ActionResult> Edit(Record_EditView model, FormCollection collection)
{
    if (ModelState.IsValid)
    {
        try
        {
            var record = await db.Record.FindAsync(model.ID);
            UpdateModel(record, collection);
            db.Entry(record).State = EntityState.Modified;
            await db.SaveChangesAsync();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }
    // do more stuff here
    ...
}

Which has been working fine, but with the additional field all fields except the DetailsFile get updated from the FormCollection that is passed in. I have inspected both the model and the collection and they have the correct value, but the record never gets the values until I do a second post of the same data. Then the values get pushed in to the fields as expected.
I don't get any errors thrown and am at a bit of a loss as to what is going on. For the time being I have resorted to modifying my controller action to this:
[HttpPost]
public async Task<ActionResult> Edit(Record_EditView model, FormCollection collection)
{
    if (ModelState.IsValid)
    {
        try
        {
            var record = await db.Record.FindAsync(model.ID);
            UpdateModel(record, collection);
            record.DetailsFile = collection["DetailsFile"]; // <-- Manually insert DetailsFile value
            db.Entry(record).State = EntityState.Modified;
            await db.SaveChangesAsync();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }
    // do more stuff here
    ...
}

And this works OK, however I'm sure that I shouldn't have to do this, and hope that someone out there can explain what I am overlooking!

A: Finally found the problem, it is not likely to benefit many people but just in case here is the answer.
More Information
In my project I started using a jquery plugin for styling file input elements in a more bootstrap fashion, namely Jasny Bootstrap.
The plugin works great, however as part of it's internal workings it takes steps to maintain state of existing data and avoid post conflict by using hidden input and renaming the file input like this:
this.$hidden.val('')
this.$hidden.attr('name', '')
this.$input.attr('name', this.name)

The Problem
Which ends up with element(s) that have an attribute name="" and that caused the page to post the element and the FormCollection to include an empty/"" item(s).
Despite the fact that no errors were thrown, nonetheless it seems to break the call to
UpdateModel(record,collection)

The Solution
To fix this and avoid posting the selected file (my project doesn't actually want the file to be posted, just the file path) I just intercept the form submit to remove the unwanted form elements prior to posting:
$('form').submit(function (e) {
    e.preventDefault();
    // get rid of any input elements that have name="" or file elemnts so will not mess with the posted form collection
    $('input[name=""],input[type="file"]').remove();
    this.submit();
})


text:
Q: Run cron at 7AM on multiple timezones I would like to run cron jobs when it is 7AM locally in Western US, Eastern US and some other timezones in Asia and Europe.
This is a node.js server, so I can probably use node-cron to do this but I'd like to use the regular cron if it's at all possible.

A: Times in the crontab always refer to the current system time. You will have to subtract or add timezone differences to calculate the execution intervals on your server.
E.g.:
Your server is in the Western US (UTC+8) and the system date is set to be UTC+8. 7am can be specified in crontab using
0 7 * * * /run/me-for-western-us

To run a script when it is 7 am in Eastern US (UTC+5), you need to subtract 3 hours
0 4 * * * /run/me-for-eastern-us

Do the same for all other timezones.


text:
Q: Error sending emails with Rails 4 & Devise (connection refused, port 25) I'be been having some massive issues getting emails to send. I've tried multiple ways of doing things; using gmail, mailgun, sendgrid, the mailgun gem etc, no luck at all. For some reason it's trying to send using port 25 although, as you can see below, I'm specifying port 587. The error I get is:
Errno::ECONNREFUSED (Connection refused - connect(2) for "localhost" port 25):
My development.rb file is as follows:
  config.action_mailer.default_url_options = { :host => 'localhost:3000' }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true

  config.action_mailer.smtp_settings = {
  :address => 'smtp.mailgun.org',
  :port => 587,
  :api_key => 'key-5d321b99f722e71f759993ee41512b99',
  :user_name => 'postmaster@sandbox3ed8de9510c845c68bf0d867a8f25394.mailgun.org',
  :password => '(mailgun password)',
  :domain => 'sandbox3ed8de9510c845c68bf0d867a8f25394.mailgun.org',
  :authentication => :plain,
  :enable_starttls_auto => true
  }

I have looked around for solutions however none seem to solve the issue. I'm totally out of ideas.
entire Development.rb document:
    Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send.

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    user_name: "chris.edhogben@gmail.com",
    password: "<password>",
    authentication: 'plain',
    enable_starttls_auto: true
  }

  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default :charset => "utf-8"

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # Adds additional error checking when serving assets at runtime.
  # Checks for improperly declared sprockets dependencies.
  # Raises helpful error messages.
  config.assets.raise_runtime_errors = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true
end

A: Try This configuration
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address:  'localhost',
  port:     25,
  domain:   'exmaple.com',
      enable_starttls_auto: false
}

A: Use the below settigns in production.rb
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true

  ActionMailer::Base.smtp_settings = {
    :address => 'smtp.mailgun.org',
    :port => 587,
    :user_name => 'postmaster@sandbox3ed8de9510c845c68bf0d867a8f25394.mailgun.org',
    :password => '(mailgun password)',
    :domain => 'sandbox3ed8de9510c845c68bf0d867a8f25394.mailgun.org',
    :authentication => :plain
  }

A: Use the below settigns for gmail:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address: "smtp.gmail.com",
  port: 587,
  user_name: "username",
  password: "password",
  authentication: 'plain',
  enable_starttls_auto: true
}

If you get SMTP authentication error , then click on http://www.google.com/accounts/DisplayUnlockCaptcha & enable it. It will enable google for registering new apps within 10 minutes

A: add same mail configuration in production.rb also.
Restart the server and check


text:
Q: Proof: $\phi$ is monotonly decreasing. Let $\phi : [0,+\infty[ \to \mathbb{R}$ be a continuousand two times differentiable function, such that $\phi'(0)=0$ and $\phi''(t) \leq -3\phi'(t)$.
Proof that $\phi$ is monotonly decreasing.
My idea was to show that the first derivative is $\leq 0 $. But I'm having a hard time to show that.

A: $$\Longleftrightarrow \phi''(x)e^{3x}+3\phi'(x)e^{3x} \le 0\Longleftrightarrow \left(\phi'(x)e^{3x}\right)' \le 0$$
We deduce that $\phi'(x)e^{3x}$ is decreasing, then for $x \in [0, +\infty[$ :
$$\phi'(x)e^{3x}\le \phi'(0)e^{0} = 0 \implies \phi'(x) \le 0$$
Q.E.D

A: $\phi$ is strictly decreasing whenever it is positive. If there were an $x$ such that $\phi'(x) > 0$, then we would also have $\phi'(y) > \phi'(x)> 0$ for all $y < x$, which would violate $\phi'(0) = 0$.


text:
Q: Unable to set default text box values Here is my html code of angularjs app
<input type="text" class="input-xlarge" id="user_name" ng-model="myModel.text1"
   name="user_name" rel="popover" data-content="Enter your first and last name."
   data-original-title="Full Name">

And here is the constructor code
    function MyCtrl2($scope) {
         var initial = {text1: 'initial value'};
         var ini = {text2: 'initialvalue'};
         $scope.myModel = angular.copy(initial);
         $scope.myModel = angular.copy(ini);
}

MyCtrl2.$inject = ['$scope'];

The default value in only one text box usr_email is getting populated.But not in user_name
Can any one point what may be wrong.

A: You can't use angular.copy as it will override the $scope.myModel when used for the second time (when copying init). Use angular.extend instead, to copy all properties of ini and initial to your model:
function MyCtrl2($scope) {
     var initial = {text1: 'initial value'};
     var ini = {text2: 'initialvalue'};
     $scope.myModel = {};
     angular.extend($scope.myModel, initial, ini);
}


text:
Q: Lambda expression in a List not working I am working in a Java application with Java 8, using the stream functionality
I have this POJO:
public class Authority implements GrantedAuthority {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private final String authority;

    public Authority(String authority) {

        this.authority = authority;
    }

    @Override
    public String getAuthority() {
        return authority;
    }

    @Override
    public String toString() {
        return "Authority [authority=" + authority + "]";
    }
}

and
public class User implements Serializable, UserDetails {

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
        return authorities;
    }

    public boolean isAdmin() {
        return getAuthorities().stream().filter
            (o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
    }
}

and I've created this Junit to check if everything os OK
  @Test
    public void isAdminTests() {

        User adminUser = UserUtils.createBasicUser("user2@gmail.com", "user2@gmail.com", true);
        Set<UserRole> adminUserRoles = new HashSet<>();
        adminUserRoles.add(new UserRole(adminUser, new Role(RolesEnum.ADMIN)));
        adminUser.getUserRoles().addAll(adminUserRoles);

        System.out.print(adminUser.getAuthorities());

        assertTrue (adminUser.isAdmin());

    }

and this is the value in the console:
[Authority [authority=ROLE_ADMIN]]

But I have an assertion error

A: My guess is that you compare the Authority Object (which is a String IIRC) with the enum object
o.getAuthority().equals(RolesEnum.ADMIN))

You have to compare these two diffrent objects so that a match is possible
You could try
o.getAuthority().equals(RolesEnum.ADMIN.name()))

when you can ensure that the enum names always are the same as the role names.

A: Not sure, but try this:
here
public boolean isAdmin () {
        return getAuthorities().stream().filter
                (o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
    }

change to smth like this:
o.getAuthority().equals(new GrantedAuthority(RolesEnum.Admin.name()))).findFirst().isPresent();

Because when you creating spring authorities "ROLE_" is added by default as a prefix to your String role representation


text:
Q: regex replace using function python I'm trying to print a table of my database using :
pd.read_sql_query("SELECT name,duration FROM activity where (strftime('%W', date) = strftime('%W', 'now'))", conn))

and it work it prints :
                   name  duration
 0        programmation       150
 1              lecture        40
 2                  ctf        90
 3                  ceh        90
 4        deep learning       133
 5  vm capture the flag       100

but I would like to use my function minuteToStr who translate the duration to string likes "1h30" on the duraton colowns.
I tried this code but it does'nt work :
tableau = str(pd.read_sql_query("SELECT name,duration FROM activity\
                 where (strftime('%W', date) = strftime('%W', 'now'))", conn))
tableau = re.sub("([0-9]{2,})",   minuteToStr(int("\\1")), tableau)
print(tableau)

Thanks

A: Make this easy, just use a little mathemagic and string formatting.
h = df.duration // 60
m = df.duration % 60

df['duration'] = h.astype(str) + 'h' + m.astype(str) + 'm'
df

                  name duration
0        programmation    2h30m
1              lecture    0h40m
2                  ctf    1h30m
3                  ceh    1h30m
4        deep learning    2h13m
5  vm capture the flag    1h40m

A: re.sub doesn't work this way. It expects a string, not a DataFrame.
Given that minuteToStr accepts an integer, you can simply use apply:
tableau['duration'] = tableau['duration'].apply(minuteToStr)

A: Similar to using a function inside re.sub in pandas  we can use str.replace . Similar type is used here i.e
If duration column is of integer type then
tableau['duration'].astype(str).str.replace("([0-9]{2,})", minuteToStr)

Else:
tableau['duration'].str.replace("([0-9]{2,})", minuteToStr)

To illustrate using function inside replace (I prefer you go with @colspeed's solution)
def minuteToStr(x):
    h = int(x.group(1)) // 60
    m = int(x.group(1)) % 60
    return str(h) + 'h' + str(m)

df['duration'].astype(str).str.replace("([0-9]{2,})",minuteToStr)

            name duration
0     programmation     2h30
1           lecture     0h40
2               ctf     1h30
3               ceh     1h30
4      deeplearning     2h13
5  vmcapturetheflag     1h40