text:
Q: Help me understand a script that uses csplit and sed I wanted a simple way to export notes from the reference manager, Zotero. I start by selecting multiple notes and dragging them into a blank text file.
I also want achieve "atomicity" of my notes, so I need to split the resulting text files which contain the individual notes in sections separated by lines of dashes.
I then want to use the heading I gave to each note to name the new files i.e.: rename with the first line of each section. I want to save these new files as markdown files.
The script I have put together is made up of suggestions for each of these functions by contributors on the web.
I am trying to make sure that I understand the commands in the script correctly before sharing it with colleagues who have a similar use case to mine. My understanding (from reading Gilles' answer to another question - see reference link below) of the need for quote marks around the "$f" in the "head" command does not seem to be correct. I tried the script without the quotes and got the same result. Are the double quotes not really needed because "$f" appears on the right-hand side of an assignment? Are they only there because it is easier to double quote by default than to remember when they are not needed? Any further explanation would be much appreciated.
An example of the input file would be the following in Notes_test.txt
This is note 1

It has some notes

--------------------------------------------------

This is note 2

It has some more notes

The output from this should be two files:
This is note 1.md
This is note 2.md

This is the script I am using on the command line:
csplit Notes_test.txt -f_ -z -b'%03d.md' /--------------------------------------------------/1 {*} && sed -i '/./,$!d' *.md && for f in *.md
    do
    f1=$(head -n1 "$f")
    mv -n "$f" "$f1.md"
    done

and this is my understanding of the commands so far:
-fPREFIX Use PREFIX as the output file name prefix. In this case an underscore is specified: "_" which I see is just a placeholder.
-z Suppress the generation of zero-length output files. I think this is necessary because otherwise csplit will produce an empty file at the end of each run through splitting the original files.
-bSuffix Use SUFFIX as the output file name suffix. In this case: "md"
%03d puts a 3 digit number as a placeholder for the file name. I added the zero before the 3 at the suggestion of FelixJN.
/--------------------------------------------------/1 specifies the delimiter for the split, with the split being made 2 lines below the the line of "-"s (count starts from 0).
{*} tells bash to run the split until the end of the file. As Felix points out, "{n}" is the number of splits to be executed. In this case "*" means do as many as possible.
&& means execute the following command on the condition that the previous command has completed
sed -i directs sed to operate on files with a particular suffix
'/./,$!d' means "remove blank lines at head of file" Thanks to Felix again for explaining that that this is to specify the range on which sed works:  A "." means any character, so it specifies the first character that occurs in the document. Since empty lines do not have any characters, we will need to apply the negative "!" after defining the range. The range is defined by the pattern /"start"/,/"end"/ to apply the command between the strings "start" and "end". $ refers to the last line, so the range is all the non-empty lines in the document. To apply the negative use "!" meaning "NOT", i.e. tell sed to select the opposite of the previous range. In this case all lines before the first line with any character. "d" then deletes these lines.
*.md means "which has any name with suffix .md"
f1=$(head -n1 "$f") means: define f1 as the first line ("head" means "first line") of the file. This is done by using the variable signifier "$" to define "f1" which will be a placeholder (in the next line of the script) for the new file names (minus suffix). "head" is a bash command that normally outputs the first 10 lines of each file: head [OPTION]... [FILE]... The option -n1 specifies to output one line only. Here, instead of specifying a particular FILE, "$f" specifies "all files." The quote marks around "$f" are needed so that whitespace is ignored (otherwise $f uses whitespace as field separator and further splits the files - see reference link below).
mv -n "$f" "$f1.md" means: rename each file as "f1.md"
The bash command "mv" takes options and arguments:  mv [OPTION]... [-T] SOURCE DEST i.e.: "Rename SOURCE to DEST." The -n option stands for   --no-clobber     "do not overwrite an existing file." I think this is just in case there are files (notes) that have the same first line.
See https://www.tutorialspoint.com/unix_commands/csplit.htm and
coreutils for unix-like operating stems at https://www.gnu.org/software/coreutils/manual/coreutils.pdf
and https://www.howtoforge.com/linux-csplit-command/ Q2.How to split files using regular expressions?
and Why does my shell script choke on whitespace or other special characters?
When is double-quoting necessary?

A: Since I do not see any problems in your understanding, I will focus on the sed part.
Ranges
sed may work a command on a range, e.g. replacing (substituting) an A (i.e. the first in a line) with a B from line 11 to line 20 looks like:
sed '11,20s/A/B/'

A range may also be defined by pattern matches lie /start/,/end/ to apply the command between the strings start and end.
In your case we have /./,$.
A . means any character, empty lines do not have any characters, so it will only apply when a line is NOT empty.
$ just refers to the last line, so we would do it for the whole document, but skip the empty lines at the beginning.
Now ! comes into play, which means NOT, i.e. select the opposite of the previous range. In this case all lines before the first line with a character.
d then deletes these lines.

One more comment on '{*}' in csplit . '{n}' is the number splits that are to be executed, the asterisk just means as many as possible. You also could only split 5 times.
Instead of %3d, I'd suggest using %03d for zero-padded three-digit numbers, it makes sorting easier.


text:
Q: Justify css menu in IE I want to make a CSS menu auto-justify full width.
HTML:

click

click

long clickclick

click

clickclickclick

click click 666

CSS:
.menu {
  text-align: justify;
  font-size: 0;
  font-size: 14px\9; /* IE6-9 hack */
  line-height: 0;
}
.menu:after {
  content: '';
  display: inline-block;
  width: 100%;
  height: 0;
  zoom: 1;
  *display: inline;
}
.menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: inline;
}
.menu ul li {
  display: inline-block;
  font-size: 14px;
  zoom: 1;
  *display: inline;
}
.menu ul li a {
  line-height: 54px;
}

Demo
It working good on Chrome/Firefox, but not working on IE 10-11. Coud someone please help me fix this?

A: I had the same problem, add text-justify: distribute to your .menu and it will work fine.

A: Do you mean you want to have the menu spread across the width of the page? In that case, adding min-width:100%; to .menu in your CSS file will achieve that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How, using TortoiseSVN, to include some of a file's changed lines but not others in a commit? I know this is possible with git (by selecting which changed lines in which changed files you want to bundle together in a single commit before then executing the commit).
Is this also in svn (and Tortoise SVN)?

A: You can do it with TortoiseSVN, but:

*

*only partially the same way, as in Git

*only with TortoiseSVN 1.8 - read "Commit only parts of a file" in Release Notes

A: No, it's not possible with SVN.
Create a backup copy of your file. Then edit the file and make it contain what you want to commit, then commit, then restore the backup copy.
That said, I would not call that a good practice, even with git. You'd better use branches to make unrelated changes to the same file.

A: You have to do that by hand. Edit your file to select only the change you want (after making a backup) and commit.


