How to write a bash script that takes optional input arguments?

Question: I want my script to be able to take an optional input,
e.g. currently my script is
#!/bin/bash
somecommand foo

but I would like it to say:
#!/bin/bash
somecommand  [ if $1 exists, $1, else, foo ]

Comment: See also http://unix.stackexchange.com/questions/122845/using-a-b-for-variable-assignment-in-scripts
Comment: ...and http://stackoverflow.com/questions/2013547/assigning-default-values-to-shell-variables-with-a-single-command-in-bash
Comment: I want to say that the this subject is not about the optional argument but a positional argument with default value. This terminology gives much confusion. "Optional argument" means it would be ok whether those arguments exist in the command line or not.
Answer: You could use the default-value syntax:
somecommand ${1:-foo}

The above will, as described in Bash Reference Manual - 3.5.3 Shell Parameter Expansion [emphasis mine]:

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

If you only want to substitute a default value if the parameter is unset (but not if it's null, e.g. not if it's an empty string), use this syntax instead:
somecommand ${1-foo}

Again from Bash Reference Manual - 3.5.3 Shell Parameter Expansion:

Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter's existence and that its value is not null; if the colon is omitted, the operator tests only for existence.
Comment: Please note the semantic difference between the above command, "return `foo` if `$1` is unset *or an empty string*", and `${1-foo}`, "return `foo` if `$1` is unset".
Comment: Can you explain why this works? Specially, what's the function/purpose of the ':' and '-'?
Comment: @jwein001: In the answer submitted above, a substitution operator is used to return a default value if the variable is undefined.  Specifically, the logic is "If $1 exists and isn't null, return its value; otherwise, return foo."  The colon is optional. If it's omitted, change "exists and isn't null" to only "exists."  The minus sign specifies to return foo without setting $1 equal to 'foo'.  Substitution operators are a subclass of expansion operators. See section 220.127.116.11 of Robbins and Beebe's *Classic Shell Scripting* [O'Reilly] (http://shop.oreilly.com/product/9780596005955.do)
Comment: @Jubbles or if you don't want to buy an entire book for a simple reference... http://www.tldp.org/LDP/abs/html/parameter-substitution.html
Comment: This answer would be even better if it showed how to make the default be the result of running a command, as @hagen does (though that answer is inelegant).
Comment: If the subcommand possible takes multiple paramters, then:    `somecommand ${@-foo}`
Comment: I am frustrated why this is optional argument. If you use $1 for a variable, it is positional argument not optional argument. If a command can receive an optional argument of -a -b -c then it should work with "command -a 10", "command -b ten",  "command -c abc" and "command -a 7 -c aaa". If it works always with three arguments such as "command 10 ten abc", it is not a optional argument.
Comment: @OhadSchneider, please reconsider linking to the ABS -- it's a source of enough bad-practice examples that [entire alternative reference sources](https://mywiki.wooledge.org/BashGuide) have been written to replace it after the #bash IRC support channel got fed up with trying to get people to unlearn bad habits they picked up there. (https://wiki.bash-hackers.org/syntax/pe is another good reference on the specific topic at hand; the Wooledge wiki also has parameter expansion coverage in [BashFAQ #100](https://mywiki.wooledge.org/BashFAQ/100) and [#73](https://mywiki.wooledge.org/BashFAQ/073))
Comment: Is it possible to "return `foo` if `$1` is set"?
Answer: You can set a default value for a variable like so:
somecommand.sh
#!/usr/bin/env bash

ARG1=${1:-foo}
ARG2=${2:-'bar is'}
ARG3=${3:-1}
ARG4=${4:-$(date)}

echo "$ARG1"
echo "$ARG2"
echo "$ARG3"
echo "$ARG4"

Here are some examples of how this works:
$ ./somecommand.sh
foo
bar is
1
Thu 19 May 2022 06:58:52 ADT

$ ./somecommand.sh ez
ez
bar is
1
Thu 19 May 2022 06:58:52 ADT

$ ./somecommand.sh able was i
able
was
i
Thu 19 May 2022 06:58:52 ADT

$ ./somecommand.sh "able was i"
able was i
bar is
1
Thu 19 May 2022 06:58:52 ADT

$ ./somecommand.sh "able was i" super
able was i
super
1
Thu 19 May 2022 06:58:52 ADT

$ ./somecommand.sh "" "super duper"
foo
super duper
1
Thu 19 May 2022 06:58:52 ADT

$ ./somecommand.sh "" "super duper" hi you
foo
super duper
hi
you

Comment: Nope - that's just a weird way bash has of doing the assignment. I'll add some more examples to clarify this a bit... thanks!
Comment: Ah, ok. The `-` confused me (is it negated?).
Comment: It looks this is the limit of bash argument. Using python terminology, this is not optional, it is positional. It is just a positional argument with default values. Is there no really optional argument in bash?
Comment: you may be able to use getopts to get what you want - Here's 2 stackoverflow answers that go into greater detail: [dfeault values](https://stackoverflow.com/q/22058316/26510) and [inside a function](https://stackoverflow.com/a/16655341/26510)
Comment: Note also, that to confuse even more (with JSON/python dicts) no space is permitted anywhere, e.g. after the colon and/or after/before the dash... where is the principle of least astonishment here?:)
Comment: good point @mirekphd - I added an example showing how to put spaces in a default value. You can use single quotes if you want a literal value, or double quotes if you want variables to be interpolated
Answer: if [ ! -z $1 ]
then
    : # $1 was given
else
    : # $1 was not given
fi

