text:
Q: shooting more than once cause swing timer to repeat ok so I have a method to shoot a spell, and whenever I press space it does fire, however if I push space while it's still on the screen my spell's speed doubles and it starts to repeat itself without me pushing space again here's my code thanks :) oh and the WizardCells is just a 2D array of JLabels I know that's created and used properly so I didn't want to waste your guys' time with that code thanks :)
 public void shootSpell(){
        final BlueSpell b = new BlueSpell(GoodGuy.getx(), GoodGuy.gety() +1, BlueSpellWizard());
        int delay = 60;

        ActionListener timeListen = new ActionListener(){
            public void actionPerformed(ActionEvent e){

                    if(b.gety() != 19){
                        WizardCells[b.getx()][b.gety()].setIcon(null);
                        WizardCells[b.getx()][b.changey(b.gety()+1)].setIcon(b.getIcon());

                    }

                    else{
                        WizardCells[b.getx()][b.gety()].setIcon(null);
                        b.changex(GoodGuy.getx());
                        b.changey(GoodGuy.gety() +1);
                        timer.stop();

                    }
                }

        };

            timer = new Timer(delay, timeListen);
            if(timer.isRunning()){
                return;
            }

            else{
            timer.start();
            }

        }

Key handler:
public class WizardKeyHandeler extends WizardBattleGrid implements KeyListener {
GoodGuy Player = new GoodGuy(10, 0, GoodGuyWizardIcon());
BlueSpell GoodSpell = new BlueSpell(10, 1, BlueSpellWizard());
WizardPause pause = new WizardPause();

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_W){

            if(Player.getx() != 0){

                Player.moveUp();
            }

        }

        else if(key == KeyEvent.VK_S){

            if(Player.getx() != 19){

                Player.moveDown();
            }
        }

        else if(key == KeyEvent.VK_D){

            if(Player.gety() != 9){

                Player.moveRight();
            }
        }

        else if(key == KeyEvent.VK_A){

            if(Player.gety() != 0){

                Player.moveLeft();
            }
        }

        else if(key == KeyEvent.VK_SPACE){

                }

        else if(key == KeyEvent.VK_ESCAPE){

            pause.createPause();
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();
        if(key == KeyEvent.VK_W){
                if(Player.getx() != 0){

                Player.remainAtPosition();
            }
            }

        else if(key == KeyEvent.VK_S){

            if(Player.getx() != 19){

                Player.remainAtPosition();
            }
        }

        else if(key == KeyEvent.VK_D){

            if(Player.gety() != 9){

                Player.remainAtPosition();
            }
        }

        else if(key == KeyEvent.VK_A){

            if(Player.gety() != 0){

                Player.remainAtPosition();
            }
        }

        else if(key == KeyEvent.VK_SPACE){

                GoodSpell.shootSpell();

                }

        else if(key == KeyEvent.VK_ESCAPE){

                pause.createPause();
        }

    }

    @Override
    public void keyTyped(KeyEvent e) {
        int key = e.getKeyCode();
        if(key == KeyEvent.VK_W){
            if(Player.getx() != 0){

                Player.moveUp();

            }

            }

        else if(key == KeyEvent.VK_S){

            if(Player.getx() != 19){

                Player.moveDown();
            }
        }

        else if(key == KeyEvent.VK_D){

            if(Player.gety() != 9){

                Player.moveRight();
            }
        }

        else if(key == KeyEvent.VK_A){

            if(Player.gety() != 0){

                Player.moveLeft();
            }
        }

        else if(key == KeyEvent.VK_SPACE){

                }

        else if(key == KeyEvent.VK_ESCAPE){

            pause.createPause();
        }
    }

A: Two good points by both MadPrgrammer and camickr. I'm like to illustrate those points.

MapPrgogrammer: You should have a single timer which is responsible for updating the state of the game/model and scheduling the repaints, don't use multiple timers

What you should do is have a have a List of Spell or BlueSpell (whatever). What you want to do is iterate through the list in the Timer and your painting method. Something like
public class GamePanel extends JPanel {
    List<BlueSpell> spells;
    Timer timer = null;

    public GamePanel() {
        spells = new ArrayList<>();

        timer = new Timer(40, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                If (spells.size() > 0) {
                    Iterator spellIt = spells.iterator();
                    while (spellIt.hasNext()) {
                        BlueSpell spell = (BlueSpell)spellIt.next();
                        if (spell.collidesWithSomthing()) {
                            // do something, then remove from list
                            spellIt.remove();
                        } else if (spell.isOffScreen()) {
                            spellIt.remove();  // remove the spell from list
                        } else {
                            spell.animate();  // animate for each tick of timer
                        }
                    }
                }
                repaint();  // just repaint once in each timer tick after all
            }               // state id update.
        });
        timer.start();
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        If (spells.size() > 0) {
             for (BlueSpell spell: spells) {
                  spell.drawSpell(g);
             }
        }
    }
}

You can see the basic idea of the spells list in the Timer callback. It iterates through the timer and if the list has BlueSpells, then it will continue to check if the spells collides with something (if you need to), it checks if the spells is off the screen. With either, you'll want to remove it from the list. (Don't be tempted to use a for each loop. In this case you should use an iterator). If it is still on screen and hasn't hit anything, then the spell animates (maybe move it x position or something) then finally for each tick, the panel is repainted. Notice the if checks in both the paintComponent and Timer. There's no need to paint or iterate through the list if it is empty.
You'll want to maintain all the game's state in the single timer, not just the spell. If the spells are the only thing that animates, you may want to add a else { timer.stop() } in the timer, if the list is empty.

camickr: Don't use a KeyListener to control player movement. See Motion Using the Keyboard for more information and an alternative approach using Key Bindings

What you can do is when the space is pressed, add a new BlueSpell to the list (and start the timer [only if necessary] ). Something like
public GamePanel() {
    ...
    InputMap inputMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(KeyStroke.getKeyStroke("SPACE"), "shootSpell");
    getActionMap().put("shootSpell", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            spells.add(new BlueSpell(...));
        }
    });
}

Once the spell is added to the list, the spell will begin to animate until it collides with something or is off the screen.

You can see a working example of both points in this answer.

Also you can see a bunch of other "animating multiple objects" answers here and here and here and here and here and here.

UPDATE

"the only question is in my repaint method do I just call the ImageIcon I created or do I have to create a new one?"

public class BlueSpell {
    BufferedImage bi;
    int x, y;
    int width = someWidth;
    int height = someHeight;
    JPanel panel;

    public BlueSpell(BufferedImage bi, int x, int y, panel) {
        this.bi = bi;
        this.x = x;
        this.y = y;
        this.panel = panel;
    }

    public void drawSpell(Graphics g) {
        g.drawImage(bi, x, y, width, height, panel);
    }

    public void animate() {
        x += 5;
    }
}

You should create just the one BufferedImage in the GamePanel and when you create a new BlueSpell in the in the key binding, just pass the image to it, along with the other arguments.


text:
Q: Multiple constructors for different arguments in C++ I'm quite new to C++ and I was wondering if there is any way around duplicating constructors, with variations in the passed arguments.
I need to identify the correct given value (either float or int), check if the float can nicely be casted to an integer (e.g. 1.0) and call another constructor that accepts two integers if my values pass the test.
If anyone as any tips on improving this solution in general that would be great.
Fraction(int n, int d) : numerator(n), denominator(d) {
    simplify(n, d);
}

Fraction(float n, float d) {
    if (!isInteger(n) && !isInteger(d)) {
        throw invalid_argument("Fractions only accept real numbers.");
    } else {
        Fraction(int(n), int(d));
    }
}

Fraction(int n, float d) {
    if (!isInteger(n) && !isInteger(d)) {
        throw invalid_argument("Fractions only accept real numbers.");
    } else {
        Fraction(int(n), int(d));
    }
}

Fraction(float n, int d) {
    if (!isInteger(n) && !isInteger(d)) {
        throw invalid_argument("Fractions only accept real numbers.");
    } else {
        Fraction(int(n), int(d));
    }
}

A: Well you could use only the floats ctor and test your parameters.
If you only have two ctors one for ints and one for floats, then only if both numbers are int the ints ctor will be called. otherwise the floats ctor will be called.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are reagent-forms meant to be using with re-frame? I'm building an application with re-frame and I'm wondering if reagent-form are meant to be used with re-frame or not, as reagent-form brings in its own way of handling state which is different than re-frame.

A: After experimenting a bit, I'd say it can be used, by completely ignoring the ratom that reagent-forms use for state and just using the callback, as in:
[bind-fields [form-template ...] default-values
               (fn [_ _ doc]
                 (re-frame.core/dispatch [:update-data doc]))]

but to me, it didn't feel right, ignoring that ratom with state. That's why I created a new library called Free-form for creating forms with Reagent and optionally, with Re-frame.
Free-form doesn't store state, it just has a similar callback mechanism and it comes with a layer that makes it plugging it into Re-frame straightforward (but optional). On top of that, it makes no assumptions about the shape of your form, you are in total control of your HTML.

A: You can, but I think you shouldn't.
One thing you could do is just require twitter bootstrap and do some glueing to use everything in the re-frame way.


text:
Q: Do I need to make a provisioning profile? I'm at the early stages of developing my app and I'd like to start testing it on others' devices. Can I not just connect their phones to my computer and use XCode to install the app on their devices the same way I installed it onto mine? Are there any disadvantages to doing this?

