text:
Q: Rails, post-deploy to Heroku: unable to run console, db:migrate Good day,
My team and I are trying to push our Rails app to Heroku - git push heroku dev:master is successful, but thereafter heroku run rails db:migrate, heroku run rails console, etc. all fail with the following error (full trace pasted at bottom of post):
   NoMethodError: undefined method `map' for nil:NilClass
    /app/vendor/bundle/ruby/2.4.0/gems/warden-jwt_auth-0.3.6/lib/warden/jwt_auth.rb:89:in `upcase_first_items'

I tracked down the failing method upcase_first_items in the files of the gem jwt_auth, but remain unable to solve this. Searching the error on Google (including iterations of the error) turns up 0 results.
We successfully pushed this app to Heroku two weeks ago, and have not since changed anything with regards to authentication (which I've made sure of by reviewing all our commits from the last 2 weeks).
Any ideas?
Thanks,
Michael
Full trace:
[cocomio-languages (dev)]$ heroku run rails db:migrate --trace
Running rails db:migrate --trace on ⬢ coco-sprint-3... up, run.2956 (Hobby)
** Invoke db:migrate (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
rails aborted!
NoMethodError: undefined method `map' for nil:NilClass
/app/vendor/bundle/ruby/2.4.0/gems/warden-jwt_auth-0.3.6/lib/warden/jwt_auth.rb:89:in `upcase_first_items'
/app/vendor/bundle/ruby/2.4.0/gems/warden-jwt_auth-0.3.6/lib/warden/jwt_auth.rb:50:in `block in <module:JWTAuth>'
/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/setting.rb:119:in `evaluate'
/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/setting.rb:70:in `value'
/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/config.rb:111:in `method_missing'
/app/vendor/bundle/ruby/2.4.0/gems/devise-jwt-0.5.9/lib/devise/jwt/railtie.rb:19:in `block (3 levels) in <class:Railtie>'
/app/vendor/bundle/ruby/2.4.0/gems/dry-configurable-0.11.1/lib/dry/configurable/methods.rb:15:in `configure'
/app/vendor/bundle/ruby/2.4.0/gems/devise-jwt-0.5.9/lib/devise/jwt/railtie.rb:15:in `block (2 levels) in <class:Railtie>'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:69:in `block in execute_hook'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:62:in `with_execution_control'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:67:in `execute_hook'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:52:in `block in run_load_hooks'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:51:in `each'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/lazy_load_hooks.rb:51:in `run_load_hooks'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application/finisher.rb:75:in `block in <module:Finisher>'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:32:in `instance_exec'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:32:in `run'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:61:in `block in run_initializers'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:431:in `each_strongly_connected_component_from'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:349:in `block in each_strongly_connected_component'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:347:in `each'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:347:in `call'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:347:in `each_strongly_connected_component'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:226:in `tsort_each'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/tsort.rb:205:in `tsort_each'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/initializable.rb:60:in `run_initializers'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application.rb:361:in `initialize!'
/app/config/environment.rb:5:in `<main>'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `block in require_with_bootsnap_lfi'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require_with_bootsnap_lfi'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `block in require'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:257:in `load_dependency'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `require'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application.rb:337:in `require_environment!'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/application.rb:520:in `block in run_tasks_blocks'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:281:in `block in execute'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:281:in `each'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:281:in `execute'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:219:in `block in invoke_with_call_chain'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:199:in `invoke_with_call_chain'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:243:in `block in invoke_prerequisites'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `each'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `invoke_prerequisites'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:218:in `block in invoke_with_call_chain'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:199:in `invoke_with_call_chain'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:243:in `block in invoke_prerequisites'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `each'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:241:in `invoke_prerequisites'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:218:in `block in invoke_with_call_chain'
/app/vendor/ruby-2.4.4/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:199:in `invoke_with_call_chain'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/task.rb:188:in `invoke'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:160:in `invoke_task'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:116:in `block (2 levels) in top_level'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:116:in `each'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:116:in `block in top_level'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:125:in `run_with_threads'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:110:in `top_level'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/commands/rake/rake_command.rb:23:in `block in perform'
/app/vendor/bundle/ruby/2.4.0/gems/rake-13.0.1/lib/rake/application.rb:186:in `standard_exception_handling'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/commands/rake/rake_command.rb:20:in `perform'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/command.rb:48:in `invoke'
/app/vendor/bundle/ruby/2.4.0/gems/railties-5.2.4.1/lib/rails/commands.rb:18:in `<main>'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `block in require_with_bootsnap_lfi'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require_with_bootsnap_lfi'
/app/vendor/bundle/ruby/2.4.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `block in require'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:257:in `load_dependency'
/app/vendor/bundle/ruby/2.4.0/gems/activesupport-5.2.4.1/lib/active_support/dependencies.rb:291:in `require'
/app/bin/rails:4:in `<main>'
Tasks: TOP => db:migrate => db:load_config => environment

Update 1
I reverted to each commit from the previous two weeks (i.e. between now and the last working deploy), and deployed, but received the same error. I reached commits from even before the last deploy (the deploy that was working), and still have the same error, which leads me to believe it has nothing to do with our commits from the last few weeks.
When I went to the Heroku dashboard and reverted the build to the deploy from two weeks ago, the Rails commands (heroku run rails c, heroku run rails db:migrate, etc.) once again work.

A: With the version 0.8.0 of devise-jwt it's no longer a problem. Please see the breaking change in version 0.7.0, when upgrading.

Previous answer
Probably someone or something upgraded the dry-configurable gem from version 0.9.0 to 0.11.1. This gem is a dependency of warden-jwt_auth which is a dependency of devise-jwt and the new version breaks it.
A few days ago the version 0.11.0 of dry-configurable was released and warden-jwt_auth uses it, because it specifies the version of this dependency with ~> 0.6, which includes the faulty version (everything from 0.6 to 1.0 would be fine). You can see that in the Gemfile.lock or in the dependencies of warden-jwt_auth.
If somebody did run bundle upgrade it will have pulled the new faulty version.
I recommend you to pin the older version of dry-configurable in your Gemfile:
gem 'dry-configurable', '0.9.0'

Then run bundle update and deploy again.

A: Now my rspec is working with following versions

*

*rails 6.1.6

*ruby 2.7.5

I needed to install
devise-jwt 0.9.0 from 0.7.0
dry-configurable 0.13.0 from 0.15.0
rspec-rails 5.1.2
. Previously was receiving following gerror
undefined method `[]' for nil:NilClass
ruby-2.7.5/gems/devise-jwt-0.7.0/lib/devise/jwt/mapping_inspector.rb:49:in `formats'


text:
Q: Uploading multiple files asynchronously by blueimp jquery-fileupload I'm using jQuery File Upload library (http://github.com/blueimp/jQuery-File-Upload), and I've been stuck figuring out how to use the library satisfying the following conditions.

*

*The page has multiple file input fields surrounded by a form tag.

*Users can attach multiple files to each input field

*All files are sent to a server when the button is clicked, not when files are attached to the input fields.

*Upload is done asynchronously

*Say the page has 3 input fields with their name attributes being "file1[]", "file2[]" and "file3[]", the request payload should be like {file1: [ array of files on file1[] ], file2: [ array of files on file2[] ], ...}

Here's jsFiddle, it's behaving weird so far in that it sends post request twice and the first one is cancelled.
Updates
Now thanks to @CBroe 's comment, the issue that request is sent twice is fixed. However the keys of request parameter is not correctly set.
Here's updated jsFiddle.
http://jsfiddle.net/BAQtG/27/

The core part of js code looks like this.
$(document).ready(function(){
    var filesList = []
    var elem = $("form")
    file_upload = elem.fileupload({
        formData:{extra:1},
        autoUpload: false,
        fileInput: $("input:file"),
    }).on("fileuploadadd", function(e, data){
        filesList.push(data.files[0])
    });

    $("button").click(function(){
        file_upload.fileupload('send', {files:filesList} )
    })

})

Anybody have idea how to get this to work?

A: Solved.
Fiddle:
http://jsfiddle.net/BAQtG/29/
And js code
$(document).ready(function(){
    var filesList = [],
        paramNames = [],
        elem = $("form");
    file_upload = elem.fileupload({
        formData:{extra:1},
        autoUpload: false,
        fileInput: $("input:file"),
    }).on("fileuploadadd", function(e, data){
        filesList.push(data.files[0]);
        paramNames.push(e.delegatedEvent.target.name);
    });

    $("button").click(function(e){
        e.preventDefault();
        file_upload.fileupload('send', {files:filesList, paramName: paramNames});
    })
})

A: The first POST request triggered by your script gets canceled, because the button submits the form (causing the second POST request).
Use type="button" on the button if you don't want it to have submit functionality.

A: You have to either add a return false;, as shown below:
$("button").click(function(){
    file_upload.fileupload('send', {files:filesList} )
    return false;
})

or specify the type="button" attribute:
<button type="button">send by fileupload send api</button>

In order to set the formData, use the following:
$("button").click(function () {
    file_upload.fileupload('send', {
        files: filesList,
        formData: {
            json: JSON.encode({
                extra: 1
            })
        }
    })
})

Specifically for JSFiddle, if you want to get the extra value in the response, you have to encode it and assign it to a property named json.
Here's a working example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PowerMock and JUnit test fails when using isAnnotationPresent I am trying to test some code that needs the method method.isAnnotationPresent(). That thing I do not get running currently, since it always throws me an exception.
java.lang.annotation.AnnotationFormatError: Attempt to create proxy for a non-annotation type.
    at sun.reflect.annotation.AnnotationInvocationHandler.<init>(AnnotationInvocationHandler.java:52)
    at sun.reflect.annotation.AnnotationParser$1.run(AnnotationParser.java:306)
    at sun.reflect.annotation.AnnotationParser$1.run(AnnotationParser.java:303)

In the test itself I just executed the method using that annotation check. There is no magic in there.
The function looks like that:
public void checkStuff(String className) {
    Class clazz = Class.forName(className);
    this.filterFancyMethods(Arrays.asList(clazz.getMethods()));
    //More code here
}

private List<Method> filterFancyMethods(List<Method> methods) {
    return methods.stream().filter(method -> method.isAnnotationPresent(Fancy.class)).collect(Collectors.toList());
}

Annotation:
 package de.htw.ai.kbe;

 import java.lang.annotation.*;

 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.METHOD)
 @Documented
 public @interface Fancy {
 }

Test:
@Test
public void shouldFilterFancyMethods() {
    object.checkStuff("me.neatoro.fancy.testutils.TestClass");
    //Assertations
}

Has somebody an idea how to fix that issue?
Thank you for your help :)


text:
Q: Sobolev integrability implies weak flatness? Let $B_1\subset \mathbb R^n$ be the unit ball, and suppose $u\in W^{1,2}(B_1)$, i.e. $\int_{B_1} u^2+|Du|^2\,dx\le K<\infty$.  Moreover, suppose $u$ is nonnegative, with $ess\inf u=0$.
Let us also define the distribution function $\rho(t)=|\{u\le t\}|$.  The nonnegativity and infimum condition simply mean $\rho(t)=0$ precisely when $t< 0$.
Question 1 (answered by supinf): can we deduce from the above that $\rho(t)\ge C t^\alpha$ for some $C,\alpha>0$ depending on $K,n$?
Question 2 (supinf): Replace $\rho(t)\ge Ct^\alpha$ with $\rho(t)\ge \rho(0)+Ct^\alpha$?  If $\rho(0)=0$?
Question 3: Can we deduce $\rho(t)\ge Ct^{\alpha}$ for small $t\ge 0$, and some $C,\alpha>0$ depending on $K$?
Here, $\rho(0)\neq 0$ is allowed, and this smallness should remove counterexamples related to the putative ``power growth" of $\rho(t)$.
Heuristics:

*

*If $u$ is smooth, then this is certainly true, with $\alpha=n$.  So it is reasonable that $\int |Du|^2<\infty$ would have a similar effect.

*If $n=1$, one would initially guess that the family $u_k(x)=|x|^{1/k}$ would comprise a counterexample, since the distribution function decays with $k$, but in fact, this family is not in $W^{1,2}$.

*Note that the distribution function also vanishes for the $W^{1,2}$ family $u_k(x)=U(|x|)^{1/k}$, where $U(x)=x-x\ln x$.  But it can be checked that the Poincare constant $\int |Du|^2/\int u^2$ blows up, so $K=K(k)$ is unbounded.

*If $u$ is Lipschitz, the distribution function is somewhat related to the $W^{1,2}$ norm using the co-area formula:
$$
\int_{B_1} |Du|=\int_{0}^\infty |\{u=t\}|dt.
$$

A: No this is not true.
Consider the example $u=0$.
Then $\rho(t) = |B_1|$ if $t\geq 0$ according to the definition of $\rho$.
Then for $C,\alpha>0$ we have
$$
\lim_{t\to\infty}\rho(t)= | B_1 | < \infty = \lim_{t\to\infty} C t^\alpha.
$$
Thus
$\rho(t)\geq Ct^\alpha$ cannot hold for every $t\geq 0$.
question 2 and general remarks:
For question 2, the function $u=1$ is a similar counterexample (here we have $\rho(0)=0$).
Fundamentally, the problem is that
$$
\rho(t) \leq |B_1| < \infty
\qquad \forall t\in\mathbb R
$$
is true for all functions $u \in W^{1,2}(B_1)$,
whereas
$$
\lim_{t\to\infty} C t^\alpha = \infty
$$
holds for all $C>0,\alpha>0$.
So slight modifications will probably not save your conjecture.


text:
Q: is a mathematical operator classed as an interger in python in python is a mathematical operator classed as an interger.
for example why isnt this code working
import random

score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer = input(int(randomnumberforq)+int(operator[randomoperator])+      int(randomnumberforq))
if answer == useranswer:
print('correct')
else:
    print('wrong')

A: You can't just concatenate an operator to a couple of numbers and expect it to be evaluated. You could use eval to evaluate the final string.
answer = eval(str(randomnumberforq)
              + operator[randomoperator]
              + str(randomnumberforq))

A better way to accomplish what you're attempting is to use the functions found in the operator module. By assigning the functions to a list, you can choose which one to call randomly:
import random
from operator import mul, add, sub

if __name__ == '__main__':
    score = 0
    randomnumberforq = random.randint(1,10)
    randomoperator = random.randint(0,2)
    operator = [[mul, ' * '],
                [add, ' + '],
                [sub, ' - ']]
    answer = operator[randomoperator][0](randomnumberforq, randomnumberforq)
    useranswer = input(str(randomnumberforq)
                       + operator[randomoperator][1]
                       + str(randomnumberforq) + ' = ')
    if answer == useranswer:
        print('correct')
    else:
        print('wrong')

A: That depends on what you're trying to do.  You've given us no sample input or output, no comments, and no error message.
It looks like you're trying to write a simple practice engine for arithmetic.  If so, then your basic problem is that you don't understand the operations allowed in programming.  You can't just throw symbols in a row and expect the computer to figure out how it's supposed to combine them.  Your assignment statements for answer and useranswer are structurally flawed.  The first gives you a list of strings; the second dies because you tried to convert a symbol (such as *) to an integer.
For more advanced user, I would recommend the "evaluate" operation.  For you, however ...
When you pick the random operator, you'll need to check to see which one you got.  Write a 3-branched "if" to handle the three possibilities.  Here's what the head of the first might look like:
if randomoperator == 0:
    operator = '*'
    answer = randomnumberforq * randomnumberforq
elif: ...

Note that the two numbers in the operation are the same.  If you want different numbers, you have to call randint twice.
Does this get you moving ... at a coding level with which you're comfortable?

A: You try to convert a string to an integer, but which isn't a number:
int(operator[randomoperator])

Your operatators in the array "operator" are strings, which don't represent numbers and can't be converted to integer values. On the other hand the input() function desires string as parameter value. So write:
... = input(str(numberValue) + operatorString + str(nubmerValue))

The + operator can be used to concat strings. But Python requires that the operands on both sides are strings. Thats why i added the str() functions to cast the number values to strings.


text:
Q: Omake getenv -- environment variables are not found Some environment variables that exist in my bash environment (set in .bashrc) are not being read by getenv (it's saying they're undefined). Is it looking in some other environment? or....?
monster@Tangerine ~/Casey/piano-core $ omake
*** omake: reading OMakefiles
--- Checking for ocamlfind... (found /home/monster/ocamlbrew/ocaml-4.02.3/.opam/4.02.2/bin/ocamlfind)
--- Checking for ocamlc.opt... (found /home/monster/ocamlbrew/ocaml-4.02.3/.opam/4.02.2/bin/ocamlc.opt)
--- Checking for ocamlopt.opt... (found /home/monster/ocamlbrew/ocaml-4.02.3/.opam/4.02.2/bin/ocamlopt.opt)
--- Checking whether ocamlc understands the "z" warnings... (yes)
*** omake error:
   File _build/score-player/stubs/OMakefile: line 14, characters 8-30
   undefined environment variable: SCORE_PLAYER
monster@Tangerine ~/Casey/piano-core $ $SCORE_PLAYER
bash: /home/monster/Casey/score-player: Is a directory
monster@Tangerine ~/Casey/piano-core $ rlwrap osh
% getenv(SCORE_PLAYER)
*** omake error:
   File -: line 1, characters 0-20
   undefined environment variable: SCORE_PLAYER
%

A: Ok, so I solved this by putting the variables in /etc/environment rather than ~/.bashrc. I guess I don't have a very good understanding of which environments are which....


text:
Q: Find all numbers $n$ such that $\phi (n) = 20$ I'm trying to find all values of $n$ that satisfy euler's phi function in the title.
I start by knowing $n$ cannot be a power of $2$ since $\phi (n)$ is not. Then, $n$ is divisible by an odd prime.
I try to find odd primes satisfying $(p-1)|20$ and so my list is $3,5,11$. Then, $n=2^a3^b5^c11^d$. I'm stuck here, since I don't know how to bound my exponents or what values to use.
I think $a\leq 2$ because $2^2|\phi(n)$. So far I have generated:
$n=2^2\cdot 11, 2\cdot 3\cdot 11, 3\cdot 11$, or $44,66,33$. This was done through trial and error i.e. sampling values for exponents and checking if they satisfy the phi function. Is there an algebraic way to determine the exponents / check if there are other solutions?

A:
I start by knowing $n$ cannot be a power of $2$ since $\phi (n)$ is not. Then, $n$ is divisible by an odd prime.
I try to find odd primes satisfying $(p-1)|20$ and so my list is $3,5,11$. Then, $n=2^a3^b5^c11^d$. I'm stuck here, since I don't know how to bound my exponents or what values to use.

This is good work so far. To continue, show that if $p$ is prime and $p^x$ divides $n$, then $p^{x-1}$ divides $\phi(n)$. Of the primes in your list ($2, 3, 5, 11$), which ones can have $p^{x-1}$ divides $n$, assuming $x \ge 2$?
What about if $x \ge 3$? In this case, $p^2$ would have to divide $20$.
This should let you narrow down to a finite (fairly small) number of possibilities for $a$, $b$, $c$, and $d$ in $n = 2^a 3^b 5^c 11^d$.

A: Use the fact that $\phi$ is multiplicative and the formula that for prime $p\  \phi(p^n)=(p-1)p^{n-1}$.  That means that $\phi(2^a3^b5^c11^d)=(2-1)2^{a-1}(3-1)3^{b-1}(5-1)5^{c-1}(11-1)11^{d-1}$ where you delete the terms where the exponent is $0$.  Clearly $b, d$ are at most $1$.  There are not so many cases to check.  You need to get exactly one factor of $5$ and there are not many ways to do that.


text:
Q: correct approach for 2 threads alternatively printing numbers I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively.
Wanted to know if the approach for using wait() and notify() is correct?
Main Class
public class MyMain {
public static void main(String[] args) {
MyThread1 obj = new MyThread1();

    Thread thread1 = new Thread(obj);
    Thread thread2 = new Thread(obj);

    thread1.setName("t1");
    thread2.setName("t2");

    thread1.start();
    thread2.start();
}
}

Thread Class
public class MyThread1 implements Runnable{
    int i = 0;
    @Override
    public synchronized void run() {
        while(i<10)
        {
            if(i%2==0)
            {
                try{
                    notify();
                    System.out.println(Thread.currentThread().getName()+" prints "+i);
                    i++;
                    wait();

                 }catch(Exception e){ e.printStackTrace(); }
            }else
            {
                try{
                    notify();
                    System.out.println(Thread.currentThread().getName()+" prints "+i);
                    i++;
                    wait();
                }catch(Exception e){ e.printStackTrace(); }
            }
        }
    }
}

Can there be a better usage of wait() and notify() instead of using it in both the if conditions?

A: Since there you have some code repetition I'd just go with something like:
while(true) {
    //If it's not my turn I'll wait.
    if(i%2==0) wait();

    // If I've reached this point is because:
    // 1 it was my turn OR 2 someone waked me up (because it's my turn)
    System.out.println(Thread.currentThread()": "+i);
    i++; // Now is the other thread's turn
    // So we wake him up
    notify();
}

Also, be very careful with monitor's behaviour. (Thread waiting/notifying queues).


text:
Q: How to strip() out a maximum of two white spaces from the front of a string My string contains three white spaces and I would like to keep one. How then can I strip-out just the first two and leave one?
Example
>>> _str='   boy'
>>> _str.lstrip('  ')
'boy'

Ideal output:
' boy'

Thanks for your suggestions.

A: A very general solution, though not a one-liner:
def strip_n_chars(s, n, char):
    """Remove at most n of char from the start of s."""
    for _ in range(n):
        if s[0] == char:
            s = s[1:]
        else:
            break
    return s

Example usage:
>>> strip_n_chars("   foo", 2, " ")
' foo'
>>> strip_n_chars(" bar", 2, " ")
'bar'

A: Here's a regular-expression approach:
import re

# 0, 1, or 2 spaces followed by a non-matched space
reg = re.compile("^([ ]{,2})(?= )")

def strip_spaces(s):
    """
    Return string with 0, 1, or 2 leading spaces removed
     (but leave one leading space)
    """
    return reg.sub("", s)

which then works like
strip_spaces("test")       # => "test"
strip_spaces(" test")      # => " test"
strip_spaces("  test")     # => " test"
strip_spaces("   test")    # => " test"
strip_spaces("    test")   # => "  test"