text:
Q: Find common values in many tables I have 5 tables and I want to find the common values between them in one column. The column name differs in two tables(account_number, account,account_id).
select * from db.table1 as a
INNER JOIN db.table2 as b
ON a.account = b.account_id
INNER JOIN db.table3 as c
ON a.account = c.account_number
INNER JOIN db.table4 as d
ON a.account  = d.account_number
INNER JOIN db.table_5 as f
ON a.account = f.account_number;`

I tried the above with the idea of every time compare the last result of the inner join with the new one but it seems wrong.

A: Your method is okay, but it can return duplicates.  Another method is to use union all:
select account
from ((select account, 'a' as which from db.table1) union all
      (select account_id, 'b' as which from db.table2) union all
      (select account_number, 'c' as which from db.table3) union all
      (select account_number, 'd' as which from db.table4) union all
      (select account_number, '3' as which from db.table5)
     ) t
group by account
having count(distinct which) = 5;

Note that this can be easily tweaked to get accounts that are in three or four tables rather than in all of them.


text:
Q: Jupyterhub using sudo without root: can't run sudospawner without pw I'm struggling to fire up jupyterhub, running with limited sudo rights, without root privileges. If I understand correctly, this makes it possible to run notebook servers as real system users on a shared system without running the Hub itself as root.
I followed the following steps, but for someone reason the following command keeps giving me the error that my new user (rhea) is required to give password:
sudo -u rhea sudo -n -u $USER /usr/local/bin/sudospawner --help
# sudo: a password is required

I added the following lines to /etc/sudoers (edited using visudo):
Cmnd_Alias JUPYTER_CMD = /usr/local/bin/sudospawner
rhea ALL=(%jupyterhub) NOPASSWD:JUPYTER_CMD

And added a new user to the group jupyterhub:
adduser -G jupyterhub newuser

I'm struggling to see why rhea is not allowed to run sudospawner. If I simply run sudo /usr/local/bin/sudospawner --help I do get the desired result.
Running on Ubuntu 16.04 EC2.
Help and advice on this is highly appreciated!

A: using the groupname in ALL=(%jupyterhub) doesn't seem to work.
try replacing it with something like
Runas_Alias JUPYTER_USERS = %jupyterhyb
rhea ALL=(JUPYTER_USERS) NOPASSWD:JUPYTER_CMD
hope it works ;)


text:
Q: After upgrading PHP to version 7, why can't I use the mongodb driver? Well here's an odd situation I've found. I've been using PHP and MongoDB together on a project, and updated the associated software. After the upgrade, I did make sure to update the new conf files and all is well --- except when I try to use the MongoClient class, I get the following fatal error:

Fatal error: Uncaught Error: Class 'MongoClient' not found in /srv/http/test.php

So my first instinct was to check my /etc/php/php.ini to make sure that mongodb.so was correctly included. I found it after the other extension lines:
extension=mcrypt.so
extension=zip.so
extension=mongodb.so ; <--- here it is

With that checked, I loaded up a quick phpinfo() script to check that I was using the right php.ini file, and confirmed that I am. And not only that, the mongodb driver also appears to be loaded correctly!
Loaded Configuration File      /etc/php/php.ini
. . .
mongodb support                enabled
mongodb                        version      1.1.1
mongodb                        stability    stable
libmongoc                      version      1.3.1-dev
libbson                        version      1.3.0

So I restarted httpd and tried again. No dice, still can't find the MongoClient class. So I tried to install it from pecl instead of my distribution's package manager, and the situation is the same as described above.

So here's a quick rundown of the situation:

*

*Linux kernel 4.3.3

*PHP Version 7.0.1

*php-mongodb version 1.1.1

*

*Yes, 1.1.1 supports php7.

*Seems properly configured, and mongodb is enabled and shown in phpinfo().

*Tried installing the mongodb driver through pecl and my distro's package manager.

Other info that may be useful:

*

*MongoDB Version 3.2.0

*mongod is running

*Also tried rebooting, no change.

A: Well I found the answer.
The class has been changed. It's no longer \MongoClient, and is now \MongoDB\Driver\Manager
All that I need is a refactor. The new driver is designed to be a lower-level driver for high-level functionality to be filled with userspace libraries, so anyone else upgrading to php7, make sure you check that you'll be comfortable with the new driver, or that the userspace libraries exist when you do it. Hopefully this question/answer helps others in the future.
Commenter ianaz below has posted this good userspace library for MongoDB: http://mongodb.github.io/mongo-php-library/


text:
Q: How to use Ajax Get method to connect WCF service? DO I need to start cros? I met an issue on Ajax to connect WCF Service. we are using Get and Post method to get JSON results. All I used is the stand coding from WebSite and We try a lot solutions about how to resolve this issue, but, unlucky, Nothing helps. We always get an error on CROS issue.
So does any new solution for this issue? It break us 2 days already.
Any suggestions is good.
Thanks for your taking time looking this post!
Rocky

A: may be below blog will help you in access WCF service in cross domain
http://www.dotnet-tricks.com/Tutorial/wcf/X8QN260412-Calling-Cross-Domain-WCF-Service-using-Jquery.html


text:
Q: How do you pull variable from an object in a linked list of objects I am currently building an address book.  I am storing each entry into the address book as an object.  My problem is that I cannot figure out how to get any specific variable from an object and display it.  Such as the firstName for example.  It's supposed to write the variables to a file which will be loaded into the array when the program is started again.
        class ExitListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        try {
            PrintWriter output = new PrintWriter(FILE);
            ListIterator it1 = set.listIterator();
            while (it1.hasNext()){

            }
            output.flush();
            output.close();

        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.exit(0);
    }
}

A: I'm going to have to apply my psychic debugging powers here, as you haven't presented any code. My guess is that you've got a variable like this:
LinkedList list = new LinkedList();
list.add(new Person());
...
Object fetched = list.getFirst();
// Problems...

If you use generics, this becomes:
// Or use an interface type, of course
LinkedList<Person> list = new LinkedList<Person>();
list.add(new Person());
...
Person fetched = list.getFirst();
System.out.println(person.getFirstName()); // Hooray!

A: If you mean LinkedList then you can simply loop thru your linkedlist and get the first name .
LinkedList<Person> list = new LinkedList<Person>();
Person p = new Person();
p.setFirstName("myname");
list.add(p);

for(Person p: list) {
  Sysout(p.getFirstName());
}


text:
Q: VCRUNTIME140_1.dll Reported Missing Although VCRuntime 2015-2019 deinstalled and VCRuntime 2015 reinstalled We are maintaining the localized release of a major CAD-program (>500 DLLs) and create add-in applications to expand its functionality (added as DLLs).
The main application installs Visual C++ Redistributables 2005 (x86), 2010 (x64), 2012 (x64) and 2015 (x64).
If we install (because of our Visual Studio version) the new Visual C++ redistributable 2015-2019 (x64), all applications work perfectly.
After the test, we now manually rolled back the installation to the original state by de-installing the runtime 2015-2019 (x64) and re-installing the original runtime 2015 (x64).
The main application does no longer start as it misses VCRuntime140_1.dll. However, it should look for VCRuntime140.dll again.
Apparently, Microsoft redistributable installation/de-installation is responsible for this error.
Any known Workaround or Solution? We greatly would appreciate your help and hints.

A: Just ran into this as well. The issue is with what happens during uninstall of the 2019 runtime:

*

*VCRuntime140_1.dll is removed (as expected, because this file did not exist in the 2015 runtime)

*VCRuntime140.dll remains (because this file existed in the 2015 runtime)

The issue is that the VCRuntime140.dll that remains is the version of that file that was installed with the 2019 runtime. The 2015 version is not restored. The result is that this DLL expects to be able to call functions found in VCRuntime140_1.dll, but that file is no longer present.
To work around this, we are opting not to rollback the runtime version from 2019 to 2015, as the 2019 runtime will support applications built for 2015 without issue (and in fact does so already if another application requiring the 2019 runtime were to be installed on the machine, independent of your add-in)

A: copy:
msvcp140.dll
vcruntime140.dll
vcruntime140_1.dll

Place the DLL files in the directory next to the executable and the other DLLs, and bundle them together in a zip file. The resulting structure looks something like this:
Release
│   flutter_windows.dll
│   msvcp140.dll
│   myapp.exe
│   vcruntime140.dll
│   vcruntime140_1.dll
│
└───data
│   │   app.so
│   │   icudtl.dat
...


text:
Q: Installing Perl DBI in SUN Solaries I am trying to install perl DBI on SUN solaries 11 but I always got the following error:
sh: line 1: cc: not found
*** Error code 127
make: Fatal error: Command failed for target `Perl.o'

I did the following steps:
Downloaded and extracted DBI-1.628 then in the shell command:
cd DBI-1.628
make realclean
perl Perlfile.PL
meke

A: This means it cannot find a compiler on your machine.  You should add the path to the compiler to your PATH variable.  gcc and cc are not the same thing.  You should install cc.


text:
Q: How to conditionally update the elasticsearch document? Using update query for document as follows:
/<indexname>/_update/<id>
{
    doc: {
        /// the doc here
    }
}

Is there a way, I can put condition like created_at field in the existing doc is less than created_at we are passing?

A: You are probably looking for update by query api.
e.g.
POST <index>/_update_by_query
{
  "query": {
    "range": {
      "created_at": {
         "lte": "2019-01-10"
      }
    }
  }
}