A: In the newest version of xcode you do not need to.

A: In the lates version of XCode you don't need to create a provisional profile but you will need to add your apple dev account.
If you have any issue you could try to create a generic dev provisional profile the one that use a '*' indicator


text:
Q: How NOT to remove an environment variable in an MSI Installer during the uninstall? I created an MSI Installer with Microsoft Visual Studio Installer Projects. During the installation process the user specifies a path for an environment variable to the registry. My problem is that the installer removes it automatically during the uninstall process. How could I achieve that it will not be removed? (Because I need this environmental variable for other programs)
The folder that stores the variable:

The variable itself:

I tried to make a copy of the variable in the BeforeUninstall event and then in the AfterInstall event set the variable again. But it did not work because I still have the environmental variable in the afterInstall event and after the installer quits the variable is gone.


text:
Q: Performance issues with LDS memory in OpenCL I have a performance problem when using LDS memory with AMD Radeon HD 6850.
I have two kernels as parts of a N-particle simulation. Each work unit has to calculate force which acts on a corresponding particle based on relative position to other particles. The problematic kernel is:
#define UNROLL_FACTOR 8
//Vernet velocity part kernel
__kernel void kernel_velocity(const float deltaTime,
                            __global const float4 *pos,
                           __global float4 *vel,
                           __global float4 *accel,
                           __local float4 *pblock,
                           const float bound)
{
    const int gid = get_global_id(0); //global id of work item
    const int id = get_local_id(0); //local id of work item within work group

    const int s_wg = get_local_size(0); //work group size
    const int n_wg = get_num_groups(0); //number of work groups

    const float4 myPos = pos[gid];
    const float4 myVel = vel[gid];
    const float4 dt = (float4)(deltaTime, deltaTime, 0.0f, 0.0f);
    float4 acc = (float4)0.0f;

    for (int jw = 0; jw < n_wg; ++jw)
    {
        pblock[id] = pos[jw * s_wg + id]; //cache a particle position; position in array: workgroup no. * size of workgroup + local id
        barrier (CLK_LOCAL_MEM_FENCE); //wait for others in the work group

        for (int i = 0; i < s_wg; )
        {
            #pragma unroll UNROLL_FACTOR
            for (int j = 0; j < UNROLL_FACTOR; ++j, ++i)
            {
                float4 r = myPos - pblock[i];

                float rSizeSquareInv = native_recip (r.x*r.x + r.y*r.y + 0.0001f);
                float rSizeSquareInvDouble = rSizeSquareInv * rSizeSquareInv;
                float rSizeSquareInvQuadr = rSizeSquareInvDouble * rSizeSquareInvDouble;
                float rSizeSquareInvHept = rSizeSquareInvQuadr * rSizeSquareInvDouble * rSizeSquareInv;

                acc += r * (2.0f * rSizeSquareInvHept - rSizeSquareInvQuadr);
            }
        }
        barrier(CLK_LOCAL_MEM_FENCE);
    }
    acc *= 24.0f / myPos.w;

    //update velocity only
    float4 newVel = myVel + 0.5f * dt * (accel[gid] + acc);

    //write to global memory
    vel[gid] = newVel;
    accel[gid] = acc;
}

The simulation runs fine in terms of results, but the problem is in the performance when using the local memory for caching the particle positions to relieve the big amount of reading from the global memory. Actually if the line
float4 r = myPos - pblock[i];
is replaced by
float4 r = myPos - pos[jw * s_wg + i];
the kernel runs faster. I don't really get that since reading from global should be much slower than reading from local.
Moreover, when the line
float4 r = myPos - pblock[i];
is removed completely and all following occurences of r are replaced by myPos - pblock[i], the speed is the same as before as if the line was not there at all. This I don't get even more as accessing private memory in r should be the fastest but the compiler somehow "optimizes" this line out.
Global work size is 4608, local worksize is 192. It is run with AMD APP SDK v2.9 and Catalyst drivers 13.12 in Ubuntu 12.04.
Can anyone please help me with this? Is that my fault or is that a problem of the GPU / drivers / ... ? Or is it a feature? :-)

A: I'm gonna make a wild guess:
When using float4 r = myPos - pos[jw * s_wg + i]; the compiler is smart enough to notice that the barrier put after the initialization of pblock[id] is not necessary anymore and remove it. Very likely all these barriers (in the for loop) impact your performances, so removing them is very noticeable.
Yeah but global access cost a lot too...So I'm guessing that behind the scene cache memories are well utilized. There is also the fact that you use vectors and as a matter of fact the architecture of the AMD Radeon HD 6850 uses VLIW processors...maybe it helps also to make a better use of the cache memories...maybe.
EDIT:
I've just found out a article benchmarking GPU/APU Cache and Memory Latencies. Your GPU is in the list. You might get some more answers (sorry didn't really read it - too tired).

A: After some more digging it turned out that the code causes some LDS bank conflicts. The reason is that for AMD there are 32 banks with 4 bytes length, but the float4 covers 16 bytes and therefore the half-wavefront accesses different addresses in the same banks. The solution was to make __local float* for x and y coordinates separately and read them also separately with the proper shift of array index as (id + i) % s_wg. Nevertheless, the overall gain in performance is small, most likely due to the overall latencies described in the link provided by @CaptainObvious (well then one has to increase the global work size to hide them).


text:
Q: use of {children} in a react component I am new to React and i am here with a very basic query. What's the use of {children} in the following react code.
const Store = ({children}) => {
    const [state, setState] = useState(initialState)
    return(
        <Context.Provider value={[state, setState]}>
            {children}
        </Context.Provider>
    )
}

A: Passing components as a body. In your case if you write
<Store>
  <Header/>
<Footer/>
//any data here
</Store>

It will automatically place here:
<Context.Provider value={[state, setState]}>
            {children} <-here you do need to define again
        </Context.Provider>

A: Children are the components nested in between your component's open and close tag. For example:
 <Header>
 <Menu />
 </Header>

In this case, Menu would be a child of Header.
In the slightly more complex example in your code, the children would be whatever you nest in Store. In this case you are using context so that any child of those children can also access the values passed into Context.Provider. The point of this is to avoid "props drilling" - but we're getting beyond the scope of your question now!

A: children is a reserved word that returns all children you pass between your opening and closing component element.
visit this page for more info:
https://reactjs.org/docs/composition-vs-inheritance.html

A: As written in the React documentation about Composition vs Inheritance, the children prop is a special prop that is used to pass directly children element into the output of the parent element.
In your example, using the Store component like this:
<Store>
    Hello!
</Store>

has the same effect as:
const Store = () => {
    const [state, setState] = useState(initialState)
    return(
        <Context.Provider value={[state, setState]}>
            Hello!
        </Context.Provider>
    )
}
// then call it like:
<Store />

or:
const Store = ({input}) => {
    const [state, setState] = useState(initialState)
    return(
        <Context.Provider value={[state, setState]}>
            {input}
        </Context.Provider>
    )
}
// the call it like
<Store input="Hello!" />


text:
Q: Trying to compile a Rust project for the web, wasm32 and emscripten, with pthreads - failing https://github.com/experiment9123/rust_wasm32_emscripten_pthreads
I have created this minimal example project which demonstrates the compile problem I'm having. It requires the emscripten SDK to be installed and in the path; compile with cargo build --target=wasm32-unknown-emscripten.
I get this error:
  wasm-ld: error: --shared-memory is disallowed by std-e42ff3047517e183.std.70dd5b92-cgu.0.rcgu.o because it was not compiled with 'atomics' or 'bulk-memory' features.

I have a Rust project which runs in the browser fine , compiled to wasm32 with the emscripten toolchain & SDK;  but when I attempt to enable pthreads, I get a linker error , which I'm guessing indicates the std lib needs to be recompiled with the same options.
Could anyone confirm if thats what I'm really seeing,
and moreover what would the remedy be?
I think cargo brings in source for most dependencies and builds them from source? - can it be made to do this for the stdlib? how would you go about injecting this option?
Is it something that would require major work within the rust stdlib itself ? (eg another target, or some way of adding options)


text:
Q: Horizontal step scroll for variable amount I have page with two buttons (scroll left and scroll right), and on click, page have to go left and right by div width (every div have different width). Could this be done with jQuery? I don't know how to read current div id (one close to left side of border), and how to define scroll (left or right) by width of previous/next div?

A: On click just increase, decrease a Counter var c. This will help us to target the desired DIV by .eq( c )
Than all we need is to get the desired DIV .offset().left and move the page to that position:
jsBin demo
HTML (add a .box to your DIVs):

div01

jQuery:
$(function(){

  var c = 0;
  var boxN = $('.box').length;

  $('#left, #right').on('click', function( e ){

    e.preventDefault();

    c = this.id=='right' ? ++c%boxN : --c ;
    if(c<0){ c=boxN-1; }
    var boxL = $('.box').eq( c ).offset().left;

    $('html, body').stop().animate({scrollLeft: boxL});

  });

});

A: If you are talking about some kind of slider then you have a containerdiv and an innerdiv with the total length of the items contained within.
The containerdiv will have overflow hidden
Next you control the position of the divs
This is just one way of thinking...