Comment: `-n` is the same as `! -z`.
Comment: because you failed to quote the variable, `[ -n $1 ]` *will always be true*. If you use bash, `[[ -n $1 ]]` will behave as you expect, otherwise you must quote `[ -n "$1" ]`
Comment: For ones like me: forget the ":" in the code, it's not required, replace it with your real commands!
Comment: Technically, if you pass in an empty string '' that might count as a parameter, but your check will miss it. In that case $# would say how many parameters were given
Comment: I get different results using `-n` and `! -z` so I would say that is not the case here.
Answer: You can check the number of arguments with $#
#!/bin/bash
if [ $# -ge 1 ]
then
    $1
else
    foo
fi

Answer: please don't forget, if its variable $1 .. $n
you need write to a regular variable to use the substitution
#!/bin/bash
NOW=$1
echo  ${NOW:-$(date +"%Y-%m-%d")}

Comment: Brad's [answer](http://stackoverflow.com/a/33419280/603516) above proves that argument variables can also be substituted without intermediate vars.
Comment: +1 for noting the way to use a command like date as the default instead of a fixed value. This is also possible: `DAY=${1:-$(date +%F -d "yesterday")}`
Answer: This allows default value for optional 1st arg, and preserves multiple args.
 > cat mosh.sh
   set -- ${1:-xyz} ${@:2:$#} ; echo $*
 > mosh.sh
   xyz
 > mosh.sh  1 2 3
   1 2 3

Answer: For optional multiple arguments, by analogy with the ls command which can take one or more files or by default lists everything in the current directory:
if [ $# -ge 1 ]
then
    files="$@"
else
    files=*
fi
for f in $files
do
    echo "found $f"
done

Does not work correctly for files with spaces in the path, alas. Have not figured out how to make that work yet.
Answer: It's possible to use variable substitution to substitute a fixed value or a command (like date) for an argument. The answers so far have focused on fixed values, but this is what I used to make date an optional argument:
~$ sh co.sh
2017-01-05

~$ sh co.sh 2017-01-04
2017-01-04

~$ cat co.sh

DAY=${1:-$(date +%F -d "yesterday")}
echo $DAY

Answer: while getopts a: flag
do
    case "$flag" in
        a) arg1=${OPTARG};;
    esac
done

echo "Print optional argument: $arg1"

if [[ -z "$arg1" ]]; then
    ARG=DEFAULT_VAL
else
    ARG=$arg1
fi

#Run using below command (eg: file name : runscript.sh)
bash runscript.sh -a argument_val &

Answer: When you use ${1: } you can catch the first parameter(1) passed to your function or(:) you can catch a blank space like a default value.
For example. To be able to use Laravel artisan, I put this into my .bash_aliases file:
artisan() {
    docker exec -it **container_name** php artisan ${1: } ${2: } ${3: } ${4: } ${5: } ${6: } ${7: }
}

and now, I can just type in command line:

artisan -- and all parameters(${1: } ${2: } ${3: } ${4: } ${5: } ${6: } ${7: }) will be just blank spaces
artisan cache:clear -- and the first parameter ( ${1: } ) will be cache:clear and all the others will be just blank spaces

So, in this case I can pass 7 parameters optionally.
I hope it can help someone.


How to get fields and their values from a static class in referenced assembly

Question: I have a static class in a refrenced assembly(named "DAL") named "A7":
A7 like this:
public static class A7
{
public static readonly bool NeedCoding = false;
public static readonly string Title = "Desc_Title"
public static readonly string F0 = "";
public static readonly string F1 = "Desc_F1";
public static readonly string F2 = "Desc_F2";
public static readonly string F3 = "Desc_F3";
public static readonly string F4 = "Desc_F4";
}

How I can get All Properties name and values from DAL assemby A7 class?
thanks
Comment: Don't consider that My class is in another assembly
Answer: Using reflection, you will need to look for fields; these are not properties.  As you can see from the following code, it looks for public static members:
class Program
{
    static void Main(string[] args)
    {
        Type t = typeof(A7);
        FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);

        foreach (FieldInfo fi in fields)
        {
            Console.WriteLine(fi.Name);
            Console.WriteLine(fi.GetValue(null).ToString());
        }

        Console.Read();
    }
}

Comment: Don't consider that My class is in another assembly
Comment: @Nima The question clearly states "in a refrenced assembly" so it will work assuming you have the relevant `using` statements.
Comment: This is for the name but not for the value!
Answer: I faced the same issue when i tried to get the properties using this syntax (where "ConfigValues" is a static class with static properties and I am looking for a property with the name "LookingFor")
PropertyInfo propertyInfo = ConfigValues.GetType().GetProperties().SingleOrDefault(p => p.Name == "LookingFor");

The solution was to use the typeof operator instead
PropertyInfo propertyInfo = typeof(ConfigValues).GetProperties().SingleOrDefault(p => p.Name == "LookingFor");

that works, you don't have to view them as fields
HTH
Answer: See this or this question.
As you will notice in the first question, you also mix up properties and fields. What you are declaring are fields, not properties
So a variant of this should work:
Type myType = typeof(MyStaticClass);
FieldInfo[] fields= myType.GetFields(
       BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (FieldInfo f in fields)
{
    // use f.Name and f.GetValue(null) here
}

Comment: GetValue needs an instance, but A7 is static.
Comment: @PVitt On static classes, pass `null`.
Comment: Ah, didnt see the FieldInfo type, thought it would be a PropertyInfo. My fault.
Answer: somthing like this: ?
FieldInfo[] fieldInfos = typeof(A7).GetFields(BindingFlags.Static | BindingFlags.Public);

Answer:  public static IEnumerable<T> GetAll<T>() where T : class
    {
      var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
       return fields.Select(f => f.GetValue(null)).Cast<T>();
    }

Answer: Just add a reference to the DAL.dll(or whatever you've called it) file and include it in the using section. Then you should be able to acces the public fields.
Comment: But you wouldn't be able to get all the names of the publicly declared fields at runtime. That's why you want to use reflection.


Problems when installing goose

Question: I followed the exact instructions from https://github.com/grangier/python-goose when installing goose, and after I typed in "mkvirtualenv --no-site-packages goose", this is what I got:
172-27-220-167:~ yitongwang$ mkvirtualenv --no-site-packages goose
New python executable in goose/bin/python
Installing setuptools, pip...done.
Error: deactivate must be sourced. Run 'source deactivate'
instead of 'deactivate'.
Usage: source deactivate
removes the 'bin' directory of the environment activated with 'source
activate' from PATH.
(goose)172-27-220-167:~ yitongwang$

I have installed virtualenv and virtualenvwrapper using 'sudo pip install virtualenv/virtualenvwrapper', and the weirdest thing is I seemed to still manage to enter the goose virtual environment (seems like it). After cloning into the git repo and change to the directory python-goose cloned earlier, I attempted to run 'pip install -r requirements.txt' and 'python setup.py install', and these are the errors:
In file included from _imagingft.c:31:

/Users/yitongwang/anaconda/include/ft2build.h:56:10: fatal error: 'freetype/config/ftheader.h' file not found

#include <freetype/config/ftheader.h>

         ^

1 error generated.

Building using 4 processes

gcc -bundle -undefined dynamic_lookup -L/Users/yitongwang/anaconda/lib -arch x86_64 -arch x86_64 build/temp.macosx-10.5-x86_64-2.7/_imagingft.o -L/Users/yitongwang/.virtualenvs/goose/lib -L/usr/local/lib -L/usr/local/Cellar/freetype/2.5.5/lib -L/usr/lib -L/Users/yitongwang/anaconda/lib -lfreetype -o build/lib.macosx-10.5-x86_64-2.7/PIL/_imagingft.so

clang: error: no such file or directory: 'build/temp.macosx-10.5-x86_64-2.7/_imagingft.o'

error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/Users/yitongwang/.virtualenvs/goose/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/64/dhzf31k50zg22rbgbz79c3dw0000gn/T/pip-build-nL0d0r/Pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/64/dhzf31k50zg22rbgbz79c3dw0000gn/T/pip-k7HUgC-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/yitongwang/.virtualenvs/goose/include/site/python2.7" failed with error code 1 in /private/var/folders/64/dhzf31k50zg22rbgbz79c3dw0000gn/T/pip-build-nL0d0r/Pillow

    In file included from _imagingft.c:31:
/Users/yitongwang/anaconda/include/ft2build.h:56:10: fatal error:
      'freetype/config/ftheader.h' file not found
#include <freetype/config/ftheader.h>
         ^
1 error generated.
clang: error: no such file or directory: 'build/temp.macosx-10.5-x86_64-2.7/_imagingft.o'
error: Setup script exited with error: command 'gcc' failed with exit status 1

I'm not sure particularly what's wrong, cause I have tried a few times from scratch where I deleted the directory 'python-goose' and './virtualenv' as well as the path from .bash_profile.
Any help would be much much appreciated!
Thanks
P.S. I'm using Anaconda with Python 2.7 in it.
Answer: Take a look at this.Here also the same problem is highlighted.It is related to workon which is in /usr/local/bin/virtualenvwrapper.sh and calls deactivate but a script in anaconda bin directory also does the same stuff.
Answer: Instead of using virtualenv, try creating an environment with conda (conda create) and install all the goose dependencies into it (apparently freetype is one of them). Then install goose directly into that environment. Something like conda create -n goose freetype ... (replace ... with the other dependencies of goose), source activate goose, python setup.py install (from the goose directory).
Answer: from your command prompt write pip install goose-extractor

Problems when installing goose


jQuery help: trying to set placeholder values for input fields

Question: So, here's my jQuery code:
 if($('#quotation_request_payment_option_lease').is(':checked')){
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  }

 else if($('#quotation_request_payment_option_finance').is(':checked'))
  {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }

If the quotation_request_payment_option_lease checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1300.
And if the quotation_request_payment_option_finance checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1500.
Right now, the default for the page is that the quotation_request_payment_option_lease checkbox is checked, so when I load the page, the placeholder for the quoation_request_down_payment input field is set to 1300 (which is what I want).
The problem I'm having is that when I check the quotation_request_payment_option_finance checkbox (note: it's set so that only one of the two checkboxes can be checked at once), the placeholder remains 1300, it doesn't change to 1500.
Can anyone think of a way to fix this?
Comment: Simply put, if you want to change something when the user changes something, you need an event handler, in your case you need to listen for the `change` event on the checkbox, and change the placeholders accordingly.
Comment: Can you include `html` at Question?
Answer: You must do these validations within an event, like change()

Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

*You can do this without a class(.ckbox), with the selector $("input[type='checkbox']")

$(".ckbox").change(function() {
  if ($('#quotation_request_payment_option_lease').is(':checked')) {
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  } else if ($('#quotation_request_payment_option_finance').is(':checked')) {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }
});

<input type="checkbox" id="quotation_request_payment_option_lease" class="ckbox">

<input type="checkbox" id="quotation_request_payment_option_finance" class="ckbox">

<input type="text" id="quotation_request_down_payment" placeholder="default">
Answer: You must have handle the onclick so that you can initiate the check you want to perform.
Something like this.
Add a class to both checkbox, and then add click listener of that class.
$('check_box_class').on('click', function(){
      if($('#quotation_request_payment_option_lease').is(':checked')) {
          $('#quotation_request_down_payment').attr('placeholder', "1300");
      }else if($('#quotation_request_payment_option_finance').is(':checked')) {
          $('#quotation_request_down_payment').attr('placeholder', "1500");
      }
});

Answer:
(note: it's set so that only one of the two checkboxes can be checked
  at once)

Substitute <input type="radio"> elements for <input type="checkbox"> elements with each having name attribute set to "quotation_request_down_payment"
. Set class attribute of two <input type="text"> elements to "quotation_request_down_payment" at html instead of single element having id. Toggle the display of the <input type="text"> elements' from inline-block to none utilizing css :checked, adjacent sibling selector + and  :not().

#quotation_request_payment_option_lease:checked
+ input + input {
  display: inline-block;
}

#quotation_request_payment_option_lease:not(:checked)
+ input + input,
#quotation_request_payment_option_lease:checked
+ input + input + input {
  display: none;
}
<form>
  <input type="radio"
         id="quotation_request_payment_option_lease"
         name="quotation_request_payment_option"
         value="finance" checked>
  <input type="radio"
         id="quotation_request_payment_option_finance"
         name="quotation_request_payment_option"
         value="finance">
  <input type="text"
         name="quotation_request_payment_option_lease"
         placeholder="1300"
         class="quotation_request_down_payment"
         value="1300">
  <input type="text"
         name="quotation_request_payment_option_finance"
         placeholder="1500"
         class="quotation_request_down_payment"
         value="1500">
</form>


Odd time riff suggestion

Question: I'm trying to record this riff as accurately as possible, but when playing it I have a few problems:

When hitting a power chord, I sometimes hit it twice (extra hit on the unnecessary up stroke).
Sometimes I do the gallop instead of 16th note chug.
6th string chugs start to sound fuzzy after playing this riff on second cycle (as you can see, there's a repeat indicated).

I've practiced it but still pretty hard for me to play. What would be your suggestions about pick positioning (90º with the strings – (nearly) perfectly perpendicular or other angles) and also maybe you can give suggestions about replacing the striking pattern. Thanks!

Comment: Unless this is quite fast I suspect I'd use only downstrokes with the pick angled so it's under my hand, which would be quite flat and damping the strings.
Answer: The direction of the pick is shown as the best way to play it. It means your hand goes up and down in a regular way, which is good. If you change that, it's asking for trouble. Play everything muted, and, as Todd says (as most others would agree with) play it all painfully slowly, giving time for muscle memory to work. If you play it faster and it's still wrong - it's still too quick! But the direction of pick needs following.

Odd time riff suggestion


Limited dependent variable → ordered probit model with Stata

Question: I have a dependent variable, credit rating, and it is a limited dependent variable. Independent variables are profitability, firm size, stock return, etc.
I was advised to use Stata and run regression with fixed effects and then predict yhat in order to obtain a target rating that a certain firm wants to target in this way:
xtreg dependent independent, fe with regression equation below:
Credit rating = $\alpha + \beta_1$R&D $+\beta_2$Size $+\beta_3$Selling Expense $+\beta_4$Market to Book $+\beta_5$Profitability $+\beta_6$Operating Risk $+\beta_7$Tangibility + error term
Then run predict yhat in order to get a proxy for the credit rating a certain firm wants to target.
The dependent variable credit rating is limited, so is the panel regression for the model: xtreg, fe oK, or should an ordered probit model be used instead? (In other studies with credit ratings they use ordered probit.)
And if a probit model should be used, what command is the corresponding command predict yhat (in the case of xtreg fe) for the ordered probit model? Or in other words, how do I get the rating that a firm wants to target (from the panel regression with xtreg, fe  and then predict yhat for the fitted values) from the ordered probit model?
Comment: Unless you focus your question a bit more on the statistical differences between linear fixed effects and ordered probit this question is likely to be flagged as off-topic. Otherwise, since the main part of it is about the corresponding Stata commands StackOverflow might be the better platform to ask your question on.
Answer: If linear fixed effects or order probit are the only two available options for you then the linear fixed effects model is the better choice. Unless you have very strong reasons to believe that there is no unobserved heterogeneity among your firms it is important to account for these unobserved fixed effects as otherwise you are unlikely to obtain consistent estimates. Generally there is a lot of unobserved time-invariant heterogeneity among firms so rejecting fixed effects is unlikely.
However, I do believe that there are other options available to you like the fixed effects ordered logit estimator by Baetschmann et al. (2013). Another paper which might be of interest to you is Riedl and Geishecker (2012). They discuss conditions under which it is better to choose

linear fixed effects
binary re-coding schemes (they discuss several available alternatives)
the Baetschmann et al. (2013) estimator

and which of those alternatives have good properties in small and large samples.
In terms of predictions in Stata you can still use the predict command after oprobit (see the Stata manual on oprobit postestimation).
Comment: Andy I love you man !!! I've never had econometrics and I never wanna have it ^. I have read that same manual on predict postestimation and it seems to me it only gives probabilities or percentages/decimals whereas with the "predict yhat" with linear fixed effects I am getting integers, hence my stupid question was which command can get roughly the same output.
Comment: Ah yes, I forgot about that. Whilst the default `predict` after `xtreg` is linear prediction (`predict yhat, xb`) you need to specify this for nonlinear models. So after the oprobit command you can use `predict yhat, xb`. If you found this answer useful you can accept it as answer to your question by ticking the check mark underneath the voting buttons :-)
Comment: Your great answers saved me vast amount of efforts in reading econometrics, statistical literature and stata manuals which I wouldn't understand .. :)


Problemas com slideDown no jQuery

Question: Estou com um problema que não faço a mínima ideia do que pode ser, entendo bem pouco de jQuery, no remover eu consegui fazer a animação do .slideUp() mas no adicionar que é um .append() não consigo fazer funcionar já tentei várias formas e não vai, segue abaixo o link com os códigos.
http://jsfiddle.net/5ucD3/373/
Answer: O novo elemento deve vir oculto para o slideDown poder mostra-lo, adicione display:none em linha ou na classe do novo elemento:
$(document).ready(function(){
    //when the Add Filed button is clicked
    $(".adicionarCampo").click(function () {
        //Append a new row of code to the "#items" div
        $(".lista").append('
<input class="input-adicional" id="nome" name="nome[]" placeholder="Nome completo" type="text" />
');
        $(".nomes").slideDown("slow");
        $("body").animate({scrollTop: $("body").prop("scrollHeight")}, 500);
    });

    $("body").on("click", ".delete", function () {
        $(this).parent("div").slideUp("fast", function() {
            $(this).remove()
        })
    });
});

Comment: Muito obrigado Jader deu certinho, abraço.

Problemas com slideDown no jQuery


Transfer files using java

Question: I need to transfer lots of small files to a remote computer within my java program. I was wondering if somebody could suggest the best way to do so... I need to transfer lots of small files and it has to be really fast. Should I use some existing protocol implementation? maybe ftp?
One important thing is that most files would be the same all the time, or the difference would be minor so I was thinking of using git for that purpose. Does anyone have experience with sth like this?
Comment: Looks like a job for `rsync`.
Comment: This should be renamed, git and java tags removed and sent over to server fault.  Is it because it's had activity that it can't be voted to move?
Answer: From your description, rsync is an absolutely perfect fit for your requirements, much superior to the alternatives that have been offered.
Comment: I'm starting to think so as well. I've found some windows implementation (http://www.itefix.no/i2/node/10650) - but will have to check how it performs before I put it to use.
Comment: Can rsync be configured, after it has done the initial copy, to delete a remote file, if it has been deleted locally? I have tried using it a little and it seems to leave those files in the remote folder.
Answer: How do you feel about compressing those files and then using ftp? Do you have possibility to decompress on receiver's side?
Git is version control system, there's no need of adding git's files on top of those files of yours, if you will not check out the files later. I'd rather use ftp.
Here's a nice article about java ftp libraries (or you can use a system call to a console ftp client, but I don't like this idea)
Comment: FTP is an option, but as I expect to transfer very large number of small files I expect this to be slow. And the speed at which those files are transfered is absolutely crucial.
Comment: Well yes, that's why I recommended compressing the files first. It's not hard implementing zip compression in java. And you will transfer one big (zip archive) file rather than a lot of small ones, there's much less overhead. Ftp client will have to do login, logout and one RETR command, and that's all. You will not suffer because of speed this way.

P.S.
If those files are plain text, then compression ratio will be huge as well, so you will get multiple advantages
Comment: And what about the fact that most of those files will be the same (most likely more then 90%) and transfering them, imho, is just an overkill.
Answer: Who is receiving the files that you send? another application? You may use a messaging software such as active MQ
or
Stick with java net APIs for FTP.
<code>URL url = new URL("ftp://user:password@server/filename;type=i");
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream(); // To download
OutputStream os = urlc.getOutputStream(); // To upload
</code>
Wondering why you want to involve git. Does it provide any API to find delta etc? I don't think so. git is a version control system as far as I know.
Comment: Files need to be copied on some other machine so that they can be processed by another application. As I already mentioned, I expect to have large number of small files. Most of those files will be the same or with some small diff. There will be very few files that are and need to be completely transfered. Sth like version control system seems like a reasonable option.
Comment: NO you would be misusing version control system for something trivial.
What if there are large number of files? why can't you use JMS or pure FTP? after all, the files are small!?
Comment: And what if I had 5000 files out of which only a few hundred need to be transfered (either because they are modified or new). How would JMS perform in that situation?
Comment: Note that JMS and FTP is only for the data transfer.
They would not identify out of 5000 files what needs to be transferred. You will have to build that kind of logic.
Answer: The most efficient way to transfer lots of small files is as an archive; e.g. ZIP or TAR.  If your network is relatively slow, compressing the archive before transmission will make a big difference files.  But if the network is really fast, compression may actually make the total time to transfer the files longer.  The other factor that makes a big difference is the rate at which the file system can read and (especially) create files.
The Git protocol can be really fast, but it achieves this by only sending files that have changed, and (where possible) sending differences instead of complete files.  This approach cannot be used for regular file transfer.  Rdist and rsync are older UNIX / Linux tools that take the same (differential) approach to transferring files as Git and other version control systems.  They won't help you for the same reasons as Git won't ... in general.
Comment: Well I actually expect most of the files to be the same and very few of them with some differences. I expect even less files to be new.
Answer: The Apache VFS project is a java library that you can use from your program to copy files between file systems.(E.g. copy local files to FTP/SCP/HTTP.)
Copying can be configured so that only files in the source that are newer than the destination are copied, reducing the amount of data sent.
Links

Apache VFS
the file systems supported.

Transfer files using java


Como coloco um alert com IF no Javascript usando Lista de Valores

Question: Estou montando uma função javascript que faz controle de lista de valores de um SELECT no meu SQL. Pois a Lista de Ambos são gigantes.
Então talvez do cara clicar diretamente pra aparecer tudo da tabela, eu coloquei um alert no valor2, onde o cara é obrigado a digitar o valor. no Filtro ele trara o que o cara escreveu. e Não a lista de valor por completa.
Antes a logica era no só valor 2 essa condição, mas agora preciso colocar o alert também no valor 1, porem o meu if morre quando tento colocar o alert para o valor 1 igual fiz no 2.
function mostra_valores(c1)
{
  var ESTILO;
  if(typeof c1.name==="undefined"){
   ESTILO=c1.previousSibling.name;
  } else {
   ESTILO=c1.name;
  }

  if(ESTILO=="P_PARAMETER_1"){
    DIV_LOV.style.display="inline";
    IFRAME.location = "PACKAGE1_PKG.VALOR?P_FILTRO="+document.PROCEDURE_VALOR.P_PARAMETER_1.value+"&P_TIPO=VALOR1";
     alert("Informe o valor 1");
  } else if(ESTILO=="P_PARAMETER_2"){
    if(document.PROCEDURE_VALOR.P_PARAMETER_2.value.length>2){
      DIV_LOV.style.display="inline";
      IFRAME.location = "PACKAGE1_PKG.VALOR?P_FILTRO="+document.PROCEDURE_VALOR.P_PARAMETER_2.value+"&P_TIPO=VALOR2";
    } else {
      alert("Informe o valor 2");
    }
  }
  IFRAME.focus();
}

precisaria que o alert("informe o valor 1"); fique igual a condição do alert ("informe o valor 2");
Answer: Ao meu ver você poderia usar dois if...else separados e quando entrar num dos else's, sair da função com return;:
if(ESTILO=="P_PARAMETER_1"){
   DIV_LOV.style.display="inline";
   IFRAME.location = "PACKAGE1_PKG.VALOR?P_FILTRO="+document.PROCEDURE_VALOR.P_PARAMETER_1.value+"&P_TIPO=VALOR1";
}else{
   alert("Informe o valor 1");
   return;
}

if(ESTILO=="P_PARAMETER_2" && document.PROCEDURE_VALOR.P_PARAMETER_2.value.length>2){
   DIV_LOV.style.display="inline";
   IFRAME.location = "PACKAGE1_PKG.VALOR?P_FILTRO="+document.PROCEDURE_VALOR.P_PARAMETER_2.value+"&P_TIPO=VALOR2";
} else {
   alert("Informe o valor 2");
   return;
}

Se o primeiro if não for satisfeito, não vai chegar no segundo. E se o primeiro if for satisfeito e o segundo não, não vai executar o IFRAME.focus();.
No segundo if você pode colocar as duas condições no mesmo if, sem ter que fazer um dentro do outro.
Comment: Nossa mais facil do que eu pensava, deu certo assim, acho que fiquei querendo enfeitar demais no IF. muito obrigado amigo


Would upgrading the pickups on my low end Ibanez make it sound like a high end one?

Question: I have an Ibanez JEM Jr, the cheap version of Steve VAI's signature JEM model (costs around 500$ compared to the 1600$~2700$ regular JEMs run for). There are many differences, among them that it uses Quantum pickups instead of DiMarzios. It plays well, but it doesn't sound that good.
Is it worth it to upgrade the pickups to DiMarzios similar to the one on the high end JEMs? Would it really improve the tone of the guitar and make it close to that of a high end JEM?
Comment: Have you tried A/B'd a signature JEM with the  JEM Jr and established that it actually *does* sound better to your ears? If so, what were the differences?
Comment: Ibanez makes some truly fantastic guitars in the $500 - 1 000 range, especially out of their Indonesia factories. It is hard to justify an upgrade to a guitar when you can get stock quality for such a good price.
Comment: @NeilMeyer the guitar plays very well and is an awesome deal for its price. It's tone though leaves a lot to be desired.
Comment: New pickups can help quite a bit, but there are things they can't fix. I bought a $300 epiphone SG copy years ago and replaced the awful stock pickup at the bridge with a seymour duncan super distortion and it sounds *amazing* for certain chords. That said, the neck on the guitar is awful and it sounds out of tune if you play too high on the neck. It's a bit of a crapshoot to replace a pickup unless you have a lot of confidence in the construction of the guitar. The neck and its join to the body are important.
Comment: "but it doesn't sound that good." ... what does this mean? ... bad eq? ... get an EQ pedal ... or a distortion ... or overdrive.

Here's a comparison of both ... both sound equally lousy because it's the amp not the pickups.

A crap guitar and a great amp is far better than a great guitar and crap amp. Eddie V Halen used to go on radio shows with his new amp and say 'give me any guitar' and he made any junker they had sound just fine.
Comment: in my humble opinion, the pickups have the **largest** effect by far on the sound, followed by construction, followed by tonewood and then components.As you surely know, playing a sig model doesn't make you sound like that person, only like that person playing that same guitar, not necessarily their own personal guitar. It only gets you **fairly** close.  I would set a budget, try some better pickups (not hard to fit) and if its still doesn't suit your ear, put it back to standard, sell it and sell the new pickups on ebay.
Answer: Better pickups, if properly matched and installed correctly, can make your guitar sound better. Many players upgrade their pickups to improve the sound of their stock guitar. Certainly putting in the same or similar pups as the higher end model should help your sound considerably, as long as they are electrically and mechanically compatible. (Not a certainty.)
Will it sound as good as the high end model? Probably not, because other factors besides the pickups go into making a guitar's sound. The internal electrical components may be of better quality on the high ender and numerous other things might be different: Quality of the wood, method of construction, nut material, bridge construction - any number of aspects that can impact your sound. (Things like 'tone woods' in the body, fingerboard woods, and nut material are sources of endless debate among musicians playing electric instruments: Some believe they make no difference in an electric, others will pay considerably more for a guitar body or neck made of a particular type of wood...)
That being said, along with the strings and your own technique, the pickups are the most important link in your sound chain (we'll leave out the amp and speakers which are completely external) so if you get the same pickups as the high ender (or any better pickups that are suitable for you and your guitar) and make sure that they are installed properly (very important) you should hear a significant improvement in your sound.
More than that, sometimes there really is very little difference between a high end model and a lower model outside of the pickups, for example. You often pay more just for cosmetic differences - a nicer paint job, pearl inlays instead of plastic, a natural bone nut instead of synthetic bone (etc etc etc).
Also having "the bona-fide signature model" or a "Made in Japan" or "Made in America" model instead of "Made in Indonesia" model will jack up the price, although objectively speaking the "Made in Indonesia" or "Junior Model" might be just as good.
All such factors  generally have little or no effect on the sound and playability of the instrument itself (outside of the player's mind - people like to think that if they paid more, it sounds better...).
Unfortunately, it's not always easy to find out the truth about the differences: The makers, the dealers and those who buy the expensive models all have an interest in keep those matters secret. Ibanez and their vendors certainly don't want people to know that they're paying double for the "high end model" because they're getting pickups worth another $100, mother of pearl inlays instead of plastic, and the labor is more expensive someplace, while the instrument itself is virtually the same!
I know bass players who will buy a Fender Squire bass for $300, change the pickups and the wiring or pre-amp and claim that it sounds as good as the $1500 American made model.

Bottom Line:
Try to do some research about others who have done what you want to do. It's probably a very good idea - well worth it. But unless you are familiar with guitar electronics, etc. you might want to have a guitar tech install the new pups, or at least get some advice from one.
Comment: Nut material can only make a difference on open strings.
Comment: @Tim _All such factors generally have little or no effect on the sound and playability of the instrument itself_
Comment: @Tim _only make a difference on open strings_ - why so? Even when you fret the note, the string sits in the nut and reacts with it. (Personally my ears could probably never detect such differences anyhow, especially on an electric. Nut construction is much more important IMO than synthetic vs natural bone.)
Comment: A little experiment for you. Bend a small strip of paper, 1/4" x1/2", put it on your guitar/bass, while it's on its back. Put paper on a string, about fret 3-4, and press any fret higher than that. Play the string. if the paper falls off, you're right - there is some transference *down* the string to the nut.
Comment: @Tim - I did not get a chance to try your paper experiment but I did try damping a fretted string between the fret and the nut - the harmonics were somewhat diminished. I measured with a clip on tuner on the headstock. In fact, since the headstock vibrates allow you to tune that way, the nut material, as part of the headstock will invariably contribute somehow to your sound. (Again - I don't claim any of this would make any appreciable difference in the audio coming out your speaker.)
Comment: Haven't tried this yet - rarely use tuners - but if a string is fretted and played, a tuner on the head will probably recognise that note. Fair enough. But what about if that note is different from that produced behind the fretted note, in other words between fret and nut. If that was transferred as you think, wouldn't the tuner be picking up that note too, thus getting confused? I'm pretty certain the tuner is picking up the open string, as we normally tune, through the nut/head, and in my scenario, through body/neck/head. Not nut.
Comment: @Tim - IDK. We can post a question on the physics site...
Answer: I have often found that the pickups are what lets affordable guitars down the most. It will definitely make a considerable improvement, but it still may not be worth it.
The change of the pickups is not going to make the feel or the look of the guitar any better. It is also not going to make the acoustics of the guitar any better.
A pickup does exactly that it pickups up the sound that the guitar makes and converts it into a signal your amp can amplify. If the acoustics is poor in the instrument then the best pickups in existence are not going to make it sound good.
I would caution you to not try and polish your turd too much, rather upgrade your guitar when you have the means and the skills to justify it.
Answer: I think the best answer (hinted at in the other answers so far) is:
IT DEPENDS
There are many factors in how your current guitar sounds. Pickups may be the primary factor, but they would only make up about 50% of it. That is why upgrading the pups won't be a cheap upgrade. That said, if the guitar sounds "bad" because of poor intonation, for example, then new hardware won't help at all.
The main reason I said "it depends" is because your target sound (as made by the signature model) has been amplified and processed through unknown equipment. Unless you have the same amp and pedals and whatnot that Steve Vai has, comparing your sound to his (both before and after new pickups) is a fruitless exercise.
However, if you have a personal tone you are developing, then upgrading pickups would be a step in that process (if you aren't going to upgrade the entire instrument). However, I'd say to find the amp you want first, then work on improving the sound of the guitar.
Answer: While pickups upgrades are a way to get a different sound, I would recommend that you try adjusting your pickup height before resorting to a pickup swap.  In many cases, poor pickup performance is more about poor pickup height adjustment rather than the pickup itself.
I personally like my pickups to be level and then start with the bridge pickup 1.6mm from the bottom of the wound E string and the neck pickup 2.4mm from the bottom of the wound E string.  This measurement is taken while depressing the wound E string at the last fret on the neck.  Once the height is set, play the guitar use both clean and distorted sounds.  Use your different pickup combinations and adjust the pickup height until you are happy with the tone.
If you have humbucker pickups you can also balance the poles on the pickups.  Poles that are either hex or flat head can be adjusted to fine tune the tone of the guitar.  Google "balancing guitar pickup poles" for specifics.  Again, use you ear and fine tune the sound to your liking.
If you try this exercise and determine that your pickups simply cannot give you what you want, a pickup swap may be in order.  Do your research and know what you are looking for in your sound then select a pickup that will deliver the tone you want.  I know people who have drawers filled with pickups from failed swap outs.
Another thing to consider is some other weak spots in the tone chain of tremolo equipped guitars.
Sustain blocks are a big contributor to under-performing instruments.  Sustain blocks are commonly downgraded by manufacturers to zinc alloy or pot metal from brass to cut production costs on lower price point instruments.  Light, soft sustain blocks absorb more vibration from the bridge.  Heavier, denser sustain blocks will leave more of the vibration in the string where the pickup can translate the vibration into amplified sound.  If your guitar is not equipped with a brass sustain block, upgrading to a brass block is probably the single most impactful tonal upgrade you could make to the instrument.  I use tungten for all of my blocks.  It is articulate, resonant and very pleasantly aggressive.
The tremolo claw is another weak point.  Upgrade to a brass claw.  I do this on all my guitars too.  It is amazing the difference this upgrade makes.  I do not know the science behind it, but it works.
Finally upgrade your tremolo springs to noiseless springs for a clearer more articulate sound that is free of the clunks, creaks and thuds commonly encountered on tremolo systems.
Given that you can get a good brass sustain block for around $40, a good brass claw for about $20 and noiseless springs for around $15.  You can spend $75 plus some of your own time and make a far greater impact on the tone of your guitar than a $100+ pickup upgrade would provide.
Answer: If you otherwise really really like that guitar, then yes. If there are other things about it that bother you whenever you play, then no. The pickups will improve the guitars sound but it won't be like suddenly having a top end guitar. Having two pickups professionally replaced will cost you almost as much as the guitar did.
Answer: i have bought many Ibanez guitars through the years.  All models were rg body types.  I have replaced every single set of factory pick ups with and EMG model of my choice.  81/85, 57/66 and a James Hetfield singature set.  Yes it makes a difference. Pick up companies make pick ups to accomidate the needs and tastes of the player.  They have different tones, amount of sustain  etc. From metal to rock to blues.  I have also used D'Marzio evolution pick ups for and RG model Genesis. If you are noy happy with what you have for the price you paid, then you never will be. If you are looking for more of a Steve Vai sound go with the evolution or Dark Matter pick ups.


How to store actix_web Json to mongodb?

Question: Trying to store incomming data into mongo using r2d2-mongodb and actix_web.
#[derive(Serialize, Deserialize, Debug)]
struct Weight {
    desc: String,
    grams: u32,
}

fn store_weights(weights: web::Json<Vec<Weight>>, db: web::Data<Pool<MongodbConnectionManager>>) -> Result<String> {
    let conn = db.get().unwrap();
    let coll = conn.collection("weights");
    for weight in weights.iter() {
        coll.insert_one(weight.into(), None).unwrap();
    }
    Ok(String::from("ok"))
}

I can't seem to understand what/how I need to convert weight into to use with insert_one.
The above code errors into error[E0277]: the trait bound 'bson::ordered::OrderedDocument: std::convert::From<&api::weight::Weight>' is not satisfied
Answer: The signature for insert_one is:
pub fn insert_one(
    &self,
    doc: Document,
    options: impl Into<Option<InsertOneOptions>>
) -> Result<InsertOneResult>

Document is bson::Document, an alias for bson::ordered::OrderedDocument.
Your type Weight does not implement the trait Into<Document>, which is required for weight::into(). You could implement it, but a more idiomatic way would be using the Serialize trait with bson::to_bson:
fn store_weights(weights: Vec<Weight>) -> Result<&'static str, Box<dyn std::error::Error>> {
    let conn = db.get()?;
    let coll = conn.collection("weights");

    for weight in weights.iter() {
        let document = match bson::to_bson(weight)? {
            Document(doc) => doc,
            _ => unreachable!(), // Weight should always serialize to a document
        };
        coll.insert_one(document, None)?;
    }

    Ok("ok")
}

Notes:

to_bson returns an enum, Bson, which can be Array, Boolean, Document, etc. We use match to make sure it is Document.
I've used ? instead of unwrap, to make use of the Result return type. Make sure the errors are Into<Error> for your Result type.
Returning &'static str instead of allocating a new String for each request.

How to store actix_web Json to mongodb?


Finding a reversed words in a given string using C program

Question: Actually I have been searching for more than 1 week to find a solution for finding a reversed words in a given string using C. My question is, I have been given a string like this "bakelovekac". Here I have a reversed word of "ake" as "eka" in a string. Now I need to find out this reversed word in a given string and print it. How can it be done? Thanks in advance!
Comment: Seems an ACM or OI problem... What's the range of string length? What's the time limit? If there's no restriction on time, you may just use a stupid brute force; otherwise you need some clever hash trick or dynamic programming I guess.
Comment: There is no time limit
Comment: is ake a word?  is it just any series of characters or does it have to be a real word?
Comment: @Bwebb No it doesn't need to be a real word. Just being a series of characters is enough.
Comment: any limit on the size of the original word?
Comment: Not like that sir!
Comment: Are you given a list of possible words?
Comment: Yes. The input will have atleast one reversed words.
Comment: whats the minimum length requirement for the "word" to be considered the reversed word?  "a" is a word and its trivially reversed in there as the second and second to last letter.  I assume atleast two but thats probably still to short, is it three like in your example?
Answer: A basic approach would be to iterate over all the characters of the string and for each character check if it is being repeated, if yes then check for the presence of a possible reverse string.
A crude code for above approach would look something like this:
<code>#include <stdio.h>

void checkForRevWord(char *str, char *rev){
        int length = 0;
        while(1){
                if(str >= rev)
                        break;
                if(*str != *rev)
                        break;
                length++;
                str++;
                rev--;
        }
        if(length > 1){
                while(length--)
                        printf("%c", *(rev+length+1));
                printf("\n");
        }
        return;
}

int main()
{
        char *inputStr = "bakelovekac";
        char *cur = inputStr;
        char *tmp;

        while(*cur != '\0'){
                tmp = cur+1;
                /* find if current char gets repeated in the input string*/
                while(*tmp != '\0'){
                        if(*tmp == *cur){
                                checkForRevWord(cur, tmp);
                        }
                        tmp++;
                }
                cur++;
        }
}
</code>
Answer: Go through this program
<code>    #include <stdio.h>
    #include <string.h>

    int main()
    {
        char text[50]; //this character array to store string
        int len,i;
        printf("Enter a text\n");
        scanf("%[^\n]s",text);//getting the user input with spaces until the end of the line
        len=strlen(text);//getting the length of the array and assigning it the len variable
        for(i=len-1;i>=0;i--)
        {
            printf("%c",text[i]); //printing the text from backwards
        }
        return 0;
    }
</code>
thank you.
Comment: This seems to not address the OPs question about finding a sub string inside the string.  I will let him decide though.


Subset specific rows in a dataframe, but keeping the observations

Question: I have a dataframe which look like this
y = data.frame(subdel = c(1, 2, 3, 1, 57, 14, 1, 2, 57, 57, 57, 3, 1, 1,
  31, 21, 34, 56, 12, 45, 1, 63, 31, 34), muni =  c("A01",  "A83", "A40", NA, NA, NA, NA, NA, NA, NA, NA,  "A45", "B26", "B42","B61", "B70", "B90", "C53", "C89","A45", "B26", "B42","B61", "B70"))

I'm expecting the next result:
z = data.frame(subdel = c(1, 2, 3, 57, 57, 57, 57, 3, 1, 1, 31, 21, 34, 56, 12, 45, 1, 63, 31, 34), muni =  c("A01",  "A83", "A40", NA, NA, NA, NA,  "A45", "B26", "B42","B61", "B70", "B90", "C53", "C89", "A45", "B26", "B42","B61", "B70"))

I want to match subdel == 57 with muni == NA, but, as you can see, conservating all the another observations in the dataframe.
Any help would be appreciated.
Comment: `x == NA` will never give you what you want. `1==NA`, `NA==NA`, `"A"==NA` are all `NA`, not true or false. The canonical way to check for it is `is.na(muni)`.
Comment: You could create a key to match them by and then merge the vectors. With data.table it would be something like: 'setDT(subdel)[subdel==57, id:=1]' and 'setDT(muni)[is.na(muni), id:=1]' and 'merge(subdel, muni, all.x=T, all.y=T, by=c("id"))'
Answer: We can use subset with a logical condition i.e. check for NA in 'muni' (is.na(muni)) and (&) where the 'subdel' is 57 (subdel == 57) or all other non-NA elements from 'muni' (!is.na(muni))
subset(y, is.na(muni) & subdel == 57 | !is.na(muni))


What statistical test to use to say frequency of one sample is higher/lower than the frequencies in other samples?

Question: I have the following table,

I used chi square test of independence to find whether the frequencies of 'c.388A>G' are same across SAMPLE_A, SAMPLE_B and SAMPLE_C. And the p-value from the test shows that they are not the same. Now , I want to make a statement that "The frequency of c.388A>G was significantly higher in SAMPLE_C compared to other groups that had similar but lower frequency." But to say that, should I do any other test? If yes, can you please advise what test I should do?
Answer: I think the simplest is to run a t-test to show that the frequency of sample_c is higher than sample_2 and then another test to show that it is higher than sample_1 and you can divide the p-value by 2 (bonferroni correction) or some other multiple hypothesis testing scheme.
There are other tests. You can take the maximum frequency between sample_A and sample_B (0.49). Then calculate a p-value by calculating the probability, using a binomial distribution, of getting 0.61 or higher and use the total number of samples in sample_C. This is called a binomial test.
Comment: can you please show me how to do this in R.
Comment: https://statistics.berkeley.edu/computing/r-t-tests
for binomial test: p_value <- pbinom(76*0.61,76,0.49)


Returing results only when two dates don't match

Question: I have a table notes.  With fields service_date and create_date.  I only want to see a result if the service_date is >='01-JAN-2012 AND if the service_date and create_date do not match.
I have tried
select applicant_id, service_date, create_date
from notes
where service_date!=create_date

But I get results where those 2 dates match, so it isn't working.
I'm sorry, I am using Oracle
Comment: Might help if you mention the RDBMS you're using.  Given the date string format and column names, I would guess Oracle.
Comment: Sure those dates don't have a time component? 01-JAN-2012 09:00:00 does not equal 01-JAN-2012 09:01:00.
Comment: Yes, there is not a time component
Answer: Try:
select applicant_id, service_date, create_date
  from notes
 where trunc(service_date) != trunc(create_date)
   and service_date >= to_date('01/01/2012', 'dd/mm/yyyy')

(Dates in oracle DB always have a time component - even if you don't display it)


Creating referenced table element

Question: I created a more or less complex table in C. Now I want to create a reference on a lower level of the tree. Is this possible?
Idea:
ELEM000 +--> ELEM010
        +--> ELEM020 +--> ELEM120
        |            +--> **ELEM121**
        |            +--> ELEM122
        +--> ELEM030 +--> ELEM130
        |            +--> ELEM131
        |            +--> ELEM132
        +--> **ELEM121**

The ELEM121 should also be visible one level above, i.e. be a reference
I added an example of what I wanted to to..
void PushL(lua_State *L, const char * str) {
char s[255];
strcpy(s, "ELEM"); strcat(s, str);   lua_pushstring(L, s);  // key
strcpy(s, "Value"); strcat(s, str);  lua_pushstring(L, s);  // value
lua_settable(L, -3);
}
void MakeTable( lua_State *L )
{
lua_pushstring(L, "TBL0");  // name of sub-table

lua_createtable(L, 0, 0);
lua_checkstack(L, 3);
{

PushL(L, "000");

lua_pushstring(L, "TBL1");

lua_createtable(L, 0, 0);
lua_checkstack(L, 3);
{
  PushL(L, "010");
  PushL(L, "020");

  lua_pushstring(L, "TBL2");

  lua_createtable(L, 0, 0);
  lua_checkstack(L, 3);
  {
    PushL(L, "120");
    PushL(L, "121");
    PushL(L, "122");
    lua_settable(L, -3);
  }
  PushL(L, "030");

  lua_pushstring(L, "TBL3");

  lua_createtable(L, 0, 0);
  lua_checkstack(L, 3);
  {
    PushL(L, "130");
    PushL(L, "131");
    PushL(L, "132");
    lua_settable(L, -3);
  }

  lua_settable(L, -3);
}

lua_pushstring(L, "ELEM121");
lua_pushstring(L, "SHOULD BE A REFERENCE TO ELEM121");
lua_settable(L, -3);
}
lua_setglobal(L,"____myTable");
}

Comment: Could you show your code doing this, so that I won't suggest something completely different.
Comment: Create the table and insert it into both other tables.
Comment: The answer completely depends on how you implemented this complex table.
Comment: Please show client code. Do you mean to change the value in either place and have the change reflected on both places? (That would be the hardest case.) Or, something simpler?
Comment: code is updated in my question. And yes, wanting a "reference" means any change should be updated in both places.
Answer: Bottom line: In Lua, field variables cannot be referenced but there are ways of doing what you want.
Here is a comparison between C data structures and Lua data structures.
In C, you either:

have a copy of the value in two places
You can create copies in Lua, too.

or, have a pointer in one place that points to the other place.
In C, that means you'd have to access them differently, one with a pointer deference, the other without.
In Lua, you could have a function in one place that returns the value in the other place. That means you'd have to access them differently, one with a function call, the other without.

The following is equivalent to a read-only pointer:
local ELEM000 = {
  ELEM010 = "ELEM010 value",
  ELEM020 = {
    ELEM120 = "ELEM120 value",
    ELEM121 = "ELEM121 value",
    ELEM122 = "ELEM122 value" },
  ELEM030 = {
    ELEM130 = "ELEM130 value",
    ELEM131 = "ELEM131 value",
    ELEM132 = "ELEM132 value" },
  ELEM121 = function(self) return self.ELEM020.ELEM121 end }

print(ELEM000.ELEM020.ELEM121)
print(ELEM000:ELEM121())
ELEM000.ELEM020.ELEM121 = ELEM000.ELEM020.ELEM121 .. " updated"
print(ELEM000.ELEM020.ELEM121)
print(ELEM000:ELEM121())

If you need a writable pointer then another approach would be needed.

Update
A simple way for a writable pointer is to add an optional value parameter. This is commonly used in JavaScript APIs but JavaScript has the advantage of the undefined data type. In Lua, we'll have to use nil, which means that you can't write nil as a value.
ELEM121 = function(self, value)
    if (value ~= nil) then self.ELEM020.ELEM121 = value end
    return self.ELEM020.ELEM121
    end

For true read-write field access, use the __index and __newindex metatmethods. This requires that the field actually not have a key in the table. The metamethods are invoked when indexing a non-existing field for reading (__index) or for writing (__newindex).
local ELEM000 = {
  ELEM010 = "ELEM010 value",
  ELEM020 = {
    ELEM120 = "ELEM120 value",
    ELEM121 = "ELEM121 value", -- captured as the initial value
    ELEM122 = "ELEM122 value"},
  ELEM030 = {
    ELEM130 = "ELEM130 value",
    ELEM131 = "ELEM131 value",
    ELEM132 = "ELEM132 value" },
  ELEM121 = nil -- ignored
}

setmetatable(ELEM000, {
  __index = function(base, key)
      if (key=="ELEM121") then return base.ELEM020.ELEM121
      else return nil end end,
  __newindex = function (base, key, value)
      if (key=="ELEM121") then base.ELEM020.ELEM121 = value
      else rawset(base, key, value) end end })

setmetatable(ELEM000.ELEM020, {
  ELEM121 = ELEM000.ELEM020.ELEM121, --[[ backing storage for field,
                                          initialized to existing value]]
  __index = function(base, key)
      if (key=="ELEM121") then return getmetatable(base).ELEM121
      else return nil end end,
  __newindex = function (base, key, value)
      if (key=="ELEM121") then getmetatable(base).ELEM121 = value
      else rawset(base, key, value) end end })

-- make sure metamethods will be invoked on these fields
rawset(ELEM000, "ELEM121", nil)
rawset(ELEM000.ELEM020, "ELEM121", nil)

Usage:
print(ELEM000.ELEM020.ELEM121)
print(ELEM000.ELEM121)

ELEM000.ELEM020.ELEM121 = ELEM000.ELEM020.ELEM121 .. " updated"
print(ELEM000.ELEM020.ELEM121)
print(ELEM000.ELEM121)

ELEM000.ELEM121 = ELEM000.ELEM121 .. " again"
print(ELEM000.ELEM020.ELEM121)
print(ELEM000.ELEM121)

There various places to store the backing field and different styles of coding the metamethods. This code is perhaps too concise. And, I leave it to you to code it in Lua C API, if you wish.
Comment: Case 1 covers putting a reference to the same table in both places. (A value is a reference or a primitive.) He didn't say if the ELEM121 value was a table or not. Case 2 is an answer for a read-only reference to a field. I'll leave it for the question asker to clarify what he needs.
Comment: Fair enough. I was assuming the elements were tables but it doesn't actually say that.
Comment: Thanks for the answers. Sorry I forgot to say:
a) All elements are table entries (nested tables)
b) it should create a real reference and not a read-only entry. The user shall either read/write to the original one or to the referenced one without any difference for him.

Creating referenced table element


How to filter out array objects whose 7th character is a colon?

Question: Edit: Thank you everyone! To make life easier in the future, I think I'm going to try to convert the strings into separate pieces of information as a few people suggested. I am a beginner programmer so it will also be good for me to learn how to do that. Thanks again.
Main Question: How do I add a second filter that will select array strings whose 7th character is a colon?
Explanation: Okay so this is really specific but I need to set up an array filter that will be able to pull out certain strings if the colon is at a certain point. I'm creating a random episode generator based on arrays where the episodes are logged as "EP: " i.e. "EP102: Cool Episode". Users are also able to pick the season they want to watch from. This is by filtering the episode strings that contain "EP(specifiedSeasonNumber)" and only picking from those. The problem is that when a show has more than 9 seasons, for example when picking from Season 10, the program will pick some from more than just the specified seasons. If choosing from S10, whose episodes are labeled EP1014, for example, the first 9 episodes from S1 can also be chosen as they contain EP10(full: EP105).
My theoretical solution is to add another filter if the season number is >= 10 that makes sure the colon is the 7th character in the string as this won't be true for episode strings in seasons less than 10.
Existent Filter:
selectFriendsSeasons = epFriends.filter { $0.contains("EP\(seasonNum)")}

Please feel free to ask further questions about the situation. Thank you!
Comment: It would be much better if you preprocessed the strings into a structure that has properties for season number, episode number, and title. Then you can much more easily filter and sort and search your arrays of structures.
Answer: You really should use a struct to represent episode rather than play around with strings.
You can check colon position using:
$0.index(of: ":") == $0.index($0.startIndex, offsetBy: 6)

Comment: This is ultimately what I was looking for, thank you. I'll mark it as the answer. However I think I might look into structs as I haven't even heard of them before, I'm quite beginner level. Thanks!
Answer: If you're not willing to create a proper struct that would model your data more easily, then I would suggest that you change the way you encode seasons on 2 digits instead of 1. And that way your filter statement would look like :
let seasonNumString = String(seasonNum)
let formattedSeasonNumString: String = seasonNum > 10 ? seasonNumString : "0" + seasonNumString
selectFriendsSeasons = epFriends.filter { $0.contains(formattedSeasonNumString)}

Comment: Ohh this took me a bit to understand but that's certainly something to look into as well as I was considering this as an option, too. Thank you.


Dirichlet's/Abel's test like convergence to $0$ for absolutely convergent series

Question: Consider the series $S_N = \sum_{k=0}^N a_k b_k$.
Let:

$a_k > 0$
$\sum_{k=0}^N a_k < M$ for any $N$
$a_k \rightarrow 0$ as $N \rightarrow \infty$
$b_k = \beta^{N-k}$ with $\beta \in (0,1)$.

I am pretty sure that this implies convergence of $\sum_{k=0}^N a_k b_k$ to $0$ as $N \rightarrow \infty$, because $a_k$ is finite and $b_k$ tends to $0$ for increasing $N$. But unfortunately, I'm not able to prove it.
The problem is that all available tests/theorems aim to prove convergence to a finite value instead of to zero. I tried a Abel's test/Dirichlet's test like approach (with summation of parts) but this alsways ends up in convergence to a nonzero value.
Any help and hint is appreciated. Thanks!
Answer: Just write
$$\sum_{k=0}^N a_kb_k = \sum_{k=0}^N a_k \beta^{N-k}=\frac{\sum_{k=0}^N a_k \beta^{-k}}{\beta^{-N}}$$
and apply Kronecker's lemma.
Comment: To apply Kronecker's lemma, you must have that $\sum a_n$ converges. So either you just assume that $\sum a_n$ converges (and you don't need to specify $a_n > 0$ indeed), otherwise you specify $a_n > 0$ and $\sum a_n$ bounded (this implies that $\sum a_n$ converges). But be careful, if you just have a bounded sum $\sum a_n$, with no assumption that $a_n > 0$, then it *will not* imply that $\sum a_n$ converges, so this will not work.
Comment: Many thanks for your answer. Is in this case the restriction $a_k > 0$ even necessary as long as $|{\sum_{k=0}^\infty a_k}| < \infty$?
Answer: Welcome in MSE.
This is tricky! The main tool we use is the summation by parts, which is an analogue of the integration by parts in the discrete world. Setting
$$T_n := \sum_{k=0}^n \frac{a_k}{\beta^k} $$
You are asking whether $\beta^n T_n$ tends to zero. Notice that $(T_p - T_{p-1})\beta^p = a_p$. Summing from $p=0$ to $p=N$ and using the second condition we have
$$ M > \sum_{p=0}^N (T_p - T_{p-1}) \beta^p $$
And applying summation by parts
$$ M > \beta^N T_{N+1} - T_0 - \sum_{p=1}^N T_p (\beta^p - \beta^{p-1} ) = \beta^n T_{n+1} - T_0 + (1-\beta)\sum_{p=1}^N T_p \beta^{p-1} $$
$$ > - T_0 + (1-\beta) \sum_{p=1}^{N+1} T_p \beta^{p-1} $$
Which implies
$$ \frac{\beta(M+T_0)}{1-\beta} > \sum_{p=1}^{N+1} T_p \beta^p $$
Now the right hand side is a bounded and positive series in $N$, hence it will converge for $N \to \infty$. Since it converges, the general term $T_p \beta^p$ must converge to zero, which was our thesis!


In Spring-based web application, where is my console/log output going to?

Question: I'm writing a simple Spring-based web application and deploying it to Websphere Liberty 22.214.171.124; I've gotten past my deployment problems and the application seems to start (according to the Liberty console.log).  However, I'm not seeing any console or log output.  My application main class, which contains print statements in the main method, is:
@Configuration
public class UserSettingApplication  extends SpringBootServletInitializer implements WebApplicationInitializer {

    ServletContext servletContext;

    private static final LoggerUtils logger = new LoggerUtils( UserSettingApplication.class );

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        builder.sources(UserSettingApplication.class);
        return builder;
    }
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addListener(RequestContextListener.class);
        this.servletContext=servletContext;
        super.onStartup(servletContext);
    }
    public static void main(String[] args) throws Exception {
        System.out.println( "Entering UserSettingApplication.main" );
        SpringApplicationBuilder applicationBuilder = new UserSettingApplication().configure(new SpringApplicationBuilder());
        applicationBuilder.run(args);
        System.out.println( "Entering UserSettingApplication.main" );
    }
    @Override
    protected WebApplicationContext run(SpringApplication application) {
        WebApplicationContext webApplicationContext = super.run(application);
        Environment env = webApplicationContext.getEnvironment();
        String sessionName = env.getProperty("server.session.cookie.name", "xplore-session-id");
        servletContext.getSessionCookieConfig().setName(sessionName);
        return webApplicationContext;
    }
    @Bean
    protected RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }
  @Bean
  public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

      logger.info("Let's inspect the beans provided by Spring Boot:");

      String[] beanNames = ctx.getBeanDefinitionNames();
      Arrays.sort(beanNames);
      for (String beanName : beanNames) {
        logger.info(beanName);
      }
    };
  }
}