text:
Q: Extension of an involutive automorphism Suppose that $g$ is a complex semi-simple Lie algebra and $g'$ its reductive subalgebra.
If $\tau$ is an involutive automorphism of $g'$, can $\tau$ be extended to an involutive automorphism of $g$ in general?
If not in general, for what kind of pair $(g, g')$ or $\tau$, this is true?

A: [REVISED]
The answer to the first question is NO.   It's difficult as a rule to show that an involutive automorphism of $\mathfrak{g'}$ fails to extend to $\mathfrak{g}$,
so it may be better to consider first the possible automorphisms of a simple Lie algebra $\mathfrak{g}$ (up to conjugacy in the adjoint group).   This is thoroughly worked out in the context of many other classification problems, in the classic 1978 book Differential Geometry, Lie Groups, and Symmetric Spaces by S. Helgason (reprinted as GSM 34, AMS, 2001).   In Chapter X, $\S5$, Helgason studies automorphisms in the style of Victor Kac, which like other topics in this long chapter requires quite a bit of notation.    But at the end of the section, Helgason explains in detail the possible automorphisms of $\mathfrak{g}$ having order 2, up to conjugacy.   Here the fixed point subalgebra $\mathfrak{g}_0$ for $\mathfrak{g}$ of type $E_8$ can only be of type $D_8$ or else $A_1 \oplus E_7$.
This already shows that the pseudo-Levi subalgebra of type $D_8$ can't have a nontrivial involutive automorphism which extends to one in $E_8$, though $D_8$ does have a nontrivial graph automorphism.    (The situation for an example such as $A_2$ embedded in $G_2$ is similar.)
As Paul Levy notes in his comments, there are other configurations (not involving simple subalgebras of simple Lie algebras) which also cause trouble here.    I've included a couple of doubtful examples of this type in my earlier answer and comments, though as Paul comments it's not possible to rule out existence of some extensions by looking at centralizer dimensions alone.
All of this cautions against expecting to find many positive answers for pairs $(\mathfrak{g}, \mathfrak{g}')$.
[EARLIER TRY]
Start with a simple Lie algebra $\mathfrak{g}$ over $\mathbb{C}$ of type $E_6$.   Using Bourbaki numbering for the vertices of its Dynkin diagram (with 2 assigned to the "extra" vertex), let $\mathfrak{g}'$ be the direct sum of the two rank 1 Lie subalgebras corresponding to the vertices 2 and 6.   The subalgebra $\mathfrak{g}'$ has an involutive automorphism which interchanges these two copies of $\mathfrak{sl}_2$.   But there seems to exist no extension to such an automorphism of $\mathfrak{g}$, essentially because the rank 1 subalgebras involved do not play interchangeable roles in the overall structure of $\mathfrak{g}$.   (For example, their centralizers have different dimensions.)
[EDIT: As Paul notes, this parenthetic comment is false.]
Clearly this would require some work to make rigorous, but such a configuration of the pair $(\mathfrak{g}, \mathfrak{g}')$ indicates the kind of challenge you'd face here and also in your follow-up question.


text:
Q: How to handle RoutedEvent in a grid with command in MVVM light wpf I am using MVVM light to refacter my code. My old code looks like this-
<Grid x:Name="root" ButtonBase.Click="LayoutRoot_Click">

The LayoutRoot_Click will handle all the RoutedEvent from child controls.
Because the grid have no command interface ,so the new code like this
<Grid x:Name="root" ButtonBase.Click="LayoutRoot_Click">
<i:Interaction.Triggers>
    <i:EventTrigger EventName="ButtonBase.Click">
        <mvvm:EventToCommand Command="{Binding InputCommand}" CommandParameter="{Binding ElementName=button1}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

The viewmodel like this-
public class SomeViewModel : ViewModelBase
{
    public SomeViewModel()
    {
        InputCommand = new RelayCommand(InputCode);
    }

    public ICommand InputCommand { get; set; }

    private void InputCode()
    {
        string input = string.Empty;
    }
}

But this doesn't work. The command did not get the RoutedEvent.

A: Try adding PassEventArgsToCommand="True" to your command binding
<Grid x:Name="root" ButtonBase.Click="LayoutRoot_Click">
<i:Interaction.Triggers>
    <i:EventTrigger EventName="ButtonBase.Click">
        <mvvm:EventToCommand Command="{Binding InputCommand}" CommandParameter="{Binding ElementName=button1}" PassEventArgsToCommand="True"/>
   </i:EventTrigger>
</i:Interaction.Triggers>

Your command would then have to have a parameter of the correct type which I think is RoutedEventArgs
public RelayCommand<RoutedEventArgs> SomeCommand { get; private set; }
    private void SomeCode(RoutedEvent routedEvent)
    {
        //Do something with the routed event
    }


text:
Q: An OR operator causes two different behaviors I am unable to understand why two conditions containing the same values do not return the same result twice.
Look at the variable content :
$quantity = 1;
var_dump(!$cart = true);
var_dump(!$product = false);
var_dump($quantity <= 0);
--------
Output : bool(false) bool(true) bool(false)

Based on those boolean, I expect the following condition will return TRUE :
$quantity = 1;
var_dump(!$cart = true || !$product = false || $quantity <= 0);
---------
Output : bool(false)

Why ? I was expected this to be TRUE
And why the following exact same condition output what I expected : TRUE
var_dump(false || true || false);
---------
Output : bool(true)

EDIT
I know that = is for assignement.
But doing this :
if(!$var = null){
  // $var is not empty
}

Is a way to assign a value and check if this value is null|false|empty|array empty... at the same time.

A: This is about operator precedence and associativity.
var_dump(!$cart = true || !$product = false || $quantity <= 0);

is the same as
var_dump(!$cart = (true || !$product = false || $quantity <= 0));

Result of (true || !$product = false || $quantity <= 0) is true. !true is false.


text:
Q: How to refer to pos and size of widget in python canvas (KIVY)? Here is what I do now, I create a function that can dynamically create a button (in boxlayout):
def create_class_button(self, size_hint_x:float, text:str, text_color:tuple, background_color:tuple) -> TextBoxLayout:
    # Ignore this box
    box = TextBoxLayout(size_hint_x=size_hint_x, padding=(30,6.5), on_press=self.list_item_pressed, background_color=(0,0,0,0))
    # RoundedButton inherited from Button
    btn = RoundedButton(text=text, on_press=self.list_item_pressed, color=text_color, background_color = (0,0,0,0))
    with btn.canvas.before:
            Color(rgba=background_color)
            Rectangle(size=btn.size, pos=btn.pos)
    box.add_widget(btn)
    return box

The canvas always draw at the point (0, 0).
How can I let it follow my RoundedButton position and size?

A: After reading your question several time, I think you are asking how to get the Rectangle to follow your RoundedButton. The best way to do that is to create a rule in kv for the RoundedButton:
<RoundedButton>:
    canvas.before:
        Color:
            rgba: self.background_color
        Rectangle:
            pos: self.pos
            size: self.size

You can do the same in python, but then you must set up bindings to get the Rectangle to follow the RoundedButton. The kv language sets up those bindings for you.
Also, note that the pos and size of a Widget initially get set to the defaults of (0,0) and (100,100), and they get updated when the Widget is drawn. So your canvas is using those initial defaults. And since no bindings are set up, the canvas does not change when the pos and size of the Widget change.


text:
Q: Logrotate not doing any rotation I just set up LogRotate on my RHEL6 server so that it rotates my custom Apache log files. However, it doesn't do anything when i try manually running it.
I expect it to rotate the log files "access.log" and "err.log". They have been there for a few days and need to be rotated.
Here is the output:
[root@pc1 httpd]# logrotate -d -f /etc/logrotate.d/apache
reading config file /etc/logrotate.d/apache
reading config info for /var/log/httpd/*log
/var/www/html/NSLogs/access.log
/var/www/html/NSErrorLogs/err.log

Handling 1 logs

rotating pattern: /var/log/httpd/*log
/var/www/html/NSLogs/access.log
/var/www/html/NSErrorLogs/err.log
 forced from command line (no old logs will be kept)
empty log files are rotated, old logs are removed
considering log /var/log/httpd/access_log
  log needs rotating
considering log /var/log/httpd/error_log
  log needs rotating
considering log /var/www/html/NSLogs/access.log
  log needs rotating
considering log /var/www/html/NSErrorLogs/err.log
  log needs rotating
rotating log /var/log/httpd/access_log, log->rotateCount is 0
dateext suffix '-20131023'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
fscreate context set to unconfined_u:object_r:httpd_log_t:s0
renaming /var/log/httpd/access_log to /var/log/httpd/access_log-20131023
disposeName will be /var/log/httpd/access_log-20131023.gz
running postrotate script
running script with arg /var/log/httpd/access_log: "
      /usr/bin/killall -HUP httpd
"
compressing log with: /bin/gzip
removing old log /var/log/httpd/access_log-20131023.gz
error: error opening /var/log/httpd/access_log-20131023.gz: No such file or directory
rotating log /var/log/httpd/error_log, log->rotateCount is 0
dateext suffix '-20131023'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
fscreate context set to unconfined_u:object_r:httpd_log_t:s0
renaming /var/log/httpd/error_log to /var/log/httpd/error_log-20131023
disposeName will be /var/log/httpd/error_log-20131023.gz
running postrotate script
running script with arg /var/log/httpd/error_log: "
      /usr/bin/killall -HUP httpd
"
compressing log with: /bin/gzip
removing old log /var/log/httpd/error_log-20131023.gz
error: error opening /var/log/httpd/error_log-20131023.gz: No such file or directory
rotating log /var/www/html/NSLogs/access.log, log->rotateCount is 0
dateext suffix '-20131023'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
fscreate context set to unconfined_u:object_r:httpd_sys_rw_content_t:s0
renaming /var/www/html/NSLogs/access.log to /var/www/html/NSLogs/access.log-20131023
disposeName will be /var/www/html/NSLogs/access.log-20131023.gz
running postrotate script
running script with arg /var/www/html/NSLogs/access.log: "
      /usr/bin/killall -HUP httpd
"
compressing log with: /bin/gzip
removing old log /var/www/html/NSLogs/access.log-20131023.gz
error: error opening /var/www/html/NSLogs/access.log-20131023.gz: No such file or directory
rotating log /var/www/html/NSErrorLogs/err.log, log->rotateCount is 0
dateext suffix '-20131023'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
fscreate context set to unconfined_u:object_r:httpd_sys_rw_content_t:s0
renaming /var/www/html/NSErrorLogs/err.log to /var/www/html/NSErrorLogs/err.log-20131023
disposeName will be /var/www/html/NSErrorLogs/err.log-20131023.gz
running postrotate script
running script with arg /var/www/html/NSErrorLogs/err.log: "
      /usr/bin/killall -HUP httpd
"
compressing log with: /bin/gzip
removing old log /var/www/html/NSErrorLogs/err.log-20131023.gz
error: error opening /var/www/html/NSErrorLogs/err.log-20131023.gz: No such file or directory

A: I'm not sure if this is the problem but if Apache is still running it might have a lock on those log-files. Maybe the /usr/bin/killall -HUP httpd does not kill Apache quick enough.
Try shutting Apache down first and see if that helps:
service httpd stop
logrotate -f /etc/logrotate.d/apache
service httpd start

If you don't start Apache with service you need to use the appropriate command.
BTW. my /etc/logrotate.d/httpd (which is your /etc/logrotate.d/apache) looks like this:
/var/log/httpd/*log {
    missingok
    notifempty
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /var/run/httpd.pid 2>/dev/null` 2> /dev/null || true
    endscript
}

A: I changed the format of the config file to the following and it seems to be working fine now.
/var/log/httpd/*log
/var/www/html/NSLogs/access.log
/var/www/html/NSErrorLogs/err.log
{
    copytruncate
    daily
    size 500M
    compress
    dateext
    maxage 60
}


text:
Q: Convert factor into integer based on frequency in R A vector of factor:
vec <- factor(c('a','b','b','c','b','c'))
[1] a b b c b c
Levels: a b c

Would expect a new vector of
vec_new
[1] 3 1 1 2 1 2

The one with higher frequency will be converted to smaller integer.
Any help is appreciated, thank you

A: x2 <- rev(sort(table(x)))
names(x2) <- names(sort(table(x)))
levels(x) <- x2[order(names(x2))]
x
[1] 3 1 1 2 1 2
Levels: 3 1 2

We first find the highest frequency factor and reverse the order (smallest to largest) with rev(sort(table(x))). Next we rename that smallest to largest vector to match the names of the regular largest to smallest frequency table. Lastly, we can now assign the new levels based on the order of the names while using the smallest to largest indices.
Another option courtesy of @RichardScriven:
s <- sort(table(x))
x <- factor(vec, labels = rev(s), levels = names(s))

Data
vec <- letters[c(1,2,2,3,2,3)]
x <- factor(vec)
[1] a b b c b c
Levels: a b c

A: Just to throw in another one-liner:
as.numeric(reorder(vec, -ave(as.numeric(vec), vec, FUN = length)))
# [1] 3 1 1 2 1 2

First, you calculate the (negative - to have the proper ordering afterwards) frequency of each vector level with ave, then you reorder the factor levels with reorder. The latter calculates the mean of -ave(.) for each level and resorts the factor levels accordingly in increasing order (that's why we used -ave(.)). Finally, transform the factor into a numeric.

A: Not sure if there's a more efficient approach, but you you can find out how frequently different levels of the factor occur with table(vec), and then you can manually order the levels of the factor with levels(vec) <- c("b", "c", "a").


text:
Q: Keep the same animation with centered elements I customized the following plus/minus toggle: https://codepen.io/Inlesco/pen/XXRRmY
It consists of 2 elements vertical and horizontal, When the two elements are visible they represent +, And on clicking the vertical disappears and they represent -.
I wanted it to be smaller so I changed the width and height to about the half, And I used transform: translate(-50%) to center the vertical and horizontal elements.
Here is a live fiddle: http://jsfiddle.net/kLc728ad/2/

$('.plusminussign').on('click', function(){
    $(this).toggleClass('opened');
});
.plusminussign{
    position: relative;
    display:inline-block;
    height: 24px;
    width: 24px;
    opacity: .7;
    background: green;
    border-radius: 50%;
    color: #fff;
    cursor: pointer;
}

.circle .horizontal {
  position: absolute;
    background-color: #fff;
    width: 15px;
    height: 2.5px;
    left: 50%;
    top: 50%;
}

.circle .vertical {
  position: absolute;
    background-color: #fff;
    width: 2.5px;
    height: 15px;
    left: 50%;
    top: 50%;
}

.closed .horizontal {
  transition: all 0.5s ease-in-out;
  transform: translate(-50%,-50%) rotate(-90deg);
  opacity: 1;
}

.closed .vertical {
  transition: all 0.5s ease-in-out;
  transform: translate(-50%,-50%) rotate(-90deg);
}

.opened {
  opacity: 1;
}

.opened .horizontal {
  transition: all 0.5s ease-in-out;
  transform: translate(-50%,-50%) rotate(-90deg);
  opacity: 0;
}

.opened .vertical {
  transition: all 0.5s ease-in-out;
  transform: translate(-50%,-50%) rotate(-90deg);
}

I think that's because of the translate() part in transform: translate(-50%,-50%) rotate(-90deg);.
How to get that to work?

A: Your transforms are colliding. When you use percentages you will have a perfectly scalable and working animation that relies only on the pixel size of the outer circle.

$('.circle-plus').on('click', function(){
   $(this).toggleClass('opened');
  });
.closed .vertical {
    transition: all 0.5s ease-in-out;
    transform: rotate(-90deg);
  }
.closed .horizontal {
    transition: all 0.5s ease-in-out;
    transform: rotate(-90deg);
    opacity: 1;
}
.closed > div {background: green;}
.opened > div {background: red;}
.opened {opacity: 1;}
.opened .vertical {
    transition: all 0.5s ease-in-out;
    transform: rotate(90deg);
}
.opened .horizontal {
    transition: all 0.5s ease-in-out;
    transform: rotate(90deg);
    opacity: 0;
}
.circle-plus {
    opacity: 1;
}
.circle-plus .circle {
    position: relative;
    width: 20px; /* only value you have to change to scale */
    height: 20px; /* only value you have to change to scale */
    border-radius: 100%;
}
.circle-plus .circle .horizontal {
    position: absolute;
    background-color: white;
    width: 60%;
    height: 10%;
    left: 50%;
    margin-left: -30%;
    top: 50%;
    margin-top: -5%;
}
.circle-plus .circle .vertical {
    position: absolute;
    background-color: white;
    width: 10%;
    height: 60%;
    left: 50%;
    margin-left: -5%;
    top: 50%;
    margin-top: -30%;
}


text:
Q: Checking Equal Pointers & Memory Roundup So, I'm implementing queue using struct and pointers in C:
Note: I'm using max_cells = 3 for my program.
Here is my queue.h:
struct queue {
int max_cells; // Maximum number of cells in the queue
int cells_used; // Number of cells used
void **head; // Pointer to the head of queue
void **tail; // Pointer to the tail of queue
void **queue_base; // Pointer to the base of the queue
};

typedef struct queue Queue; // For convenience

And here is my code for enqueue:
/**
  * Enqueue a pointer into the queue
  * @param which_queue Pointer to Queue you want to push onto
  * @param ptr Pointer to be pushed
  * @return 1 if successful, 0 if not
  */
  int enqueue(Queue *which_queue, void *ptr) {

  // If the Queue is already full, print a message and terminate the function
  if ((which_queue->cells_used) == (which_queue->max_cells)) {
  printf("The queue is full. It can only contains %d cells.\n", which_queue->max_cells);
  return 0;
  }

  // Otherwise, enqueue the cell that head points to
  // Checking tail++ to see if it goes off the queue
  // If it does, then make tail point to the queue_base
  if (((which_queue->tail)++) == ((which_queue->queue_base) + (which_queue->max_cells))) {
  which_queue->tail = which_queue->queue_base;
  } else {
    // Push the pointer to the queue
    *(which_queue->tail) = ptr;
    // Point to the next free cell
    (which_queue->tail)++;
    // Then, increase the number of cells used in the Queue
    (which_queue->cells_used)++;
  }
  return 1; // Indicate success
  }

I check my program by printing out the memory location that each one points to: (Foo are just random structs)

Enqueued new_foo1.
Current number of cells in the queue: 1
Head pointer is pointing to: 0x147d040
Tail pointer is pointing to: 0x147d050
Base pointer is pointing to: 0x147d040
Enqueued new_foo2.
Current number of cells in the queue: 2
Head pointer is pointing to: 0x147d040
Tail pointer is pointing to: 0x147d060
Enqueued new_foo3.
Current number of cells in the queue: 3
Head pointer is pointing to: 0x147d040
Tail pointer is pointing to: 0x147d070
The queue is full. It can only contains 3 cells.
-----------------------
Dequeued new_foo1
Current number of cells in the queue: 2
Head pointer is pointing to: 0x147d050
Tail pointer is pointing to: 0x147d070
Enqueued new_foo4
Current number of cells in the queue: 3
Head pointer is pointing to: 0x147d050
Tail pointer is pointing to: 0x147d080
*** (which_queue->queue_base) + (which_queue->max_cells) = 0x147d058
Dequeued new_foo2
Current number of cells in the queue: 2
Head pointer is pointing to: 0x147d060
Tail pointer is pointing to: 0x147d080
Dequeued new_foo3
Current number of cells in the queue: 1
Head pointer is pointing to: 0x147d070
Tail pointer is pointing to: 0x147d080

The problem lies in the line marked with ***. Why does this happen? I think the memory location should be 0x147d070.
Please help me. Thanks.

A: You also need to be more explicit about exactly what the tail pointer does -- does it point to the last entry added to the queue, or does it point to the free space after the last entry added to the queue? Some people like to do it one way, and some like to do it the other.
Since you are incrementing the tail pointer first, this implies that you want the tail pointer to point to the last entry added. But as rpattiso already pointed out, then you should not also increment the pointer after using it to store the entry into the queue.
One other thing -- If you use the tail pointer this way, be sure that when you add something to an empty queue that the head pointer is set properly.


text:
Q: How to build apk of Webview in flutter How we build apk of web view app in a flutter. Does anyone help me, please?

A: For build an APK you use:
flutter build apk .

For build a bundle:
flutter build appbundle

For build apk and split by arch
flutter build apk --split-per-abi

These is the modes that can you build for Android in flutter.
The webView is a feature of your application, so don't have a different type of build .
Check this doc:
https://docs.flutter.dev/deployment/android

A: flutter build apk

This typically build for debug mode. For more specific result, use ~
flutter build apk --release

or,
flutter build apk --debug


text:
Q: Prove that even + odd is odd. Prove that a even number + odd number = odd number
Let $x$ be the even number, let $y$ be the odd number.
From the definition of odd numbers, $y + 1$ is even.
Let:
$$x + y = z$$
Suppose $z$ is even.
$$x + y = z$$
It follows that:
$$x = x + y - y = z - y$$
But I cant think of any other contradiction here. The issue is with the assumption I suppose. Any help is appreciated!

A: An even number $n$ can always be written as $2k$. An odd number $m$ can always be written as $2h+1$.
Hence $n+m=2k+2h+1=2(h+k)+1$ which is odd.

A: If $x$ is even, then $x$ can be written as $2a$ for some integer $a$. If $y$ is odd, then $y$ can be written as $2b + 1$ for some integer $b$.


text:
Q: Can Functor instance be declared with additional type restriction for function I'm working on porting GHC/Arr.hs into Frege.
Array is defined:
data Array i e = Array{u,l::i,n::Int,elems::(JArray e)}

There is function:
amap :: (Ix i, ArrayElem e) => (a -> b) -> Array i a -> Array i b

Now, I don't know how to define Functor instance for it, because
instance (Ix i) => Functor (Array i) where
    fmap = amap

But compiler complains that inferred type is more constrained that expected, what seems true. Can I make Array an functor with restrction for functions ArrayElem -> ArrayElem?

A: No, this is not possible.
If you base Array on JArray and want a functor instance, you must not use any functions that arise the ArrayElem (or any other additional) context.
Another way to say this is that you cannot base Array on type safe java  arrays, but must deal with java arrays of type Object[]. Because, as you have without doubt noted, the ArrayElem type class is just a trick to be able to provide the correct java type on creation of a java array. This is, of course, important for interfacing with Java and for performance reasons.
Note that there is another problem with type safe java arrays. Let's say we want to make an array of Double (but the same argument holds for any other element type). AFAIK, Haskell mandates that Arrays elements must be lazy. Hence we really cannot use the java type double[] (to which JArray Double would be the Frege counterpart) to model it. Because, if we would do this, every array element would have to be evaluated as soon as it is set.
For this reason, I suggest you use some general custom array element type, like
data AElem a = AE () a
mkAE = A ()
unAE (AE _ x) = x
derive ArrayElement AElem

and change your definition:
data Array i e = Array{u,l::i,n::Int,elems::(JArray (AElem e))}

Now, your functor instance can be written, because the ArrayElem constraint does not arise, because when you access the elems array, the compiler knows that you have AElem elements and can and will supply the correct instance.
In addition, construction of AElems and usage of AElems as actual array elements does not impose strictness on the actual value.
Needless to say, the user of the Array module should not (need to) know about those implementation details, that is, the AElem type.


text:
Q: Timed animated gif display Noob Alert.....
I have searched previous questions and can not find this specific request.
For my Art project I have created an animated gif and want it to display/run my animated gif for just one hour per day on the website I have created for my other projects.
I have this script which is very similar but I need to automate the display (for one hour each day) and not on click or stepped. I can get rid of these stages but not sure on what to replace them with.

      JavaScript Animation
  <script type="text/javascript">
     <!--
        var imgObj = null;
        var animate ;

        function init(){
           imgObj = document.getElementById('myImage');
           imgObj.style.position= 'relative';
           imgObj.style.left = '0px';
        }

        function moveRight(){
           imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
           animate = setTimeout(moveRight,20); // call moveRight in 20msec
        }

        function stop(){
           clearTimeout(animate);
           imgObj.style.left = '0px';
        }

        window.onload =init;
     //-->
  </script>

Thank you in advance.....

A: Ok, first thing to notice is that you'll have to check the current time every now and then, to check if we're at that certain hour you want to show the animation.
Let's take as example: between 13h and 14h (1pm and 2pm)- from now on I'll use the 24h notation.
We can use an interval to check if it's past 13h already. We choose the precision ourselves. For the sake of the example, let's say that we check every 5 minutes:
//Note: we could say "300000" immediately instead, but with the calculation, we can easily change it when we want to.
var gifInterval = setInterval(function() {canWeAnimateYet ();}, 5 * 60 * 1000);

So, we got an interval that will check every 5 minutes. Now we need a flag (or bool) to see if the animation should run or not...
var animateThatGif = false;

And now.. We need the function to check the time:
var canWeAnimateYet = function() {
    //Checks here.
}

On that function, we need to check the currenttime. If it's past 13 but before 14h, we need to put our flag to true, otherwise it stays false.
var canWeAnimateYet = function() {

     //Get current time
     //Note: "new Date()" will always return current time and date.
     var time = new Date();

     //Note: getHours() returns the hour of the day (between 0 and 23 included). Always in 24h-notation.
     if (time.getHours() >= 13 && time.getHours < 14)
        animateThatGif = true;
     else
        animateThatGif = false;
}


text:
Q: Seating in a movie theater In a movie theater there are $n$ rows and $k_1,k_2,...,k_n$ chairs in each row. How many different ways can $m$ people sit in this movie theater?
My thought process: There are $k_1+\dots+k_n$ places to sit. The first person has $k_1+\dots+k_n$ many choices, the second has $k_1+\dots+k_n-1$ many choices and the $m.$ person has $k_1+\dots+k_n-m+1$ many choices. So there are ${k_1+\dots+k_n\choose m}m!$ many ways. Is that correct?

A: As stated above there are two interpretations. In both case let's define $s = \sum_{i=1}^n k_i$.

*

*Case 1, we assume that each person is unique namely that if Alice sits in seat 1 and Bob sits in seat 2 then this is a different combination than Alice in 2 and Bob in 1. Then the total possible combinations is indeed $\frac{s!}{(s-m)!}$.

*Case 2, we assume that every person is the same namely that if Alice sits in seat 1 and Bob sits in seat 2 then this is the same as if Alice sits in 2 and Bob in 1. Then the total possible combinations is $\binom{s}{m}$.


text:
Q: What's the use of the component type file in SCA? I am reading about Service Component Architecture (SCA). One thing that I did not understand its use, is the definition of a component type in a file with the extension .componenttype.
This source says:
"Component type represents the configurable aspects of an implementation. A component type consists of services that are offered, references to other services that can be wired and properties that can be set. The settable properties and the settable references to services are configured by a component that uses the implementation."
And here's an example for that file:
<?xml version="1.0" encoding="ASCII"?>
<!-- Component type schema snippet -->
<componentType xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200903"
               constrainingType="xs:QName"? >

   <service … />*
   <reference … />*
   <property … />*
   <implementation … />?

</componentType>

My confusion is because we do define the component services, references, properties, and implementation in the composite file (the file with .composite extension). So why do we define it in both files (the component type file and the composite file) ? Aren't we repeating things here? What's really so special about the component type in SCA? Thanks.

A: The componentType and component configuration are actually two different things. The ComponentType describes a component implementation. It's analogous to type information that can be gathered from reflection on a Java class (hence the "type" in the name). Think "type" vs. "instance". This is an important distinction since a component implementation may be used more than once with different configuration.
In practice, applications generally do not need to provide a componentType file as the information can be gathered (in most cases) via some type of reflection. For example, with Java implementations, the componentType file is never provided (it's actually not supported in the latest version of the Java spec).
The only case where a componentType may be necessary is for languages where type information cannot be determined programmatically.


text:
Q: How to remove all files with same extension except one with rm I want to remove all files with .o extension except the specific example.o, how can I do that with rm?
Edit:
Environment: zsh

A: In zsh, you may use KSH_GLOB that works as extglob of bash:
setopt KSH_GLOB

echo rm !(example).o

Other option is to use extended_glob with a slightly different globbing syntax:
setopt extended_glob

echo rm (^example).o

Where ^ is used for negation.
Once you're satisfied with the output, remove echo before rm.

A: Could be something like this?
 find -iname '*.o' -not -iname 'example.o' -execdir rm {} \;


text:
Q: Remove "empty space" in splot with log scaled z axis I have a gnuplot script which generates a surface plot from data. I've scaled the z axis logarithmically, such as in an example on gnuplot.info1 - and just as in the example, I get a lot of empty room at the "bottom" of the plot.
In that example, the ticks on the z axis end at 1, but the axis doesn't end there - the origin of the plot is further "down" (in the z direction).
How do I set the origin to be where the data actually starts? A dynamic approach (that's not dependent on me knowing the data set in advance) is greatly preferred, if it's possible.

1 Follow the link and search the page for "Surfaces with z log scale" to find the relevant example.

A: This is not an obvious one, but (as usual) there is a setting for that.  Try
set xyplane 1

and
help set xyplane

for more details.


text:
Q: Sending other data through Pyapns (iOS push notifcations) with Django Is it possible to data other data through pyapns? For example, say I have a post model. Each post has a post_id. I would like to send the post_id with the push notification. The user who receives the push notification will receive something like, "Alex commented on your post."
The user will not see the post_id. It is hidden to the user but I would still like to send this extra data so that when the user clicks on the push notification, it leads them to the correct post.
This is what I have in my util.py:
import pyapns
import xmlrpclib

class PyapnsWrapper(object):

     def __init__(self, host, app_id, apns_certificate_file, mode='production'):
         self.app_id = app_id
         pyapns.configure({'HOST': host})
         pyapns.provision(app_id,
                          open(apns_certificate_file).read(),
                          mode)

     def notify(self, token, message):
         try:
             pyapns.notify(self.app_id,
                           token,
                           {'aps':{'alert': message}})
         except xmlrpclib.Fault, e:
             print e

How could I possibly modify this to send in an extra field with the notify argument?

A: Try replacing
{'aps':{'alert': message}}
with
{'aps':{'alert': message},'post-id':post_id}.
I'm not familiar with pyapns and I don't know python, but the APNS payload format allows to add custom properties to the payload. I'm not sure if my syntax is accurate (as I said I don't know python), but you should get the idea from it.
The JSON payload should look like this :
{

    "aps" : {

        "alert" : "Alex commented on your post.",

    },

    "post-id" : 435472

}

When the user clicks on the notification and the app is opened, you'll be able to access the custom data this way (notificationInfo will contain the post-id key with its value):
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary* notificationInfo =
        [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (notificationInfo) {
        [self someProcessing:notificationInfo];
    }
    ...
    return YES;
}


text:
Q: How to override 'data-testid' in the 'findByTestId function from Cypress Testing Library Most of my existing codebase uses a 'id' only in few places 'data-testId' attribute present.
tried this code
import { configure } from '@testing-library/cypress';

configure({ testIdAttribute: ['data-testId','id'] });

But, still its not working.
Is there any way to use 'id' value in any of the testing-library functions.
My HTML code is something like:

SB

I want click that element with this code:
cy.findByTestId("userprofile-open", { timeout: 120000 }).click();

A: I don't think you can configure testing-library with an array of ids, ref API configuration,
import { configure } from '@testing-library/cypress'
configure({ testIdAttribute: 'id' })

But even this fails. Instead you have to use the Cypress command to change the attribute name (only one name is allowed).
cy.configureCypressTestingLibrary({ testIdAttribute: 'id' })

To use either/or attribute name you can change the attribute name on the fly, wrapping it in a custom command (based on Custom Queries)
Cypress.Commands.add('findByTestIdOrId', (idToFind) => {

  let result;

  const { queryHelpers } = require('@testing-library/dom');
  let queryAllByTestId = queryHelpers.queryAllByAttribute.bind(null, 'data-testId');

  result = queryAllByTestId(Cypress.$('body')[0], idToFind)
  if (result.length) return result;

  queryAllByTestId = queryHelpers.queryAllByAttribute.bind(null, 'id');
  result = queryAllByTestId(Cypress.$('body')[0], idToFind);
  if (result.length) return result;

  throw `Unable to find an element by: [data-test-id="${idToFind}"] or [id="${idToFind}"]`

})

cy.findByTestIdOrId('my-id')
  .should('have.attr', 'id', 'my-id')
// passes and logs "expected
 to have attribute id with the value my-id"

Note this custom command works only for synchronous DOM.

If you need to have Cypress retry and search for either/or attribute, don't use testing-library in the custom command.
Instead use Cypress .should() to enable retry
Cypress.Commands.add('findByTestIdOrId', (selector, idToFind) => {
  cy.get(selector)
    .should('satisfy', $els => {
      const attrs = [...$els].reduce((acc, el) => {
        const id = el.id || el.getAttribute('data-test-id')  // either/or attribute
        if (id) {
          acc.push(id)
        }
        return acc
      }, [])
      return attrs.some(attr => attr === idToFind); // retries when false
    })
    .first();                                       // may be more than one
})

cy.findByTestIdOrId('div', 'my-id')
  .should('have.attr', 'id', 'my-id')
// passes and logs "expected
 to have attribute id with the value my-id"

A: The usual cypress way - which has an inherent check on the element visibility and existence as well as included retries for a period of time is using cy.get()
If you want to select element using property like data-id you need this sintax: cy.get('[propertyName="propertyValue"]')
If you want select an element by CSS selector you just pass CSS selector like this:
cy.get('#id')


text:
Q: JavaScript not showing remaining characters, but works on other pages So I have implemented JavaScript which notifies the user how much characters a user has remaining.
Here is my textarea and where the feedback should be shown:
<form action='' method='post' enctype='multipart/form-data'>
   <textarea id="txtarea" name='msg' rows='2' maxlength='255' cols='80' placeholder=' Share a thought...'></textarea>
   <input type='submit' name='send' value='Share'/>
</form>

// this is where the feedback should be shown...
<div id="textarea_feed">  </div>

And here is the JavaScript to achieve the desired functionality:
        <script type="text/javascript">
            $(document).ready(function() {
                var text_max = 255;
                $('#textarea_feed').html(text_max + ' characters remaining');

                $('#txtarea').keyup(function() {
                    var text_length = $('#txtarea').val().length;
                    var text_remaining = text_max - text_length;

                    $('#textarea_feed').html(text_remaining + ' characters remaining');
                });
            });
        </script>

I have the exact same form and JavaScript layout on profile_page.php, and it works there, but for some reason, I no text is being shown in the div. I know the div is not hidden behind any other divs because I have tested with sample content.

A: Ensure that you are including a jQuery script tag in your html.
It works for me when I add the CDN.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

https://jsfiddle.net/aeuzfLao/


text:
Q: Inserting into database with NodeJS How does one use a NodeJS back-end to execute a function then store that value into a database?

A: A popular approach is to combine Node.JS (as a REST API back-end server) with MongoDB (a NoSQL database system). The Node.JS application exposes a series of endpoints for the outer world to interact with (e.g. create user, delete user, update user's preferences, etc.) and, under the hood, each endpoint has its own business logic, related to its scope.
Check out this guide for more.

A: A common approach is to use a ORM in case of relational databases, two popular ORM in node.js ecosystem are sequelize and TypeORM, in case of databases like MongoDB you can use a ODM a popular library is mongoose
There is a lot of tutorials in the web this one of my favorites one using: Node, Express (Web Server) and MongoDB


text:
Q: Optimization mysql very slowly Hello I have a server in kimsufi 2gb RAM and 500gb storage but the query with php mysql is very slowly
I have change innodb buffer pool size to 500M but i have error too many connections, i add max connection to 500
Why my server is slowly and have many connection (with buffer 500M, if i have buffer 2M i dont have error too many connection) ?
Thanks for your help
My.cnf :
[client]
port            = 3306
socket          = /var/run/mysqld/mysqld.sock

[mysqld_safe]
socket          = /var/run/mysqld/mysqld.sock
nice            = 0

innodb_buffer_pool_size=2M
innodb_additional_mem_pool_size=500K
innodb_log_buffer_size=500K
innodb_thread_concurrency=2

[mysqld]
local-infile=0
#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking<br>
key_buffer              = 16M
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover          = BACKUP
#max_connections        = 500
max_user_connections    = 0
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit       = 16M
query_cache_size        = 1M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
general_log_file        = /var/log/mysql/mysql.log
general_log             = 1
#
# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# Here you can see queries with especially long duration
#log_slow_queries       = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id              = 1
#log_bin                        = /var/log/mysql/mysql-bin.log
expire_logs_days        = 10
max_binlog_size         = 100M
#binlog_do_db           = include_database_name
#binlog_ignore_db       = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

#innodb_buffer_pool_size=500M
#innodb_additional_mem_pool_size=500K
#innodb_log_buffer_size=500K
#innodb_thread_concurrency=2
[mysqldump]
quick
quote-names
max_allowed_packet      = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completition

[isamchk]
key_buffer              = 16M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/


text:
Q: TypeError: Object(...) is not a function useImperativeHandle? Я получаю такую ошибку TypeError: Object(...) is not a function  в строке 14
// Core
import React, {
    forwardRef,
    useRef,
    useImperativeMethods,
    useState,
    useEffect,
} from 'react';
import { render } from 'react-dom';

const Child = forwardRef((props, ref) => {
    const nameInputRef = useRef(null);

    useImperativeMethods(ref, () => {
        return {
            focusImperatively: () => {
                nameInputRef.current.focus();
            },
        };
    });

    return (
        <input
            disabled = { !props.isEditing }
            ref = { nameInputRef }
            value = { props.name }
            onChange = { props._setName }
        />
    );
});

const Parent = () => {
    const [ name, setName ] = useState(' Дед Мороз');
    const [ isEditing, setIsEditing ] = useState(false);
    const childRef = useRef(null);

    const _setName = (event) => setName(event.target.value);
    const _toggleIsEditing = () => setIsEditing(!isEditing);

    useEffect(
        () => {
            childRef.current.focusImperatively();
        },
        [ isEditing ],
    );

    const buttonText = isEditing ? 'Заблокировать' : 'Разблокировать';

    return (

{name}

            <Child
                _setName = { _setName }
                isEditing = { isEditing }
                name = { name }
                ref = { childRef }
            />
            <button onClick = { _toggleIsEditing }>{buttonText}</button>

    );
};

render(<Parent />, document.getElementById('app'));

Скриншот ошибки:


text:
Q: Python package in ubuntu My current python version is python 2.7 (python --version), However, I've accidentally removed python2.7 from /usr/lib/ so I cannot do anything and I see this error:
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
ImportError: No module named site

Any suggestion?


text:
Q: Sitecore Logs - Azure Search Currently I'm seeing the following a lot in my logs, I'm using Sitecore 8.2 rev 2 with azure.  The issue only started recently when I added some new indexes to the site for a new microsite.  Any ideas of where to start investigating, I've raised with Sitecore too?
ManagedPoolThread #17 22:03:10 ERROR Exception

Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.

Source: mscorlib

   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj)
   at Sitecore.Jobs.JobRunner.RunMethod(JobArgs args)
   at (Object , Object[] )
   at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)
   at Sitecore.Jobs.Job.ThreadEntry(Object state)

Nested Exception

Exception: System.AggregateException
Message: One or more errors occurred.

Source: mscorlib

   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`2 body)
   at Sitecore.ContentSearch.AbstractSearchIndex.PerformUpdate(IEnumerable`1 indexableInfo, IndexingOptions indexingOptions)