text:
Q: PHP5 Using a class within a class I am trying to use a class within a class, but seem to be having an issue with the initialised content of the class. It can see the class structure fine if you do a var_dump, but it wont see the content you have initialised with. I know im probably missing something pretty obvious, any pointers would be great. An example is below...
class firstClass()
{

    public $thedate;

    function __construct()
    {
        $this->thedate = date();
    }

}

class secondClass()
{

    public $datefrom1stclass;

    function __construct()
    {
        $this->datefrom1stclass = new firstClass;

        echo $this->datefrom1stclass->thedate;

    }

}

Sorry if I have not explained very well, If I do a var_dump I get the following:
object(firstClass)#3 (1) { ["thedate"]=> NULL }

Any pointers would be appreciated!

A: You shouldn't call date() without any parameters: at least one (a format, as a string) should be given:
$this->thedate = date('D M j G:i:s T Y');

The rest of your code is correct (although I'd prefer new firstClass() form, with parentheses - it's more readable).

A: Here is the correct code  :) Enjoy
`

public $thedate;

function __construct()
{
    $this->thedate = date("Ymd");
}

}
class secondClass
{
public $datefrom1stclass;

function __construct()
{
    $this->datefrom1stclass = new firstClass;

    echo $this->datefrom1stclass->thedate;

}

}
$var = new secondClass();
var_dump(  $var );
?>
`


text:
Q: ZSH alternative to BASH export VAR+='...'
I'm a Zsh user and I've encountered a problem I don't fully know how to solve:

*

*If I  append an env variable within my zshrc [BB_ENV_EXTRAWHITE], which works in Bash, I receive a parsing error:
export BB_ENV_EXTRAWHITE+=' CCACHE_DEPEND CCACHE_SLOPPINESS ICECC_REMOTE_CPP

/home/dev/.zshrc:export:139: not valid in this context:
BB_ENV_EXTRAWHITE+

*I tried fixing this by changing the export command to the below, which helped to correctly set the variable, but now when I source my zshrc multiple times, I get repeated values in the variable, which I don't want:
export BB_ENV_EXTRAWHITE="${BB_ENV_EXTRAWHITE} CCACHE_DEPEND CCACHE_SLOPPINESS ICECC_REMOTE_CPP"

I'm looking for a solution that will append to the variable but won't do so every time I source my zshrc if I added an alias, etc.

A: You can almost certainly just do
BB_ENV_EXTRAWHITE+=' CCACHE_DEPEND CCACHE_SLOPPINESS ICECC_REMOTE_CPP'

If it is an environment variable, the export flag well likely already be set. You could also add a separate export BB_ENV_EXTRAWHITE command if that really might not be the case.
There is nothing intrinsic to the bash syntax that is avoiding duplicates. Where are you setting the variable for bash? Perhaps use .zlogin perhaps instead of .zshrc to only have it set for the initial login. The other common way is to set environment variables in .zshenv but only within an if condition that checks things like $SHLVL to avoid running in subshells, I often use:
if [[ ! -o login && ! -o privileged && -o rcs && $SHLVL = 1 ]]; then

The -o login test in there may be removed - it depends.

A: If you are fine using an array, you can stick to the += syntax.
Here is an example:
# define the array (-a) to hold only unique values (-U)
typeset -U -a foo_array

# initial values
foo_array=(one two three)

# print the content
print -l $foo_array
 one
 two
 three

# add values
foo_array+="one"
foo_array+="four"
foo_array+=(two five)

# recheck the array
print -l $foo_array
 one
 two
 three
 four
 five

Notice that the repeatedly added values do not show up multiple times, because we used -U in the declaration!
You can use the array either as $foo_array (behaves as if the values are single arguments) or as "$foo_array" (behaves as if the values are stitched together to a single string separated by blanks):
$ printf "%s|" $foo_array
one|two|three|four|five|

$ printf "%s|" "$foo_array"
one two three four five|