Shouldn't I be seeing the print statements in the main method in the WASLiberty console.log?
Answer:
Shouldn't I be seeing the print statements in the main method in the WASLiberty console.log?

You will not see any printouts from the main method as it is not executed in the Liberty. The main method is used for standalone apps started from the command line not run from the app server. Put your messages in the configure method like below and you will see it.
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        System.out.println("##############@@@@@@@@@@@@##############Starting app");

Answer: System.out.println() will NOT write into files such as console.log.
Instead it will write into console such as commandline window or eclipse console.
You need to use loggers such as log4j or Java.util.logging for writing into files.
You can find more info here what-is-the-difference-between-java-logger-and-system-out-println
Comment: This answer is not correct, all System.out.printlns go to the `message.log` in the Liberty and to the `console.log` if you started the server with the `run` command instead of `start`. So check your `message.log` file for these entries.
Comment: I *thought* I've seen println output in ...//logs/console.log in the past.   Also, I am writing to both stdout and to log files, so I'm still puzzled as to why I don't see my output.
Comment: Downvoted because this is inaccurate and misleading. Please be aware you can delete your answer and get rep points back.
Comment: @NathanHughes, Thanks for teaching, I am here to learn and this answer is one of the mistakes. Sometimes points are less important than a reminder :-)


How to append object in postgresql jsonb field while update