(if you really like one-liners, you can try
from functools import partial
import re

strip_spaces = partial(re.compile("^([ ]{,2})(?= )").sub, "")

Edit: (shrug) alright, I misunderstood what you wanted; use "^([ ]{,2})" instead (matches 0, 1, or 2 spaces), results in
strip_spaces("test")       # => "test"
strip_spaces(" test")      # => "test"
strip_spaces("  test")     # => "test"
strip_spaces("   test")    # => " test"
strip_spaces("    test")   # => "  test"

although not needing the look-ahead does away with most of the justification for a regular expression.


text:
Q: Are trigonometric polynomials dense in $C_{2\pi}^m$? Let $m \in N$ be fixed and let $C_{2\pi}^m$ be a class of functions $f : R \rightarrow R$ of class $C^m$ and periodic with a period $2\pi$ with the following metric
$$d(f,g)=\sum_{k=0}^m  \sup_{\{x \in R \}}|f^{(k)}(x)-g^{(k)}(x)|$$
for $f,g \in C_{2\pi}^{m}$. Is the set of trigonometric polynomials dense in this metric space?

A: Yes they are, because you can restrict to an interval $[0, 2 \pi]$ of function $f(0) = f(2 \pi)$, and use that they are dense in $C[0,2 \pi]$. Integration $k$-times and observing carefully what gets added will give you an affirmative answer. It is a continuous, surjective operator $C \mapsto C^k$.

A: I have an another idea using Fourier series. Let $f \in C_{2\pi}^m$ and let
$(S_n)_{n=0}^\infty$ be the sequence of partial sum of the Fourier series of $f$. Then it is known that   $(S_n^{(k)})_{n=0}^\infty$, for each $k\in \{0,\ldots m\}$, (that is sequuences of $k$-th derivatives) is a sequence of the partial sum for $f^{(k)}$. By continuity and $2\pi$-periodicity of each $f^{(k)}$, for $k=0,\ldots,m$, and the  Feier Theorem we have that  for each $k\in \{0,\ldots ,m \}$:
$$\left(\frac{S_0(x)+S_1(x)+\ldots S_n(x)}{n+1}\right)^{(k)}=\frac{S_0^{(k)}(x)+S_1^{(k)}(x)+\ldots S_n^{(k)}(x)}{n+1} \rightrightarrows f^{(k)}(x) $$
as  $n\rightarrow \infty$, for $x \in R$. Obviously $\left(\frac{S_0+S_1+\ldots S_n}{n+1}\right)_{n=0}^\infty$ is a sequence of trigonometric polynomials.


text:
Q: Associating one class to belong to two different classes in DataMapper using Sinatra I am working with DataMapper and Sinatra to create a simple app. Here's the structure:
The app has Accounts. Each account has users and campaigns. Each user has comments that should be related to a specific campaign.
Comments should ideally have a user_id and a campaign_id to relate them both.
How can I relate the 2 together? Here's the code that I have which does not work:
class Account
  include DataMapper::Resource
  property :id, Serial
  property :mc_username, String, :required => true
  property :mc_user_id, String, :required => true
  property :mc_api_key, String, :required => true
  property :created_at, DateTime
  property :updated_at, DateTime
  has n, :users
  has n, :campaigns
end

class User
  include DataMapper::Resource
  property :id, Serial
  property :name, String, :required => true
  property :email, String, :required => true
  property :is_organizer, Integer
  property :created_at, DateTime
  property :updated_at, DateTime
  belongs_to :account, :key => true
  has n, :comments
end

class Campaign
  include DataMapper::Resource
  belongs_to :mailchimpaccount, :key => true
  has n, :comments
  property :id, Serial
  property :cid, String
  property :name, String
  property :current_revision, Integer
  property :share_url, Text, :required => true
  property :password, String
  property :created_at, DateTime
  property :updated_at, DateTime
end

class Comment
  include DataMapper::Resource
  belongs_to :campaign, :key => true
  belongs_to :user, :key => true
  property :id, Serial
  property :at_revision, Integer
  property :content, Text
  property :created_at, DateTime
end

With this code, I can't save a comment since I can't figure out how to associate it to a campaign and a user at the same time. I can't really get my head around wether I should even try to relate them at all using DataMapper.
I would love to know if this code is correct, how I can go about creating a comment that is related to both. If not, what structure and associations would be optimal for this scenario?
Thanks so much for the help!

A: What you're doing seems reasonable, I think you just need to get rid of the :key => true options since you don't really want those associations to be part of the comment's primary key.

A: You should probably start by looking at these datamapper docs on properties.
Alex is right, what you have there is a composite primary key. This would be ok if you only wanted each user to have one comment per campaign, but this is probably not the case but you do want to make sure that the comment is associated to a user and a campaign so use required => true, like so:
class Comment
   include DataMapper::Resource
   property :id, Serial
   belongs_to :campaign, :required => true
   belongs_to :user, :required => true
   property :at_revision, Integer
   property :content, Text
   property :created_at, DateTime
end

Also your key in the campaign model may be problematic:
class Campaign
   include DataMapper::Resource
   belongs_to :mailchimpaccount, :key => true
   #......

You probably just want to make that required too.

A: So it seems that my thinking was correct. I can relate a comment to both a user and a campaign in this way:
# Get a user and a campaign first that we can relate to the comment
user = User.get(user_id)
campaign = Campaign.get(campaign_id)
comment = Comment.new
comment.content = "The comment's content"
user.comments << comment # This relates the comment to a specific user
campaign.comments << comment # This now relates the comment to a specific campaign
comment.save # Save the comment

Dangermouse's suggestion to replace the :key => true option with :required => true also helped clean up the schema. Thanks!


text:
Q: Valgrind error - can not open cache simulation output file I try to profile my program with Valgrind:
valgrind --tool=callgrind --callgrind-out-file=/home/user/callgrind.%p --instr-atstart=no ./src/Leonardo --https leosd:11443

After I reach my file where in my target-profile function I have:
CALLGRIND_START_INSTRUMENTATION;

/* a lot of code to profile */

CALLGRIND_STOP_INSTRUMENTATION;
CALLGRIND_DUMP_STATS;

The program crashes and the output in the console is:

==3117== Error: can not open cache simulation output file `/home/user/callgrind.3117.1014'

P.S. If I run the valgrind from QtCreator with profiling from application start it runs perfectly but I dont need this.
Any idea how to fix this? Google does not help, unfortunately.

A: I had de same problem and I solved going to project and in the run section remove tick from "run in terminal"

A: Try first more basic things i.e.

*

*do not give the option --callgrind-out-file

*do not give the option --instr-at-start=no

*do not insert CALLGRIND_START/STOP_INSTRUMENTATION

So, in other words, just do:
    valgrind --tool=callgrind your_program your_program_args
Then when the simple basic usage works, try adding one thing at a time.
Typically, the 'can not open cache simulation' is because the directory
does not exist or is not writable or a similar problem.
If the basic usage does not work, file a bug on Valgrind bugzilla, giving
the relevant information (platform/version/...)


text:
Q: MySQL: Error Code: 1054. Unknown column 'status' in 'field list' I have a table ItemType in my database which has the following structure:

When I try to add a new item to it, it gives an error of Error Code: 1054. Unknown column 'status' in 'field list'
The query I used is:
INSERT INTO itemtype(itemType, bookType, suggestedPrice, status, cashreceipt_cashdisbursment)
    VALUES ('Death Certificate', 1, 2500.00, 1, 1);

Clearly there is a status column in my table, so why is MySQL complaining about it being missing?

A: @Donovan Keating You miss details, in the request try this :
INSERT INTO itemtype(itemType, bookType, suggestedPrice, status, details, cashreceipt_cashdisbursment) VALUES ('Death Certificate', 1, 2500.00, 1, 'NULL', 1);

A: The problem here is that after status the next column is details that has a TEXT datatype:
so, before cashreceipt_cashdisbursment you should add either NULL or a text value:
INSERT INTO itemtype(itemType, bookType, suggestedPrice, `status`, details, cashreceipt_cashdisbursment) VALUES ('Death Certificate', 1, 2500.00, 1, NULL, 1);

Also, please note that status is a MySQL keyword, so you should wrap its name in backticks.

A: I have noticed that you have one of the column names and the table are same. itemType is your table name and the same name is repeated for a column name right after the table name in the insert query. Maybe this could help at a time when other solutions herein did not work. Besides the table name is not case sensitive here which could be a problem.

A: I had the same error. Just turn off and turn on your database and server.


text:
Q: Develop a pedometer as a web app? I wanted to ask if it is possible to develop a pedometer in a web app. I want to get the data from the phone (on iPhone the app is called Health). I don't want to do it over Google Maps with gps because of the battery life and the roaming. I didn't find any clues to this question.
Thank you and best regards


text:
Q: WordPress: TypeError: Cannot read property 'type' of undefined I try to solve this problem, at Object.user_setting (jscript.js?ver=3.2.0:1894)
here his error message:
jscript.js?ver=3.2.0:1894 Uncaught TypeError: Cannot read property 'type' of undefined
    at Object.user_setting (jscript.js?ver=3.2.0:1894)
    at admin.php?page=user-settings:1078
user_setting @ jscript.js?ver=3.2.0:1894
(anonymous) @ admin.php?page=user-settings:1078

and the code is:
        for(var i in _keys) {

            if(_keys[i] == 'layout' || _keys[i] == 'map_layout'  || _keys[i] == 'infobox_layout' || _keys[i] == 'color_scheme' || _keys[i] == 'color_scheme_1' || _keys[i] == 'color_scheme_2' || _keys[i] == 'font_color_scheme') {

                var $elem = $form.find('#asl-'+_keys[i]+'-'+_configs[_keys[i]]);
                $elem[0].checked = true;
                continue;
            }

            var $elem = $form.find('#asl-'+_keys[i]);

            if($elem[0].type == 'checkbox')
                $elem[0].checked = (_configs[_keys[i]] == '0')?false:true;
            else
                $elem.val(_configs[_keys[i]]);
        }


text:
Q: How to echo environment variable in Makefile? Goal is to print value of environment variable GOPATH
Below command in bash:
echo "$GOPATH"

gives output:
OPATH

GitHub runner runs this makefile target:
test:
    bash --version
    go env GOPATH
    export GOPATH=$(go env GOPATH)
    echo "$GOPATH"
    go test -v -race -tags=unit -cover ./...

Below is the bash version used and pipeline output in GitHub runner(version: '2.286.1')
$ bash --version
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ go env GOPATH
/home/vsts-agent/go
$ export GOPATH=
$ echo "OPATH"
OPATH
$ go test -v -race -tags=unit -cover ./...
go: downloading ...

Why $G is considered special token?
Edit:
Below changes:
test: env
    go env GOPATH
    export GOPATH=$$(go env GOPATH)
    echo "$$GOPATH"
    go test -v -race -tags=unit -cover ./...

give output:
$ go env GOPATH
/home/vsts-agent/go
$ export GOPATH=$(go env GOPATH)
$ echo "$GOPATH"

$ go test -v -race -tags=unit -cover ./...
go: downloading ...

A: I understand now.
You are NOT in a bash shell here (as your question originally stated).
You are actually executing commands in a Makefile.  Make isn't running a shell and its handling of variables is different to a shell.
If you want to do a simple expansion of the variable GOPATH in a Makefile you write $(GOPATH).  Your $GOPATH attempts to expand the (non-existent) variable G, not because G is special, but because that is how the Makefile syntax works.
Also, export means something different.  It is actually defining variables to be passed to a sub-make.  And you aren't using a sub-make here, as far as I can tell.
Makefiles are not shell scripts.  It looks like you have a lot of reading to do.
Reference:

*

*GNU Make manual - 6 How to use Variables


text:
Q: AE Script to change font style Could someone help me by advising why the last line in below code is not working? The objective is to set the font style to bold of a text layer.
var myComp = app.project.activeItem;
var myTextLayer = myComp.layer(1);
var mySourceText = myTextLayer.property("ADBE Text Properties").property("ADBE Text Document");
var myTextDoc = mySourceText.value;
myTextDoc.ScriptUIFont.style.setValue(["Bold"]);

A: I'm not aware of any way to change the style directly without changing the font.
You need to change the font attribute in myTextDoc to the desire font.
myTextDoc.font = 'Arial-BoldMT';
mySourceText.setValue(myTextDoc);

If the only change you want is to make it bold, you can use fauxBold attribute (It's a bit different, but maybe it'll make you satisfy).
myTextDoc.fauxBold = true;
mySourceText.setValue(myTextDoc);

A: You need to set the textDocument.font property to the style name (without spaces), put a dash and write a font style with a captial letter. For example "NunitoSans-Bold" or "Montserrat-SemiBold"


text:
Q: Azure durable functions - send reminder I want to wait for an external event and send a reminder if the event hasn't occurred in 5 days. I am new to how tasks work. Will the following orchestrator function run as expected? I didn't use Task.WhenAll as I though this way was simpler:
[FunctionName("Function1")]
public static async Task RunOrchestrator(
    [OrchestrationTrigger] IDurableOrchestrationContext context)
{
    using (var cts = new CancellationTokenSource())
    {
        SendReminder(context, cts.Token); // dont await so this happens in the background
        await context.WaitForExternalEvent("MyEvent");
        cts.Cancel(); // cancel the reminder as the event has now happened

        // react to MyEvent ...

    }
}

public static async Task SendReminder(IDurableOrchestrationContext context, CancellationToken cancellationToken)
{
    await context.CreateTimer(context.CurrentUtcDateTime.AddDays(5), cancellationToken);
    await context.CallHttpAsync(...) // http call to ms graph to send a reminder email
}

Do I need to use Task.Run instead of just directly calling SendReminder?


text:
Q: Get base64 string from a big StorageFile and store it in another StorageFile i have a >4 GB StorageFile and i want to convert it to a base64 string and store the string in another StorageFile.
I have IBuffer to read the file:
Dim tempFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim ftemp As StorageFile = Await tempFolder.TryGetItemAsync(filename)
Dim ibuf As IBuffer = Await FileIO.ReadBufferAsync(ftemp)
Dim b64list As New List(Of String)
Dim b64string As String = String.Empty
Dim countins As Long = 0
Dim byt As Byte() = {}

If ibuf.Length > 500000000 Then

While ibuf.Length - countins > 500000000
byt = ibuf.ToArray(countins, 500000000) 'when countins exceeds 2 Gb, i get overflowexception: Arithmetic operation resulted in an overflow
Dim b1 As String = Convert.ToBase64String(byt, 0, 500000000)
b64list.Add(b1)
countins = countins + 500000000
End While

byt = ibuf.ToArray(countins, ibuf.Length - countins)
Dim b2 As String = Convert.ToBase64String(byt, countins, ibuf.Length - countins)
b64list.Add(b2)

else

b64string = Convert.ToBase64String(ibuf.ToArray())

End If

Because the limits of the size of the Byte() object is about 2Gb, i tried to split the bytes stored in the buffer array in other smaller bytes and convert it in a base64 string, then add the string in a list of string and write the base64 string in the file by the list of string. The problem is when the offset of bytes to read and convert exceeds 2Gb of size (please, see the comments in the code!).
is there a way to read the bytes from 2 gb to up contained in the ibuffer?
Thank you very much!
Edit:
The solution of Nico Zhu is perfect! Thank you very much.
That's just what i was looking for.
I tried with files of about 6 GB and it seems to work perfectly, occupying an average of 7 GB of ram to finish the operation. For the x86 version i set a limit of 2 Gb for the files to open, it is not a problem.
I paste my vb.net code version for the vb.net community (tested up to 6Gb):
Dim BufferList As List(Of IBuffer) = New List(Of IBuffer)()
Dim lclFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim ftemp As StorageFile = Await lclFolder.TryGetItemAsync(filename)

Dim stredam = Await ftemp.OpenAsync(FileAccessMode.Read)
Dim size As ULong = stredam.Size
Dim splLength As UInteger = 1024 * 1024 * 128
Dim splCount = size / splLength
Dim res As IBuffer = Nothing

If size < splLength Then
res = Await FileIO.ReadBufferAsync(ftemp.generalfileselectedsmp)

Else

Dim splitCount = size / splLength

For i As Integer = 0 To CInt(splitCount) - 1
Dim postition = i * splLength

Using inputStream = stredam.GetInputStreamAt(CULng(postition))

Using dataReader = New Windows.Storage.Streams.DataReader(inputStream)
Dim numBytesLoaded As UInteger = Await dataReader.LoadAsync(splLength)
Dim buffder = dataReader.ReadBuffer(numBytesLoaded)
BufferList.Add(buffder)
End Using

End Using
Next

Dim leftLength = size Mod splLength

Using inputstream As IInputStream = stredam.GetInputStreamAt(splitCount * splLength)

Using dataReader As New DataReader(inputstream)
Dim numBytesLoaded As UInteger = Await dataReader.LoadAsync(CUInt(leftLength))
Dim leftBuffer = dataReader.ReadBuffer(numBytesLoaded)
BufferList.Add(leftBuffer)
End Using

End Using

Dim nnb As Long = 0

Dim tempFolder As StorageFolder = ApplicationData.Current.TemporaryFolder
Dim ftempdest As StorageFile = Await tempFolder.CreateFileAsync("tmpxencrxx0212", CreationCollisionOption.ReplaceExisting)

For Each ibb As IBuffer In BufferList
If ibb.Length > 0 Then

Await FileIO.AppendTextAsync(ftempdest, Convert.ToBase64String(ibb.ToArray()))

nnb = nnb + 1
End If
Next

A:
is there a way to read the bytes from 2 gb to up contained in the ibuffer?

For your requirement, we suggest you cut the big file into slices and use IBuffer list to store each slip. Please note you need set the app target platform to x64 that has enough memory to store such buffers.
private List<IBuffer> BufferList = new List<IBuffer>();

var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".zip");

Windows.Storage.StorageFile sampleFile = await picker.PickSingleFileAsync();
var stredam = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
ulong size = stredam.Size;
uint splLength = 1024 * 1024 * 128;
var splCount = size / splLength;

if (size < splLength)
{
  var res = FileIO.ReadBufferAsync(sampleFile);
}
else
{
    var splitCount = size / splLength;
    for (int i = 0; i < (int)splitCount; i++)
    {
        var postition = i * splLength;
        using (var inputStream = stredam.GetInputStreamAt((ulong)postition))
        {
            using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
            {
                uint numBytesLoaded = await dataReader.LoadAsync(splLength);
                var buffder = dataReader.ReadBuffer(numBytesLoaded);
                BufferList.Add(buffder);
            }
        }

    }
    var leftLength = size % splLength;
    using (var inputStream = stredam.GetInputStreamAt(splitCount * splLength))
    {
        using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
        {
            uint numBytesLoaded = await dataReader.LoadAsync((uint)leftLength);
            var leftBuffer = dataReader.ReadBuffer(numBytesLoaded);
            BufferList.Add(leftBuffer);
        }
    }

}


text:
Q: call multiple times client side callback function in asp .net in devexpress How do I call multiple times client side callback function in asp .net in devexpress.
Here is the pageload event:
protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsCallback)
        return;
    //Creating a reference of Client side Method, that is called after callback on server
    String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg","ReceiveServerData", "");

    //Putting the reference in the method that will initiate Callback
    String callbackScript = "function CallServer(arg, context) {" +cbReference + "; }";

    //Registering the method
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"CallServer", callbackScript, true);
}

public void RaiseCallbackEvent(String eventArgument)
{
    DateTime dob = Convert.ToDateTime(eventArgument);
    DateTime Today = DateTime.Now;
    TimeSpan ts = Today - dob;
    DateTime Age = DateTime.MinValue + ts;

    int Years = Age.Year - 1;
    int Months = Age.Month - 1;
    int Days = Age.Day - 1;
    result = Years.ToString();
}

public string GetCallbackResult()
{
    return result;
}

Here is the javascript function:
<script language="javascript" type="text/javascript">
    function InitiateCallBack(value) {
        CallServer(value, '');
    }

    // Called after the server side processing is done
    function ReceiveServerData(arg, context) {
        $("#MainContent_ASPxtxtAge_I").val(arg);
    }
</script>

Here only the single time call back occurs, but how can I call multiple times from multiple buttons?
I am using devexpress along with asp .net c#.
Any suggestions regarding this problem?

A: That looks like a simple function, not a callback itself, you can call that function from any Button this way
<dx:ASPxButton ID="btnOther" runat="server" Text="Function" AutoPostBack="false"
                                      ClientSideEvents-Click="function(s, e) { InitiateCallBack(value); }">
                                  </dx:ASPxButton>


text:
Q: Refreshing list view with affecting the view of the current position In my app ,
i am downloading image one by one , for each image is downloaded and i will update item in the list view. Currently when i downloading some images, each image is downloaded and each will update or refresh the list view. For each refreshing, the visible portion of an item in the list view is automatically moving to first item. What i needed, suppose i watching the image 3 and image4 is downloaded and refreshing the list view now it will moved to first position but i need visible portion remains same what i seen before refreshing the listview (i.e., image 3should be in display portion).  I am refreshing the list view like
 CustomAdapterClass adapter = new CustomAdapterClass(context,lstOfDishes);
 lv.setAdapter(adapter);

can anyone suggest some ideas to clear my problems.
Thanks in Advance.

A: use adapter.notifyDataSetChange(); method to update the list adapter. do not create the adapter again and set it to list.

A: first tiem u create adapter like this
CustomAdapterClass adapter = new CustomAdapterClass(context,lstOfDishes);
lv.setAdapter(adapter);

if u added any value in your array Like (lstOfDishes) than u call This
adapter.notifyDataSetChange();


text:
Q: Removing elements in an array using Lodash I have this array:
var fruits = ['Apple', 'Banana', 'Orange', 'Celery'];

And I use Lodash's remove like so:
_.remove(fruits, function (fruit) {
  return fruit === 'Apple' || 'Banana' || 'Orange';
})

The result is ['Apple', 'Banana', 'Orange', 'Celery'], while I expected it to be ['Apple', 'Banana', 'Orange']. Why is this so?

A: Because when fruit is "Celery", you are testing:
"Celery" === 'Apple' || 'Banana' || 'Orange'

which evaluates to
false || true || true

which is true.
You can't use that syntax. Either do it the long way around:
_.remove(fruits, function (fruit) {
  return fruit === 'Apple' || fruit === 'Banana' || fruit === 'Orange'
});

or test for array membership:
_.remove(fruits, function (fruit) {
  return _.indexOf(['Apple', 'Banana', 'Orange'], fruit) !== -1
});

This is not limited to JavaScript, and is in fact a common mistake (e.g. this question)

A: You can use the method _.pull from lodash 2.0 and up

var fruits = ['Apple', 'Banana', 'Orange', 'Celery'];

_.pull(fruits, 'Apple', 'Banana', 'Orange'); // ['Celery']

document.write(fruits);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>

A: Use an array of values that you'd like to compare against, and check for a returned index greater than -1. This indicates the value evaluated was found in the collection.
_.remove( fruits, function ( fruit ) {
  return _.indexOf( [ "Apple", "Banana", "Orange" ], fruit ) >= 0;
});

Alternatively you could use lo-dash's _.contains method to get a boolean response.
The problem with the approach you took was that you weren't comparing fruit against each one of those strings; instead, the only comparison taking place was fruit against "Apple", after that you were coercing strings all on their own.
Non-empty strings coerce to true (!!"Banana"), and as such are truthy. Therefore, the following condition will always short-circuit at "Banana" (unless fruit strictly equals "Apple"), returning true:
return fruit === "Apple" || 'Banana' || "Orange";

A: If you want to remove a set of items from another set, there are set operations intended specifically for that.  Lodash has https://lodash.com/docs/4.17.2#difference which takes two array parameters A and B and will return another array which contains all of the elements of A which are not in B.
In your case, you could write
const fruits = ['Apple', 'Banana', 'Orange', 'Celery'];
const filteredFruits = _.difference(fruits, ['Apple', 'Banana', 'Orange']);

which will result in ['Celery'].

A: The problem isn't with Lo-Dash; your problem is with your conditional within your callback function. This:
return fruit === 'Apple' || 'Banana' || 'Orange';

Is not correct. You need to actually compare fruit with each string:
return fruit === 'Apple' || fruit === 'Banana' || fruit === 'Orange';

Or, you can use another Lo-Dash function to make it a little more compact:
_.remove(fruits, function (fruit) {
  return _.contains(['Apple', 'Banana', 'Orange'], fruit);
})

Note: In the latest versions of Lo-Dash the _.contains function is deprecated. Please use _.includes


text:
Q: Stored procedure works in Crystal Reports but does not work in SQL Developer I have a report that works fine with this stored procedure in Crystal Reports:
BEGIN "CMS"."CMS_RP_MERCHANDISE"."SP_M4_OH_ITEMS"(:MCUR, 1, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', NULL); END ;

When I try to use the same stored procedure in Oracle SQL Developer, I get this message:

Error starting at line : 2 in command -
  Error report -
  ORA-06550: row 1 ، col 2543 :
  PLS-00306: wrong number or types of arguments in call to 'SP_M4_OH_ITEMS'
  ORA-06550: row 1 ، col 2543 :
  PL/SQL: Statement ignored
  06550. 00000 -  "line %s, column %s:\n%s"
  *Cause:    Usually a PL/SQL compilation error.
  *Action:

This is stored procedure Declaration
Image from sql dev

A:
wrong number or types of arguments in call to 'SP_M4_OH_ITEMS'

I presume you did something wrong. That procedure has zillion of parameters, and it seems that you either missed some (i.e. you have too few or too many of them), or you missed their datatype (e.g. should be NUMBER but you provided a string).
Such a procedure is difficult to debug; error is in line 1, column 2543 (two thousand five hundred forty three?!); can't you format it somehow and make it easier to read and maintain? Who is going to scroll that far right?
Besides, you didn't post CREATE PROCEDURE code; we saw you declared many variables, passed them to the procedure, but - without seeing it, it is difficult to say much more. I hope you'll manage to fix it after reading what I wrote. Good luck!


text:
Q: Whats the best practice to validate plugin with jquery I need write a jQuery plugin to validate forms, I was thinking on something like this to start:
Just a EXAMPLE:
$('form').submit(function() {
    var isValid = true;
    var required = $('.required').val();

    if(required== ''){
        isValid = false;
    }

    return isValid;
});

I'ts a good practice? exist some pattern to validate forms?, What is the best option?
Note: I wont use a plugin.

A: try:
$('form').submit(function() {
    var isValid = true;
    $('.required').each(function(){
         if($(this).val() == ''){
            isValid = false;
         }
    })
    return isValid;
});

A: Here's a start:
$('form').submit(function()
{
    var isValid = true;

    $('.required', this).each(function()
    {
        if (this.value == '')
        {
            isValid = false;

            $(this).addClass('error').focus();

            return false;
        }
    });

    return isValid;
});

Here's the fiddle: http://jsfiddle.net/DUNc2/

A: I know you don't want to use a plugin but it's a great way to learn, you can download the most popular jquery validation plugin here:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Take some lessons from how that plugin is made to create your own.


text:
Q: Twilio Authy 2FA for OneCode C# Implementation I am developing a web application using C# that uses 2 factor authentication during Sign Up. I have already tried 2FA using Nexmo's API. It worked fine. All I had to do was call their API and speciy the 'to' number. Here is the code:
public ActionResult Start(string to)
{
    var start = NumberVerify.Verify(new NumberVerify.VerifyRequest
    {
        number = to,
        brand = "NexmoQS"
    });
    Session["requestID"] = start.request_id;

    return View();
}

Now, I decided to give Twilio a try. I came across Authy and it's process. I found their 2FA API here. But I don't understand where should I enter the 'to' number as specified in Nexmo. I am a beginner and using .NET(C#) code snippet. Here is the code snippet. Please help me configure this code as I am able to do in Nexmo.
public static async Task VerifyPhoneAsync()
  {
    // Create client
    var client = new HttpClient();

    // Add authentication header
    client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);

    // https://api.authy.com/protected/$AUTHY_API_FORMAT/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE
    HttpResponseMessage response = await client.GetAsync("https://api.authy.com/protected/json/phones/verification/check?phone_number=5558675309&country_code=1&verification_code=3043");

    // Get the response content.
    HttpContent responseContent = response.Content;

    // Get the stream of the content.
      using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
      {
        // Write the output.
        Console.WriteLine(await reader.ReadToEndAsync());
      }
    }

They have given a cURL implementation of their api here, please help me configure it in C#.
curl "http://api.authy.com/protected/json/users/new?api_key=d57d919d11e6b221c9bf6f7c882028f9" \
-d user[email]="user@domain.com" \
-d user[cellphone]="317-338-9302" \
-d user[country_code]="54"

A: Twilio developer evangelist here.
When making a call to the API, you do need to add the X-Authy-API-Key header as well as a URL parameter api_key. Also, to start the process of verifying a number you should be making a POST request with the data you need to send to the API.
The two bits of data that you need are the phone number and the country code for that phone number. Though you can set some other values, like the way you want to send the verification code (via sms or call).
I would update your code to look like this:
public static async Task StartVerifyPhoneAsync()
  {
    // Create client
    var client = new HttpClient();

    var AuthyAPIKey = 'YOUR AUTHY API KEY';

    // Add authentication header
    client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);

    var values = new Dictionary<string, string>
    {
      { "phone_number", "PHONE NUMBER TO VERIFY" },
      { "country_code", "COUNTRY CODE FOR PHONE NUMBER" }
    };

    var content = new FormUrlEncodedContent(values);

    var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}";

    HttpResponseMessage response = await client.PostAsync(url, content);

    // do something with the response
  }

Then when the user enters the code, you need to check it. Again you should add the API key as a header and send as a URL parameter too, along with the phone number, country code and the verification code the user entered, this time as a GET request.
public static async Task CheckVerifyPhoneAsync()
  {
    // Create client
    var client = new HttpClient();

    var AuthyAPIKey = 'YOUR AUTHY API KEY';

    // Add authentication header
    client.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey);

    var phone_number = "PHONE NUMBER TO VERIFY";
    var country_code = "COUNTRY CODE FOR PHONE NUMBER";
    var verification_code = "THE CODE ENTERED BY THE USER";
    var url = $"https://api.authy.com/protected/json/phones/verification/start?api_key={AuthyAPIKey}&phone_number={phone_number}&country_code={country_code}&verification_code={verification_code}";

    HttpResponseMessage response = await client.GetAsync(url);

    // do something with the response
  }

Let me know if that helps at all.


text: Q: Integrate Dialogflow with Custom application like Google Assistant I want to create a App like Google Assistant to integrate with Dialogflow. Is there any way to do so? How can we create an app to send rich response to dialogflow?


text:
Q: Why is BERT Storing cache even after Caching is disabled? I am trying to extract hidden state features from a fine-tuned BERT model, but each text entry consumes memory and does not free it up after the next call. I can only run 20-30 sentences with 24 GB of ram memory.
from transformers import BertTokenizer, BertModel
import numpy as np

data = pd.read_csv('https://docs.google.com/spreadsheets/d/' +
                   '1cFyUJdpFC3gpQsqjNc4D8ZCxBAMd_Pcpu8SlrsjAv-Q' +
                   '/export?gid=0&format=csv',
                  )
data = data.MESSAGES

# I will be using my own fine-tuned model, but with
# bert-base-uncased, I get the same problem
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained(
    "bert-base-cased",
    from_tf=True,
    output_hidden_states=True,
    use_cache=False)

sentences = data[0:].tolist()
inputs = tokenizer(sentences, return_tensors='pt', padding=True,truncation=True)
featuresINeed = model(inputs['input_ids'])['pooler_output']

In the case above, I run out of memory. I tried breaking it into chunks and using torch.cuda.empty_cache(), but it doesn't seem to clear all the memory. I tried both with and without GPU. In my case, I am using a dataset of size 60,000 (possibly larger in the future) and using a fine-tuned model of BERT large. I will have a 24GB GPU available for me.
Any suggestions?
To keep in mind, my main goal is to have 1 Language Model predict the next token and extract features of the current sentence.

A: The code snippet has several issues.

*

*It does not use GPU at all. You need to send both model and the data to a GPU explicitly, e.g., by doing the following:

device = torch.device("cuda" if torch.cuda.is_available() else "CPU")
model.to(device)
inputs.to(device)

*PyTorch automatically prepares for computing the gradients, which requires storing intermediate results. You can wrap the call in with torch.no_grad() to ensure no gradients are collected.

*60k sentences is too much, regardless of your GPU memory. In any case, you need to split it into more batches. You can use the Dataset interface from Transformers for that.


text:
Q: How can I get Libre Office to not list fonts I have uninstalled.? How can I get Libre Office to not list fonts I have uninstalled?  The drop down menu lists all the fonts that were part of the original installation. I want to purge the list of uninstalled fonts.

A: Try to update font cache, LO might see old information from not up-to-date cache.
sudo fc-cache -f -v

Also, are you sure you did uninstall all copies of fonts?
sudo updatedb
locate <fontname>


text:
Q: ExtJs 4, is there a way to find control? (not by "id") I have button with id = 'someid', i can find it by Ext.getCmp('someid')...
Is there a way to set some kind of "extraId" to that button, and find that button by "extraId'?

A: You can search for it by doing an Ext.ComponentQuery.
Example that will work in the console on the linked page:
Ext.ComponentQuery.query('button[text=OK]')

You can replace text=OK with the attribute you are searching for.

A: I don't have access to the ExtJS 4 API docs, but I know that in 3.X and previous verions have some other ways of getting references to your compoents without the use of the DOM ID.
If your components are part of a form or form panel, you should have access to a method called findField(). It is inherited from Basic Form.  This method can take an id, dataIndex, name, or hiddenName to get a reference to your component.
There is also a helper method called findByType(xtype) that you can use to try and find your buttons.  Another option would be to extend the button you use to place a unique property that you can use as a reference.

A: The question is where you want to search to get your item.
Another way could be the itemId.

An itemId can be used as an alternative way to get a reference to a component when no object reference is available.  Instead of using an id with Ext.getCmp, use itemId with Ext.container.Container.getComponent which will retrieve itemId's or id's. Since itemId's are an index to the container's internal MixedCollection, the itemId is scoped locally to the container -- avoiding potential conflicts with Ext.ComponentManager which requires a unique id.

Source and further documentation: http://docs.sencha.com/ext-js/4-0/#/api/Ext.AbstractComponent-cfg-itemId
The ComponentQuery (mentioned by wombleton) is also a good way but maybe not as performant as the itemId.

A: An alternative to id is itemId and it is limited to the scope of the container in which it is defined. So, in this case, there is not need to define globally unique itemId as done in case of id. We can use component query to get the component object having the itemId. Please follow  this link where i have posted about how to use itemId and what is its benefit.
 http://jksnu.blogspot.in/2012/11/use-itemid-instead-of-id.html


text:
Q: How do I disable the mousewheel zoom in Here Maps JavaScript API v3? The code to disable mousewheel zoom on Here Maps JS API v2 was this:
map.removeComponent(map.getComponentById("zoom.MouseWheel"));

But that is an undefined function in v3 of the API. What is the best way to disable mousewheel zoom in the latest API?
Thank you for the help.

A: behavior.disable(H.mapevents.Behavior.WHEELZOOM);


text:
Q: how to setPadding and background in runtime with performance? I want to have a speed performance
mainLayout.setBackground(getResources().getDrawable(R.drawable.background));

curlContainerLayout.setPadding(5, 35, 5, 25);

my problem is slow changing in this code
could any one know a trick to make it fast ?
thanks in advance
Edit :
i use the above code in textview on afterTextChanged listener
  new Thread(new Runnable() {
                        public void run() {
                            Looper.prepare();
                            myCurlActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    CurlActivity.tvCurrentPageNumber.setText(String.valueOf(mCurrentIndex + 1));
                                }
                            });
                        }
                    }).start();


text:
Q: MySQL user loses privileges I have really weird problem that I can't wrap my mind around. I'm using Debian Jessie for our servers. I've added testing repos and upgraded mysql version from 5.5 to 5.7.2 then setup private network between 2 servers:
Server A - 192.168.0.1 as database server
Server B - 192.168.0.2 as application server
I've created user and gave him all required privileges (i've tested multiple hosts and multiple variations of global and database privileges). Everything is working fine but randomly after couple days the user starts getting "Access denied" and can not log in to the database. Communication between servers works just fine, servers can ping each other and connection to mysql is not blocked as its sending Access Denied as response. I've flushed privileges many times and the user has no limits by default.
I've turned off firewall and checked system logs and I don't see anything even remotely related to my problem. I've tried all steps suggested by mysql docs where they suggest possible solutions to "Access Denied". I've tried with different app/database. I've tried many different users with both wildcard and classic hosts definitions, with different permissions and after couple days my application server is still getting "Access denied". If I log in locally on the database server and perform "Show grants" and "Show databases" everything seems fine - user has correct host and privileges yet can not log in remotely.
Application stack used for our apps is PHP with Symfony2/3. Is there anything I can do about it? Is there any software that could help me debug?


text:
Q: Excel Power Query. Different Formulas for Each Row of Values from Other Rows I have a table 1 of 500+ rows that are updated multiple times during a month by a request.
And there is a updated table of different formulas (200+) that should be calculated using values from table 1.
Table 1

year
product
value

1993
Apple
98.45

1994
Mushrooms
67.54

1992
Apple
95.45

2021
Melon
112.0

Table 2

id
formula

1
1994/1993*100-100

2
1994-1993

3
2021/1992*100-100

etc...
My way:

*

*in table_1 I have created a key column - year.

*I have modified the formula (below - a pic):

Code for table_2:
   let
        src = Excel.CurrentWorkbook(){[Name="table_2"]}[Content],
        pq_auto1 = Table.PromoteHeaders(src, [PromoteAllScalars=true]),
        pq_auto2 = Table.TransformColumnTypes(pq_auto1,{{"Id", Int64.Type}, {"formula", type text}}),
        result = Table.AddColumn(pq_auto2,"value",each Expression.Evaluate([modified_formula],#shared))
   in
        result

Can you suggest me to find a better way to do this calculations by each row?

A: It is not possible to do that just like with Excel formula however BI Accountant showed elegant solution by shifting column by one row:

let
     Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content]
    ,ShiftedList = {null} & List.RemoveLastN(Table.Column(Source, "ColumnToBeShifted"), 1)
    ,NewShiftedColumn = Table.FromColumns(Table.ToColumns(Source) & {ShiftedList}, Table.ColumnNames(Source) & {"NewColumnName"})
in
    NewShiftedColumn

With this your calculation should be very easy.


text:
Q: Update DataTable on Tap event in Bokeh I am trying to calculate euclidean distance of two points. Initial distance is calculated in the data.
Then, when the user is moving the line, I'd like the distance column to update based on the new coordinates. I can see that x and y columns are updating, but not the distance column. Below is my attempt:
output_file("tools_point_draw.html")

_tools_to_show = 'box_zoom,pan,save,hover,reset,tap'

p = figure(x_range=(0, 10), y_range=(0, 10), tools=_tools_to_show,
           plot_width=862, plot_height=604,
           title='Plot name')

p.background_fill_color = 'white'

d_true = {'x': [2, 3], 'y': [4, 1],
          'color': ['red', 'red'],
          'desc': ['true','true']}

df_true = pd.DataFrame(d_true)
df_true['distance'] = np.sqrt(np.sum((df_true['x'] - df_true['y'])**2))
source = ColumnDataSource(df_true)

renderer2 = p.scatter(x='x', y='y', source=source, color='color', size=15,
                      line_color='red', line_width=5)
renderer = p.line(x='x', y='y', source=source, color='red',
                  line_dash='dashed', line_width=10)

columns = [TableColumn(field="x", title="I am X"),
           TableColumn(field="y", title="I am Y"),
           TableColumn(field='color', title='color'),
           TableColumn(field='desc', title='desc'),
           TableColumn(field='distance', title='distance')]

update = CustomJS(args=dict(source_data=source), code="""
    var data = source_data.data;
    var f = cb_obj.value; //is this necessary?

    //Sum of squares for euclidean
    for(var i = 0, i < data['x'].length; i < size ; i++) {
        var res += Math.pow(data['x'][i] - data['y'][i], 2)
    }

    //Take square root
    var res2 = Math.sqrt(res)

    //Update table
    data['distance'] = res2

    source_data.change.emit();

    """)

update.js_on_change('tap', update)

table = DataTable(source=source, columns=columns, editable=True, height=200, width=862)

draw_tool = PointDrawTool(renderers=[renderer, renderer2], empty_value='black')
p.add_tools(draw_tool)
p.toolbar.active_tap = draw_tool

show(Column(p, table))

A: Your callback actually never triggers here. It's just the pointdraw event doing its thing.
You should have your callback trigger when source.data is changed.
source.js_on_change('data', update)

I did it for distance from the first point but you could do from origin too.
If it's from the first point you need to update all the distances each time (since the draw tool lets you drag existing points)
from bokeh.plotting import figure
from bokeh.io import output_file, show
from bokeh.models import DataTable, TableColumn, Column, PointDrawTool, ColumnDataSource, CustomJS
import pandas as pd
import numpy as np

output_file("tools_point_draw.html")

_tools_to_show = 'box_zoom,pan,save,hover,reset,tap'

p = figure(x_range=(0, 10), y_range=(0, 10), tools=_tools_to_show,
           plot_width=862, plot_height=604,
           title='Plot name')

p.background_fill_color = 'white'

d_true = {'x': [2, 3], 'y': [4, 1],
          'color': ['red', 'red'],
          'desc': ['true','true']}

df_true = pd.DataFrame(d_true)
df_true['distance'] = [0]+[np.sqrt((df_true['x'][i]-df_true['x'][i-1])**2+(df_true['y'][i]-df_true['y'][i-1])**2) for i in range(1,len(df_true['x']))]
source = ColumnDataSource(df_true)

renderer2 = p.scatter(x='x', y='y', source=source, color='color', size=15,
                      line_color='red', line_width=5)
renderer = p.line(x='x', y='y', source=source, color='red',
                  line_dash='dashed', line_width=10)

columns = [TableColumn(field="x", title="I am X"),
           TableColumn(field="y", title="I am Y"),
           TableColumn(field='color', title='color'),
           TableColumn(field='desc', title='desc'),
           TableColumn(field='distance', title='distance')]

update = CustomJS(args=dict(source_data=source), code="""
    var data = source_data.data;
    var res = 0;

    //Sum of squares for euclidean
    for(var i = 1; i < data['x'].length ; i++) {
        res += Math.sqrt(Math.pow(data['x'][i] - data['x'][i-1], 2)+Math.pow(data['y'][i] - data['y'][i-1], 2));

        //Update table
        data['color'][i] = 'red';
        data['desc'][i] = 'true';
        data['distance'][i] = res;
    }

    source_data.change.emit();
    """)

source.js_on_change('data', update)

table = DataTable(source=source, columns=columns, editable=True, height=200, width=862)

draw_tool = PointDrawTool(renderers=[renderer, renderer2])
p.add_tools(draw_tool)
p.toolbar.active_tap = draw_tool

show(Column(p, table))

A: While I could not find a way how to update the table, I simply added a Div and updated the text inside. Not elegant, but it gets the job done.
div_euclid = Div(text="""
               Diameter of predicted form is: 334.80

               Diameter of true form is: 368.64

               RMSE is: 34.13
               """,
               align='center',
               style={'font-size': '100%'})

p.js_on_event(events.MouseMove,
            CustomJS(args=dict(div=div_euclid,
                              source_data_pred=src_pred,
                              source_data_true=src_true),
     code="""
     var data_p = source_data_pred.data;
     var data_t = source_data_true.data;

     var x_p = data_p['x']
     var y_p = data_p['y']

     var x_t = data_t['x']
     var y_t = data_t['y']

     var diam_p = 0
     var diam_t = 0
     var rmse = 0

     //Diameter of pred form
     diam_p = Math.sqrt(Math.pow((x_p[0]-x_p[1]),2) + Math.pow((y_p[0]-y_p[1]),2))

     //Diameter of true form
     diam_t = Math.sqrt(Math.pow((x_t[0]-x_t[1]),2) + Math.pow((y_t[0]-y_t[1]),2))

     //RMSE
     rmse = Math.sqrt(Math.pow(diam_p - diam_t,2)/1)

     //Result
     div.text = "Diameter of predicted form is: " + diam_p.toFixed(2) + "
 Diameter of true form is: " + diam_t.toFixed(2) + "
 RMSE is: " + rmse.toFixed(2);

     """))


text:
Q: Integration by parts for fractional Ornstein-Uhlenbeck process I have encountered a problem in a paper called Volatility is rough by Jim Gatheral et al.
A stationary fractional Ornstein–Uhlenbeck process ($X_t$) is
defined as the stationary solution of the stochastic differential
equation
$$dX_t = \nu dW^H_t− \alpha (X_t − m)dt$$
where $m ∈ \mathbb{R}$ and $\nu$ and $\alpha$ are positive parameters (see Cheridito et al. 2003). As for usual Ornstein–Uhlenbeck processes,
there is an explicit form for the solution which is given
by
$$X_t = \nu \int^t_{−\infty}e^{−\alpha (t−s)}dW^H_t+ m  \qquad \quad (3.3) $$
Here, the stochastic integral with respect to fBm is simply a
pathwise Riemann–Stieltjes integral, see again Cheridito et al.
(2003).
Proposition 3.1 Let $W_H$ be a fBm and $X^\alpha$ defined by (3.3)
for a given $\alpha > 0$. As \alpha tends to zero,
$$E\left[\sup_{t\in[0,T]}|X^\alpha_t− X^\alpha_0− \nu W^H_t|\right]\to 0$$
Then the proof goes like this:
Starting from equation (3.3) and applying integration by parts, we get
$$X^\alpha_t = \nu W^H_t −\int_t^{−\infty}\nu \alpha e^{−\alpha(t−s)}W^H_s ds + m$$
and some proofs that I know; it is just this part that I don't understand.
So my question is: How do I even perform integration by parts for the fractional Ornstein-Uhlenbeck process in this proof. I don't see anyway how to obtain the answer by integration by parts. I'd appreciate if someone can answer or link me to somewhere that has methods/answers!

A: You can look at the Proposition A.1 in link, they provide a more rigourous proof.
Essentially, we apply the integration by part to $(e^{\alpha t}W_t^H)$
\begin{equation}
d(e^{\alpha t}W_t^H) = \alpha e^{\alpha t}W_t^Hdt +e^{\alpha t}dW_t^H
\end{equation}
Then integrate
\begin{equation}
e^{\alpha t}W_t^H - e^{\alpha b}W_b^H = \int_b^t \alpha e^{\alpha s}W_s^Hds + \int_b^te^{\alpha s}dW_s^H\end{equation}
So we have : $\int_b^te^{\alpha s}dW_s^H = e^{\alpha t}W_t^H - e^{\alpha b}W_b^H - \int_b^t \alpha e^{\alpha s}W_s^Hds$. Replacing the latter in $(3.3)$ by taking $b\to-\infty$, you will find the answer.


text:
Q: MVC 3 & EF 4 Database First, Model not linking to Table Name correctly? Busy learning MVC 3 and EF ...
I have an existing database, I then create my Model aligned to my DB Table (Agency):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace Dataset_Test.Models
{
    public class Agency
    {

        public int AgencyID { get; set; }
        [Required(ErrorMessage="Give me a name.")]
        [StringLength(5)]
        [MinLength(2)]
        public string AgencyName { get; set; }

    }

}

My DAL class:
public class DBContext: DbContext
    {
        public DbSet<Person> Persons { get; set; }
        public DbSet<Agency> Agency { get; set; }
    }

After using the controller generator popup to create the controller and views and then running the code:
private DBContext db = new DBContext();

        //
        // GET: /Agency/

        public ViewResult Index()
        {
            return View(db.Agency.ToList());
        }

I get an error which it simply cant find the Table as EF is automatically looking for the Table (dbo.Agencies) yet I have declared my Model Class as Agency, my question is how and where do you set the Table Name reference that the Model should be linked to, i.e. it should look for dbo.Agency and NOT dbo.Agencies?
Layout:

A: You need to add a
[Table("Agency")]

attribute to your Agency class


text:
Q: Segmentation fault when Initializing QRegularExpression, but only sometimes this is one of my strangest errors.
QRegularExpression regexp("  .*");

This works fine, sometimes. But than it crashes with segmentation faul.
0   _int_malloc /usr/lib64/libc.so.6        0x7ffff59f2196
1   malloc  /usr/lib64/libc.so.6        0x7ffff59f411c
2   operator new(unsigned long) /usr/lib64/libstdc++.so.6       0x7ffff62ac0cd
3   QRegularExpression::QRegularExpression(QString const&, QFlags<QRegularExpression::PatternOption>)   /usr/lib64/libQt5Core.so.5      0x7ffff6b45fdd

The Strange thing ist, if i start the program sometimes its okay! No Error at all.
Sometime its crashes after this loc was excecuted excacly 71 times.
I just dont have any clue -.-
EDIT:
char hname[255] ="";
char hname80[255] ="";
char hcas[255] = "";
int i = number;

NAMEdll(i,hname,hname80,hcas);

shortName=hname;
fullName=hname80;
cas=hcas;

// remove unecessary spaces
QRegularExpression regexp("  .*");
cas.remove(regexp);
shortName.remove(regexp);
fullName.remove(regexp)

like suggested i removed code to find the error.
Its seems to have something to do with NAMEdll ( which is a fortran function). If i take out this command, its all fine. With it i get this:
0   _int_malloc /usr/lib64/libc.so.6        0x7ffff59f2196
1   malloc  /usr/lib64/libc.so.6        0x7ffff59f411c
2   QArrayData::allocate(unsigned long, unsigned long, unsigned long, QFlags<QArrayData::AllocationOption>) /usr/lib64/libQt5Core.so.5      0x7ffff6a7c0f6
3   QRegularExpressionMatchPrivate::QRegularExpressionMatchPrivate(QRegularExpression const&, QString const&, QRegularExpression::MatchType, QFlags<QRegularExpression::MatchOption>, int)  /usr/lib64/libQt5Core.so.5      0x7ffff6b4617a
4   QRegularExpression::match(QString const&, int, QRegularExpression::MatchType, QFlags<QRegularExpression::MatchOption>) const    /usr/lib64/libQt5Core.so.5      0x7ffff6b475e4
5   QRegularExpression::globalMatch(QString const&, int, QRegularExpression::MatchType, QFlags<QRegularExpression::MatchOption>) const  /usr/lib64/libQt5Core.so.5      0x7ffff6b47c77
6   QString::replace(QRegularExpression const&, QString const&) /usr/lib64/libQt5Core.so.5      0x7ffff6b1c4a9
7   QString::remove qstring.h   429 0x4852fe

Just guessing, but is there a chance that inside the fortran code (its not my ) something can cause a malloc call to fail ?  And if it is so, can someone explain how ?
EDIT:
Solved:
Okay i found it by accident.
In a diffrent part of the program i had the following code:
char href[3] ="";
strcpy(href,"DEF");

This is bad, cause strcpy also writes an end character '\0'. So the written chararray has the length of 4.


text:
Q: Bad practice to call base methods in derived constructors? I was just wondering on the most efficient way of setting inherited members was and if the following code is alright to use:
This is the declaration of the base class:
class cEntity{
private:
    int X, Y;
    int Height, Width;
public:
    cEntity();
    cEntity(int x,int y,int h,int w);
    ~cEntity();

    void setX(int x){X=x;};
    void setY(int y){Y=y;};
    void setCoords(int x, int y){X=x;Y=y;};

    void setHeight(int h){Height = h;};
    void setWidth(int w){Width = w;};
    void setArea(int h, int w){Height=h;Width=w;};

    int getX(){return X;};
    int getY(){return Y;};
    //void getXY(int,int);

    int getHeight(){return Height;};
    int getWidth(){return Width;};
    //void getArea(int,int);
};

and here is the constructor of the derived class:
cOrganism::cOrganism () {
    setCoords(0,0);
    setArea(0,0);
    Name = "UNKNOWN";
    Health = 100;
    MaxHealth = 100;
    HealthHiRange =100;
    HealthLoRange = 100;
};

So. Is is alright to call the setCoords() and setArea() in the derived class' constructor?

A: It's alright, but you can do much better by calling the base constructor:
cOrganism::cOrganism() : cEntity(0, 0, 0, 0) {
  // other stuff
}

In fact, you should initialize your new, derived members the same way:
cOrganism::cOrganism()
: cEntity(0, 0, 0, 0),
  Name("UNKNOWN"),
  Health(100),
  ...
{
}

(You might also want to read up a bit on general C++ class design: If you expose getters and setters to all your private variables, something isn't quite right. A class is supposed to encapsulate a model, while you're doing essentially the opposite. But that's not a technical error.)

A: Much better to call it like this:
cOrganism::cOrganism () : cEntity(0,0,0,0) {
  Name = "UNKNOWN";
  Health = 100;
  MaxHealth = 100;
  HealthHiRange =100;
  HealthLoRange = 100;
}

Or even better:
cOrganism::cOrganism ()
 : cEntity(0,0,0,0), Name("UNKNOWN"), Health(100),
   MaxHealth(100), HealthHiRange(100), HealthLoRange(100)
{}

That way the base class members are set as the base class implementation is constructed.

A: If the default constructor of the base class already intializes it to good values you don't have to do it all.
Otherwise the good solution is something like below.
class A
{
int x;
public:
    A( int xin) :x(xin) {}
};

class B : public A
{
int y;
public:
    B( int xin , int yin ) :A(xin) , y(yin) {}
};

Notice A(xin) in B constructor. This will called pass xin to the A constructor.
If you have something like integers it doesn't really matter what you do. But if A::X was actually a heavy weight object. With your approach A::x will be constructed once with default constructor and then assigned again when setCoords() is called from derived class constructor. My solution will ensure A::x* is only constructed once and that too with all the right value of its parameters.
More details here


text:
Q: Three.js missing shadowCamera I am currently learning Three.js and I am trying out this demo:
function init(){
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, .1, 500);
  var renderer = new THREE.WebGLRenderer();

  renderer.setClearColor(0xdddddd);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMapEnabled = true;
  renderer.shadowMapSoft = true;

  //Enable orbit controls
  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.addEventListener('change', render);

  var axis = new THREE.AxisHelper(10);
  scene.add(axis);

  var grid = new THREE.GridHelper(50, 5);
  var color = new THREE.Color("rgb(255,0,0)");
  grid.setColors(color, 0x000000);
  scene.add(grid);

  var cubeGeometry = new THREE.BoxGeometry(5, 5, 5);
  var cubeMaterial = new THREE.MeshLambertMaterial({color:0xff3300});
  var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

  cube.position.x = 2.5;
  cube.position.y = 4;
  cube.position.z = 2.5;
  cube.castShadow = true;
  scene.add(cube);

  camera.position.x = 40;
  camera.position.y = 40;
  camera.position.z = 40;

  camera.lookAt(scene.position);

  var planeGeometry = new THREE.PlaneGeometry(30, 30, 30);
  var planeMaterial = new THREE.MeshLambertMaterial({color:0xffffff});
  var plane = new THREE.Mesh(planeGeometry, planeMaterial);

  plane.rotation.x = -.5*Math.PI;
  plane.recieveShadow = true;
  scene.add(plane);

  var guiControls = new function(){
    this.rotationX = 0.01;
    this.rotationY = 0.01;
    this.rotationZ = 0.01;

    this.lightX = 20;
    this.lightY = 35;
    this.lightZ = 40;
    this.intensity = 1;
    this.distance = 0;
    this.angle = 1.570;
    this.exponent = 0;
    this.shadowCameraNear = 10;
    this.shadowCameraFar = 100;
    this.shadowCameraFov = 50;
    this.shadowCameraVisible = true;
    this.shadowMapWidht = 1028;
    this.shadowMapHeight = 1020;
    this.shadowBias = 0.01;
    this.shadowDarkness = 0.5;
  }

  var spotlight = new THREE.SpotLight(0xffffff);
  spotlight.castShadow = true;
  spotlight.position.set(20, 35, 40);
  spotlight.intensity = guiControls.intensity;
  spotlight.distance = guiControls.distance;
  spotlight.angle = guiControls.angle;
  spotlight.exponent = guiControls.exponent;
  spotlight.shadowCameraNear = guiControls.shadowCameraNear;
  spotlight.shadowCameraFar = guiControls.shadowCameraFar;
  spotlight.shadowCameraFov = guiControls.shadowCameraFov;
  spotlight.shadowCameraVisible = guiControls.shadowCameraVisible;
  spotlight.shadowBias = guiControls.shadowBias;
  spotlight.shadowDarkness = guiControls.shadowDarkness;

  scene.add(spotlight);

  var datGUI = new dat.GUI();
  datGUI.add(guiControls, 'rotationX', 0, 1);
  datGUI.add(guiControls, 'rotationY', 0, 1);
  datGUI.add(guiControls, 'rotationZ', 0, 1);
  datGUI.add(guiControls, 'lightX', -60, 180);
  datGUI.add(guiControls, 'lightY', 0, 180);
  datGUI.add(guiControls, 'lightZ', -60, 180);

  datGUI.add(guiControls, 'intensity', 0.01, 5).onChange(function(value){
    spotlight.intensity = value;
  });
  datGUI.add(guiControls, 'distance', 0, 1000).onChange(function(value){
    spotlight.distance = value;
  });
  datGUI.add(guiControls, 'angle', 0.001, 1.570).onChange(function(value){
    spotlight.angle = value;
  });
  datGUI.add(guiControls, 'exponent', 0, 50).onChange(function(value){
    spotlight.exponent = value;
  });
  datGUI.add(guiControls, 'shadowCameraNear', 0, 100).name('Near').onChange(function(value){
    spotlight.shadowCameraNear = value;
    spotlight.shadowCamera.updateProjectionMatrix();
  });
  datGUI.add(guiControls, 'shadowCameraFar', 0, 5000).name('Far').onChange(function(value){
    spotlight.shadowcameraFar = value;
    spotlight.shadowCamera.updateProjectionMatrix();
  });
  datGUI.add(guiControls, 'shadowCameraFov', 0, 180).name('Fov').onChange(function(value){
    spotlight.shadowcameraFov = value;
    spotlight.shadowCamera.updateProjectionMatrix();
  });
  datGUI.add(guiControls, 'shadowCameraVisible').onChange(function(value){
    spotlight.shadowcameraVisible = value;
    spotlight.shadowCamera.updateProjectionMatrix();
  });
  datGUI.add(guiControls, 'shadowBias', 0, 1).onChange(function(value){
    spotlight.shadowBias = value;
    spotlight.shadowCamera.updateProjectionMatrix();
  });
  datGUI.add(guiControls, 'shadowDarkness', 0, 1).onChange(function(value){
    spotlight.shadowDarkness = value;
    spotlight.shadowCamera.updateProjectionMatrix();
  });

  var container = document.getElementById("webglcontainer");
  container.appendChild(renderer.domElement );

  //Add stats
  var stats = new Stats();
  stats.domElement.style.position = "absolute";
  stats.domElement.style.left = "0px";
  stats.domElement.style.top = "0px";

  container.appendChild(stats.domElement);

  function render() {
    cube.rotation.x = guiControls.rotationX;
    cube.rotation.y = guiControls.rotationY;
    cube.rotation.z = guiControls.rotationZ;

    spotlight.position.x = guiControls.lightX;
    spotlight.position.y = guiControls.lightY;
    spotlight.position.z = guiControls.lightZ;
  }

  function animate(){
    requestAnimationFrame(animate);
    render();
    stats.update();
    renderer.render(scene, camera);
  }

  animate();
}
init();

The thing is I cannot seem to make the shadow camera to appear. The light is visible, I can manipulate it, but the cube is not casting any shadows on the plane below it...
Any ideas what am I doing wrong?
Thanks in advance!

A: I am glad this already did it for you, but I hate solved stackoverflow questions that arent marked as such :-)
So Im reposting the solution that it was just a spelling error in plane.receiveShadow = true;.
It looks like the code is based on this example (where it is spelled correctly) and may be of interest for someone to learn about lighting.


text:
Q: Killing developer's debugging connection with server Please don't mark it as a duplicate of how to kill process running on server. This is question how to detach developer from port so that another one could attach.
Is it possible to kill somehow a connection to a debug port?
Our server exposes debug port: 5551
$netstat -an | grep 5551

Gives me:
tcp        0     55 (serverIp):4442         (developerIp):51237         ESTABLISHED

This blocks the application. Developer went to coffee. If I want to kill this session I must restart whole server.
Is it possible to kill only this connection and how?

A: I haven't tried this, but look into tcpkill or cutter which kills the connection:
tcpkill -i eth0 port 4442


text:
Q: Wordpress else statement on custom query i have a custom query and i want to know how i can add an if statement, so that if there is no posts for this query, a simple message gets displayed.
My query:

        <?php if ( $spQuery->have_posts() ) while ( $spQuery->have_posts() ) : $spQuery->the_post(); ?>

<?php the_post_thumbnail( 'themename-bw-image' ); ?>

        <?php endwhile; wp_reset_postdata(); ?>

I was trying this:

            <?php if ( $spQuery->have_posts() ) while ( $spQuery->have_posts() ) : $spQuery->the_post(); ?>

<?php the_post_thumbnail( 'themename-bw-image' ); ?>

            <?php endwhile; wp_reset_postdata(); ?>

        <?php else : ?>

No Posts Currently Added.

        <?php endif; ?>

But i get this error: Parse error: syntax error, unexpected T_ELSE
Probably doing something stupidly wrong here, but i thought this was a valid way of doing it.

A: Add curly braces  (or put a colon after the : if ( $spQuery->have_posts() ) instead of curly braces)

        <?php if ( $spQuery->have_posts() ) { while ( $spQuery->have_posts() ) : $spQuery->the_post(); ?>

<?php the_post_thumbnail( 'themename-bw-image' ); ?>

        <?php endwhile; wp_reset_postdata(); ?>

    <?php } else {  ?>

No Posts Currently Added.

    <?php } ?>


text:
Q: Корректно ли специально для тестов объявлять классы в основном коде с модификатором public? Есть проект консольного приложения с библиотекой классов, находящихся в namespace MyProject;
Для тестирования кода в решение я добавил новый проект MSTest Test Project c namespace MyProject.Test;
В тестах проекта MyProject.Test я использую директиву using MyProject;
Соответственно, получаю доступ только к тем классам MyProject, которые с модификатором public.
Корректно ли специально для тестов объявлять классы в основном коде с модификатором public?
Как можно получить доступ к private классам MyProject с MyProject.Test другим способом (хотя наверное это невозможно..)
Как правильно поступать в таких случаях?
Спасибо!


text:
Q: BATMAN & OMNET++ I am a newbie to OMNET++.
I have a reasonable Background of BATMAN.
Now I want to implement BATMAN in OMNET++. I have a code of BATMAN in NED language. But I have no idea of how to compile it.
So far I have made a .ned file and copy pasted the code lines there.But obviously It had lots of error.What is the proper way to run a protocol in OMNET++.
Code: https://searchcode.com/codesearch/view/25196881/
Any help will be highly appreciated.

A: Probably some modules, which are imported in the copied .ned-file are missing.
It would be helpful, if you provide some more information about you errors and what you did exactly.
Have you installed and imported inet? Do you have the .cc and .h for your
        @class(Batman);

class?


text:
Q: How to get to linear form? This question is probably dead easy, but I am having difficulties to answer it.
I found the function of the tangent to the curve at a point of abscissa a by doing this :
$$f'(a)(x-a)+f(a)$$
So if I want to "convert" this expression to :
$$ax+b$$
In this expression, what is a, and what is b ?
EDIT : I think that $a$ is $f'(a)$ but I am not sure about this.

A: Tangent to the curve at a point of $x_0$:
$$   f(x) = f'({x_0})(x - {x_0}) + f({x_0})  = f'({x_0})x + f({x_0}) - {x_0}f'({x_0})  $$
So :
$$\eqalign{
  & a = f'(a)  \cr
  & b = f(a) - af'(a) \cr} $$
Note: There are two different $a$ in $a=f'(a) ~!$
In order to avoid confusion, I rewrite it at $(x_0,f(x_0))$:
$$\eqalign{
  & a = f'({x_0})  \cr
  & b = f({x_0}) - x_0f'({x_0}) \cr} $$

A: $a$ is the coefficient in from of $x$ in the expression of $y = f(x) = ax+b$
$b$ is the value of $f(0) $ in the expression of $y = f(x) = ax+b$


text:
Q: for-loop behavior when iterating a Set instead of a List How does the behavior of the for-loop change when a Set instance is given instead of a List instance?
Fiddle: http://scalafiddle.net/console/67ed94744426295f96268f4ac1881b46
Code:
case class Book(title: String, authors: List[String]) {}

val books = List(
  Book("Book 1", List("Author 1", "Author 2")),
  Book("Book 2", List("Author 2")),
  Book("Book 3", List("Author 3")),
  Book("Book 4", List("Author 4"))
)

def authorsWithMultipleBooks(books: Iterable[Book]) =
  for {
    b1 <- books
    b2 <- books
    if b1 != b2
    a1 <- b1.authors
    a2 <- b2.authors
    if a1 == a2
  } yield a1

println(authorsWithMultipleBooks(books))
// Output: List(Author 2, Author 2)
println(authorsWithMultipleBooks(books.toSet))
// Output: Set(Author 2)

A: In both cases you yield "Author 2" twice, but since Set only holds one istance of each element, the second time you yield it it doesn't change the set.
So the for loop doesn't change in its behavior, the only thing acting differently is the insertion in the resulting collection, which - being a set - discards duplicate insertions.
Here's an example to further clarify the idea:
scala> val authors = List("Author 1", "Author 2", "Author 3")
authors: List[String] = List(Author 1, Author 2, Author 3)

scala> for {
     | _ <- authors
     | } yield "Author 2"
res8: List[String] = List(Author 2, Author 2, Author 2)

scala> val authorsSet = authors.toSet
authorsSet: scala.collection.immutable.Set[String] = Set(Author 1, Author 2, Author 3)

scala> for {
     | _ <- authorsSet
     | } yield "Author 2"
res10: scala.collection.immutable.Set[String] = Set(Author 2)