text:
Q: Rails 4: Specified Unicorn in Procfile, but Webrick is executed I am using Rails 4.0.1 and I want to run unicorn as my web server, but when I execute rails s, Webrick is used instead (the unicorn gem is in my Gemfile, so it can't be that).
This is my Procfile:
worker:  bundle exec rake jobs:work
web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb

And this is the unicorn.rb file:
worker_processes 2
timeout 30
preload_app true

before_fork do |server, worker|

  Signal.trap 'TERM' do
    puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
    Process.kill 'QUIT', Process.pid
  end

  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|

  Signal.trap 'TERM' do
    puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to sent QUIT'
  end

  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection
end

What is going on? Thanks!

A: rails server doesn't use your Procfile; that's for foreman. Start your application with foreman instead:
bundle exec foreman start

If you want rails server to use Unicorn as well, you can include the unicorn-rails gem.

A: I am adding this as a general help article to those that have landed here because of a related search on Google.
If you want to run Unicorn then add this in your project
Gemfile
# Use unicorn as the app server
gem 'unicorn'
gem 'unicorn-rails'

Then in your terminal run bundle install
You will then get something like this in your terminal that shows that you are now using Unicorn.
=> Booting Unicorn
=> Rails 4.0.0 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
I, [2014-10-24T18:39:41.074259 #32835]  INFO -- : listening on addr=0.0.0.0:3000 fd=8
I, [2014-10-24T18:39:41.074399 #32835]  INFO -- : worker=0 spawning...
I, [2014-10-24T18:39:41.075407 #32835]  INFO -- : master process ready
I, [2014-10-24T18:39:41.076712 #32836]  INFO -- : worker=0 spawned pid=32836
I, [2014-10-24T18:39:41.237335 #32836]  INFO -- : worker=0 ready

Additional Reading
Unicorn Rails
Deploying to Heroku with Unicorn

A: You need to start everything by running foreman, e.g.,
$ foreman start

Otherwise you're just starting up Rails' default server.
See this Getting Started guide for further background info.


text:
Q: How to find two repetitive elements in a unsorted array on python In this problem I had to find duplicates from 1-N integers in an array given that N+2 size array with N no of integers, below is my code and error it is showing,
Please tell me what is the wrong
def find_duplicates(a,n):
    for i in range(n+2):
        if(a[abs(a[i])]>0):
            a[abs(a[i])]= - a[abs(a[i])]
        else:
            print(abs(a[i]), end= " ")
    print("\n")

if __name__ =='__main__':
    cases=int(input())
    for _ in range(cases):
        n=int(input())
        a=list(map(int,input().strip().split()))[:n+2]
        find_duplicates(a,n)

error is
Wrong Answer. !!
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:
2
1 1 2 2

Its Correct output is:
1 2

And Your Code's output is:

1 2 4 2 8 15 3 6 2 1 7 6 19 5 7 16 9 2 2 4 35 30 30 2...

A: Your code already works, you can see the first two outputs are "1 2" which are correct. However, the issue is you print all outputs of testcases in one line which may possibly cause the error. Please try to go to a new line before solving a new testcase as below:
if __name__ =='__main__':
    cases=int(input())
    for _ in range(cases):
        n=int(input())
        a=list(map(int,input().strip().split()))[:n+2]
        find_duplicates(a,n)
        print()


text:
Q: Retrieve public render parameter from OrignalParameterMap in renderRequest I have passed a render parameter from one portlet to another using user friendly url navigation.
response.setRenderParameter("params", renderParams);
response.sendRedirect(response.encodeURL("/wps/myportal/Home/abcPortlet"), "params");

Here Home and abcPortlet are user friendly page names for specific pages.
While debugging I found that OriginalParameterMap contains the render parameter in its URL.
Can someone tell me how to retrieve it? As usual getter methods are not able to retrieve that value.

A: You cannot pass render parameters from one portlet to another. It has to be Pubic Render Parameter (PRP). The approach of setting PRP is same as that of render parameter, but both portlets should agree that, they support that PRP. For that you need to register the supported PRPs in portlet.xml file of both the portlets. Please refer to this link for more info.This is what the specification insist. Imagine a scenario where in we have multiple portlets from various vendors on a portal page. It is a security concern if one portlet could retrieve the parameters from the URL even if it is not targeted to that portlet.
Another approach (which is not recommended) is to type case the RenderRequest to HttpServletRequest and get the parameter from request. It is not mentioned in the specification that PortletRequest should be a HttpServletRequest. So it is better not to do that. Future implementation of Portal can change this.
Third approach is to use the URL Generation APIs and construct the URL which has the parameters targeting the portlet. You can refer to the below link which has some helper classes. This will simplify your job. Advanced URL Generation Helper Classes
The best way is to use PRP. Both the source portlet and target portlet are loosely coupled.


text:
Q: When do values get written to a Google Sheet cell? I'm experiencing a weird issue.  When I type text in a Google Sheet cell, then run a custom script (below) to get those values, it doesn't get the values I just type in.  The values only become available once I move away from that cell (tab or enter).
var data = dataRange.getValues();
I'm not sure when the values actually get written to the cell.  If I script a move away from that cell (below), I get the same issue.
var newRange = sheet.getRange("C4");
sheet.setCurrentCell(newRange);
Is there a way to write all the data to the sheet?
Can test using this code.  Write some text to A1, run custom script and check the logs.  If you don't move away from A1 before running script, logs will be empty.
function moveTest(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var newRange = sheet.getRange("A2");
  sheet.setCurrentCell(newRange);
  var cellOfInterest = sheet.getRange("A1").getValue();
  Logger.log(cellOfInterest);
}

Edit: same issue with setActiveSelection instead of setCurrentCell

A:
When do values get written to a Google Sheet cell?

When you press tab, arrow keys, enter or any other method that takes the focus away from the cell, the value gets written or committed.

A: I'm not sure if it would work for you, but if you are checking for 1 exact cell, an if statement checking if the input is recognized before running the script would be alright:

    function checkwritten(){
      var app = SpreadsheetApp;
      var ss = app.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var ui = SpreadsheetApp.getUi();
      var InterestCell = sheet.getRange("A1");
      var cellOfInterest = sheet.getRange("A1").getValue();

      if (InterestCell.isBlank()) {
        Logger.log("missing value");
        ui.alert('There are missing values');
      }
      else {
        Logger.log(cellOfInterest);
        /*
        enter code here
        */
      }
    }

The other solutions proposed, such as making the button a menu option, or greying out the button until all entry is filled is also viable.
If you are checking for a range, the following two options are viable:
Option 1: create a cell with countblank in your sheet and it would be the cell of interest.
function checkwritten(){
  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var InterestCell = sheet.getRange("A6");
  var cellOfInterest = sheet.getRange("A6").getValue();

  if (cellOfInterest == 0) {
    Logger.log("success");
  }
  else {
    Logger.log(cellOfInterest);
    /*
    enter code here
    */

  }

}

Option 2 - allow the script to ensure that there is no blank cells before running.
function checkwritten(){
  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var CellCheckCount = 100; // 1 above the total number of rows to check
  var ui = SpreadsheetApp.getUi();
  var BlankCellCount = 0;
  var CheckCell = null;

  for (var i = 1; i < CellCheckCount; i++){
    CheckCell = sheet.getRange(i,1); //currently set to check column 1 up till 100-1 row
    if (CheckCell.isBlank()){
        BlankCellCount++;
        }
    else{
        }
  }

  if (BlankCellCount == 0) {
    Logger.log("success");
    /*
    enter code here
    */
  }
  else {
    Logger.log("fail" + BlankCellCount);
  }
}


text:
Q: Regular Expression to identify string containing dot(s), excluding dot(s) in double quotes I want to match strings that contains dot(s) ., complexity is, it should not consider dot(s) that are enclosed in double quotes.
<<8001_011._>>[01990.a|c01]+<<8001_011._>>[01990.b|c.01] Match
[01990.a|c01]+[01990|c.01] Match
"a" + "$.1" +  $1 + "b" NOT Match, dot is enclosed in quotes.

A: Try to use this expression
([^."]*"[^"]*")*[^."]*\..*


text:
Q: Envelope of signal in time domain I'm trying to get envelope of a signal.  In an old topic, I found some old code abs(hilbert(signal)).
After filtering the acceleration signal in time domain with 1/3-octave-band and using the code from above my signal look like this:
Red -->Hilbert Blue-->Signal

(source: 1.ii.gl)
I was expecting something more like this:

(source: tugraz.at)
It seems like my envelope doesn't quite fit.
Here's my code for the 1/3-octave-band:
Fs = 5000;
N= 4;
Fc1= 1425;
Fc2= 1795;
h= fdesign.bandpass('N,F3dB1,F3dB2', N, Fc1, Fc2, Fs);
Hd= design(h, 'butter');

What am I doing wrong?


text:
Q: Strange for loop in javascript i have an helper class in javascript and i must use like this
menu
     .createMenu("TestMenu", "Description")
    .addMenuItem("test", "", true, true, "callServerTrigger",
"testServerEvent")
.addMenuItem("test", "", true, true, "callServerTrigger", "testServerEvent")
.addMenuItem("test", "", true, true, "callServerTrigger", "testServerEvent")
.addMenuItem("test", "", true, true, "callServerTrigger", "testServerEvent")
   .addCloseButton();

but i must use for loop here.
menu
     .createMenu("TestMenu", "Description")
    for (var i = 0; i < arr.length; i++) {
        .addMenuItem(arr[i], "", true, true, "callServerTrigger", "testServerEvent")
    }
   .addCloseButton();

I tried this but "." gives syntax error. How can i make this ?

A: You could use a variable for keeping the chained object.
var temp = menu.createMenu("TestMenu", "Description");
for (var i = 0; i < arr.length; i++) {
    temp = temp.addMenuItem(arr[i], "", true, true, "callServerTrigger", "testServerEvent");
}
temp.addCloseButton();

Or use Array#reduce, where the return value keeps the chained object.
arr.reduce(function (r, a) {
    return r.addMenuItem(a, "", true, true, "callServerTrigger", "testServerEvent");
}, menu.createMenu("TestMenu", "Description")).addCloseButton();

A: Also, if you don't have anything in your arr-array. The length will be 0 at the start and that might be causing the error.


text:
Q: Objective-C = operator vs stringWithString/arrayWithArray I'm new to obj-c development but partly have background in C development. It might be a noob question but I couldn't get an exact answer in other places. What is the difference between these snippets for arrays and strings and possibly other types of objects:
NSArray *original = [NSArray arrayWithObjects:someObjects,nil];
//Case 1
NSArray *copy1 = original;
//Case 2
NSArray *copy2 = [NSArray arrayWithArray:original];

and for strings
NSString *original = @"aString";
//Case 1
NSString *copy1 = original;
//Case 2
NSString *copy2 = [NSString stringWithString:original];

If I make changes to copy1 and copy2 later will they be reflected on original objects? And does the same rules apply to other object types?

A: The second code snippet does for NSString what the first code snippet does for NSArray. There is no difference in the behavior, because both NSString and NSArray objects in Cocoa are immutable.
When you call [NSString stringWithString:original], Cocoa is smart enough not to create a new object: the reasoning behind this decision is that since original cannot be changed, there's nothing you could do to tell apart a copy from the original. Same goes for [NSArray arrayWithArray:original], because you get the same instance back.
Note: If someObjects is mutable, one could tell apart an array from its deep copy by modifying the object, and seeing if it changes in the other place. However, arrayWithArray: method makes a "shallow" copy, so you wouldn't be able to detect a difference even if the objects inside your array are mutable.

A: Your question is really about what objects pointers are pointing to. When you say make changes to copy1 and copy2 later, I guess you mean to the pointer contents, not to the object referenced by that pointer. This is a rather functional way to think, but it important non-the-less.
In your example, the array / string part doesn't matter, because you aren't doing anything with the objects, you are just doing things with the pointers to those objects.
original points to one object. copy1 points to the same object. copy2 points to a different object (but which, in this case, is a copy of the first object).

A: copy1 is not a copy, but another pointer to the same memory as original. copy2 is actually a copy, pointing at a different piece of memory.
If you modify copy1 (assuming it was mutable, which you example code is not), you are modifying original too, as they point at the same piece of memory.
If you modify copy2, original should be unchanged (generally speaking). In your array example, the objects in the array original and in the array copy2 are, I believe the same. So you in this case, you have two arrays, but they have in them the same objects.

A: NSArrays and NSStrings are immutable so you can't change them.
You can't add or remove objects from NSArray, but if you change some object in array, it will change in its copy because NSArray holds a pointer to it.


text:
Q: Error: getStaticPaths is required for dynamic SSG pages and is missing for '/category/[...Id]' in nextjs I faced build time error, Error: getStaticPaths is required for dynamic SSG pages and is missing for '/category/[...Id]', How can I use getStaticPaths in my code refered https://nextjs.org/docs/messages/invalid-getstaticpaths-value this but how to call path in my function, Could you solve my issue please
Code
[...Id].js
import { useRouter } from 'next/router'
import Head from 'next/head'
import { Grid, Image,Segment, Card } from "semantic-ui-react"
import 'semantic-ui-css/semantic.min.css'
import Layout from '../../components/layout'

const Post = (props) => {
  const router = useRouter()
  const { Id } = router.query
  console.log(props.category_list)
  return(
    <>
    <Layout>

    <meta charSet="utf-8" />
    <title></title>
            {/* <meta name="description" content={seo_description} /> */}
            <meta name="keywords" content=""/>
            <meta name="google-site-verification" content="rtIRrUNRpgZ_lFtlfS8LJ0-8j_d569BXS9NOGa_nM6Y" />

      <Grid className="store-list">
        <Grid.Column width={16}>

            {props.category_title.heading_label}

        </Grid.Column>
      </Grid>
      <Grid columns={4} className="all-offers storeList">
        {props.category_list.map((x) => {
          return (
            <Grid.Column>
              <Segment>
                <Card>

                    {" "}
                    <Image
                      src={x.image}
                      alt=""
                      className="collection-img"
                    ></Image>

                  <Card.Content>

                      {" "}
                      <Card.Header>{x.name}</Card.Header>

                    <Card.Description>{x.store_summary}</Card.Description>
                  </Card.Content>
                  <Card.Content extra>

                      Cash rewards upto AED {x.cashback}

                      {x.store_branches}
                      {/* {x.store_branches.map((locations, index) => (

                          {index === 0 ? (
                            {locations.store_location}
                          ) : index >= 1 ? (

                              ,  {locations.store_location}

                          ) : null}

                      ))} */}

                  </Card.Content>
                </Card>
              </Segment>
            </Grid.Column>
          );
        })}
      </Grid>
      </Layout>
    </>

  )
}

export async function getStaticProps(context) {
  const id = context.params.Id[1];
  const postBody = {
    category_id: id,
    offer_type: "",
  };
  const offerList = await fetch('https://le.app.ae/api/v5/web/list',{
    method:'POST',
    body: JSON.stringify(postBody),
    headers: { "Content-Type": "application/json" },
  })
  const category = await offerList.json();
    // const bookJson = JSON.stringify(book)
    // const bookJson=offerData.stores;
  const category_list=category.stores;
  const category_title=category;
  return {
    props: {
      category_list,
      category_title
    }
  };
}
export default Post;

A: will try to help you!
With getStaticProps you need (obliged) to use getStaticPath (link)
After your code in getStaticProps add getStaticPaths function. !IMPORTANT! you write your getStaticPaths only after getStaticProps function, otherwise it can trigger some error
export async function getStaticPaths() {
// change your API url to get ALL categories
const res = await fetch(process.env.APIpath + '/api/public/getCategories')
const posts = await res.json()

// Get the paths we want to pre-render based on posts, play with params variable you are returning
const paths = posts.map((post) => ({
  params: { id: post._id },
}))

// We'll pre-render only these paths at build time.
// { fallback: blocking } will server-render pages
// on-demand if the path doesn't exist.
return { paths, fallback: 'blocking' }
}

For the fallback, you can check this post, to check the differences between possible values.
So, file need to have next hierarchy of functions:

*

*Const Post

*async function getStaticProps()

*async function getStaticPaths()


text:
Q: can d3js stack layout function v4 support minPointLength from highcharts for zero value? Can D3Js V4 support something similar with minPointLength from highcharts?
The requirement is: when the bar chart height is 0, we should take consider into this and give a minimized value, say, 1px, for example.
Currently, zero value will cause the bar chart is 0 and no visual feedback.
It is not my expectation?
Thanks~!


text:
Q: Codemirror Auto Format after setValue http://liveweave.com/UxEJ0s
I'm using Codemirror for my app.
I noticed if I select all the text and press SHIFT+Tab it will auto align my code making it easier to read.
Here's an example of what my app currently renders:

  Apples

  Oranges

Here's what I'm trying to get it to render:

      Apples

      Oranges

Edit
Does anyone know if there's a way to do this without selecting the whole code manually in Codemirror?
Why? I have Codemirror running in my background of my app all code that's added is added dynamically, but when I save the final code it looks like above.

A: You can use the following code to achieve what you want :
function format() {
    var totalLines = editor.lineCount();
    editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
}

Bind this function with your events, and it will auto-format the code.

A: By using codemirror formatting add-on you can achieve your requirement
JSFiddle Demo
 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: true,
        mode: "htmlmixed",
        extraKeys:{"Shift-Tab":autoFormatSelection}
      });

      function getSelectedRange() {
        return { from: editor.getCursor(true), to: editor.getCursor(false) };
      }

      function autoFormatSelection() {
        var range = getSelectedRange();
        editor.autoFormatRange(range.from, range.to);
      }

Source Link
http://codemirror.net/2/demo/formatting.html

A: Here is the original addon including a small update to let it work with CodeMirror V3 :
CodeMirror.extendMode("css", {
    commentStart: "/*",
    commentEnd: "*/",
    newlineAfterToken: function(type, content) {
        return /^[;{}]$/.test(content);
    }
});

CodeMirror.extendMode("javascript", {
    commentStart: "/*",
    commentEnd: "*/",
    newlineAfterToken: function(type, content, textAfter, state) {
        if (this.jsonMode) {
            return /^[\[,{]$/.test(content) || /^}/.test(textAfter);
        } else {
            if (content == ";" && state.lexical && state.lexical.type == ")") return false;
        return /^[;{}]$/.test(content) && !/^;/.test(textAfter);
        }
    }
});

CodeMirror.extendMode("xml", {
    commentStart: "",
    newlineAfterToken: function(type, content, textAfter) {
        return ( type == "tag" && />$/.test(content) || /^</.test(textAfter) ) || (  type == "tag bracket" && />$/.test(content) );
    }
});

CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
    var cm = this, curMode = CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(from).state).mode;
    cm.operation(function() {
        if (isComment) { // Comment range
            cm.replaceRange(curMode.commentEnd, to);
            cm.replaceRange(curMode.commentStart, from);
        if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside
            cm.setCursor(from.line, from.ch + curMode.commentStart.length);
        } else { // Uncomment range
            var selText = cm.getRange(from, to);
            var startIndex = selText.indexOf(curMode.commentStart);
            var endIndex = selText.lastIndexOf(curMode.commentEnd);
            if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
                // Take string till comment start
                selText = selText.substr(0, startIndex)
                // From comment start till comment end
                + selText.substring(startIndex + curMode.commentStart.length, endIndex)
                // From comment end till string end
                + selText.substr(endIndex + curMode.commentEnd.length);
            }
            cm.replaceRange(selText, from, to);
        }
    });
});

CodeMirror.defineExtension("autoIndentRange", function (from, to) {
    var cmInstance = this;
    this.operation(function () {
        for (var i = from.line; i <= to.line; i++) {
            cmInstance.indentLine(i, "smart");
        }
    });
});

CodeMirror.defineExtension("autoFormatRange", function (from, to) {
    var cm = this;
    var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
    var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
    var tabSize = cm.getOption("tabSize");

    var out = "", lines = 0, atSol = from.ch == 0;
    function newline() {
      out += "\n";
      atSol = true;
      ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
      var stream = new CodeMirror.StringStream(text[i], tabSize);
      while (!stream.eol()) {
        var inner = CodeMirror.innerMode(outer, state);
        var style = outer.token(stream, state), cur = stream.current();
        stream.start = stream.pos;
        if (!atSol || /\S/.test(cur)) {
          out += cur;
          atSol = false;
        }

        if (!atSol && inner.mode.newlineAfterToken &&
            inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
          newline();
      }
      if (!stream.pos && outer.blankLine) outer.blankLine(state);
      if (!atSol)newline();
    }

    cm.operation(function () {
      cm.replaceRange(out, from, to);
      for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
        cm.indentLine(cur, "smart");
      cm.setSelection(from, cm.getCursor(false));
    });
});

A: autoFormatRange was removed from codemirror, so we should use another way, register our own extension:
1. generate js
Go to js generator (just an easy way to get minified js with plugins and custom extensions). http://codemirror.net/doc/compress.html
Updated link for version 3: http://codemirror.net/3/doc/compress.html
2. Select options desired
Paste custom extension code and press "Compress" button.
CodeMirror.defineExtension("autoFormatRange", function (from, to) {
    var cm = this;
    var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
    var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
    var tabSize = cm.getOption("tabSize");

    var out = "", lines = 0, atSol = from.ch == 0;
    function newline() {
        out += "\n";
        atSol = true;
        ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
        var stream = new CodeMirror.StringStream(text[i], tabSize);
        while (!stream.eol()) {
            var inner = CodeMirror.innerMode(outer, state);
            var style = outer.token(stream, state), cur = stream.current();
            stream.start = stream.pos;
            if (!atSol || /\S/.test(cur)) {
                out += cur;
                atSol = false;
            }
            if (!atSol && inner.mode.newlineAfterToken &&
                inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
                newline();
        }
        if (!stream.pos && outer.blankLine) outer.blankLine(state);
        if (!atSol) newline();
    }

    cm.operation(function () {
        cm.replaceRange(out, from, to);
        for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
            cm.indentLine(cur, "smart");
    });
});

// Applies automatic mode-aware indentation to the specified range
CodeMirror.defineExtension("autoIndentRange", function (from, to) {
    var cmInstance = this;
    this.operation(function () {
        for (var i = from.line; i <= to.line; i++) {
            cmInstance.indentLine(i, "smart");
        }
    });
});

3. Use generated .js as follows
Html:
<textarea id=code><?=$value?></textarea>

<link rel="stylesheet" href="/codemirror/codemirror.css">

Code was found here

A: Ever since Codemirror has removed support for autoFormatRange() it's not worth the trouble to use it for formatting text. I use js-beautify instead.
var beautify_js = require('js-beautify').js_beautify
var beautify_html = require('js-beautify').html

var formattedJSON = beautify_js(jsonText, { indent_size: 2 });
var formattedXML = beautify_html(xmlText, { indent_size: 2 });

A: A bit late, but maybe this can help someone who faces the same issue
autoFormatRange is not available anymore, however it is possible to indent the editor's value line by line, and no need to select the content
editor.eachLine(line => {
   editor.indentLine(editor.getLineNumber(line), "smart");
})


text:
Q: How to force android application to print stack trace of uncaught exception? when my app crashes it throws some lines in Logcat:
07-10 10:35:34.671  32391-32391/com.noframe.farmisagronom D/AndroidRuntime﹕ Shutting down VM
07-10 10:35:34.671  32391-32391/com.noframe.farmisagronom W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415bf8b0)

How to force app to print stack trace of exception?
my application class code:
public class Application extends MultiDexApplication {

    @Override
    protected void attachBaseContext(Context base) {
        try {
            super.attachBaseContext(base);
            MultiDex.install(this);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {

        try {
            Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    Log.e("Uncaught Exception detected in thread {}", t.getName(), e);
                }
            });
        } catch (SecurityException e) {
            Log.e("Could not set the Default Uncaught Exception Handler", "" ,e);
        }
        super.onCreate();
    }
}

Note that setDefaultUncaughtExceptionHandler is my try to get stack trace form exception, but it dose not work.
When i go wild with try-catch every where, i catch those exceptions. But that's not always an option, and requires a huge amount of time.

A: You can see the overrides of all the log  methods Here's the link with (String tag, String msg, Throwable tr) signatures.
Passing an exception as the third parameter should give you the full stacktrace in logcat.
The three-argument log methods use the getStackTraceString() method

A: I did this way:
StackTraceElement[] st = new StackTraceElement[12];
st = ex.getStackTrace();
for (StackTraceElement el: st)
    com.example.android.common.logger.Log.e(TAG, " " + el);

Hope it will help.


text:
Q: play local video file on a web browser Okay, I have video files on my network drive which I would like to play on my website, only pc's connected to my network and visit my site will see the files.
So I am trying to use videojs.com to get this working...
If I enter a video file that is hosted online it will play it, entering
file://mybooklive/Public/Shared%20Movies/Anchorman%20(2004).mp4

it will not play (even though typing that into chrome's URL bar will play the video).
So basically this WILL play a online video...
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="http://vjs.zencdn.net/v/oceans.mp4"
type='video/mp4'> </video>

and this will not play (local file)
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="file://mybooklive/Public/Shared%20Movies/Anchorman%20(2004).mp4"
type='video/mp4'> </video>

Please help!!!
I'm using MyBookLive so I don't think I can enter an IP address.

A: You are trying to play using your file path, you will need to use the Internet URL absolute path
Please change your code, so that the file will be available through URL, and not file system
Using this model, you can place your files anywhere, as long as you point the correct URL to them
Read more about video.js documentation and starting up here
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="http://path-to-your-website/Shared%20Movies/Anchorman%20(2004).mp4"
type='video/mp4'> </video>

Read more about it here
If you don't want to use an absolute path, you can use a relative path, based on where your script is :
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="relative-path-to-your-mp4/Anchorman%20(2004).mp4"
type='video/mp4'> </video>

A: No need for file:// Put your video in the same folder as your html fime and use,
<video width="640" height="264" controls>
  <source src="filename.mp4" type="video/mp4">
</video>


text:
Q: What happens to Application after IntentService is killed because of no requests to it I read about IntentService and wonder about it´s lifestyle and effect on  the Android Application. I know when the IntentService starts Android first starts the android.app.Application by running onCreate() . When the IntentService running queue is empty the IntentService can be killed.
But what happens then to the started android.app.Application?

A: The Application class is a Singleton and will exist as long as your app's process still exits. The IntentService exits on its own once the are no more Intents for it to handle, but that does not mean the app process exits. Read about processes and threads here to get more information: https://developer.android.com/guide/components/processes-and-threads.html


text:
Q: Apache Ignite's Continuous Queries event handler group & sequencing We are trying to use the Continuous Query feature of Ignite. But we are facing an issue on handling that event. Below is our problem statement

*

*We have defined a Continuous Query with remote filter for a cache and shared the filter definition with Thick Client.

*We are running multiple replica of the "Thin Client" in Kubernetes cluster.

*Now the problem is each instance of the "Thin Client" running in k8s cluster have registered the remote filter and each instance receiving the event and trying to process the data in parallel. This resulting in duplicating data process or even overriding the data in my store.

Is there any way to form a consumer group and ensure that only one instance of the "Thin Client" is receiving the notification and its processing the data ?
My Thick client and Thin Clients are in .NET
Couldn't found any details on Ignite document
https://ignite.apache.org/docs/latest/key-value-api/continuous-queries

A: Here each thin client is starting its own continuous query and thereby, by design, each thin client is getting its own event to consume. If you want to route an event to a specific client then you would need to start only one continuous query, and distribute that event to your app as you see fit.
Take a look at ignite messaging to see whether it fits your use case.
Also check out the distributed Queue/Set which have unique delivery guarantees.


text:
Q: How can I get current buffer length of MPMoviePlayer How can I get current buffered length of MpMoviePlayer in seconds?
This link described how to get it in bytes, but I need to convert it to seconds.
Is there any way that I can do that?

A: You can access the playableDuration property of the MPMoviePlayerController.
According to Apple Docs,

The amount of currently playable content. (read-only)
Declaration
   @property(nonatomic, readonly) NSTimeInterval playableDuration

Discussion
For progressively downloaded network
content, this property reflects the amount of content that can be
played now.


text:
Q: tkinter scrolledtext.ScrolledText has no get attribute I can't seem to print the contents of the ScrolledText Widget to the console.
I have run the help command on the ScrolledText Widget:
print(help(scrolledtext.ScrolledText))

This outputs that the .get method (used to get the contents of tk.Text Widgets) is present in this widget aswell.
 |  get(self, index1, index2=None)
 |      Return the text from INDEX1 to INDEX2 (not included).

So why is it then that the line:
print(myScrollTextWidget.get("1.0","end"))

Results in this error:
AttributeError: 'NoneType' object has no attribute 'get'

When the button is pressed.
Here is a runnable code snippet that I'm working from:
import tkinter as tk
from tkinter import scrolledtext
#Declare Root
root = tk.Tk()
root.title("Scrolltext Widget")
tk.Label(root,text="My Scrolled Text Widget",font=("Times New Roman",25))\
    .grid(row=0,column=1)
#Define ScrollTextWidget
#wrap keyword used to wrap around text
myScrollTextWidget = scrolledtext.ScrolledText(root,wrap=tk.WORD,width=50,height=20,font=("Times New Roman",15))\
    .grid(row=1,column=1)
print(help(scrolledtext.ScrolledText))
def printToConsole():
    print(myScrollTextWidget.get("1.0","end"))
#Buttons
myButton = tk.Button(root,text="Print to console!",command=printToConsole).grid(row=2,column=1)

root.mainloop()

A: When you .pack() or .grid() in the sameline, you do not return anything to the variable thus the variable is None
Instead, .pack() or .grid() in another line as shown:
myScrollTextWidget = scrolledtext.ScrolledText(root,wrap=tk.WORD,width=50,height=20,font=("Times New Roman",15))
myScrollTextWidget.grid(row=1,column=1)

Generally, gridding or packing in the same line is quite erroneous. You should avoid it if you want to access your objects for configuration or other purposes.


text:
Q: Collections list and dictionary I have a list that contains roleids and a dictionary that has database of roleids and menus accessible to that roleid.
Suppose a user has role 1,2,3 then how do I retrieve the distinct menus he can access from a dictionary?
List<int> roleids = new List<int>();

roleids.Add(1);
roleids.Add(2);
roleids.Add(3);

Dictionary<int, List<String>> Links = new Dictionary<int, List<string>>
{
    { 1, new List<String> { "Home", "About Us", "Logout", "Help" } },
    { 2, new List<String> { "Home", "Products", "Logout", "Help" } },
    { 3, new List<String> { "Home", "Customers", "Users", "Help" } }
};

I want to create a new list that contains menus accessible to user based on values in List roleids

A: If you do your initial select across the roleids list - you can leverage the fast-lookup nature of the dictionary
var menuItems = roleids
    .Select(id => Links[id])
    .SelectMany(roles => roles)
    .Distinct();

A: Try this:
var distinct = Links
    .Where(i => roleids.Contains(i.Key))
    .SelectMany(i => i.Value).Distinct()
    .ToList();

A: Retrieve at first Links where role id in user's roleids, then select from this subset the values and avoid duplicates with distinct:
   var menus = Links.Where(l => roleids.Contains(l.key))
                     .SelectMany(k => k.Value)
                     .Distinct();

A: use this algorithm
public static List<string> GetMenuItems(List<int> userRoles)
    {
        var roleids = new List<int>();
        roleids.Add(1);
        roleids.Add(2);
        roleids.Add(3);
        var Links = new Dictionary<int, List<string>>()
        {
             {1,new List<String> {"Home","About Us","Logout","Help"}},
             {2,new List<String>{"Home","Products","Logout","Help"}},
             {3,new List<String>{"Home","Customers","Users","Help"}}
        };
        var roleLinks = Links
            .Where(item => userRoles.Contains(item.Key))
            .SelectMany(item => item.Value)
            .ToList()
            .Distinct();
    }


text:
Q: Blue J Java Print string specified by int val How do I print a string multiple times specified by an Int val.
say for instance
int value = 5;

print("?")

basically need to make the question mark print 5 times.
The int value can change. Just some homework i needed help on,
thanks

A: for(int i = 0; i<value; i++) {
    //print("?")
}

A: Use loop
int value = 5;
for (int i = 0; i < value; i++) {
    System.out.println("something");
}
// at the end of code `value` is 5

or you can use while, but notice the difference that value variable always decremented here :
int value = 5;
while (value > 0) {
    System.out.println("something");
    value = value - 1;
}
// at the end of code `value` is 0


text:
Q: Spring with Thymeleaf, BindingResult nor plain target object for bean name 'user' available as request attribute I have created a form using Thymeleaf and Spring and run into this issue.
I also read This question but it didn't work for me
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/>
    </parent>
    <groupId>mz.painting</groupId>
    <artifactId>mz</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>M&Z Painting</name>
    <description>Web Application for M&Z </description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Controller Update
@Controller
 public class SavingUser{

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/addUser")
    public String addUser(Model model){
        System.out.println("Adding User in registration page..");
        model.addAttribute("user", new Customer());
        return "service";

    }

    @PostMapping("/registerUser")
    public String userRegistration(@ModelAttribute Customer user, Model model){
        System.out.println("User in registration page..");
        model.addAttribute("user", user);
//        userRepository.save(user);
        return "redirect:/service";

    }

**Bean Class**
    Getters()
    Setters()
    toString()

HTML Form

        <form action="registerUser" th:action="@{/registerUser}"
     th:object="${user}" method="POST">

            Your Name:

            <input type="text" th:field="*{name}"  placeholder="" />

            Your Suburb

            <input type="text"  th:field="*{suburb}"  placeholder="" />

            Email

            <input type="email" th:field="*{email}"  placeholder="" />

            Phone

            <input type="tel" th:field="*{phone}" placeholder="" />

            Please tell us how we can help

            <textarea type="text" th:field="*{text}" rows="10" cols="40"></textarea>

                <input class="submit" type="submit" value="Submit"  />

        </form>

Full Error Message
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 86, col 32)] with root cause

"index" - line 86, col 32)] in HTML Form is this ->
            <input type="text" th:field="*{name}"  placeholder="" />

I also checked this solution and it didn't work for me
Update
Terminal Page
"C:\Program Files\Java\jdk-13.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.1.2\lib\idea_rt.jar=49969:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.1.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\shuja\Desktop\mz\target\classes;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter\2.5.3\spring-boot-starter-2.5.3.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot\2.5.3\spring-boot-2.5.3.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-context\5.3.9\spring-context-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.5.3\spring-boot-autoconfigure-2.5.3.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.5.3\spring-boot-starter-logging-2.5.3.jar;C:\Users\shuja\.m2\repository\ch\qos\logback\logback-classic\1.2.4\logback-classic-1.2.4.jar;C:\Users\shuja\.m2\repository\ch\qos\logback\logback-core\1.2.4\logback-core-1.2.4.jar;C:\Users\shuja\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.14.1\log4j-to-slf4j-2.14.1.jar;C:\Users\shuja\.m2\repository\org\apache\logging\log4j\log4j-api\2.14.1\log4j-api-2.14.1.jar;C:\Users\shuja\.m2\repository\org\slf4j\jul-to-slf4j\1.7.32\jul-to-slf4j-1.7.32.jar;C:\Users\shuja\.m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-core\5.3.9\spring-core-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-jcl\5.3.9\spring-jcl-5.3.9.jar;C:\Users\shuja\.m2\repository\org\yaml\snakeyaml\1.28\snakeyaml-1.28.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.5.3\spring-boot-starter-web-2.5.3.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.5.3\spring-boot-starter-json-2.5.3.jar;C:\Users\shuja\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.12.4\jackson-databind-2.12.4.jar;C:\Users\shuja\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.12.4\jackson-annotations-2.12.4.jar;C:\Users\shuja\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.12.4\jackson-core-2.12.4.jar;C:\Users\shuja\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.12.4\jackson-datatype-jdk8-2.12.4.jar;C:\Users\shuja\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.12.4\jackson-datatype-jsr310-2.12.4.jar;C:\Users\shuja\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.12.4\jackson-module-parameter-names-2.12.4.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.5.3\spring-boot-starter-tomcat-2.5.3.jar;C:\Users\shuja\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.50\tomcat-embed-core-9.0.50.jar;C:\Users\shuja\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.50\tomcat-embed-el-9.0.50.jar;C:\Users\shuja\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.50\tomcat-embed-websocket-9.0.50.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-web\5.3.9\spring-web-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-beans\5.3.9\spring-beans-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-webmvc\5.3.9\spring-webmvc-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-aop\5.3.9\spring-aop-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-expression\5.3.9\spring-expression-5.3.9.jar;C:\Users\shuja\.m2\repository\org\thymeleaf\thymeleaf\3.0.12.RELEASE\thymeleaf-3.0.12.RELEASE.jar;C:\Users\shuja\.m2\repository\ognl\ognl\3.1.26\ognl-3.1.26.jar;C:\Users\shuja\.m2\repository\org\javassist\javassist\3.20.0-GA\javassist-3.20.0-GA.jar;C:\Users\shuja\.m2\repository\org\attoparser\attoparser\2.0.5.RELEASE\attoparser-2.0.5.RELEASE.jar;C:\Users\shuja\.m2\repository\org\unbescape\unbescape\1.1.6.RELEASE\unbescape-1.1.6.RELEASE.jar;C:\Users\shuja\.m2\repository\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-thymeleaf\2.5.3\spring-boot-starter-thymeleaf-2.5.3.jar;C:\Users\shuja\.m2\repository\org\thymeleaf\extras\thymeleaf-extras-java8time\3.0.4.RELEASE\thymeleaf-extras-java8time-3.0.4.RELEASE.jar;C:\Users\shuja\.m2\repository\org\thymeleaf\thymeleaf-spring5\3.0.12.RELEASE\thymeleaf-spring5-3.0.12.RELEASE.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.5.3\spring-boot-starter-data-jpa-2.5.3.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.5.3\spring-boot-starter-aop-2.5.3.jar;C:\Users\shuja\.m2\repository\org\aspectj\aspectjweaver\1.9.7\aspectjweaver-1.9.7.jar;C:\Users\shuja\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.5.3\spring-boot-starter-jdbc-2.5.3.jar;C:\Users\shuja\.m2\repository\com\zaxxer\HikariCP\4.0.3\HikariCP-4.0.3.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-jdbc\5.3.9\spring-jdbc-5.3.9.jar;C:\Users\shuja\.m2\repository\jakarta\transaction\jakarta.transaction-api\1.3.3\jakarta.transaction-api-1.3.3.jar;C:\Users\shuja\.m2\repository\jakarta\persistence\jakarta.persistence-api\2.2.3\jakarta.persistence-api-2.2.3.jar;C:\Users\shuja\.m2\repository\org\hibernate\hibernate-core\5.4.32.Final\hibernate-core-5.4.32.Final.jar;C:\Users\shuja\.m2\repository\net\bytebuddy\byte-buddy\1.10.22\byte-buddy-1.10.22.jar;C:\Users\shuja\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\shuja\.m2\repository\org\jboss\jandex\2.2.3.Final\jandex-2.2.3.Final.jar;C:\Users\shuja\.m2\repository\org\dom4j\dom4j\2.1.3\dom4j-2.1.3.jar;C:\Users\shuja\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.2.Final\hibernate-commons-annotations-5.1.2.Final.jar;C:\Users\shuja\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.4\jaxb-runtime-2.3.4.jar;C:\Users\shuja\.m2\repository\org\glassfish\jaxb\txw2\2.3.4\txw2-2.3.4.jar;C:\Users\shuja\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.12\istack-commons-runtime-3.0.12.jar;C:\Users\shuja\.m2\repository\com\sun\activation\jakarta.activation\1.2.2\jakarta.activation-1.2.2.jar;C:\Users\shuja\.m2\repository\org\springframework\data\spring-data-jpa\2.5.3\spring-data-jpa-2.5.3.jar;C:\Users\shuja\.m2\repository\org\springframework\data\spring-data-commons\2.5.3\spring-data-commons-2.5.3.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-orm\5.3.9\spring-orm-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-tx\5.3.9\spring-tx-5.3.9.jar;C:\Users\shuja\.m2\repository\org\springframework\spring-aspects\5.3.9\spring-aspects-5.3.9.jar;C:\Users\shuja\.m2\repository\mysql\mysql-connector-java\8.0.26\mysql-connector-java-8.0.26.jar;C:\Users\shuja\.m2\repository\jakarta\xml\bind\jakarta.xml.bind-api\2.3.3\jakarta.xml.bind-api-2.3.3.jar;C:\Users\shuja\.m2\repository\jakarta\activation\jakarta.activation-api\1.2.2\jakarta.activation-api-1.2.2.jar;C:\Users\shuja\.m2\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;C:\Users\shuja\.m2\repository\org\hibernate\validator\hibernate-validator\6.2.0.Final\hibernate-validator-6.2.0.Final.jar;C:\Users\shuja\.m2\repository\jakarta\validation\jakarta.validation-api\2.0.2\jakarta.validation-api-2.0.2.jar;C:\Users\shuja\.m2\repository\org\jboss\logging\jboss-logging\3.4.2.Final\jboss-logging-3.4.2.Final.jar;C:\Users\shuja\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar mz.painting.com.Application

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.3)

2021-09-07 23:03:00.710  INFO 13304 --- [           main] mz.painting.com.Application              : Starting Application using Java 13.0.1 on DESKTOP-2FIIHFN with PID 13304 (C:\Users\shuja\Desktop\mz\target\classes started by shuja in C:\Users\shuja\Desktop\mz)
2021-09-07 23:03:00.798  INFO 13304 --- [           main] mz.painting.com.Application              : No active profile set, falling back to default profiles: default
2021-09-07 23:03:09.837  INFO 13304 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-09-07 23:03:10.394  INFO 13304 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 475 ms. Found 1 JPA repository interfaces.
2021-09-07 23:03:17.773  INFO 13304 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-09-07 23:03:17.874  INFO 13304 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-09-07 23:03:17.874  INFO 13304 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.50]
2021-09-07 23:03:18.723  INFO 13304 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-09-07 23:03:18.723  INFO 13304 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 16400 ms
2021-09-07 23:03:19.900  INFO 13304 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-09-07 23:03:20.230  INFO 13304 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-09-07 23:03:20.927  INFO 13304 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-09-07 23:03:21.830  INFO 13304 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-09-07 23:03:26.191  INFO 13304 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-09-07 23:03:26.507  INFO 13304 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2021-09-07 23:03:31.234  INFO 13304 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-09-07 23:03:31.296  INFO 13304 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-09-07 23:03:33.646  WARN 13304 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-09-07 23:03:35.159  INFO 13304 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2021-09-07 23:03:35.961  WARN 13304 --- [           main] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2021-09-07 23:03:37.067  INFO 13304 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-09-07 23:03:37.116  INFO 13304 --- [           main] mz.painting.com.Application              : Started Application in 42.214 seconds (JVM running for 50.262)
2021-09-07 23:04:09.649  INFO 13304 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-09-07 23:04:09.649  INFO 13304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-09-07 23:04:09.658  INFO 13304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms
User is in Homepage
2021-09-07 23:04:12.849 ERROR 13304 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "index": Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 86, col 32)