Question: I want to update my jsonb field it store array of object.
i want to add new object in it.
CREATE TABLE justjson ( id INTEGER, doc JSONB);
INSERT INTO justjson VALUES ( 1, '[
  {
    "name": "abc",
    "age": "22"
  },
  {
    "name": "def",
    "age": "23"
  }
]');

then value like
select doc from justjson;

doc
[{"age": "22", "name": "abc"}, {"age": "23", "name": "def"}]

Now I want to append new object in this jsonb
{"age": "45", "name": "xyz"}

How can i update this field?
my output such as
doc
    [{"age": "22", "name": "abc"}, {"age": "23", "name": "def"},{"age": "45", "name": "xyz"}]

Comment: [Look here for](https://www.postgresql.org/docs/current/static/functions-json.html) *Concatenate two jsonb values into a new jsonb value.*
Answer: Use the concatenation operator || to append an element to an array:
UPDATE justjson
SET doc = doc || '{"age": "45", "name": "xyz"}'::jsonb
WHERE is = 1;

Comment: Thank you for this code snippet, which might provide some limited, immediate help.  A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions.  Please [edit] your answer to add some explanation, including the assumptions you've made.
Comment: @YvetteColomb Such an ardent appeal cannot remain unheard.
Comment: @LaurenzAlbe
How can I update in jsonb such as i want to set age by name
Ex. where name = xyz set age = 46
in above table


Assembly - Round floating point number to .001 precision toward -∞

Question: I am trying to write all my floating point numbers to .001 precision toward -∞. I have set the RC field to 01 binary, but I am only able to print out the initial floating point number with the wanted precision and thereafter it disregards the rounding. I think I might be missing something obvious in how I am handling the precision towards -∞, but I am not sure.
INCLUDE Irvine32.inc

.data

ctrlWord  WORD  010000000000b ; set the RC field to round down toward -∞.

.code

     fild   sum                         ; load integer into ST(0)
     fidiv  count                       ; divide ST(0) by mem int
     fstcw  ctrlWord                    ; store control word
     fldcw  ctrlWord                    ; load control word
     call   WriteFloat                  ; +2.5000000E+000

     fild   stdDev                      ; load variance integer into ST(0)
     fidiv  count                       ; average the result
     fsqrt                  ; ST(0) = square root
     call   WriteFloat                  ; +2.5495097E+000

Comment: 'numbers to .001 precision toward': Do you mean decimal or binary?
Comment: I mean decimal (float).
Answer: The rounding mode of the FPU applies only to the last binary digit of the floating point mantissa. It cannot be used for a decimal rounding. There is one exception from that rounding rule: FRNDINT. This instruction "rounds the source value in the ST(0) register to the nearest integral value, depending on the current rounding mode (setting of the RC field of the FPU control word), and stores the result in ST(0)." (Intel Manual).
For decimal rounding you can use FRNDINT with a trick: First calculate n * 10^x (x is the desired decimal precision of the fractional part). Then use FRNDINT which rounds the integral part and truncates the fractional part. Finally you can divide the number by 10^x or you can convert the number to a string and insert the decimal point appropropriate.
Take a look at this example (it's your code, just a little bit modified):
INCLUDE Irvine32.inc

.data

newCtrlWord  WORD 010000000000b ; set the RC field to round down toward -∞.
oldCtrlWord  WORD ?
sum WORD 25
count WORD 10
stdDev WORD 65
thousand WORD 1000

.code
main:

    fstcw oldCtrlWord               ; store control word
    mov ax, oldCtrlWord
    and ah, 11110011b               ; clear _only_ RC field
    or  ah, 00000100b               ; set _only_ RC field (rounding to -∞)
    mov newCtrlWord, ax
    fldcw newCtrlWord               ; load control word

    fild   sum                      ; load integer into ST(0)
    fidiv  count                    ; divide ST(0) by mem int
    fimul thousand                  ; thousand=10^3 - preserve three decimal digits of the fractional part
    frndint                         ; only for this you need the control word
    fidiv thousand                  ; adjust integer to a correct rational number (reverse the `fimul thousand`)
    call WriteFloat                 ; +2.5000000E+000
    call CRLF

    fild stdDev                     ; load variance integer into ST(0)
    fidiv count                     ; average the result
    fsqrt                           ; +2.5495097E+000
    fimul thousand                  ; thousand=10^3 - preserve three decimal digits of the fractional part
    frndint                         ; only for this you need the control word
    fidiv thousand                  ; adjust integer to a correct rational number (reverse the `fimul thousand`)
    call WriteFloat                 ; +2.5490000E+000
    call CRLF

    fldcw  oldCtrlWord              ; restore control word

    exit

END main


Add space every 3 characters in span

Question: I have some span like this :
12345678
123456

But I want my number to be displayed like this :
12345678 -> 12 345 678
123456 -> 123 456
Is it possible in CSS or only in JS/jQuery ?
Answer: No, it is not possible.  You will have to use JS/jQuery.
Comment: @mplungjan Well, I don't think so.
Comment: Because I don't have to _vote_. And I didn't say this answer is good or not! I meant to say not every answer should provide code.
Comment: The answer is correct, as illustrated by the duplicate @mplungjan provided.  If you don't want to accept it, that is up to you.  However, I don't see why you wouldn't.

Add space every 3 characters in span


Date_format não funciona em codigo

Question: Depois de seguir varias instruções e guias de funcionamento do Date_format, preferi pedir ajuda, pois tentei tudo e não consegui formatar a saída da data e hora do banco de dados Mysql.
Alguém sabe o porque desta função não funcionar neste código?
eu preciso da hora na saída 29/02/2006 20:20.
Na minha tabela a minha linha data esta do tipo datetime.
<?php
        // aqui inicia a busca de comentarios dentro do banco de dados.

        require 'conexao.php';

            $buscaComentario = mysql_query("SELECT * FROM comentarios WHERE identificacao = '1' AND moderacao ='nao' ORDER BY data DESC ");

                while ($lista = mysql_fetch_array($buscaComentario)) {

                    $nome =         $lista['nome'];
                    $site =         $lista['site'];
                    $comentario =   $lista['comentario'];
                    $avatar =       $lista['avatar'];
                    $data =         $lista['data'];

                    DATE_FORMAT('data','%d/%c/%Y %H:%i:%s');
                    date_default_timezone_set('America/Sao_paulo');

                    echo "

 $nome

$comentario $site

                             $data

                        ";
        }
        ?>

    <?php

Comment: Você está confundindo as coisas. O `date_format` do `mysql` é uma coisa, a do `php` é outra.
Comment: obrigado colega, o que devo usar neste caso entao para conseguir buscar uma data no banco de dados do jeito que eu preciso?
Answer: Existe um erro no seu código.
Você está tentando formatar a data pelo php, observando o seu código, mas pela sua intenção percebo que quer formatar pelo Mysql.
Então altere esse trecho da sua query para:
SELECT *, DATE_FORMAT(data, 'd/m/Y') AS data_formatada FROM comentarios

Assim, basta utilizar $lista['data_formatada'] para acessar a data formatada
Comment: entendi entao o porque, so me falta acertas esta chamada, tive um erro logo apos a chama, esta certo fazer assim?
    $buscaComentario = mysql_query("SELECT * FROM comentarios WHERE identificacao = '1' AND moderacao ='nao' ORDER BY data DESC ");

    $buscaComentario .= mysql_query("SELECT *, DATE_FORMAT(data, 'd/m/Y') AS data_formatada FROM comentarios");
Comment: tive erro a seguir a este codigo que postei
Warning: mysql_fetch_array() expects parameter 1 to be resource
Answer: O problema é na função mysql_fetch_array(), ela recebe dois parâmetros, a primeira é a variavel que recebeu o resultado da sua query, e o segundo o tipo de array a ser retornado. Tente assim:
mysql_fetch_array($buscaComentario, MYSQL_ASSOC);

Basicamente retorna um array associativo, veja mais aqui.
Com relação ao formato da hora, você quer no formato dd/mm/yyyy hh:mm, similar a resposta anterior adicione apenas:
SELECT *, DATE_FORMAT(data, 'd/m/Y H:i') AS data_formatada FROM comentarios
Veja uma referencia completa da função aqui
A razão que eu imagino pela você está sendo negativado (não tenho certeza) é por estar usando a extensão MYSQL para manipulação de bases de dados mysql. Uma vez que ela está em desuso, já que existem outras opões como mysqli e pdo. Além disso a extensão MYSQL foi removida da versão 7 do PHP. Então seria aconselhável você migrar para mysqli (funções similares a MYSQL). Um breve tutorial.

Date_format não funciona em codigo


If $X\sim U\{1,2,3,\cdots n\}$, $Y|X=x\sim U\{1,2,3,\cdots,x\}$ find $P(Y=j)$

Question: I think that
\begin{eqnarray}
P(Y=j)&=& \sum_{x=1}^nP(Y=j|X=x)P(X=x)\\
&=& \sum_{x=1}^n(\frac{1}{x})(\frac{1}{n})\\
&=& \frac{1}{n}\sum_{x=1}^n\frac{1}{x}
\end{eqnarray}
This is correct?
Comment: You are almost right! Just note that $P(Y=j|X=x)=0$ for $j>x$ and not $1/x$ and correct your sum :)
Answer: The answer below was written before the OP specified that $X$ and $Y$ were dependent. In light of that information, it's obviously incorrect so please disregard!
Is $j$ related to $X$ in any way? Otherwise, the answer is just $P(Y=j) = \frac{1}{n}$ since $Y$ is uniform over $\{1,...,n\}$: $$
\begin{align}
P(Y=j) &= \sum_{x=1}^n P(Y=j, X=x) \\
&= \sum_{x=1}^n P(Y=j | X=x) P(X=x) \\
&= \frac{1}{n} \sum_{x=1}^n P(Y=j | X=x) \\
&= \frac{1}{n} \sum_{x=1}^n P(Y=j) ~~~~\text{ since $Y$ doesn't depend on $X$}\\
&= \frac{1}{n} \, \left( n \cdot P(Y=j) \right) ~\text{ again because $Y$ doesn't depend on $X$}\\
&= P(Y=j) \\
&= 1/n ~~~~~~~~~~~~~~~~~~~~~~~~\text{ since $Y$ is uniform on $1 \ldots n$}
\end{align}
$$
Comment: The relation is that $Y|X $ is uniformly distributed in $\{0,1,2,\cdots, X\}.$
Comment: This condition will probably change the answer
Comment: I agree that this answer is not correct - Y is not independent of X, as the OP clearly states in the title
Comment: @Tom - originally it was not specified in the question whether X and Y were conditionally related. That's why I ask if they are related at the top of the post. Please don't ding me on this.
Comment: @ted Sorry did not know that


Antd, Form, No label but I want to display required red mark

Question: I'm using Ant design on my reactjs project. Without label, the design is better but required red mark is gone. And I want it back if it's possible.
Thank you
<Form
  name="normal_login"
  className="login-form"
  initialValues={{ remember: true }}
  onFinish={onFinish}
>
  <Form.Item
    name="username"
    rules={[{ required: true, message: 'Please input your Username!' }]}
  >
    <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
  </Form.Item>
  <Form.Item
    name="password"
    rules={[{ required: true, message: 'Please input your Password!' }]}
  >
    <Input
      prefix={<LockOutlined className="site-form-item-icon" />}
      type="password"
      placeholder="Password"
    />
  </Form.Item>
  <Form.Item>
    <Form.Item name="remember" valuePropName="checked" noStyle>
      <Checkbox>Remember me</Checkbox>
    </Form.Item>

      Forgot password

  </Form.Item>

  <Form.Item>
    <Button type="primary" htmlType="submit" className="login-form-button">
      Log in
    </Button>
    Or register now!
  </Form.Item>
</Form>

Answer: Probably my solution is not good enough. But anyway it works
<Form.Item
  label={}
  name="name"
  rules={[{ required: true, message: "This field is required" }]}
>
  <Input />
</Form.Item>

Just hide it  from css
.ant-form-item-required span {
  display: none;
}

.ant-form-item-required:after {
  display: none;
}

Comment: .ant-form-item-label >
label.ant-form-item-required:not(.ant-form-item-required-mark-optional)::before{
        content:none;
    }


Why is width of critical strip what it is?

Question: For Riemann zeta function and $L$-functions of number fields, the width of critical strip is $1$. For $L$-functions of modular forms of weight $k$, the width of the critical strip is $k$.
Why is there a variation in the width of the critical strip for various $L$-functions? Is there a conceptual explanation or an underlying heuristics?
Answer: Roughly speaking the critical strip is where the $L$-function
is hard to compute/understand. Its right edge is the boundary
of the region where the Dirichlet series/Euler product converges
nicely (absolutely, locally uniformly etc). Its left edge
is the image of the right edge under the functional equation
(to compute it to the left of the critical strip you can use
the functional equation to reduce it to comuting a nice series/product).


The base-10 integers 36, 64, and 81 can be converted into other bases so that their values are represented by the same digits

Question: The base-10 integers 36, 64, and 81 can be converted into other bases so that their values are represented by the same digits $\triangle\Box\Box$, where $\triangle$ and $\Box$ are two distinct digits from 0-9. What is the value of $\triangle\Box\Box$?
This problem is very interesting to me. I don't have a lot of experience with changing the base. Any hints are greatly appreciated.
Comment: Is it possible for $\triangle = 0$?
Answer: Hint:
$$
36=6^2 \qquad 64=8^2 \qquad 81=9^2
$$
Comment: Yes! Thank you...
Answer: Let us call the number you get $xyy$.  In base $b,xyy_b$ represents $xb^2+yb+1$.  We know that $b^2 \le 36 \lt b^3$ for its base to have three digits, so $3 \lt b \le 6$ and we have only three possibilities.  We can compute $36_{10}=210_4=121_5=100_6$ and only the last can be $xyy$.  This means each number is the square of its base, so $64=100_8,81=100_9$
Answer: Cute.
Note: $36, 64, 81$ are all perfect squares so they are all in the form $1*b^2 + 0*b + 0 = 100_b$. So $\triangle = 1; \Box = 0$ is certainly a solution.  But is it the only solution?
$\triangle\Box\Box_b = b^2*\triangle + b*\Box + \Box = 36$.
If we assume $\triangle \ne 0$ we have $36 = 6^2 + 0 + 0$; So the lowest possible base can be $6$  $36 = 100_6=121_5;210_4;1100_3$ which is more than $3$ digits. Only $100$ is of the form $\triangle\Box\Box$.
If we allow for $\triangle = 0$ we have $\triangle\Box\Box = 0\Box\Box = \Box*b + \Box = \Box(b+1)$ for some base $b$.
Thus we have $\Box(b+1) = 36;\Box(c+1) = 64; \Box (d+1) = 81$ so $\Box$ is a common divisor of $36, 64$ and $81$.  $1$ is the only common factor.
So $\triangle\Box\Box = 011$ will work for $011_{35} = 36; 011_{63}=64;011_{80} = 81$.  But those answers are ... perverse.
I am certain, that $\triangle = 0$ was not to be considered.
So I think we can safely so $\triangle = 1; \Box = 0$ for bases $6,8,9$.


Why is $Y=\beta_0 x^{\beta_1} e$ a linear model?

Question: Why is $Y=\beta_0 x^{\beta_1} e$ a linear model? When we apply the transform, it becomes $lnY = ln\beta_0+\beta_1 lnx +lne$, and why is it still linear when the $\beta_0$ part is under ln?
Comment: Just give $\log\beta_0$ another name, such as $\gamma_0.$ The two models aren't equivalent, though: think about what happens when $\beta_0$ is negative.
Answer: $Y=\beta_0 x^{\beta_1} e$ is not a linear model, it's a power model that can be linearized to a linear model, $\ln Y = \ln \beta_0+\beta_1 \ln x +\ln e$.
Doing that, and estimating it with least-squares, entail an assumption on the original model: $\ln e \sim \mathcal N (0, \sigma^2)$.
In other words, you assume that the $e$ terms are lognormal-distributed.
Comment: Least-squares estimation does not assume normally distributed errors.
Answer: The meaning of linear is not on based on the predictors. It's based on the beta's. In your example the predictor is on the power of beta 1 not the beta itself.
Comment: Your characterization of "linear" seems overly restrictive.  See https://stats.stackexchange.com/a/148713/919 for a detailed discussion of various possible meanings of "linear model."


How to make this code in faster time complexity

Question: I need to make a code that takes in list with tuples with two numbers such as [ (1, 2), (5, 8), (1, 3), (1, 1), (3, 6) ]. First number of tuple is day of the start of event and second number is the day it ends. This code should return biggest number of events going on at the same time and time complexity should be O(n). What i have problem with, is time complexity. This is the least time complex code i could write:
def divide_to_groups(calendar):
    if len(calendar) == 0:
        return 0

    def group_num(j, groups):    # takes index of group and list groups, returns last number of last tuple
        if isinstance(groups[j][-1], int):
            return groups[j][-1]
        else:
            return groups[j][-1][1]

    calendar = list(sorted(calendar))
    groups = [[calendar[0]]]

    for i in range(1, len(calendar)):

        for j in range(len(groups)):

            if group_num(j, groups) < calendar[i][0]:   # if previous group has time when current event begins
                groups[j].append(calendar[i])

                break
            elif j+1 == len(groups):
                groups.append([calendar[i]])

    return len(groups)

# Tests
def test_default():
    calendars = [
        [ ],
        [ (1, 2), (3, 3), (500, 800), (50, 56) ],
        [ (1, 2), (5, 8), (1, 3), (1, 1), (3, 6) ],
        [ (1, 1), (1, 50), (25, 75), (60, 100), (2, 3) ]
    ]

    answers = [ 0, 1, 3, 2 ]

    for i in range(len(calendars)):
        result = divide_to_groups(calendars[i])
        if result == answers[i]:
            print("[", i, "] OK.", sep="")
        else:
            print("[", i, "] Not OK. Expected ", answers[i], " but got ", result, ".", sep="")

if __name__ == '__main__':
    test_default()

Comment: What does `n` in `O(n)` stand for?
Comment: @dedObed it stands for how many actions your code will make if your input is n. Here is a link so you can read on it: https://www.geeksforgeeks.org/understanding-time-complexity-simple-examples/
Comment: I (think that I) understand the big `O` notation quite well. My question is, what exactly does the `n` represent. Number of what, events? Or the total timespan covered?
Comment: It stands for number of events
Answer: If N is your number of events.
In linear time O(N), you can probably fill out your ranges in a calendar-matrix with ones (or an X mark) where the columns would be days and sum each columns to see how many events there is on day D.
           1 2 .... 31
event1     x x x .....
event2       x x x ...
event3       x x .....
...
-----------------------
SUM        1 4 5 .....

And then calculate the maximal index i where SUM(D=i) is maximal.
You can even write a sums(d) list directly without having to store in an intermediate matrix, just using your range structures.
Another problem to consider would be encoding the day of the year in the column. Date libraries usually give you which day of the year (1 <= d <= 366) your date is.
Good luck.


How do I change $\csc x+\cot x$ into $\frac1{\csc x-\cot x}$?

Question: I have the trigonometric expression:
$$\csc x+\cot x$$
And I have to manipulate it into:
$$\frac1{\csc x-\cot x}$$
I've tried, of course, changing the $\csc$ and $\cot$ into $\frac1\sin$ and $\frac1\tan$, but it's gotten me nowhere. I suspect I have to multiply it by some expression over itself but I'm not sure what or how.
Comment: $$\csc^2x-\cot^2x=?$$
Answer: Notice that the difference of two squares: $$(\csc x+\cot x)(\csc x-\cot x)=\csc^2x-\cot^2x=\frac1{\sin^2x}-\frac{\cos^2x}{\sin^2x}=\frac{\sin^2x}{\sin^2x}=1$$ so indeed, $$\boxed{\csc x+\cot x=\frac1{\csc x-\cot x}}$$
Answer: Show backward:
$$\frac{1}{\frac{1}{\sin x}-\frac{1}{\tan x}}=\frac{\sin x}{1-\cos x}=\frac{\sin x(1+\cos x)}{\sin^2 x}=\frac{1}{\sin x}+\frac{1}{\tan x}$$


Building random forest and svm in R caret take a very long time

Question: I have searched for that problem but I haven't found a straight forward answer, so I am working with about 1.4 million numeric values and a few train() funtions. Now the problem is with "svmradial" and the "Random Forest" models which they take a really long time with my i7 6500U CPU and my 4GB of RAM. Is there a way to speed up that process?
<code>control=trainControl(method="cv", number=10)
metric="Accuracy"
fit.knn=train(class~., data=dataset, method="knn", metric=metric, trControl=control)
fit.rf=train(class~., data=dataset, method="rf", metric=metric, trControl=control)
</code>
Comment: There is automatic tuning in random forest in caret, that takes some extra time. Try the ranger package. There you can set the number of cores that you use, if you have a lot of cores this will be much faster.
Answer: I am surprised by your set up: doing 10 fold cross validation with random forest or SVM on 1.4 million data can take weeks if not months to run!
Here is the basic complexity on SVM. Note that, the space complexity for kernel matrix is $O(n^2)$, when $n$ is in order of $10^6$, getting SVM to work is almost impossible (require ~8000G memory). See this discussion for details:
Can support vector machine be used in large data?

I would suggest to do small scale experiments before you run 10 fold cross validation on complicated model. In addition, before you try some model, try to estimate the time and space complexity. For example, if you are building a linear regression, and using QR decomposition on least square, try to see how number of data $n$ and number of features $p$, impact the complexity.
Here are some high level suggestions:

Step 1, try to sample your data say get 20% of the data, and make it into training and testing set. (no cross validation)
Step 2. start with some simpler models, such as decision tree or linear model. (In fact, random forest and neural network may be OK, but SVM definitely not efficient on this amount of data.)

Finally try to do some diagnostic experiments such as learning curve to see if you are underfitting or overfitting. Then treat it with different approaches.
Comment: I am working with a machine learning script and a raster image, should I try to aggregating the image instead of getting a sample?


Beamed half note

Question: How can I play this sheet?
What that beamed half note means?
Comment: The dotted half note isn't beamed, its stem is _down_, "overlapping" an eighth note with stem up.
Comment: The stated duplicate is probably not the closest match, but we have a meta answer collection the multi-voice issues [here](https://music.meta.stackexchange.com/questions/3503/new-tag-for-multiple-voices-issue-helpful).
Answer: The half note, with it's stalk pointing down, isn't beamed. Its head just coincides with the first of a group of six 8th notes in the upper voice.  The two noteheads could have been written side by side, sometimes we notate them this way, with the black notehead hidden behind the open one.  The two 'voices' indicate a musical intent rather than something that can be literally played on a keyboard.  Hit the note once!
This is the alternative notation.  But then, I guess you'd be asking whether to play the note twice!
Answer: The beamed half note just means you press and hold that key with one finger while you play the eighth notes with two other fingers.  It even tells you which finger to use to hold the dotted half note down. in the second and third full measures.

Beamed half note


Find angle between two planes

Question: Given two planes:
$\pi_1: 2x+4y-2z+1=0$
and
$\pi_2: \begin{cases} x(p,t)=2+p-t\\ y(p,t)=2p+t\\ z(p,t)=3-p \end{cases}$
Find the angle between the planes $\pi_1$ and $\pi_2$.
How to find the normal vector from the below plane equations?
$\pi_2: \begin{cases} x(p,t)=2+p-t\\ y(p,t)=2p+t\\ z(p,t)=3-p \end{cases}$
Comment: Write $\pi_2$ as $v+p \vec u + t\vec w$. Then $\vec n = \vec u\times\vec w$
Answer: You need to find the normal vectors of these planes. Than the angle between those planes will be equal with the angle between their normal vectors. So you need to find the angle between vectors: $n_1=(2,4,-2)$ and $n_2=(1,1,3)$.
Comment: Emin, Could you write to me, how to calculate vector $n_2$?
Comment: from x=2+p−t and y=2p+t we have t=-x+2+p and t=y-2p. By equalizing right sides of the equations we have that -x+2+p=y-2p or p=(x+y-2)/3. Than by replacing that p in z=3−p we have x+y+3z-11=0.

Find angle between two planes


How to print pdf from my Android app with Brother HL-1110 Series Printer

Question: I check Brother Printer's Developer site and they provide SDK without support of Ink-jet and Laser printer. But another app "StarPrint" can print on this printer but it too slow process and sometime This app cannot print any thing in brother printer. I am looking for a better solution which can print PDF directly from my app using Brother  HL-1110 Series Printer.
Please help me with your valuable suggestion.
Thanks
Answer: just had the same question.
Printer (here HL-1110) connected how ? Own WiFi or via Windows or Ubuntu (here 16.04) via USB. Installed and shared open for internal Network.
Problem under Ubuntu, there are after Installation two Printer
* HL-1110, use the USB, but dont print
* HL-1110 series, using brother driver and can print from PC good
Android:
I used install the App "PrinterShare, as less MB using", after starting, search WiFi search (or choose what you use) and I saw directly the HL-1110. Test Page goes into that Que, but as before cant print,
I have to manually move the job to the KL-1110 series, then OK.
Advantage by this "mistake", I can check the jobs before the printer gets crazy.
Happy to get other solutions may be more better. Problem, when choose brother driver, the 1110 series not there, so I took "generic" driver, works.