Nested Exception

Exception: System.InvalidOperationException
Message: Sequence contains no elements

Source: System.Core

   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Sitecore.ContentSearch.Azure.CloudSearchUpdateContext.Delete(IIndexableId id)
   at Sitecore.ContentSearch.SitecoreItemCrawler.Update(IProviderUpdateContext context, IIndexableUniqueId indexableUniqueId, IndexEntryOperationContext operationContext, IndexingOptions indexingOptions)
   at Sitecore.ContentSearch.AbstractSearchIndex.<>c__DisplayClass93_2.<PerformUpdate>b__0(IndexableInfo info, ParallelLoopState parallelLoopState)
   at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.<>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object )

A: For those with the same issue,
The patch is Sitecore.Support.158988 found here:
https://github.com/SitecoreSupport/Sitecore.Support.158988
Versions cover Sitecore 8.2 update 1 and update 2.

164633 The CloudSearchUpdateContext.Delete(IIndexableId) fails with an exception in case the search index does not contain any matching documents.

Thanks.

A: Looks like there is a patch for this from Sitecore, hopefully this will resolve the issue.


text:
Q: How to display html as a tree in Swing? I would like to display html as treeview similar to firebug in my swing. Looking for community help to achieve this. Found similar stuff(Not Exactly) here. But i could not move further with the information in the link.