org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 86, col 32)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:366) ~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:190) ~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1397) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1142) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1081) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.50.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.50.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.9.jar:5.3.9]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.9.jar:5.3.9]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.9.jar:5.3.9]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.9.jar:5.3.9]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.50.jar:9.0.50]
    at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306) ~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253) ~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227) ~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174) ~[thymeleaf-spring5-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.12.RELEASE.jar:3.0.12.RELEASE]
    ... 52 common frames omitted

Any idea how to fix this ?  thank you

A: At first glance, the
 is missing the closing tag and Thymeleaf processor may complain about it.
It should be
<input type="text" th:field="*{name}"  placeholder="" />
. Note the ending slash of
.
You cut out the exception message exactly where it would specify the actual cause, namely after with root cause [...]. :)


text:
Q: Show that there is a star for which there are less stars in its column than in its row. In a table there are n columns and m rows, n > m. Some cells are
marked by stars, and in each column there's at least one star. Show
that there is a star for which there are less stars in its column than in
its row.

A: First,
$\underline{Note}$: If the result holds for a matrix $A^{m, m +k}:=B$, it holds for $A^{m, m+k + 1}:=C$, for $k \ge 1$, the same matrix $B$ with a column added.
This is obvious: there is at least one row-column combination in $B$ where the result holds. Adding one or more stars in a new column cannot change this.
So, wlog, one can assume in what follows that the matrix is of form
$$A \in M^{m, m+1}.$$
Note next that the sum of stars $r_i$ in row $i$ and the sum of stars $r^j$ in column $j$ must satisfy.
$$\sum_{i = 1}^m r_i = \sum_{j=1}^{m+1} r^j \quad (1),$$
and that, by construction,
$$r^j \geq 1 \text{ for all j} \quad (2).$$
Now, assume to the contrary that the claim is wrong.  Then
$$r_i \leq r^i \text{ for all i} \quad (3)$$
But then:
$$\begin{align}
\sum_{j=1}^{m+1} r^j & = r^{m+1} + \sum_{j=1}^m r^j \\
& \geq r^{m+1} + \sum_{i=1}^m r_i \quad \text{using (3)} \\
& \gt \sum_{i=1}^m r_i \quad \text{using (2), } \\
\end{align}$$
which contradicts (1). So there is at least one $i$ for which (3) is false, which was to be shown.
Edit (03/04): See Macavity's comment below for how to complete the argument (thank you!).

A: While completing @gnometorule's argument was easier, I thought the following approach is also worth mentioning:
Let $S(i, j)$ denote a function which gives $1$ if there is a star in cell from column $i$ and row $j$, and $0$ otherwise.  Then we have,
$\sum_{i, j} S(i, j) = X$, the total number of stars.
Also if $C_i$ denotes the number of stars in column $i$ and $R_j$ denotes the number of stars in row $j$, we have
$\sum_{i=1}^n C_i = \sum_{j=1}^m R_j = X$
Further, it can be noted that $\sum_j S(i,j) = C_i$ and $\sum_i S(i,j) = R_j$
If all starred cells $(i, j)$ are such that $C_i \ge R_j$,  then
summing over all cells we have:
$\sum_{i, j} (C_i - R_j) S(i, j) \ge 0$
$\implies \sum_{i, j} C_i S(i, j) \ge \sum_{i, j} R_j S(i, j) $
$\implies \sum_{i} C_i C_i \ge \sum_{j} R_j R_j $
$\implies \sum_{i=1}^n C_i^2 \ge \sum_{j=1}^m R_j^2 $
Now, I believe the above inequality is not possible for such column and row sums, i.e. if:
$0 < C_i \le m$ and $0 \le R_j \le n$ with $n > m$, but have not been able to prove it.