A: In general, you need a HTML DOM parser (like JSoup) to create a DOM tree from the HTML code you have. Then you should probably build your own TreeModel to respresent the DOM tree in a swing JTree.

A: You can use this http://java-sl.com/JEditorPaneStructureTool.html to see how it could be implemented.
After reading HTML with HTMLEditorKit use the HTMLDocument's tree.

A: This tutorial will tell you exactly how to create a JTree that shows the DOM structure of an HTML document.


text:
Q: Get data distribution given a dataframe R I'm new to R and I would like to "see" which distribution my data follow.
My data represent the entering passengers at 10 bus stops for 1 month at the same time each day.
Date    Stop.1    Stop.2    Stop.3    Stop.4    Stop.5  ...
2-9    3    26    11    3    0
3-9    2    44    23    0    12
4-9    26    16    0    0    4
...

My goal is to understand the distribution of the "entering" passengers at each stop so that I can create a simulation for the arrivals at each Stop.

A: Density Plot
You can plot the probability density function to let you "see" the distribution. Assuming df is a dataframe containing the information:
d <- density(df$Stop.1) # returns the density data for Stop 1.

plot(d) # plots the results

Summary statistics
Or you can use the basicStats function from the fBasics package to give some useful summary statistics.
library(fBasics)

basicStats(df)