text:
Q: Http request inside a loop I'm having some troubles in making a HTTP request inside a loop.
Let me explain what I have....
I make an http GET to retrieve some values and then I need to make another HTTP GET for each couple of values that I've just taken from the first request.
The two calls are ok, and if I cut the for cycle and try to run the whole request chain it works perfectly, but just one time since I removed the cycle. How can I make it work?
Here's the code:
request({
url: "some_url",
    method: "GET",
    json:true,
    headers:[{'content-type': 'application/json'}]
    }, function (error, response, body){
            if(!error & response.statusCode === 200){
                for(var i=0;i<body.length;i++){
                    for(var j=i;j<body.length-1;j++){
                        //if(i === body.length-1) return;
                        src = body[i].name;
                        dest = body[j+1].name;
                        console.log("sorgente ",sorg);

                        request({
                            url: "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+src+"&destinations="+dest,
                            method: "POST",
                            json:true,
                            headers:[{'content-type': 'application/json'}]
                        }, function (error, response, body){
                            if(!error & response.statusCode === 200){
                                console.log("TIME ",body.rows[0].elements[0].duration.text);
                                return;
                            }else{
                                console.log("google API failed!: ");
                                return;
                            }
                        });

                    }
                }

            }else{
                console.log("/google_api failed!: ");
                return;
            }
 });