text:
Q: How do I get Windows XP IIS to handle more than 2 concurrent requests? Microsoft has intentionally crippled IIS in XP to keep people from using it as a web server platform. It defaults to handling only two simultaneous incoming requests. Is there any way to tweak this without serious system file abuse? If so, is there an easy way to test that the change was successful?
I found a suggestion from Tess Ferrandez's debugging blog about some registry settings but all the tests I run after-the-fact seem to indicate nothing has changed (even after an IIS reset and, ultimately, a system restart). In the case of her ASP.NET debugging labs, there is a test page that does a five-second sleep and logs the start and completion of the request but multiple requests to that page on this test system all start five seconds after each other instead of starting around the same time and simply taking five seconds longer from start to completion.

A: Here is a post by Jeff Atwood on how you can increase the limit to 10 or 40 connections. One way to possibly test would be to use a load tester like Microsoft Application Center Test that comes with Visual Studio 2003 or the Microsoft Application Stress Tool that you can download. This tools will allow you to simulate multiple users hitting your site. I would test it it before you make the change and after to see if it makes a difference.


text:
Q: JavaScript's offsetWidth and offsetHeight give wrong value when element is resizing quickly I'm creating my own scrollbar component using vanilla javascript. The element is resizable, so when it's resized, the scrollbar's maximum scroll position and size will follow.
Everything is fine if I resize with normal speed, but if I test quickly, the calculation result (size and max. pos) produce wrong result, I guess because of the  offsetWidth or offsetHeight mistake.
My scrollbar's render function triggered when on resize, sbv means scrollbar vertical and sbh means scrollbar horizontal:
this.sbv.size = this.content.offsetHeight / this.content.scrollHeight;
this.sbv.style.height = (this.sbv.size * 100) + "%";
this.sbv.max = (100 - this.sbv.size * 100) / 100 * this.content.offsetHeight;
this.sbv.pos = this.content.scrollTop / this.content.scrollHeight * this.content.offsetHeight;
this.sbv.style.top = (this.sbv.pos / this.content.offsetHeight * 100) + "%";

this.sbh.size = this.content.offsetWidth / this.content.scrollWidth;
this.sbh.style.width = (this.sbh.size * 100) + "%";
this.sbh.max = (100 - this.sbh.size * 100) / 100 * this.content.offsetWidth;
this.sbh.pos = this.content.scrollLeft / this.content.scrollWidth * this.content.offsetWidth;
this.sbh.style.left = (this.sbh.pos / this.content.offsetWidth * 100) + "%";

Does anyone know why this happen? TiA

A: That will be a theoretical answer only, because I didn't took the time to setup a repro case, and because "produce wrong results" is a bit broad of a description.

I suspect the problem is actually the inverse of your claim:
offsetWidth, offsetHeight, scrollHeight and scrollWidth actually give you the correct values, in a mean you may not have expected.
These properties, in order to return the correct values do trigger a recalculation of all the bounding boxes of the elements in the document, this is known as a "reflow".
This reflow implies that all the CSS rules you did set previously are now applied and active.
So in your code, when you do
elem.size = content.offsetHeight / content.scrollHeight;
elem.style.height = (elem.size * 100) + "%";
elem.max = (100 - elem.size * 100) / 100 * content.offsetHeight;

The value of content.offsetHeight at the first line, and the one at the third line will probably not be the same anymore.

var elem = document.getElementById('elem');
var content = document.getElementById('content');

console.log('before', content.offsetHeight);
elem.size = content.offsetHeight / content.scrollHeight;
elem.style.height = (elem.size * 100) + "%";
elem.max = (100 - elem.size * 100) / 100 * content.offsetHeight;
console.log('after', content.offsetHeight);
body{
  height: 100vh;
}
#content,#elem {
  border: 1px solid;
}
#elem {
  height: 800px;
}

So, not only triggering multiple reflows like that is terrible for the performances, but you will probably have your calculations wrong indeed.
The best is probably to cache all the current values before hand in variables, make all your calculations and only at the end set all the new styles.
Also note that all this would be better ran in a requestAnimationFrame debouncer, so it happens only once per painting frame.


text:
Q: After Graduation vs since Graduation
(1). He has been running his own business since graduation.
  (2). He has been running his own business after graduation.

I don't know the difference between "since graduation" and "after graduation" when referring to time.
Without given any date in each sentence, which of the above sentences implies that he has run his business at an earlier time? (1) or (2)?

A: The second sentence doesn't make sense. If you want to express a time frame you'd use the first.
Sentence 1
He has been running his own business since graduation.

This means he currently runs his own business, and he started running his own business at or very near graduation and is still running it today. This is emphasizing him running his business during the entire time-frame from graduation to present.
Sentence 2
He has been running his own business after graduation.

This doesn't make sense. Has been running... implies that this is an ongoing activity and to complete that sentence you'd need a continuous time-frame.

*

*He has been running his own business for ten years.

*He has been running his own business since he was a child.
The simple non-progressive moment in time "after graduation" is not a suitable tense. That would be like saying He has been running his own business in January. this is a verb tense confusion.


text:
Q: Error while connecting to mysql from container to container I am getting some difficulties to connect from my scala/slick application from one container to mysql in another container.
Here is how I am running docker containers:
// MySQL
docker container run --publish 3306:3306  --name mysqlDb -e MYSQL_ROOT_PASSWORD=123123 -d mysql

// Scala/slick app
docker container run -v /Users/userHome/Sources/slick-dev-box:/home --expose=3306 -it --link mysqlDb:mysql hseeberger/scala-sbt

$ docker ps -a
CONTAINER ID        IMAGE                  COMMAND                  CREATED              STATUS                         PORTS                               NAMES
f12b46821f69        hseeberger/scala-sbt   "bash"                   About a minute ago   Up About a minute              3306/tcp                            gracious_engelbart
afcd1902b741        mysql                  "docker-entrypoint.s…"   About an hour ago    Up 37 minutes                  0.0.0.0:3306->3306/tcp, 33060/tcp   mysqlDb

application.conf
mysql = {
  profile = "slick.jdbc.MySQLProfile$"
  dataSourceClass = "slick.jdbc.DatabaseUrlDataSource"
  properties = {
    driver = "com.mysql.cj.jdbc.Driver"
    url  = "jdbc:mysql://172.17.0.2:3360/slick"
    user = "root"
    password = "123123"
  }
}

Error I am getting:

warn] There may be incompatibilities among your library dependencies; run 'evicted' to see detailed eviction warnings.
[info] Running com.avelimited.slick.demo.Runner
[error] (run-main-0) java.sql.SQLTransientConnectionException: mysql - Connection is not available, request timed out after 30005ms.
[error] java.sql.SQLTransientConnectionException: mysql - Connection is not available, request timed out after 30005ms.
[error]     at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:676)
[error]     at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:190)
[error]     at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:155)
[error]     at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:100)
[error]     at slick.jdbc.hikaricp.HikariCPJdbcDataSource.createConnection(HikariCPJdbcDataSource.scala:14)
[error]     at slick.jdbc.JdbcBackend$BaseSession.<init>(JdbcBackend.scala:494)
[error]     at slick.jdbc.JdbcBackend$DatabaseDef.createSession(JdbcBackend.scala:46)
[error]     at slick.jdbc.JdbcBackend$DatabaseDef.createSession(JdbcBackend.scala:37)
[error]     at slick.basic.BasicBackend$DatabaseDef.acquireSession(BasicBackend.scala:250)
[error]     at slick.basic.BasicBackend$DatabaseDef.acquireSession$(BasicBackend.scala:249)
[error]     at slick.jdbc.JdbcBackend$DatabaseDef.acquireSession(JdbcBackend.scala:37)
[error]     at slick.basic.BasicBackend$DatabaseDef$$anon$3.run(BasicBackend.scala:275)
[error]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[error]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[error]     at java.lang.Thread.run(Thread.java:748)
[error] Caused by: java.lang.NullPointerException
[error]     at slick.jdbc.DriverDataSource.getConnection(DriverDataSource.scala:101)
[error]     at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369)
[error]     at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198)
[error]     at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467)
[error]     at com.zaxxer.hikari.pool.HikariPool.access$100(HikariPool.java:71)
[error]     at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:706)
[error]     at com.zaxxer.hikari.pool.HikariPool$PoolEntryCreator.call(HikariPool.java:692)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[error]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[error]     at java.lang.Thread.run(Thread.java:748)
[error] Nonzero exit code: 1

What I've tried so far:
I tried to use different port like 3360 and 33060, but same result.
Networkwise, when I run ping from app container, I am getting response from mysql container and when I run cat /etc/hosts on app container:
root@f12b46821f69:/home# cat /etc/hosts
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.2  mysql afcd1902b741 mysqlDb
172.17.0.3  f12b46821f69

Please let me know if there is something else I could check to fix connection issue.

A: Well, apparently issue was to do with myql-connector driver,
here is the fix I have to apply:
// Before
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.34"

// After
libraryDependencies += "mysql" % "mysql-connector-java" % "8.0.11"


text:
Q: Should perfect and progressive tenses be avoided in research papers? Writing a research paper, I came across a remark from one of the reviewers:

"Keep it simple" […] try to stay with present simple and past simple tense.

This would discourage the use of perfect / progressive tenses.
Now, I'm not a native speaker—and neither is the reviewer—but I'm sure there are valid uses for the present perfect tense. For example:

Research has shown that […]
This effect has often been cited as […]
The authors of […] have published a database […]

This, specifically, would imply that whatever research has shown is still valid today, whereas using a past tense here would mean that the research isn't accepted at the time of writing.
Regarding that reviewer comment:

*

*Why should these tenses be avoided in the first place? I wouldn't say that the "keep it simple" rule literally refers to the "simple" tenses. Or does it?

*Is that a general rule or are the examples I've mentioned valid uses of the perfect tense?

A: There is absolutely no need to avoid progressive and perfect constructions. It would be difficult to write a paper without them. Perhaps you should ask the reviewer for details on what the objection to progressive and perfect constructions might be.

A:
"Keep it simple" […] try to stay with present simple and past simple tense

is in general good advice; I imagine the reviewer isn't implying you can't use progressive and perfect constructions, but instead that they've noticed a problem with your use or overuse of progressive and perfect.  (It is also possible the reviewer is merely trying to force his or her own stylistic preferences upon you, so it is worthwhile to ask them to point out passages they would change.)
Regarding your three examples,

Research has shown that […]
   This effect has often been cited as […]
   The authors of […] have published a database […]

all three of those may benefit from use of simple present or past:

Research shows that […]
   This effect is often cited as […]
   The authors of […] published a database […]

These forms are shorter, stronger, more direct, less pompous, and quite as accurate.  (Except in the third case, you might write  "The authors of […] maintain a database […]" if the database is kept current.)
Regarding your assertion about whether research is still valid, I agree that using past tense in the first example would be a mistake; but using present tense casts no such shadow.


text:
Q: Is it possible to handle or receive SES Bounce/Complaints through the AWS PHP SDK? I am using AWS SES with PHP SDK to send emails with attachments to customers, some of them provide an invalid email causing SES to complaint or bounce. I would like to find out what emails have failed and do a follow up by inactivating that item, calling the customer to provide a valid email or any other solution.
Is it posible to get bounce or complaints in some way?

A: Yes.  But you really should be validating email addresses before you ever attempt to do anything with it.
You create an SNS topic, and add one (or more) subscriptions.  There are a number of different options when creating a subscription, but you probably want to use https.  You can have multiple subscriptions, so put your email address in there too so you can see what information is coming in.
Then, in SES, set up your SNS topic to handle bounces and/or complaints.
The AWS PHP toolkit has code and examples to handle bounces & complaints - it's pretty simple.  You'll also need to implement a validation method - SNS won't start sending data to your endpoint until it has been validated.