I hope I was clear with the question.

A: The issue here is one of Javascript scoping, and typos.
First, you hardcoded the array indexes of body[0] and body[1]. It looks like you meant for them to be the loop variables.
Second, an outline of your scoping problem, in simplified pseudo-Javascript:
var requestList = [...];

for(var i = 0; i < requestList.length; i++){
    var current = requestList[i];

    // make a request based on current or the data
    // in current.
    request(..., function(result){
        // do something with the current variable
        current.foo = result.bar;
    });
}

All web requests are asynchronous. There used to be a way to force them to run synchronously, but it is deprecated in most major browsers. This means that the request is made, and may get a response, outside of your actual code, and then calls some sort of callback--in this case, the anonymous inner function function(result){...}.
What this means is that that for loop continues to execute and loop while the request is being made, meaning if the request isn't fast enough, current will update and be different when the request comes back, and so will the for loop variables.

The solution I've run into for this sort of thing is function scoping out the inner request in the for loop.
Instead of making the new request directly inside the for loop, you move that out to its own function:
var requestList = [...];

for(var i = 0; i < requestList.length; i++){
    var current = requestList[i];

    GetMyResourceData(current);
}

function GetMyResourceData(current){
    request(..., function(result){
        // do something with the current variable
        current.foo = result.bar;
    });
}

Every time the GetMyResourceData function is called, a new scope is created for that function, so the current variable in that function is held when you reach the callback.
So, that's what I'd recommend you do for your code. Move the second request outside of the for loop into its own scope.

A: Did you forget to use your looping variables i and j. The code above will keep making requests with body[0] as src and body[1] as dest for the duration of the loop provided body has length >= 2.
Try using https://github.com/caolan/async#forEachOf or https://github.com/caolan/async#each for calling async functions in a loop.


text:
Q: Hahn Banach Application in Cybenko (1989) My understanding of the Hahn-Banach theorem is as follows: given a linear subspace $U$ of $V$, a linear functional $f$ defined on $U$, and a sub-linear functional $p$ which dominates $f$, there exists a linear functional $F$ on $V$ with $F(x) \leq p(x)$ for all $x \in V$ and $F(x) = f(x)$ for $x\in U$.
In Cybenko 1989, the proof of Theorem 1, the first step uses Hahn Banach.  Specifically, $R$ is a proper subspace of $C(I)$ where $I$ is the unit cube, the author states that by the Hahn Banach theorem, there exists a linear functional $L$ on $C(I)$,  with the property that $L\neq 0$ but $L(R) = 0$.
How does this follow from the Hahn Banach theorem?  In particular, why does the Hahn Banach theorem state that there exists an $L$ is not just zero everywhere?  Also, where is the dominating sublinear functional coming into play?

A: This is a consequence of the Hahn Banach theorem. It says that if $F$ is a closed proper subspace of $V$ and $x\in V\setminus F$, then there exists a nonzero $f\in V^*$ which is identically equal to zero on $F$ and such that $f(x)=\text{dist} (x, F)=\delta>0$. You can find its proof in every functional analysis textbook. Basically, the idea is to set $Z=\text{span}\{F, x\}$ and consider the functional $f:Z\rightarrow \mathbb{R}$ for which $f(z)=f(y+\lambda x)= \lambda \delta$, for $z\in Z$. This functional is majorized by the norm on $Z$. Then you apply the usual form of the Hahn-Banach theorem.