text:
Q: How to query nested elements in Firebase?     "John" : {
      "David" : {
        "-KIMA0aPsujdAOpkzP0w" : {
          "message" : "hallu",
          "sender" : "10154053432889835",
          "time" : 1463898873196
        }
      }
    },
    "Harry" : {
      "Christina" : {
        "-KIMA0aPsujdAOpkzP0v" : {
          "message" : "hallu",
          "seen" : true,
          "sender" : "self",
          "time" : 1463898873195
        }
      },
      "Pierce" : {
        "-KILZ_GH7Ji9hQYNK-6p" : {
          "message" : "Eli there.",
          "seen" : true,
          "sender" : "179914035712208",
          "time" : 1463888795301
        },
        "-KIM8yPz2UDOZwHEg_nn" : {
          "message" : "hahjajak",
          "seen" : true,
          "sender" : "self",
          "time" : 1463898597847
        },
}

I wanted to query the count of nodes where "seen" key has value "true" of top node which is John OR Harry There are multiple child node inside it and each child node has multiple child node which has automatic id set.
I just want to know the count of objects which has "seen" key set to true and also count of objects which has "seen" key set to false
I can extract all the values in node as follows:
ref.observeSingleEventOfType(.Value, withBlock: { snap in
    for (key,value) in snap.value as! NSDictionary {
    }

})

I can loop through the dictionary and count the number of objects manually. But that is not too computationally or data efficient as firebase is volume based.
What I want is to know if there is any query to count the number of objects whose "seen" key in root node is "true" or whose "seen" key in root node is "false".
UPDATE:
Data Structure
John  and Harry  are user unique ID. and the node David which is immediate child of  John node is unique ID of person who the user has chatted with earlier.
And the KIMA0aPsujdAOpkzP0w node represent a unique message from user John to/from David.
So what i wanted was to count the number of messages from David to John not seen by John

A: If you want to get only the "seen" value, you should reconsider your database structure and denormalize where possible to make reading as fast as you can.
Keeping your structure to get "seen" value, each time you read you have to get the entire node and loop through it to get the value, downloading unnecessary data, wasting processing time and making overall operation slower.
You should create a new node and store just the "seen" value the way you are going to get it later. Lets say, the best way to structure your database is based on which read operations are going to do and what data do you need in those operations.
You shouldn't worry about duplicating data. Remember that Firebase has the "updateChildren" method that allows you to update data in different nodes in a single operation.
For more info you can read the docs about structuring data here: https://firebase.google.com/docs/database/android/structure-data
Cheers!

A: Not sure if this is the most efficient way to handle it, but for a rapid prototype I've been searching for the answer to this problem as well.  I settled on using this strategy to isolate child nodes of the data structure:
   ref.observeSingleEventOfType(FIRDataEventType.Value, withBlock: { snapshot in
        for (key,value) in snapshot.value as! NSDictionary {

            if (key as! String == "John/David/etc")
            {
                let newRef  = FIRDatabase.database().reference().child("John").child(key as! String)

                newRef.observeSingleEventOfType(FIRDataEventType.Value, withBlock: { snapshot in

                    for (childKey, childValue) in snapshot.value as! NSDictionary{
                       //do whatever you want with child values/etc
                    }

                })
            }

        }

    })

Keep in mind I am VERY new to Firebase on iOS and they just changed their documentation so I'm working through it as I can.  I'm sure there are way better ways to accomplish accessing child data but this worked for my MVP so I went with it.
EDIT:  This assumes that your original reference is aimed at the part of the data tree that you want to target.  For example:
   let ref = FIRDatabase.database().reference().child("John")

That way when you did ref.observeSingle..etc, it would look for the values underneath that child object, instead of the entire tree.


text: Q: Exit function in PHP exit(9) In PHP I often exit from the program using exit(0). Also, exit(1) means there is an error. In fact, any number other than 0 indicates an error. So, if I use exit(9) - is their any significance of numbers greater than zero or it is immaterial. PHP manual from php.net shows exit(0376) as octal.


text:
Q: Is it possible to style the past and future dates of react date picker? I am using react date picker to build a custom date but I cant seem to be able to style past dates. All dates lower than the present date should have a grey background.The present date should have a past background and the future dates should all have a white background with a black border;
Code I have written to override current styles but I cant seem to figure this out

.css-gbrmys>*:not(style)~*:not(style){
    margin-top: 0px !important;
}

.react-datepicker__input-container > input {
 height: 42px !important;
 border-radius: 8px !important;
 background: #fff !important;
 width: 100% !important;
 border: 1px solid #E0E0E0 !important;
 text-indent: 12px;
}

.react-datepicker__triangle{
    display: none !important;
}

.react-datepicker__header{
  border: none !important;
  background-color: #fff !important;
}
.css-2v22cu{
    margin-top: 13px !important;
    margin-bottom: 13px !important;

}
.react-datepicker{
    font-family: 'Red Hat Display', sans-serif !important;
    font-size: 14px !important;
    border: none !important;
    border-radius: 8px !important;
    box-shadow: 0px 8px 16px rgba(17, 17, 17, 0.06) !important;
}

.react-datepicker__current-month{
    font-size: 18px !important;
}
.react-datepicker__day-name{
    color: #9C9C9C !important;
    font-size: 14px !important;
    line-height:  21px !important;
}

.react-datepicker__day-names{
    margin-left: 18px !important;
    margin-right: 18px !important;
}

.react-datepicker__day{
    background: #EEEEEE !important;
    font-size: 14px !important;
    line-height:  21px !important;
    border-radius: 4px !important;
    color: #9C9C9C !important;
}

.react-datepicker__day--selected{
    background: #000000 !important;
    color: white !important;
}
.react-datepicker__month {
    margin-bottom: 25px !important;
    margin-top: 0.4rem !important;
    margin-left: 0.4rem !important;
    margin-right: 0.4rem !important;
}


text:
Q: XQuery: select distinct nodes I am trying to learn XQuery and I haven't figured out how to select distinct teachers in the following xml file that I have made. I have looked up distinct-values() but it only seems to return a sequence of Strings only. If I want to run XQuery only without declaring functions such as functx:distinct-deep and functx:distinct-nodes from http://www.xqueryfunctions.com/xq/c0015.html#c0053, is there a way I can select distinct teachers who have taught in both credit and non-credit courses in the same year from the xml file below? I'd appreciate your help. Thank you.
<DB>
<credit>
<course_title>biology101</course_title>
    <teacher>
        <lastname>Smith</lastname>
        <firstname>Amy</firstname>
    </teacher>
    <teacher>
        <lastname>Hanson</lastname>
        <firstname>John</firstname>
    </teacher>
    <teacher>
        <lastname>Lee</lastname>
        <firstname>Sandra</firstname>
    </teacher>
    <year>2013</year>
</credit>
<credit>
<course_title>chemistry101</course_title>
    <teacher>
        <lastname>Richardson</lastname>
        <firstname>Rob</firstname>
    </teacher>
    <teacher>
        <lastname>Hanson</lastname>
        <firstname>John</firstname>
    </teacher>
    <year>2013</year>
</credit>
<noncredit>
<course_title>physics101</course_title>
    <teacher>
        <lastname>Hanson</lastname>
        <firstname>John</firstname>
    </teacher>
    <teacher>
        <lastname>Head</lastname>
        <firstname>Peter</firstname>
    </teacher>
    <year>2013</year>
</noncredit>
<noncredit>
<course_title>physics101</course_title>
    <teacher>
        <lastname>Lee</lastname>
        <firstname>Sandra</firstname>
    </teacher>
    <teacher>
        <lastname>Head</lastname>
        <firstname>Peter</firstname>
    </teacher>
    <teacher>
        <lastname>Hanson</lastname>
        <firstname>John</firstname>
    </teacher>
    <year>2013</year>
</noncredit>
</DB>

I used the XQuery below:
let $DB := doc("myDB.xml") /DB
let $credit_teacher := $DB/credit/teacher

for $noncredit_teacher in $DB/noncredit/teacher
where $DB/credit/year = $DB/noncredit/year
and $credit_teacher/lastname = $noncredit_teacher/lastname
and $credit_teacher/firstname = $noncredit_teacher/firstname
return $noncredit_teacher

But the duplicating teachers are returned:
<teacher>
  <lastname>Hanson</lastname>
  <firstname>John</firstname>
</teacher>
<teacher>
  <lastname>Lee</lastname>
  <firstname>Sandra</firstname>
</teacher>
<teacher>
  <lastname>Hanson</lastname>
  <firstname>John</firstname>
</teacher>

If I use distinct-values, a sequence of Strings is returned:
     HansonJohn LeeSandra

A: One possible solution is to:

*

*Find all the teachers that have taught in both credit and non-credit modules within the same year.

*Filter those teachers so that they are distinct. I have used a tail-recursive function local:distinct-teachers to achieve this, that operates over the sequence of all teachers found in (1). It examines each teacher in turn and if it has not see it before, it adds it to an accumulator of $distinct teachers.
declare function local:distinct-teachers($teachers as element(teacher)*, $distinct as element(teacher)*) as element(teacher)* {
  if(empty($teachers)) then
    $distinct
  else
    let $teacher := $teachers[1]
    return
      let $new-distinct := if($distinct/.[lastname eq $teacher/lastname]
          [firstname eq $teacher/firstname]
      ) then
          $distinct
      else
          ($teacher, $distinct)
      return
          local:distinct-teachers($teachers[position() gt 1], $new-distinct)
};

let $teachers :=
    let $credit-teachers := doc("myDB.xml")/DB/credit/teacher
    let $non-credit-teachers := doc("myDB.xml")/DB/noncredit/teacher
    return
        for $credit-teacher in $credit-teachers
        for $non-credit-teacher in $non-credit-teachers
        return
            $credit-teacher
                [lastname eq $non-credit-teacher/lastname]
                [firstname eq $non-credit-teacher/firstname]
                [following-sibling::year eq $non-credit-teacher/following-sibling::year]
return
    local:distinct-teachers($teachers, ())

A: You are already selecting the distinct nodes. The teacher nodes you are selecting are repeated in the source XML, and therefore have separate node identities.
You'll have to do some form of de-duplication based on the contents of the nodes. functx:distinct-nodes() and  functx:distinct-deep are good examples of that kind of de-duplication.


text:
Q: QueryDSL: extract Table name from Predicate (BooleanExpression) object A method is dynamically building a list of Predicates that is later passed to a database service object. In order to create table joins based on the predicate list I need to determine the underlying generated class Q* of each predicate. Calling getType() or getClass() on the Predicate doesn't help.
This is how I build the predicates:
Class<?> tableClazz = Class.forName("foo.bar.database.model.Q"+ WordUtils.capitalize(tableName));
Object tableObj = tableClazz.getConstructor(String.class).newInstance(tableName +"1000");
Field colField = tableClazz.getDeclaredField(fieldName);
Object colObj = colField.get(tableObj);
// method name is one of eq, ne, like...
Method m = colObj.getClass().getMethod(methodName, classParam );
return (Predicate) m.invoke(colObj, operand);

The query building code:
JPAQuery query = new JPAQuery(entityManager);
query = query.from(company);
for(Predicate p : predicates){
   // if there's at least one predicat with the underlying db class Foo:
   query = query.join(company.foos, new QFoo());
   break;
}
List<Object[]> rows = query.where(predicates.toArray(new Predicate[0])).listDistinct(company.id);

A: Don't use the generated Q-types for dynamic Expression creation. You can use dynamic paths instead http://www.querydsl.com/static/querydsl/2.9.0/reference/html/ch03.html#d0e1379
In your case something like this
Class<?> entityType = Class.forName(...)
PathBuilder entityPath = new PathBuilder(entityType, "entity");
PathBuilder relation = entityPath.get("relation");
Predicate predicate = relation.get...(...).eq(...)

For Path extraction use this class http://www.querydsl.com/static/querydsl/2.9.0/apidocs/com/mysema/query/types/PathExtractor.html
PathExtactor extracts the first path out of a given Expression


text:
Q: ControllerBase extension method for SeeOther with UrlHelper.Action that is returning null I have a need to use a SeeOther HTTP response code for one of my API routes.
The ControllerBase class has no SeeOther method so I have made an extension method for it, trying to follow the same pattern as the AcceptedAtAction method, passing in a string for action and controller name and an object of route values, but my UrlHelper.Action method keeps returning null when trying to build the action URL for my "Location" header.
I know I must have missed something simple but I just cant spot it, any thoughts?
Here are some (simplified) snippets of code my code
Extension method
public static class ControllerBaseExtensions
{
    public static ActionResult SeeOther(this ControllerBase controller, string actionName, string controllerName, object routeValues)
    {
        var url = controller.Url.Action(
            actionName,
            controllerName,
            new RouteValueDictionary(routeValues),
            controller.Request.Scheme,
            controller.Request.Host.ToUriComponent());

        controller.Response.Headers.Add("Location", url);
        return new StatusCodeResult(303);
    }
}

Controller route
[ApiController]
[Route("/{id:guid}/forms")]
public class FormsController : ControllerBase
{
    [Authorize(Policy = "AuthPolicy")]
    [HttpPost]
    public async Task<IActionResult> Post([FromRoute] Guid caseId, [FromBody] PostFormResourceRepresentation body, CancellationToken cancellationToken)
    {
        if (body.Type != FormType.A) return BadRequest("Unsupported form type provided");

        var requestId = Guid.NewGuid();

        return this.SeeOther("Pending", "Forms", new { requestId });
    }

    [Authorize(Policy = "AuthPolicy")]
    [HttpGet("pending/{requestId:guid}")]
    public IActionResult Pending([FromRoute] Guid caseId, [FromRoute] Guid requestId, CancellationToken cancellationToken)
    {
        return Ok();
    }
}

A: Okay I worked it out, was something very simple.
I forgot to pass one of the route parameters into my Extension when I was calling it.
[Route("/{id:guid}/forms")]
public class FormsController : ControllerBase
{
    [Authorize(Policy = "AuthPolicy")]
    [HttpPost]
    public async Task<IActionResult> Post([FromRoute] Guid caseId, [FromBody] PostFormResourceRepresentation body, CancellationToken cancellationToken)
    {
        if (body.Type != FormType.A) return BadRequest("Unsupported form type provided");

        var requestId = Guid.NewGuid();

        return this.SeeOther("Pending", "Forms", new { requestId, id // this was missing });
    }
}