text:
Q: Multiprocessing Pool in Python - Only single CPU is utilized Original Question
I am trying to use multiprocessing Pool in Python. This is my code:
def f(x):
    return x

def foo():
    p = multiprocessing.Pool()
    mapper = p.imap_unordered

    for x in xrange(1, 11):
        res = list(mapper(f,bar(x)))

This code makes use of all CPUs (I have 8 CPUs) when the xrange is small like xrange(1, 6). However, when I increase the range to xrange(1, 10). I observe that only 1 CPU is running at 100% while the rest are just idling. What could be the reason? Is it because, when I increase the range, the OS shutdowns the CPUs due to overheating?
How can I resolve this problem?
minimal, complete, verifiable example
To replicate my problem, I have created this example: Its a simple ngram generation from a string problem.
#!/usr/bin/python

import time
import itertools
import threading
import multiprocessing
import random

def f(x):
    return x

def ngrams(input_tmp, n):
    input = input_tmp.split()

    if n > len(input):
        n = len(input)

    output = []
    for i in range(len(input)-n+1):
        output.append(input[i:i+n])
    return output

def foo():

    p = multiprocessing.Pool()
    mapper = p.imap_unordered

    num = 100000000 #100
    rand_list = random.sample(xrange(100000000), num)

    rand_str = ' '.join(str(i) for i in rand_list)

    for n in xrange(1, 100):
        res = list(mapper(f, ngrams(rand_str, n)))

if __name__ == '__main__':
    start = time.time()
    foo()
    print 'Total time taken: '+str(time.time() - start)

When num is small (e.g., num = 10000), I find that all 8 CPUs are utilised. However, when num is substantially large (e.g.,num = 100000000). Only 2 CPUs are used and rest are idling. This is my problem.
Caution: When num is too large it may crash your system/VM.

A: First, ngrams itself takes a lot of time. While that's happening, it's obviously only one one core. But even when that finishes (which is very easy to test by just moving the ngrams call outside the mapper and throwing a print in before and after it), you're still only using one core. I get 1 core at 100% and the other cores all around 2%.
If you try the same thing in Python 3.4, things are a little different—I still get 1 core at 100%, but the others are at 15-25%.
So, what's happening? Well, in multiprocessing, there's always some overhead for passing parameters and returning values. And in your case, that overhead completely swamps the actual work, which is just return x.
Here's how the overhead works: The main process has to pickle the values, then put them on a queue, then wait for values on another queue and unpickle them. Each child process waits on the first queue, unpickles values, does your do-nothing work, pickles the values, and puts them on the other queue. Access to the queues has to be synchronized (by a POSIX semaphore on most non-Windows platforms, I think an NT kernel mutex on Windows).
From what I can tell, your processes are spending over 99% of their time waiting on the queue or reading or writing it.
This isn't too unexpected, given that you have a large amount of data to process, and no computation at all beyond pickling and unpickling that data.
If you look at the source for SimpleQueue in CPython 2.7, the pickling and unpickling happens with the lock held. So, pretty much all the work any of your background processes do happens with the lock held, meaning they all end up serialized on a single core.
But in CPython 3.4, the pickling and unpickling happens outside the lock. And apparently that's enough work to use up 15-25% of a core. (I believe this change happened in 3.2, but I'm too lazy to track it down.)
Still, even on 3.4, you're spending far more time waiting for access to the queue than doing anything, even the multiprocessing overhead. Which is why the cores only get up to 25%.
And of course you're spending orders of magnitude more time on the overhead than the actual work, which makes this not a great test, unless you're trying to test the maximum throughput you can get out of a particular multiprocessing implementation on your machine or something.
A few observations:

*

*In your real code, if you can find a way to batch up larger tasks (explicitly—just relying on chunksize=1000 or the like here won't help), that would probably solve most of your problem.

*If your giant array (or whatever) never actually changes, you may be able to pass it in the pool initializer, instead of in each task, which would pretty much eliminate the problem.

*If it does change, but only from the main process side, it may be worth sharing rather than passing the data.

*If you need to mutate it from the child processes, see if there's a way to partition the data so each task can own a slice without contention.

*Even if you need fully-contended shared memory with explicit locking, it may still be better than passing something this huge around.

*It may be worth getting a backport of the 3.2+ version of multiprocessing or one of the third-party multiprocessing libraries off PyPI (or upgrading to Python 3.x), just to move the pickling out of the lock.

A: The problem is that your f() function (which is the one running on separate processes) is doing nothing special, hence it is not putting load on the CPU.
ngrams(), on the other hand, is doing some "heavy" computation, but you are calling this function on the main process, not in the pool.
To make things clearer, consider that this piece of code...
for n in xrange(1, 100):
    res = list(mapper(f, ngrams(rand_str, n)))

...is equivalent to this:
for n in xrange(1, 100):
    arg = ngrams(rand_str, n)
    res = list(mapper(f, arg))

Also the following is a CPU-intensive operation that is being performed on your main process:
num = 100000000
rand_list = random.sample(xrange(100000000), num)

You should either change your code so that sample() and ngrams() are called inside the pool, or change f() so that it does something CPU-intensive, and you'll see a high load on all of your CPUs.


text:
Q: How to skip a step execution from beforeStep method in StepExecutionListener? I´d like to implement a generic StepExecutionListener for any step so in the beforeStep method (that is to say, before the current step tasklet started) it could check some database related conditions: if not succeeded, it would skip the current step and continue with the next one.
Under the:
public void beforeStep(StepExecution stepExecution)

at the moment I didn´t find anything in "stepExecution" object to do that. I just get to change the exit status to COMPLETED, but still the corresponding tasklet executes.
Is there a way to achieve this? I´ve also heard about deciders, but I don´t like adding too much verbose configuration on my XML.
Thanks in advance.

A: Deciders are a better option in this case, as their sole purpose is to decide wether to execute your step or not. They do make the xml verbose but that is better as someone else ca understand at the first glance.
The only way I think beforeStep can handle this is if you throuw an exception whene the task name is of the one you want to ignore. Your next step however may need to be configured to run even if previous step fails (Not recommended if that is not exactly what you want when the step is not skipped).
Although, handling in beforeStep will become a lot cumbersome if your task expands and you need to decide for 3-4 steps.
Let me know what you go with!
EDIT:
Example on usage of deciders along with steps
<batch:decision id="decider1" decider="deciderClass1">
        <batch:next on="FAILED" to="decider2" />
        <batch:next on="COMPLETED" to="task1"/>
    </batch:decision>
    <batch:step id="step1" next="decider2" parent="step1Class"/>

    <batch:decision id="decider2" decider="deciderClass2">
        <batch:next on="FAILED" to="step3" />
        <batch:next on="COMPLETED" to="step2"/>
    </batch:decision>
    <batch:step id="step2" parent="step2Class" next="step3"/>
.....

A: I´ll answer to myself in order to introduce some code.
Following the proposal of Priteesh I defined one Decider like this:
    <decision id="deciderId" decider="deciderDeclaration">
        <next on="CONTINUE" to="step1" />
        <next on="SKIP" to="finalStep" />
    </decision>

Putting it at first place in my context.xml. This is important because step1 doesn´t execute ever if the conditions are not met.
And my decider is something like this:
public class StepExecutionDecider implements JobExecutionDecider{

    /** LOGGER. */
    private Logger LOGGER = ...

    private static final String FLOW_STATUS_CONTINUE = "CONTINUE";
    private static final String FLOW_STATUS_SKIP = "SKIP";

    @Override
    public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) {

        String status = FLOW_STATUS_CONTINUE;

        String condition = ....

        if (Constants.NO.equals(condition)){

            LOGGER.warn(jobExecution.getJobInstance().getJobName(), " -> The Step execution is disabled. Continuing with the next Step.");

            status = FLOW_STATUS_SKIP;
        }

        return new FlowExecutionStatus(status);
    }

    ...
}

The strange thing is that, whenever my condition is not met, the LOGGER message is printed twice in my log, with exactly the same timestamp...
Anyway, thank you very much Priteesh for your kind help.

A: I had the same goal: use beforeStep() in the StepExecutionListener to check non-spring batch related conditions to decide if the step should run or not.
What doesn't work
Using a decider (JobExecutionDecider) does not work because JobExecutionDecider.decide() receives as parameter the step previously executed. The purpose of the decider is to allow you to check the status of the previous step execution to choose what to do next. If I'm testing a condition that is specific to StepXYZ, I need to have that step execution at hand before it's executed.
Well, StepExecutionListener.execute() puts StepXyz  execution on your hand prior to execution. It sounds promising... However, the API does not have any mechanism to tell spring batch not to run StepXyz. To illustrate the point, none of the statements below will do what we want.
stepExecution.status = BatchStatus.ABANDONED
stepExecution.exitStatus = ExitStatus.NOOP
stepExecution.setTerminateOnly()

Conclusion
After searching all around the framework code, SO, and the spring documentation, my conclusion is:

One cannot use beforeStep() to gracefully tell spring batch not to run that step.

(I'm using Spring Boot 2.3.9.)
My simple solution
In my case the condition to be tested is one or more feature flags. I already had a FeatureFlags Component, so I injected it into the tasklets and tested the pre-condition at the start of execute():
override fun execute(contribution: StepContribution, chunkContext: ChunkContext): RepeatStatus? {
    if (!featureFlags.stepShouldRun) {
        contribution.exitStatus = ExitStatus("SKIPPED BASED ON FEATURE FLAGS")
        return RepeatStatus.FINISHED
    }
    return execute()
}

fun execute(): RepeatStatus {
    // the actual step logic goes here
    // add StepContribution as a param if necessary
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't javascript/jquery-feature be applied to multiple nodes? I have a small javascript that changes the title of a input-field to it's value and some other stuff:
  function autoFill(id){
   if(jQuery(id).val()==""){
                    jQuery(id).val(jQuery(id).attr("title"))
                    .addClass("help");
             };
    jQuery(id).focus(function(){
    if(jQuery(this).val()==jQuery(this).attr("title")){
     jQuery(this).val("").removeClass("help");
    }
   })
   .blur(function(){
    if(jQuery(this).val()==""){
     jQuery(this).val(jQuery(this).attr("title"))
     .addClass("help");

    }
   });
   jQuery(".trip").submit(function(){
    if(jQuery(id).val() == jQuery(id).attr("title")){
    jQuery(id).val('');
  }

 });
  }

When I try to use this script on a class that is on several nodes on one page it only works on the first. For example:
autoFill(".field");

Now I have to make it like this instead:
 autoFill("#driver_from");
  autoFill("#driver_to");
  autoFill("#driver_when");
  autoFill("#passenger_from");
  autoFill("#passenger_to");
  autoFill("#passenger_when");

how do I make it so that it works on every field instead?

A: Something like this would work:
function autoFill(selector){
  jQuery(selector).each(function() {
    if(jQuery(this).val() == "") {
      jQuery(this).val(jQuery(this).attr("title"))
                  .addClass("help");
    };
    jQuery(".trip").submit(function(){
      if(jQuery(this).val() == jQuery(this).attr("title")) {
         jQuery(this).val('');
      }
    });
  }).focus(function(){
     if(jQuery(this).val() == jQuery(this).attr("title")) {
        jQuery(this).val("").removeClass("help");
     }
  }).blur(function(){
     if(jQuery(this).val() == "") {
        jQuery(this).val(jQuery(this).attr("title"))
                    .addClass("help");
     }
  });
}

The important part is the .val() check at the beginning, it's getting the .val() of the first match, you need to handle each separately.

Or, rewrite it as a plugin like this:
(function($) {
  $.fn.autoFill = function() {
     return this.each(function() {
       $(".trip").submit(function(){
         if($(this).val() == $(this).attr("title")) {
           $(this).val('');
         }
       });
     }).focus(function(){
        if($(this).val() == $(this).attr("title")) {
           $(this).val("").removeClass("help");
        }
     }).blur(function(){
        if($(this).val() == "") {
           $(this).val($(this).attr("title")).addClass("help");
        }
     }).blur();
  };
})(jQuery);

Then you can call it like this:
$(".field").autoFill();


text:
Q: How can I apply a limit on input(not more than 20 letters) and the input value can be just alphabet? def save_load_page():
    bg = pygame.image.load(resource_path("./Game_Assets/Backgrounds/menu_background.png"))
    bg = pygame.transform.scale(bg,(900,600))
    ogre_set = pygame.image.load(resource_path("./Game_Assets/Character_Name/Ogre_Character_Overview.png"))
    ogre_set = pygame.transform.scale(ogre_set,(844,420))

    name_input = ''
    change_click = False
    click = False
    while True:
        mx, my = pygame.mouse.get_pos()
        screen.blit(bg,(0,0))
        screen.blit(ogre_set,(22,140))
        text_surface = base_font.render(name_input,True,(255,255,255))
        screen.blit(text_surface,(60, 445))
        # Logic goes here

        change_click = False
        click = False
        # Event Collections
        for event in pygame.event.get():
            # Function to quit game
            '''if event.type == QUIT:
                event.quit()
                sys.exit()'''
            if event.type == KEYDOWN:
                if event.key == K_RETURN:
                    pass
                elif event.key == K_KP_ENTER:
                    ogre1_name = name_input
                    break
                elif event.unicode == K_alpha:
                    name_input += event.Ascii
                    if len(name_input) <= 21:
                        pass
                while name == '' or len(name) > 20 or name in names_list:
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    change_click = True
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    click = True

        pygame.display.update()
        clock.tick(120)

A: You have to evaluate if the length of the text is less than 20, before you add the new character. isalpha()  can be used to test whether a character is a letter (see How can I check if character in a string is a letter?):
if event.type == KEYDOWN:
    if event.key == K_RETURN:
        # [...]
    elif event.key == K_KP_ENTER:
        # [...]

    elif len(name_input) < 20 and event.unicode.isalpha():
        name_input += event.unicode


text:
Q: Position a JFrame I have a simple question. How do I set the position of a JFrame on the screen? When I use setVisible(), I want the window to appear in a certain location on the screen, perhaps by x-y coordinates. Is it possible?
EDIT: I found the solution. I had to call setLocationByOs(false) or something like that, then use setLocation(x,y)

A: Try this:
        final Dimension d = this.getToolkit().getScreenSize();
        this.setLocation((int) ((d.getWidth() - this.getWidth()) / 2), (int) ((d.getHeight() - this.getHeight()) / 2));

This lets the JFrame appear in the center of every screen.

A: Try searching for an existing answer before asking a new question. Entering your question into the StackOverflow search box would easily have given you an answer.
When you initialize your form just put setLocation(int x, int y); on the line after you call pack();
pack();
setLocation(int x, int y);

See here for a more in depth answer: Best practice for setting JFrame locations
When looking for a method, you can often find it in the JavaDocs, for example the answer to your question: http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setLocation%28int,%20int%29

A: There are many different ways you could approach this. Below is how I usually setup my JFrames:
import java.awt.Canvas;
import javax.swing.JFrame;

public class Window extends Canvas{
    public Window(Launcher launcher){
        JFrame frame = new JFrame("Example");
        frame.setSize(800,480);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(launcher);
        frame.setVisible(true);
        launcher.setFrame(frame);
    }
}

This class is initialized by Launcher which extends Canvas implements Runnable and uses threading.
frame.setLocationRelativeTo(null); is the magic word.


text:
Q: Send Webm buffer to php server I'm recording video and audio from the browser using MediaRecorder. After I finish recording I try to upload it to the server with something like this:
function upload() {
  var fileName = 'video.webm';
  var formData = new FormData();
  formData.append('filename', fileName);
  formData.append('blob', blobs);
  $.ajax({
    type: 'POST',
    url: '/upload.php',
    data: formData,
    processData: false,
    contentType: false
  }).done(function(data) {
       console.log(data);
  });

  xhr('upload.php', formData, function (fName) {
    window.open(location.href + fName);
  });

  function xhr(url, data, callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
          alert('Done');
        }
    };
    request.open('POST', url);
    request.send(data);
  }
}

Apparently the $_FILES variable doesn't get set in php, but the $_POST does. The file name has been passed correctly, but if I output the blobs to a file, I'm not able to reproduce the file in an html5 video object, so I guess something is wrong with that.
Could anyone explain what's the best way to accomplish this upload?
Thanks


text:
Q: still troubled by escaping HTML in bookdown and markdown A more complete, and corrected version of a question from earlier.
I am trying to do the following using rmarkdown and bookdown:

*

*process a saved image as a text-wrap-around in HTML. I have a CSS definition that works perfectly:

<aside class="marginfigure">
<3 ticks>{r rabbit, fig.cap="Kuhn's favorite example.",  echo=FALSE,dev='png'}
knitr::include_graphics('./images/0_Introduction/Duck-Rabbit_illusion.jpg')
<3 ticks>
</aside>

*Process that same block as text-wrap in the LaTeX export. I have a wrapfig setup in the preamble that works perfectly from bookdown as well:

\begin{wrapfigure}{R}{.45\textwidth}
  \begin{center}
    \includegraphics[width=.40\textwidth]{./images/0_Introduction/Duck-Rabbit_illusion.jpg}
    \captionsetup{style=figures}
    \caption{Kuhn's favorite example.}
  \end{center}
\end{wrapfigure}

This works perfectly.

*My goal is to have both processes aimed at both outputs in the same build and I'm prepared to repeat instructions in my source, like:

<!--.........................................-->

<aside class="marginfigure">
<3 ticks>{r rabbit, fig.cap="Kuhn's favorite example.",  echo=FALSE,dev='png'}
knitr::include_graphics('./images/0_Introduction/Duck-Rabbit_illusion.jpg')
<3 ticks>
</aside>

<!--.................-->

\begin{wrapfigure}{R}{.45\textwidth}
  \begin{center}
    \includegraphics[width=.40\textwidth]{./images/0_Introduction/Duck-Rabbit_illusion.jpg}
    \captionsetup{style=figures}
    \caption{Kuhn's favorite example.}
  \end{center}
\end{wrapfigure}

<!--.........................................-->

If I do that, then the LaTeX "distillation" by pandoc from bookdown is properly ignored and the HTML result is perfect.
However, the pdflatex distillation by pandoc does not ignore the HTML stuff and takes the :include_graphics('./images/0_Introduction/Duck-Rabbit_illusion.jpg instruction from knitr as the LaTeX instruction to render that image...a second time, and of course, full-width.
I found that the pandoc exception:
`<aside class="marginfigure">
<3 ticks>{r rabbit, fig.cap="Kuhn's favorite example.",  echo=FALSE,dev='png'}
knitr::include_graphics('./images/0_Introduction/Duck-Rabbit_illusion.jpg')
<3 ticks>
</aside>`{=html}

Properly escapes the HTML code in the LaTeX distillation, but the figure number in the knitr outcome is then ignored and instead the figure caption comes out: (#fig:rabbit)Kuhn's favorite example.
The only way I can find to have the figure caption properly number the figure in the HTML result is to insert a blank line after :
`<aside class="marginfigure">

<3 ticks>{r rabbit, fig.cap="Kuhn's favorite example.",  echo=FALSE,dev='png'}
knitr::include_graphics('./images/0_Introduction/Duck-Rabbit_illusion.jpg')
<3 ticks>
</aside>`{=html}

But this then makes LaTeX spit out some of the {=html} characters and again give a second figure.
It would be great if it was possible to have tags that tell bookdown to ignore everything betwen the tags in the HTML or LaTeX processing.
Or, it would be great if ignoring the blank line could not break the figure numbering in the caption.
Am I missing something obvious?


text:
Q: Group of order $p^2q^n$, $q\neq 3$, $p,q$ prime. Let $p,q$ be prime numbers, $q \neq 3$, and $G$ be a group with order $p^2q^n$. Prove that $G$ has a normal subgroup with order $q^n$. Prove that $G$ is a semidrect product of a group with order $q^n$ and a group with order $p^2$.
My attempt:
For $n \geq 2$, $q^n>p^2$ and we have a unique $q$-sylow group, thus, we have our normal subgroup. I'm having some problems to show that the group is normal when $n=1$, but I think I can handle this.
For the semidirect product I don't know what I can do, any hint?

A: This is not true when $p \gt q$: take $G=S_3 \times C_6$, so a group of order $36=3^2 \cdot 2^2$, hence $p=3, q=2=n$. A Sylow $2$-subgroup of $G$ is not normal.
But it is true when $p \lt q$. Let $Q \in Syl_q(G)$, then $n_q(G) \in \{1,p,p^2\}$. If $n_q(G)=p$, then $p \equiv 1$ mod $q$, hence $q \leq p-1 \lt p \lt q$, which is absurd.
If $n_q(G)=p^2$, then $q \mid p^2-1=(p-1)(p+1)$, hence by the previous argument $q \mid p+1$, but $p \lt q$, so this can only happen when $q=p+1$, meaning $p=2$ and $q=3$, contradicting $q \neq 3$.
So $Q \lhd G$, and if $P \in Syl_p(G)$, $PQ$ is actually a subgroup, but then $G=PQ$ and $P \cap Q=1$, so $G$ is a semi-direct product $P \ltimes Q$.


text:
Q: Where can the Sources\SxS" folder be obtained from? I am getting an error when I run this command in PowerShell:
Install-WindowsFeature -Name Web-Net-Ext -source D:\Sources\SxS

Install-WindowsFeature : The request to add or remove features on the
  specified server failed. Installation of one or more roles, role
  services, or features failed. The source files could not be found.

Every article and blog I've read says that that path needs to be specified. How can a reference to this folder be obtained?

A: Figured it out

*

*Download the .ISO for Windows Server 2016 (could be the 180 day evaluation version).
https://www.microsoft.com/en-us/evalcenter/evaluate-windows-server-2016

*Mount the .ISO as a drive.

this is mounted by default to D:

*Copy the /sources/sxs folder to wherever it needs to go. by default, the SxS file will be at D:\Sources\SxS

*run the command :D
Install-WindowsFeature -Name Web-Net-Ext -source D:\Sources\SxS

A: The source parameter defines the folder where your windows installation media / feature files are stored. The parameter itself is optional and the command should work without specifying the source.
Here's the documentation for the cmdlet.

A: @cataster the sxs folder is in windows server installation files


text:
Q: can't fetch base64 of image created using PHP using fopen and file_get_contents? So, what I want is where user can upload image, a PHP script will add watermark to it,a nd the pic will be hosted on imgur using imgur API
Adding watermark to the image and hosting it to imgur is not the problem, but the problem is: to upload image to imgur, we must pass the base64 of the picture, and I can't fetch the pic that has been given watermark by PHP script using file_get_contents and fopen, it always gives error
Someone please help me with the problem so I can fetch the image, encode it to base64
That's all
UPDATE:
Just to tell you, i used the function to open the PHP file DIRECTLY without saving the pic to disk first, for some reason i can't save the image to the disk, that's why i use imgur
UPDATE AGAIN:
here's my code:
<?php
    header('Content-type: image/png');
    $image = $_GET['url'];
    $imagesize = getimagesize($image);
    $img = imagecreatetruecolor($imagesize[0], $imagesize[1] + 50);
    imagecopy($img, imagecreatefrompng($image), 0, 0, 0, 0, $imagesize[0], $imagesize[1]);
    $string = "Some wild watermarks";
    $font = "font.ttf";
    $fontSize="30";
    $textColor = imagecolorallocate($img, 255,255,255);
    $x=7;
    $y=$imagesize[1] + 42;
    imagettftext($img,$fontSize,0,$x,$y,$textColor,$font,$string);
    imagepng($img);
?>

Here's the error i got:
Using file_get_contents:
Warning: file_get_contents(watermark.php?url=roughdesign.png) [function.file-get-contents]: failed to open stream: Result too large in URL

Using fopen:
Warning: fopen(watermark.php?url=roughdesign.png) [function.fopen]: failed to open stream: Result too large in URL
Warning: filesize() [function.filesize]: stat failed for URL
Warning: fread(): supplied argument is not a valid stream resource in URL

A: You can try this-
<?php
function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}
?>

You can find more info on base64_encode
OR
Alternatively you can do this-
$imageContent= file_get_contents($yourImage);
$encoded = base64_encode($imageContent);

A: Simple pseudo code idea

*

*Open image and add watermark in accordance to http://php.net/manual/en/image.examples-watermark.php

*Save your newly created image (which includ ethe watermark) to disk

*Calculate base64 of the newly created file

This should work fine. If you get any errors state what they say and where you get them.


text:
Q: Determining whether or not a set contains an element, and proving set equalities. I have two problems that are giving me a bit of a difficulty. I've already completed one of them, but I have a feeling I'm doing something wrong, and would greatly appreciate feedback. For the other one, I'm lost entirely.
For each of the following sets, determine whether 4 is an element of that set.

a) {x ∈ R | x is an integer greater than 4}

b) {x ∈ R | x is the square of an integer|

c) {4,{4}}

d) {{4},{{4}}}

e) {{4},{4,{4}}}

f) {{{4}}}

I answered as the following:
a. As x is greater than 4, 4 is not in the set.
b. If the integer is 2, the square of 2 is 4, meaning that 4 is an element of the set. (Truthfully, I'm on the fence about this. How do I know that the square is 2?)
c. The set contains the value 4, and the subset {4}. 4 is in the set.
d. The set contains the subsets {4} and {{4}}. 4 is not an element in the set. (I assume that {4} isn't the same as 4)
e. The set contains the subset {4} and {4,{4}}. 4 is an element of the subset, but not the set.
f. The set consists wholly of the subset {{{4}}}. 4 is not an element.
The second problem I'm lost on completely is
Prove or disprove:
A - (B n C) = (A-B) u (A-C)

I know that A is equivalent to (A u A), so I can go from
A- (B n C) = (A-B) u (A-C)
   (A u A) - (B n C) = (A-B) u (A-C)
But from there, I'm lost. I don't even know how A-B or A-C would translate into anything else, so any assistance would be greatly, greatly appreciated.

A: Your logic in 1 is fine.  For part 2,  to prove two sets are equal, show they are subsets of each other.
So, assume $x\in A-(B\cap C)$  Xo,  $x\in A$  and $x\notin (B\cap C)$  Thus,  we have $x\notin B$ or $x\notin C$ along with $x\in A$.  thus,  we have $x\in A-B$ or $x\in A-C$
Hence, $x\in (A-B)\cup(A-C)$
To argue the reverse, just start with an element of the right hand side and follow the same logic backward to the left hand side

A: For your set equality,
draw a Venn diagram with
circles for A, B, and C.
You can then visually see
what the two sides are
and why they are equal.


text:
Q: Using robocopy /NP writes odd sequence around percentage I am using robocopy with /NP and capturing stdout and stderr using >>log.txt 2>&1. I am copying all files from the "Outbound" directory to an "Archive" directory.
robocopy "%PNAME%\Outbound" "%ARCHIVE_PATH%" * /NP /MT:32

The output appears to contain character sequences that are classic problems with DOS vs. UNIX line endings.
New File            3381    DIM_DATE_CCYYMM.txt^M  0%  ^M100%
New File          340759    DIM_DATE_CCYYMMDD_PAID_DT.txt^M100%
New File          340730    DIM_DATE_CCYYMMDD_SVC_DT.txt^M100%

Looking into the log file, there are indeed instances of 0x0D which are not followed by 0x0A. Is this just the way Microsoft envisioned the output? Can I do anything to change it short of manipulating the log file post-production?
000670    64    5c    0d    0a    09    20    20    20    20    4e    65    77    20    46    69    6c
         d   \  \r  \n  \t                   N   e   w       F   i   l
000680    65    20    20    09    09    20    20    20    20    33    33    38    31    09    44    49
         e          \t  \t                   3   3   8   1  \t   D   I
000690    4d    5f    44    41    54    45    5f    43    43    59    59    4d    4d    2e    74    78
         M   _   D   A   T   E   _   C   C   Y   Y   M   M   .   t   x
0006a0    74    0d    20    20    30    25    20    20    0d    31    30    30    25    20    20    0d
         t  \r           0   %          \r   1   0   0   %          \r
0006b0    0a    09    20    20    20    20    4e    65    77    20    46    69    6c    65    20    20
        \n  \t                   N   e   w       F   i   l   e


text:
Q: Proving not equicontinuity in $\Bbb R$ but equicontinuity in any other closed subset of $\Bbb R$ Let $F = {f_{n} | n ∈\Bbb N }$ be an infinite collection of functions $f_{n}(x)=e^{−n(x−n)^2} , x ∈ \Bbb R$. Prove that $F$ is not equicontinuous on $\Bbb R$ but equicontinuous on $[−a, a]$ for any $a > 0$.
I am trying a modified proof (Initially I posted a proof but didn't reach any conclusions):
First proving not equicontinuous on $\Bbb R$,
$f_{n}(x)=e^{−n(x−n)^2}$
Let $\epsilon =1/2$. let $x=n$
Then, for $|n-y|<\delta$ , we have $|f_{n}(n)-f_{n}(y)|$=$|1-e^{-n(y-n)^2}|\leq 1$.
For $n$ large enough, $|f_{n}(n)-f_{n}(y)|=1>\epsilon$ . So $f_{n}$ is not equicontinuous on $\Bbb R$.
Now proving equicontinuous on $[-a,a], a>0$,
Here lets use the fact that on a compact set, if $f_{n}$ is continuous and if $f_{n}$ converges uniformly on the compact set, then it is equicontinuous on the compact set.
So lets prove that $f_{n}$ converges uniformly on $[-a,a]$. To do this lets first look at the following:
Given an interval $[-a,a]$ and  any $\epsilon>0$.
The pointwise limit of $f_{n}$ is $0$.
Now, what I need to show for uniform convergence is the following:
$$|f_{n}(x)-0|<\epsilon \implies |e^{-n(x-n)^2}|<\epsilon \implies |{n(x-n)^2}|<ln (\epsilon) $$
$$\implies n-\sqrt(ln \epsilon/n)\leq x \leq n+\sqrt(ln \epsilon/n)$$
So for any $a>0$, I can always choose $n$ such that the above condition is satisfied, i.e., $n>a$. hence, $F_{n}$ is equicontinuous on $[-a,a]$
Please check if it is correct. Else suggest a suitable proof.


text:
Q: Java HashSet performance I understand HashSet based on HashMap, since they are pretty similar. It makes the code more flexible and minimizes implementation effort. However, one reference variable in the HashSet's Entry seem to be unnecessary for me if the class forbids null element, therefore the whole Entry makes no point. Despite this fact, an Entry takes 24 byte memory / element, whereas a single array with the set's elements would take only 4 byte / element if my figures are correct. (aside from array's header)
If my argument is correct, does the advantages really overweight this performance hit?
(if i am wrong, i would learn from it aswell)

A: Though this question is primarily opinion-based, I'll summarize a few points on the topic:

*

*HashSet appeared in Java 1.2 many years ago. It's hard to guess now the exact reasons for design decisions made at that times, but clearly Java wasn't used for high-loaded applications; performance played less role than simplicity.

*You are right that HashSet is suboptimal in its memory consumption. The problem is known, the bug JDK-6624565 is registered, and discussions at core-libs-dev are held from time to time. But is this a blocker for many real world applications? Probably, no.

*For those uncommon applications where HashSet memory usage is unacceptable, there are already good alternatives, like trove THashSet.

*Note that open addressing algorithms has their disadvantages, e.g. significant performance degradation with load factors close to 1; element removal difficulties. See the related answer.


text:
Q: Uable to declare a char string properly in C #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  int i, j,
      matriz[4][4] = {0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, l, c,
      matrizcontrolo[4][4] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      ponto = 0, ntentativa = 0;
  const char array1[4][4] = {"0000", "0000", "0000", "0000"};
  for (i = 0; i < 4; i++) {
    do {
      printf("Tentativa %d\n", ntentativa + 1);
      do {
        printf("Linha:\n");

        scanf("%d", &l);
      } while (l < 1 || l > 4);
      do {
        printf("Coluna:\n");
        scanf("%d", &c);
      } while (c < 1 || c > 4);
    } while (matrizcontrolo[l][c] == 1);
    if (matriz[l - 1][c - 1] == 0) {
      printf("Splash!\n");
      strcpy(array1[l - 1][c - 1], "x");
    } else {
      printf("Boom!\n");
      ponto = ponto + 2;
      i--;
      strcpy(array1[l - 1][c - 1], "S");
    }
    matrizcontrolo[l][c] = 1;
    ntentativa++;
  }
  printf("O campo de batalha foi\n");
  for (i = 0; i < 4; i++) {
    printf("\n");
    printf("%s ", *array1[i]);
  }
  if (ponto == 8) {
    printf("Parabéns, acertou em todos os barcos e a sua pontuação foi de %d",
           ponto);
  }
  return 0;
}

I receive an error which states:
main.c:31:20: warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]
/usr/include/string.h:129:14: note: expected 'char * restrict' but argument is of type 'char'
main.c:37:20: warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast [-Wint-conversion]
/usr/include/string.h:129:14: note: expected 'char * restrict' but argument is of type 'char'
main.c:45:18: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]
And then it just simply:
Segmentation fault (core dumped)
When I try to run the program by inserting values in the matriz variable.
Can someone help me out?
Thanks in advance!

A: Honestly, I'm not sure what exactly is the logic and goal behind your program. But the problems are clear, and they all are solvable:

*

*In this syntax:
strcpy(array1[l - 1][c - 1], "x");

When you access the two-dimensional array with two subscript operators, it is no longer referred to as a pointer, but the type char. Whereas, the strcpy() asks you the following parameter:
char *strcpy(char *dest, const char *src);

You need to pass array1[] (char*), not array1[][] (char). In simple, you don't need strcpy() function:
array[l - 1][c - 1] = 'x';

*You don't have sufficient rooms in the defined two-dimensional array. There is always a null-terminated character that is put at the end of each string. Thus, instead of providing 4 for 0000, increase it by one, i.e. 5, and similarly with others that are a type of char[] or char[][].

*In the following statement:
matriz[4][4] = {0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}

You're initializing the 2-D array in an incorrect way. You need to make it with nested-braces:
matriz[4][4] = {{0, 0, 1, 1}, {0, 0, 0, 0}, {1, 1, 0, 0}, {0, 0, 0, 0}}

Do the same with matrizcontrolo[][].

*You need not put an asterisk to dereference this:
printf("%s ", *array1[i]);
              ^^^___ remove the asterisk

A: The bad news is you're using strcpy wrong. The good news is you don't need to use it anyway.
Fyi, strcpy requires a non-const target buffer sufficient to store the source string you're copying, and including one additional spot for the terminating nullchar. you're targeting a single char, not a char*
Additionally, your string buffers are all undersized. A string "0000" requires five characters for storage: four of the string, plus one for the terminating nullchar.
Finally, the string buffer array cannot be const. You're going to be changing data in those rows.
This code shouldn't be using strcpy anywhere. All you're really trying to do is set specific characters in terminated string to specific values. C provides a way to do that: assignment. A modified version of your program is below. I cannot attest to whether the game play is correct or not, but it addresses the specific issue you're having regarding your reported errors, and shows you how direct cell-assignment is what you're really after.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int i, j, l, c, ponto = 0, ntentativa = 0;

    int matriz[][4] = {
        {0, 0, 1, 1},
        {0, 0, 0, 0},
        {1, 1, 0, 0},
        {0, 0, 0, 0}
    };

    int matrizcontrolo[][4] = {
        {0, 0, 0, 0},
        {0, 0, 0, 0},
        {0, 0, 0, 0},
        {0, 0, 0, 0}
    };

    char array1[][5] = {
        "0000",
        "0000",
        "0000",
        "0000"
    };

    for (i = 0; i < 4; i++)
    {
        do
        {
            printf("Tentativa %d\n", ntentativa + 1);
            do
            {
                printf("Linha:\n");
                scanf("%d", &l);
            } while (l < 1 || l > 4);
            do
            {
                printf("Coluna:\n");
                scanf("%d", &c);
            } while (c < 1 || c > 4);
        } while (matrizcontrolo[l][c] == 1);

        if (matriz[l - 1][c - 1] == 0)
        {
            printf("Splash!\n");
            array1[l-1][c-1] = 'x';
        }
        else
        {
            printf("Boom!\n");
            ponto = ponto + 2;
            i--;
            array1[l - 1][c - 1]= 'S';
        }
        matrizcontrolo[l][c] = 1;
        ntentativa++;
    }

    printf("O campo de batalha foi\n");
    for (i = 0; i < 4; i++)
    {
        puts(array1[i]);
    }

    if (ponto == 8)
    {
        printf("Parabéns, acertou em todos os barcos e a sua pontuação foi de %d",
               ponto);
    }
    return 0;
}


text:
Q: Java 6 Annotations Repeating with or without parameter I have the following annotation:
public @interface ExcludeVariable {
    String list();
}

I want to be able preprocessing this in two different ways
First:
@ExcludeVariable // without parameter
int a;

Second:
@ExcludeVariable(list="a,b") // with parameter
public void test(){
     int a;
     int b;
     int c;
}

In Java 8 there is an option to "repeat" annotations
http://docs.oracle.com/javase/tutorial/java/annotations/repeating.html
How to handle this in Java 6
Best regards

A: Use "default". Read more here
public @interface ExcludeVariable {
    String list() default "";
}


text:
Q: Extracting rows based on list of target words in a certain column I have a list of fundamental frequency data taken from full sentences, such that I have values for different times (50 time points per word) for all words in the sentence. The data looks like this (but 50 points for each word, 5-8 words per phrase, 20 phrases per set, 3 sets... the data adds up quickly!):
    Speaker Accent   rowLabel ActualTime    F0
1     102-1      N     {SL} 0.00000000 105.954
2     102-1      N     {SL} 0.03757985 105.954
3     102-1      N     {SL} 0.07515970 105.954
4     102-1      N     {SL} 0.11273954 105.954
...
130   102-1      N    NOVEL   2.201260 115.82318
131   102-1      N    NOVEL   2.208244 112.42151
132   102-1      N    NOVEL   2.215228 108.82458
133   102-1      N    NOVEL   2.222212 105.19330
...
1328   102-1      N    NYLON   23.90094 113.44101
1329   102-1      N    NYLON   23.90693 113.01347
1330   102-1      N    NYLON   23.91292 112.44099
1331   102-1      N    NYLON   23.91890 111.77279

What I am trying to do is take a subset of this huge dataset based on a list of target words I have (which would fall under the 'rowLabel' category). I want to find those target words within the Excel file and copy the data for the entire row that has one of those target words in the rowLabel column (so in the example above, the words labeled NOVEL or NYLON are both on my list, so I would be looking for those as well as 38 other target words).
How would I get all of those rows (in this example, 130-133, and 1328-1331) based on searching for the rowLabel words from a list of 40 target words)?
And is it possible to get this to copy to another spreadsheet, rather than replacing the current one?

A: If I understand correctly, a PivotTable should suit:
Add labels to columns A and C.
Select A1:F1331, Insert > Tables - PivotTable, PivotTable and choose whether in New or Existing Worksheet.
Drag to areas as indicated from Choose fields to add to report:

Filter rowLabelwith Select Multiple Items and the words of choice.
Ensure you PT is totalled for rows and columns.
Double-click on the bottom RH corner cell of the PT.


text:
Q: Javascript alert not working on live server in codeigniter I am working in codeigniter. I have an error in javascript code. I have a login form and want to show a javascript alert box if the login name or user name is wrong. I had completed my project on localhost and javascript is working fine on localhost. But when i upload the project on live server, it displays an error message.
A PHP Error was encountered

Severity: Warning Message: Cannot modify header information - headers
  already sent by (output started at
  /home/servername/public_html/projectdemo/wms/application/controllers/login.php:36)
  Filename: helpers/url_helper.php Line Number: 540

I put this javascript code in controller
<script type='text/javascript'>
function jsfunction()
{
    window.alert("Wrong User Name or Password");
}
</script>

and in controller, I called this function:
echo "<script type='text/javascript'>jsfunction();</script>";

Later I put the script in head section but same error message appears.
Can you please help me.
Thanks in advance.

A: CodeIgniter officially replies to the client using the view/template rendering system. Echoing something earlier than that part of the framework's procedure causes the server to reply to the client early, hence "headers already sent". After so, CodeIgniter cannot anymore do anything with the intended because you forced the server to reply prematurely.
What you should do is to set some flag along with the template/view data so that the view can conditionally render a section of HTML in the view/template (which would be your error alerting code)

A: Headers must be parsed before any HTML, JS, CSS etc.
As https://stackoverflow.com/users/920374/setsuna mentioned you should put JavaScript into the view file. Your PHP error is basically saying that there was output before the headers for the page were sent which screws it up.

A: Check the accepted answer here: How to fix "Headers already sent" error in PHP
Spoiler: You are not allowed to start output in the controller, that's why you have views.


text:
Q: Tooltip showing hidden values in table format on hover My site is set up in the following way:
4 user groups. Each user group can see different information. An example would be stock quantity for a store. So the user from London can't see the stock availability for Manchester. This information is taken from the database for EACH item in stock. So if you have a list of 20 items, their individual values will be displayed.
I would like to do the following:
If I, or anyone I give permission to, hovers over the "In Stock" column for their own store, a tooltip table must appear showing the current stock levels for the 3 other stores, for each individual product. So if I hover over item SKU-001, I will only see the stock availability for that item. I had an issue where it was displaying the whole list for each item.
I was thinking of this:

Store1>
Store2>
Store3>
Store4>

<?php foreach($this->products as $product) { ?>

Stock of Item 1st store	 *If I hover/mouseover here, another table must appear showing only store name and values of "#stock2, #stock3 and #stock4* for the stock item I am hovering on.
Stock of Item 2nd store
Stock of Item 3rd store
Stock of Item 4th store

<?php } ?>

Here is some code I wrote:
function myFunction() {
var x = document.createElement("TABLE");
x.setAttribute("id", "table10");
document.body.appendChild(x);

var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);

var z = document.createElement("TD");
var t = document.getElementByID("riyadhbalance").value();
z.appendChild(t);
document.getElementById("myTr").appendChild(z);

However, for some reason this is not working. I have not found a way to include a tooltip. All the stock values are there for each individual item, so I just need to find a way to add the 3 values for the other stores and display them in a table format via a tooltip. That would be ideal.
So basically the tooltip should show the 3 values of the stores which are currently not on display, as the other 3 values are hidden. The user can only see their store's stock levels. But I would like to include this for myself as it would make it easier to view stock levels across the board.

A: Check this solution with jQuery and Bootstrap Working fiddle
You have four options:
1 - You can dynamically add it to your code on domReady (like the fiddle)
2 - You can directly print the needed html to make the plugin work. Check docs POPOVER or TOOLTIP
<button type="button" class="btn btn-lg btn-danger my_elements" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>

// and then, just call from javscript

3 - You can create it when you hover any element. Like the following example (this is particulary helpful if you have a lot of elements needing popover/tooltip, which would consume a lot of time and memory to init and handle)

      SKU
      Description>
      Stock Tooltip
      Stock Popover

SKU-0001	This is a description for SKU-0001	5	5

4 - with AJAX
<?php
// server side PHP
$other_stores_stock = [ "store_1" => 5, "store_2" => 20, "store_3" => 50 ];
header( 'Content-Type: application/json' );
echo json_encode( $other_stores_stock );
?>

//client side JS - like 1st example


text:
Q: jQuery scroll function only works once I am trying to add a class to the header if the user scrolls past the div #home - and remove the class when you scroll back to the top.
The issue is, when you scroll past the div it adds the class but when you keep scrolling and then scroll back up, the class does not get removed. The event is only firing once...
I created this jsFiddle here - https://jsfiddle.net/breezy/9evksr7y/
It works in my jsFiddle file but not on my actual web page, I've also tried this...
$(window).on( 'scroll', function() {

        var header = $('#header'),
            target = $("#home").offset().top;

        var interval = setInterval(function() {
            if ($(window).scrollTop() > 400) {
                // alert("made it!");

                header.addClass('fixed');

                clearInterval(interval);

            } else {

                header.removeClass('fixed');

            }

        }, 250);

    });

But it still does not work. Any idea what I am doing wrong?
Thanks

Edit: The issue was that one of my other functions in the same document was conflicting w/ this scroll function.

A: So I made some minor tweaks to the code. Not sure what the issue was but this seemed to work for me on my webpage.
$(window).on('scroll', function() {

  var header = $('#header'),
    target = $("#home").offset().top;

    if ($(window).scrollTop() > target) {

      header.addClass('fixed');

    } else {

      header.removeClass('fixed');

    }

});


text:
Q: How can I compile a GUI executable with ghc? I ported a little Haskell program I wrote from Mac to Windows. It's a GUI application (wxHaskell, compiled with ghc 6.12.1), so it does not need the command prompt window to open. It does so, anyway, so my question: What must I do so that the program starts without opening a prompt window first? Is there some ghc switch for this?

A: When using wxWidgets with cygwin, you can avoid having a console window appear by passing the -mwindows flag to the linker. You can tell GHC to pass flags to the linker using the -optl prefix, so you could try building with -optl-mwindows and see if that works.
I've done that before when building a Haskell SDL application on Windows, and it worked for me. I think the -mwindows flag is cygwin-specific though, and I'm not sure what your install of GHC might be using as a linker.

A: I don't have access to GHC on Windows, but it looks like you need to tell linker to use "windows" subsystem. ghc -optl-mwindows ... may work.


text:
Q: Passing a matrix through multiple functions A little complicated but I'll try to explain best I can, but I have values I am trying to calculate that are based on two other functions with multiple inputs. In the code below, my inputs are various theta values which then should create an array of m & n values. From the m & n arrays, I then need to calculate the various Q_bar terms which should output an array for each term as well.
theta = np.array([0, 25, -80, 90, 20])

m = math.cos(math.radians(theta)) #[deg]
n = math.sin(math.radians(theta)) #[deg]

Q_bar11 = Q11*(m**4) + 2*(Q12 + 2*Q66)*(n**2)*(m**2) + Q22*(n**4)
Q_bar12 = (Q11 + Q22 - 4*Q66)*(n**2)*(m**2) + Q12*(n**4 + m**4)
Q_bar16 = (Q11 - Q12 - 2*Q66)*n*(m**3) + (Q12 - Q22 + 2*Q66)*(n**3)*m
Q_bar22 = Q11*(n**4) + 2*(Q12 + 2*Q66)*(n**2)*(m**2) + Q22*(m**4)
Q_bar26 = (Q11 - Q12 - 2*Q66)*(n**3)*m + (Q12 - Q22 + 2*Q66)*n*(m**3)
Q_bar66 = (Q11 + Q22 - 2*Q12 - 2*Q66)*(n**2)*(m**2) + Q66*(n**4 + m**4)

I've seen similar posts about passing arrays through functions however I have not been successful in implementing them, any help would be much appreciated!

A: Instead of passing a list into function. pass each values differently might help!
    deg = np.array([math.cos(math.radians(theta[i])) for i in range(5)])

    news = pd.Series(theta,deg)

Sorry, I couldn't understand the q part exactly but if you explain it deeper than I'll try to help it too


text:
Q: Use decltype and std::function with lambda This works ...
auto x = 4;
typedef decltype(x) x_t;
x_t y = 5;

... so why doesn't this?
int j = 4;
auto func = [&] (int i) { cout << "Hello: i=" << i << "  j=" << j << endl;};
typedef decltype(func) lambda_t;
lambda_t func2 = [&] (int i) { cout << "Bye: i=" << i << "  j=" << j << endl;};

... and how would I declare lambda_t manually using std::function?

A: Lambda types are unutterable (cannot be named), which is the reason you cannot do what you are asking. Besides that, each lambda is of a different type, so even if you could name the type, you would not be able to assign the second lambda to the first. If you think of the lambda syntax as a shortcut for a function object that becomes clearer: the member operator() is different for each lambda and thus they are of different types.
You can, on the other hand assign a lambda to a std::function<> object of the appropriate signature, which in your case would be std::function<void(int)>.

A:
... so why doesn't this [work]?

Because each lexical instance of a lambda has a different type. It does not matter if the same characters are used.

.. and how would I declare lambda_t manually using std::function?

The lambda takes an int argument and does not return anything... Therefore:
typedef std::function<void(int)> lambda_t;

A: Here's some solid proof that this doesn't work. Similar scenario:
int foo = 3;
int bar = 3;

std::cout << (typeid(foo).hash_code() == typeid(bar).hash_code()); // prints one -- obviously - they are the same type

Now, lets use the exact same code, but with lambdas. What do you think the response will be.
  auto foo = [](){std::cout << "HELLO\n"; };

  auto bar = [](){std::cout << "HELLO\n"; };

  std::cout << (typeid(foo).hash_code() == typeid(bar).hash_code()); // prints 0 -- different type even though they are declared exactly the same.


text:
Q: How will a c# tcp socket block if I send too many bytes? I am writing a tcp server which needs to send data to connected remote hosts. I'd prefer socket send calls to not block at all, ever. To facilitate this I am using Socket.Select to identify writable sockets and writing to those sockets using Socket.Send. The Socket.Select msdn article states:

If you already have a connection established, writability means that all send operations will succeed without blocking.

I am concerned about the case where the remote socket is not actively draining the buffer, said buffer fills, and tcp pushes back onto my server's socket. In this case I thoguht the server will not be able to send and the accepted socket's buffer will fill.
I wanted to know the behavior of socket.Send when the send buffer is partially full in this case. I hope it would accept as many bytes as it can and return that many bytes. I wrote a snippet to test this, but something strange happened: it always sends all the bytes I give it!
snippet:
var LocalEndPoint = new IPEndPoint(IPAddress.Any, 22790);
var listener = CreateSocket();
listener.Bind(LocalEndPoint);
listener.Listen(100);
Console.WriteLine("begun listening...");

var receiver = CreateSocket();
receiver.Connect(new DnsEndPoint("localhost", 22790));
Console.WriteLine("connected.");

Thread.Sleep(100);
var remoteToReceiver = listener.Accept();
Console.WriteLine("connection accepted {0} receive size {1} send size.", remoteToReceiver.ReceiveBufferSize, remoteToReceiver.SendBufferSize);

var stopwatch = Stopwatch.StartNew();
var bytes = new byte[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
var bytesSent = remoteToReceiver.Send(bytes, 0, 16, SocketFlags.None);
stopwatch.Stop();
Console.WriteLine("sent {0} bytes in {1}", bytesSent, stopwatch.ElapsedMilliseconds);

public void CreateSocket()
{
    var socket = new Socket(SocketType.Stream, ProtocolType.Tcp)
    {
        ReceiveBufferSize = 4,
        SendBufferSize = 8,
        NoDelay = true,
    };
    return socket;
}

I listen to an endpoint, accept the new connection, never drain the receiver socket buffer, and send more data than can be received by the buffer alone, yet my output is:
begun listening...
connected.
connection accepted, 4 receive size 8 send size.
sent 16 bytes in 0

So somehow socket.Send is managing to send more bytes than it is setup for. Can anyone explain this behavior?
I additionally added a receive call and the socket does end up receiving all the bytes sent.

A: I believe the Windows TCP stack always takes all bytes because all Windows apps assume it does. I know that on Linux it does not do that. Anyway, the poll/select style is obsolete. Async sockets are done preferably with await. Next best option is the APM pattern.
No threads are in use while the IO is in progress. This is what you mean/want. This goes for all the IO-related APM, EAP and TAP APIs in the .NET Framework. The callbacks are queued to the thread-pool. You can't do better than that. .NET IO is efficient, don't worry about it much. Spawning a new thread for an IO would frankly be stupid.
Async network IO is actually super simple when you use await and follow best-practices. Efficiency-wise all async IO techniques in .NET are comparably efficient.


text:
Q: Slicing different areas of two images in one go Slicing different areas of two images in one go
I have two images of [2, height, width, channel] dimension and same size. I want to slice two images by a same size kernel (say 5 x 5) at different locations in one go. For example, for image one, the slicing area is [125px,125px] to [130px,130px]; for the second image, the slicing is [140px,140px] to [145px, 145px].
I used the following code
    imgs[:, yst:yend, xst:xend]
in which yst is the two-entry array of starting coordinates (i.e. [125, 140]) for two images respectively. yend is for the ending coordinates similarly. So do xst and xend for width axis coordinates.
Instead of getting two slicing areas, the code resulted in four areas. That is, the two slices had been applied to each image.
What I expect is that the first slice is applied to the first image and the second slice is applied to the second image respectively. I have tried various dimensional combinations and none of them worked as I desired so far. I ended up looping them one by one at the moment. But my gut feeling tells me it could be done in one go. Could anyone lend a hand on this?
Thanks in advance

A: I see two options to achieve what you want.

*

*move to fancy indexing

*use stride tricks

The latter is faster but a bit dangerous (a typo in the dimension setup magic can hard crash your script):
Here is an example:
import numpy as np
from numpy.lib.stride_tricks import as_strided
from scipy.misc import face
from timeit import timeit

def fancy_idx():
    ino, y, x = np.ogrid[:nim,:yw,:xw]
    ywo, xwo = ywoff.reshape(-1,1,1), xwoff.reshape(-1,1,1)
    return im[ino, ywo+y, xwo+x]

def stride_trx():
    nim, y, x = im.shape
    st = im.strides
    wins = as_strided(im, (nim, y-yw+1, x-xw+1, yw, xw), (*st, *st[1:]))
    return wins[np.arange(nim), ywoff, xwoff]

# set up example
# use the scipy example image
# use the color channels (RGB) as individual images
im = np.ascontiguousarray(np.moveaxis(face(), 2, 0))
nim = len(im)
# set the window height and width
yw, xw = 150, 200
# set the top left corners for window in each image
ywoff, xwoff = np.array([[510,530,520],[700,720,750]])

# test
assert (fancy_idx()==stride_trx()).all()

print(timeit(fancy_idx, number=1000))
print(timeit(stride_trx, number=1000))

Sample run:
0.4873827249975875    # fancy indexing
0.028213004930876195  # stride tricks

Some explanation:

*

*fancy indexing: this method addresses each pixel individually, this is flexible and safe but slow

*stride tricks: this method is faster because only the top left corner of each window is addressed fancy, the windows themselves are created by slicing
how does it work? we essentially create a 5D array by duplicating (in admin, not in data) the y and x axes. That way we can use the first copy of y and x to pick the offsets and the second copy of y and x to slice


text:
Q: Not calling Dispose on HttpRequestMessage and HttpResponseMessage in asp.net core What is the best practice for calling Dispose (or not) on HttpRequestMessage and HttpResponseMessage with asp.net core?
Examples:
https://github.com/aspnet/Security/blob/1.0.0/src/Microsoft.AspNetCore.Authentication.Google/GoogleHandler.cs#L28-L34
protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens)
{
    // Get the Google user
    var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken);

    var response = await Backchannel.SendAsync(request, Context.RequestAborted);
    response.EnsureSuccessStatusCode();

    var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
    ...
 }

and
https://github.com/aspnet/Security/blob/1.0.0/src/Microsoft.AspNetCore.Authentication.Facebook/FacebookHandler.cs#L37-L40
Both examples are not calling Dispose
Could this be an omission? or is there a valid reason behind it, maybe because the method is async? Of course the CG will eventually finalize them, but is this the best practice to do so under this circumstance and why?  Notice that the above examples are part of ASP.NET Core Middleware components.

A: I opened an issue on the github repository where the code examples belong to.
https://github.com/aspnet/Security/issues/886

It's not important in these scenarios. Disposing a request or response only calls Dispose on their Content field. Of the various HttpContent implementations, only StreamContent needs to dispose anything. HttpClient's default SendAsync fully buffers the response content and disposes the stream, so there's nothing the caller needs to do.

But for the sake of not getting weird bugs down the line, we are better off disposing those object. MemoryStream is another class that is also often not dispose because of his current underlying implementation.
https://stackoverflow.com/a/234257/6524718

If you're absolutely sure that you never want to move from a MemoryStream to another kind of stream, it's not going to do you any harm to not call Dispose. However, it's generally good practice partly because if you ever do change to use a different Stream, you don't want to get bitten by a hard-to-find bug because you chose the easy way out early on. (On the other hand, there's the YAGNI argument...)
The other reason to do it anyway is that a new implementation may introduce resources which would be freed on Dispose.


text:
Q: Is it possible to access audio playing from the browser in javascript? Ok, since youtube doesn't allow you the use of the <audio> tag, is it possibile to capture the audio that is playing in the browser? (the stream transmitted to hardware).
And a question still relevant, is it possibile to capture the audio of an <object> tag? How could i make an <object> of a youtube video?

A: No and no, respectively.
There is no way to capture audio within a web page, especially across origins (e.g, capturing the audio of a YouTube frame, which has the origin https://youtube.com).
YouTube used to support an <object> embedding method based on Flash. This still exists, but it hasn't been recommended for quite some time, so I won't go into detail. Nor does it help you, as there is no way to capture the audio output from a browser plugin either.


text:
Q: Authentication in an HTML5 application talking to WCF REST Service I am a .Net developer looking to learn some HTML5 development. Traditionally all my web development has been done in ASP.Net or Silverlight and has always been business applications. I am now trying to put together an application using pure HTML5 - and by this I mean not using ASP.Net and instead having .html pages with javascript in. This app will be talking to a WCF service implementing REST.
I want to start by authenticating a user in the application. Traditionally I would use ASP.Net's authentication provider or Windows basic. Neither of these are an option now. Everything will be hosted under SSL, but how do I implement an authentication model in the HTML/JS? I have looked at OAuth, but this seems more fitting for delegation. Something closer to forms authentications feels better.
I intend to use the same code to compile a mobile app using PhoneGap for example, hence I am not using ASP.Net.
I'd like some suggestions on how to implement security/authentication and some examples if possible. Ideally a token based approach so I can also consider ws-* on the server side.


text:
Q: Is it possible to animate a group of controls in wpf? I have 3 buttons in a wpf application. Upon loading, the buttons should translate from the left side to the center of the app. I don't want to apply animations to each and every button, is there any way to group these buttons & then add the animation properties to the group which will animate the group of buttons?

A: You could group the buttons in a container such as a grid and then animate the container.
An alternative would be to put the animation in a style and apply the style to the buttons, either explicitly by setting the style of each button or implicitly by setting the default style for buttons in the parent of the buttons (so again a container)
Here is an example using a style.
Unfortunately the loaded event of the window is repeatedly called so the animation keeps on going. The only solution I see is by setting a boolean after the first time and preventing the animation from occuring again.
<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Grid>
        <Grid HorizontalAlignment="Center"
              VerticalAlignment="Center">
            <Grid.RowDefinitions>
                <RowDefinition Height="auto" />
                <RowDefinition Height="auto" />
                <RowDefinition Height="auto" />
            </Grid.RowDefinitions>
            <Grid.Resources>
                <Style TargetType="Button">
                    <Setter Property="Width"
                            Value="150" />
                    <Setter Property="Padding"
                            Value="15" />
                    <Setter Property="Margin"
                            Value="15" />
                    <Setter Property="RenderTransform">
                        <Setter.Value>
                            <TranslateTransform X="0" />
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <EventTrigger RoutedEvent="Window.Loaded">
                            <BeginStoryboard>
                                <Storyboard FillBehavior="HoldEnd">
                                    <DoubleAnimation Storyboard.TargetProperty="(Button.RenderTransform).(TranslateTransform.X)"
                                                     From="-150"
                                                     To="0"
                                                     RepeatBehavior="1"
                                                     Duration="0:0:2" />
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </Style.Triggers>
                </Style>
            </Grid.Resources>
            <Button Grid.Row="0">Start</Button>
            <Button Grid.Row="1">Setup</Button>
            <Button Grid.Row="2">Quit</Button>

        </Grid>
    </Grid>
</Window>


text:
Q: How wrap image around cylinder in Silverlight I am trying wrap image around cylinder in silverlight. I looked a lot in Google but don't found anything. As I know it can be done with pixel shader, but don't know how.
Is it possible?
Thanks.

A: It's not a complete wrap onto cylinder, but you will get a starting idea/example:
(code is in GLSL, not in HLSL, but i think it will be not hard to convert it)
uniform sampler2D tex;

void main()
{
 vec2 cen = vec2(0.5,gl_TexCoord[0].y)-gl_TexCoord[0].xy;
 cen = vec2(pow(cen.x,1.7),pow(cen.y,2.2));
 cen.y = 3.9*sin(1.8*gl_TexCoord[0].x-2.3);
 vec2 mcoord = 1.65*vec2(-0.22+gl_TexCoord[0].x,1.95+gl_TexCoord[0].y);
 gl_FragColor = texture2D(tex, mcoord+cen);
}

From this

you will get something like that
Good luck

A: You may want to try Zam3d. I have used trial versions previously, and you can get the 3D shape and try and set the background to an image. Have a look and see if that helps.


text:
Q: how to get google friend list i am trying to get the Google plus circle friend list with the  below  URL
https://www.googleapis.com/plus/v1/people/{userid}/people/visible?key={apikey}
but found the below error
{
 "error": {`enter code here`
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured"
   }
  ],
  "code": 403,
  "message": "Access Not Configured"
 }
}

A: It sounds like you have not used the API Console to indicate that your app requires access to the Google+ API. See https://developers.google.com/+/web/people/ and the "Before you Begin" section for the steps you need to go through.
In particular, see steps 3 and 4 regarding how to get the client ID from the API console.

A: It is important to note that people.list can only be called on an authenticated user. You can include the API Console client ID when configuring your Google+ Sign-In button, if the trouble is coming from the API Console set up. However, a user will have to log in to your app before you can request their list of Circled people. This is because when they log in, they control which Circles are shared with your app, and your app receives the flat list of users--without Circle names.


text:
Q: Spring RESTTemplate with HTTPS Authentication
Possible Duplicate:
Spring Security Authentication using RestTemplate

I can use Spring RESTTemplate to get data from a URL. However I want to reach an https URL that needs authentication(I have a username and password).
How can I use RESTTemplate with authentication?
EDIT: I want to connect an https URL and it is coded at another language and different system that I have.
PS: If there exist any good RESTTemplate examples and RESTTemplate with authentication examples (I use json and jackson at my application) and you suggest, you are welcome.


text:
Q: Problem in handling large number in Python I was solving a problem on codeforces:- Here is the Question
I wrote python code to solve the same:-
n=int(input())
print(0 if ((n*(n+1))/2)%2==0 else 1)

But it failed for the  test-case: 1999999997 See Submission-[TestCase-6]
Why it failed despite Python can handle large numbers effectively ? [See this Thread]

Also the similar logic worked flawlessly when I coded it in CPP [See Submission Here]:-
#include<bits/stdc++.h>
using namespace std;

int main(){
    int n;
    cin>>n;
    long long int sum=1ll*(n*(n+1))/2;
    if(sum%2==0) cout<<0;
    else cout<<1;
return 0;
}

A: Ran a test based on the insight from @juanpa.arrivillaga and this has been a great rabbit hole:
number = 1999999997

temp = n * (n+1)
# type(temp) is int, n is 3999999990000000006. We can clearly see that after dividing by 2 we should get an odd number, and therefore output 1

divided = temp / 2
# type(divided) is float. Printing divided for me gives 1.999999995e+18
# divided % 2 is 0

divided_int = temp // 2
# type(divided_int) is int. Printing divided for me gives 1999999995000000003

// Forces integer division, and will always return an integer: 7 // 2 will be equal to 3, not 3.5
As per the other answer you have linked, the int type in python can handle very large numbers.
Float can also handle large numbers, but there are issues with our ability to represent floats across languages. The crux of it is that not all floats can be captured accurately: In many scenarios the difference between 1.999999995e+18 and 1.999999995000000003e+18 is so minute it won't matter, but this is a scenario where it does, as you care a lot about the final digit of the number.
You can learn more about this by watching this video

A: As mentioned by @juanpa.arrivillaga and @DarrylG in comments, I should have used floor operator// for integer division, the anomaly was cause due to float division by / division operator.
So, the correct code should be:-
n=int(input())
print(0 if (n*(n+1)//2)%2==0 else 1)


text:
Q: Secondary dropdown menu arrow symbol drawn at wrong size on screen with different DPI/scaling (WinForms) If a WinForms app is dragged from a screen with high scaling to one with lower scaling, the arrow designating a secondary menu pulldown is displayed with incorrect scaling. Once the menu is opened while the form is on the high scaling screen, then the arrow is displayed at the correct size on all screens from that point forward. The issue seems to exist both in .Net Framework 4.8 and .NET 6.0.
Here's a picture of the oversized arrow:

Does anyone know a good work-around to this issue?

A: This is pretty ugly, but seems to solve the issue in all cases I have tried so far.  Just calling ShowDropDown() did not fix the issue. But calling ShowDropDown() followed by DoEvents() before the form is shown corrects the problem:
public Form1()
    {
    this.Font = SystemFonts.IconTitleFont;
    InitializeComponent();

    // Show the file menu momentarily to fix arrow scaling issue

    fileToolStripMenuItem.ShowDropDown();
    Application.DoEvents();
    }

Or in Shown():
private void Form1_Shown(object sender, EventArgs e)
    {
    fileToolStripMenuItem.ShowDropDown();
    Application.DoEvents();
    fileToolStripMenuItem.HideDropDown();
    }


text:
Q: how to load shape file in react functional component with react-leaflet I was trying to load shape file to my react app and i used react-leaflet npm for display result in map
i got some demo code this is the link
this example is in react class component but i was working on react functional component but some how managed to change code but facing error
the below is root folder code
import { MapContainer, TileLayer, LayersControl } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import { useEffect, useState } from "react";
import ShapeFile from "./SamShape";
export const Mymap = () => {
const { BaseLayer, Overlay } = LayersControl;
const [geoData, setGeoData] = useState(null);
const [ShapeLayers, setShapeLayers] = useState(null);

const readTheFile = (e) => {
let reader = new FileReader();
let file = e.target.files[0];
//  console.log(file);
reader.readAsArrayBuffer(file);
reader.onload = function (buffer) {
  // console.log(buffer.target.result);
  setGeoData(buffer.target.result);
};
};

const onEachFeature = (feature, layer) => {
console.log(feature.properties);
if (feature.properties) {
  layer.bindPopup(
    Object.keys(feature.properties)
      .map(function (k) {
        return k + ": " + feature.properties[k];
      })
      .join("
"),
    {
      maxHeight: 200,
    }
  );
}
};
const Style = () => {
return {
  weight: 2,
  opacity: 1,
  color: "blue",
  dashArray: "3",
  fillOpacity: 0.7,
};
};
useEffect(() => {
if (geoData !== null) {
  setShapeLayers(
    <Overlay checked name="Feature group">
      <ShapeFile
        data={geoData}
        style={Style}
        onEachFeature={onEachFeature}
      />
    </Overlay>
  );
 }
 }, [geoData]);

return (
<>

    <input type="file" onChange={(e) => readTheFile(e)} />

  <MapContainer
    style={{ height: "100vh", width: "100wh" }}
    center={[18.56, 78.76]}
    zoom={2}
    scrollWheelZoom={true}
  >
    {/* {geoData
      ? (ShapeLayers = (
          <Overlay checked name="Feature group">
            <ShapeFile data={geoData} />
          </Overlay>
        ))
      : console.log(ShapeLayers, ";kliko")} */}
    <LayersControl position="topright">
      <BaseLayer checked name="OpenStreetMap.Mapnik">
        <TileLayer
          attribution='&copy OpenStreetMap contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
      </BaseLayer>
      {ShapeLayers}
    </LayersControl>
  </MapContainer>
  {/* <ExampleShape zipUrl={zipurl}/> */}
</>
);
};

this code is being passed as props in useEffect
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true,
});
exports.default = void 0;

var _regenerator = _interopRequireDefault(
  require("@babel/runtime/regenerator")
);

var _extends2 = _interopRequireDefault(
  require("@babel/runtime/helpers/extends")
);

var _asyncToGenerator2 = _interopRequireDefault(
  require("@babel/runtime/helpers/asyncToGenerator")
);

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(
  require("@babel/runtime/helpers/objectWithoutPropertiesLoose")
);

var _react = _interopRequireWildcard(require("react"));

var _reactLeaflet = require("react-leaflet");

var _shpjs = _interopRequireDefault(require("shpjs"));

var _excluded = ["data"];

function _getRequireWildcardCache(nodeInterop) {
  if (typeof WeakMap !== "function") return null;
  var cacheBabelInterop = new WeakMap();
  var cacheNodeInterop = new WeakMap();
  return (_getRequireWildcardCache = function _getRequireWildcardCache(
    nodeInterop
  ) {
    return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  })(nodeInterop);
}

function _interopRequireWildcard(obj, nodeInterop) {
  if (!nodeInterop && obj && obj.__esModule) {
    return obj;
  }
  if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) {
    return { default: obj };
  }
  var cache = _getRequireWildcardCache(nodeInterop);
  if (cache && cache.has(obj)) {
    return cache.get(obj);
  }
  var newObj = {};
  var hasPropertyDescriptor =
    Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var key in obj) {
    if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor
        ? Object.getOwnPropertyDescriptor(obj, key)
        : null;
      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }
  newObj.default = obj;
  if (cache) {
    cache.set(obj, newObj);
  }
  return newObj;
}

var ShapeFile = function ShapeFile(props) {
  console.log(props, "props");
  var _useState = (0, _react.useState)(null),
    geoJSONData = _useState[0],
    setGeoJSONData = _useState[1];

  var data = props.data,
    geoJSONProps = (0, _objectWithoutPropertiesLoose2.default)(
      props,
      _excluded
    );
  (0, _react.useEffect)(
    /*#__PURE__*/ (0, _asyncToGenerator2.default)(
      /*#__PURE__*/ _regenerator.default.mark(function _callee() {
        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) {
            switch ((_context.prev = _context.next)) {
              case 0:
                _context.t0 = setGeoJSONData;
                _context.next = 3;
                return (0, _shpjs.default)(props.data);

              case 3:
                _context.t1 = _context.sent;
                (0, _context.t0)(_context.t1);

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      })
    ),
    [props.data]
  );
  return /*#__PURE__*/ _react.default.createElement(
    _reactLeaflet.GeoJSON,
    (0, _extends2.default)(
      {
        key: Math.random(),
        data: geoJSONData,
      },
      geoJSONProps
    )
  );
};

var _default = ShapeFile;
exports.default = _default;

i can able choose file from input once i select file the browser throws erro saying Error: nodebuffer is not supported by this browser i googled the error but no use if anyone out there who had solved same issue pleas let me know I would really appreciate it


text:
Q: Class Diagrams, Operation Specification - What are "Lower and Upper"? I am unsure of the meaning of Lower and Upper as seen in the screenshot below.
I'm using Visual Paradigm to document my design.
I've searched their documentation for answers but could not find any.
Can someone explain to me the meaning of those input fields?

A: These parameters are intended to show the operation's multiplicity - the upper and lower boundary. 1..* here will be set as lower=1, upper=*. The problem is, that there are some bugs and you can't either see this multiplicity on the diagram, or have it engineered in the code.
The bug is not repaired till now. (
http://forums.visual-paradigm.com/posts/list/6652.html)

A: Upper and Lower are multiplicity of return parameter of operation you define in your example. It is normally not set to operation directly, but to operation's return parameter. Operation can have zero or one return parameter.


text:
Q: windows 8 modern ui apps - access to data Where can i find folder with installed modern ui apps? Im developing some app which uses .txt files to store information (win8 doesnot support datebase on arm - facepalm) but they seem to not work properly - thats why i want to access them.
Thanks!

A: That is not the correct way of doing things in Metro.  I assume you mean db files, or txt files.  Simply access the local text file from the project folder.
Here is a great tutorial on how you would go about doing so: http://www.codeproject.com/Articles/432876/Windows-8-The-Right-Way-to-Read-Write-Files-in-Win
An example:
    private async void ProjectFile()
{
    // settings
    var _Path = @"Metro.Helpers.Tests\MyFolder\MyFolder.txt";
    var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

    // acquire file
    var _File = await _Folder.GetFileAsync(_Path);
    Assert.IsNotNull(_File, "Acquire file");

    // read content
    var _ReadThis = await Windows.Storage.FileIO.ReadTextAsync(_File);
    Assert.AreEqual("Hello world!", _ReadThis, "Contents correct");
}


text:
Q: How can I stop Eclipse from helping me and overriding what the 'End' key does? Eclipse is being helpful again, and I want it to stop. The situation is this:

*

*It auto-completes a function name, to foo(), and because takes an argument, the cursor is now between the ().

*I fill in the argument, and because the line still needs a semicolon at the end of line, I press the End key.

*The cursor jumps to the end of the line (after the closing paren), and I press the ; key.

*Eclipse is being dumb, jumps back into the parens, selects my argument, and replaces it with the semicolon.

Result: foo(;)
Why is it doing this, and how do I stop it? It's bad enough that Eclipse is doing something ridiculous here, but I can't even explain what it is that it is trying to achieve!

A: Press Return/Enter instead of End. Eclipse will then jump to the end of the line for you to insert your semicolon.


text:
Q: Display DIV on right click of image I'm trying to figure out how I can get a DIV to show at the position of the mouse when someone right clicks on an image. An example can be found here.
I've searched around and found the following code...
$('img').bind('contextmenu', function(e){
return false;
});

This of course will prevent the right click. Though I don't know how to make the DIV appear at the location of the mouse click.
May I please get pointed in the right direction?
Thanks!

A: I've thrown together a quick demo (check it out here) of how to possibly do this. The div is absolutely positioned and we capture the contextmenu event, on which we preventDefault() and set the position of the div based on the pageX and pageY key's in the event object.
The JS looks something like this:
$('body').on('contextmenu', function(event) {
    event.preventDefault();
    $('div').css({
        'top': event.pageY,
        'left': event.pageX
    });
});

And the CSS looks something like this:
body {
    width: 500px;
    height: 500px;
}

div {
    width: 100px;
    height: 100px;
    background-color: #ccc;
    position: absolute;
    top: 0;
    left: 0;
}

I've tested the demo in the latest Firefox and Chrome, as well as IE7 - IE9, and it has worked in all of them. Hope this helps.

A: You can use the offsetX and offsetY properties of the event object that gets passed to the contextmenu handler like so:
HTML:

Pretty picture of a kitten

Javascript:
$('#pictureCaption').hide();

$('#picture').contextmenu( function(e) {
    e.preventDefault();
    $('#pictureCaption').offset( {top: e.offsetY, left:e.offsetX} ).show();
});

jsFiddle here: http://jsfiddle.net/HFC5g/


text:
Q: Power BI Data Flows Access to the resource is forbidden error I have created a new workspace in Power BI that has dataflows which are backed by Azure Data Lake Gen2 storage.  I have created several of these and can use them without issue in Power BI Desktop.  I have given another person permission (currently they have Admin role) to the Workspace and I have even given them permission (again Owner at this point) to the Gen2 Data Lake.  But whenever that person tries to use Power BI to pull in that Data Flow they get the following error message
"Expression.Error: Access to the resource is forbidden"
Can somebody please tell me what permissions are needed to allow people to read information from the data flows that are backed by Gen2 Data Lake.

A: Not sure if you managed to fix this, but I came across the same issue and I found a trace of a solution on Power BI Community Website: https://community.powerbi.com/t5/Service/Read-access-to-a-Dataflow-as-a-data-source-by-a-non-owner-of-the/m-p/743544/highlight/true#M72483
It seems that any other user that wants read access on a Dataflow, if the Dataflow data is physically saved in a dedicated ADLS Gen2 Storage Account, that user will also need to be granted permissions on every folder and file there is in there...
Thanks


text:
Q: How to move image in Glcontrol in OpenTk I am new to opentk I want to move image from left to right smoothly. How can I do this?
I have tried moving viewport but it doesn't look smooth rendering.
int cnt = 1920;
public void DrawImage(int image)
{
        GL.Viewport(new Rectangle(cnt, 0, ScreenWidth, ScreenHeight));
        cnt--;
        GL.MatrixMode(MatrixMode.Projection);
        GL.PushMatrix();
        GL.LoadIdentity();

        //GL.Ortho(0, 1920, 0, 1080, 0, 1);

        GL.MatrixMode(MatrixMode.Modelview);
        GL.PushMatrix();
        GL.LoadIdentity();

        GL.Disable(EnableCap.Lighting);

        GL.Enable(EnableCap.Texture2D);

        GL.ActiveTexture(TextureUnit.Texture0);
        GL.BindTexture(TextureTarget.Texture2D, image);

        RunShaders();

        GL.Disable(EnableCap.Texture2D);
        GL.PopMatrix();

        GL.MatrixMode(MatrixMode.Projection);
        GL.PopMatrix();

        GL.MatrixMode(MatrixMode.Modelview);

        //ErrorCode ec = GL.GetError();
        //if (ec != 0)
        //    System.Console.WriteLine(ec.ToString());
        //Console.Read();
        glControl1.SwapBuffers();
    }


text:
Q: Initialize std::array using element type from the declaration implicitly In the following code I'm trying to initialize arrays (raw C-classic and std::array) minimizing the usage of the element type, i.e. S:
#include <array>

struct S { unsigned u; int i; };

auto std_array = std::array<S, 3>{
    S{0U, 0},
    S{1U, 1},
    S{2U, 2}
};

S raw_array[] = {
    {0U, 0},
    {1U, 1},
    {2U, 2}
};

/*  // compile error: excess elements in struct initializer
std::array<S,3> std_array_no_type = {
    {0U, 0},
    {1U, 1},
    {2U, 2}
};
*/

std::array<S,3> std_array_one_type_only = {
    S{0U, 0},
    {1U, 1},
    {2U, 2}
};

int main() {}

Using the raw_array I can specify S only once. But trying the same with std::array doesn't work (see the commented std_array_no_type). I have to specify S type for each or (this is also an interesting part of the question) only for the first element in the initializer list (see std_array_one_type_only).
So, is there a way to define an initialized std::array object using the type S only once? If no, according to which clause of the standard? And why single explicit type S allows std_array_one_type_only to be compiled?

A: About the 1st question,

So, is there a way to define an initialized std::array object using the type S only once?

You can add another pair of {}, because std::array contains an underlying array in fact.
std::array<S,3> std_array_one_type_only = {{{0U, 0}, {1U, 1}, {2U, 2}}};
//                                        ^                           ^ for std::array
//                                         ^                         ^  for underlying array
//                                          ^     ^                     for the 1st element of underlying array
//                                                   ^     ^            for the 2nd element of underlying array
//                                                            ^     ^   for the 3rd element of underlying array

About the 2nd question,

And why single explicit type S allows std_array_one_type_only to be compiled?

In aggregate initialization, the braces for nested initializer lists may be omitted,

If the aggregate initialization uses copy- (until C++14)list-initialization syntax (T a = {args..} or T a {args..} (since C++14)), the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

Given
std::array<S,3> std_array_no_type = {{0U, 0}, {1U, 1}, {2U, 2}};
//                                  ^                         ^  for std::array
//                                   ^     ^                     for underlying array

The 1st {0U, 0} would be tried to be used to initialize the whole underlying array, then leads to the error like excess elements in initializer because std::array doesn't contain any further subobjects.
Given
std::array<S,3> std_array_no_type = {S{0U, 0}, {1U, 1}, {2U, 2}};
//                                  ^                          ^ for std::array
//                                    ^     ^                    for the 1st element of underlying array
//                                             ^     ^           for the 2nd element of underlying array
//                                                      ^     ^  for the 3rd element of underlying array

S{0U, 0} can't be used to initialize the underlying array (which doesn't satisfy the style of aggregate initialization), then it'll be used to initialize the 1st element of the underlying array, i.e. the above braces-omitting rule gets applied, then the following {1U, 1} and {2U, 2} are used to initialize the following members of the underlying array.


text:
Q: Nuke – How to select random nodes with Python? I'm not too proficient in Python - I'd love a little help with some code. I'm trying to select two random nodes out of all selected nodes in nuke.
I've got far enough that I can print two randomly chosen node names in the array of selected nodes, but could anyone help finish off the code so that the two nodes with the matching names are selected? Essentially I'm imagining if a node name contains chosen_nodes string, select these nodes.
Thanks.
import nuke
import random

array = []
for node in nuke.selectedNodes():
    n = node['name'].value()
    array.append(n)

chosen_nodes = random.sample(array, k=2)
print chosen_nodes

A: With this code you can select two random nodes out of several selected ones:
import nuke
import random

array = []

for node in nuke.selectedNodes():
    name = node['name'].value()
    array.append(name)

print(array)

if nuke.selectedNodes():
    for index in nuke.selectedNodes():
        index['selected'].setValue(False)

for i in range(1, 3, 1):      # range(start, non-inclusive stop, step)
    r = random.randint(1, len(array))
    nuke.toNode(array[r-1]).setSelected(True)
    array.remove(array[r-1])  # delete randomly generated element from array

array = []

A:
Essentially I'm imagining if a node name contains chosen_nodes string, select these nodes.

This should be close to what you want!
match = 'chosen_nodes'

for node in nuke.selectedNodes():
    node.setSelected(False)
    if match in node['name'].value():
        node.setSelected(True)

A slightly more complicated version:
def selectNodesWithFuzzyName(name, nodes=None):
    """
    Set the selected nodes to only those that match the passed name.

    Parameters
    ----------
    node : str
        Glob-style name of a node e.g. 'Grade*'
    nodes : Optional[Iterable[nuke.Node]]
        If provided, only operate on only these nodes. Otherwise
        the currently selected nodes will be used.
    """
    import fnmatch

    if nodes is None:
        nodes = nuke.selectedNodes()

    for node in nodes:
        node.setSelected(False)
        if fnmatch.fnmatch(node['name'].value(), name):
            node.setSelected(True)

selectNodesWithFuzzyName('Grade*')


text:
Q: Django 1.7 (apparently) not running migrations on manage.py test Working on a Django 1.7 project, I've had the need to add a field to an existing model.
I added the following:  bairro = models.CharField(max_length=200)
Then I ran both commands:
python manage.py makemigrations
python manage.py migrate

And now, tests won't run anymore.
Whenever I run python manage.py test it gives this error:
django.db.utils.ProgrammingError: column admin_starbeli_salao.bairro does not exist

Which is strange, since if I open the shell I can add objects and the field does work.
What can I do?

A: It was a problem in one of the migrations.
To find what it was, I dropped my db and tried to run python manage.py migrate, but the same error ocurred.
Then I noticed one the related models had a default for this model, like this:
def first_my_model():
    return MyModel.objects.first().pk if MyModel.objects.first() else 0

It was trying to use that newly added (and not yet existing on the db) field on this call, thus throwing the error.


text:
Q: Composer not using key set through SSH agent forwarding I'm using SSH agent forwarding with my Vagrant box. It looks like this is set up correctly, as I can successfully perform a git clone on my private repository:
$ git clone git@github.com:myorganisation/myrepo.git
Cloning into 'myrepo'...
This repository also features in my composer.json:
{
    "type": "vcs",
    "url":  "git@github.com:myorganisation/myrepo.git"
},

However when I run composer update under the same user, I get an error indicating that I'm unauthenticated:
The "https://api.github.com/repos/com:myorganisation/myrepo" file could not be downloaded (HTTP/1.1 404 Not Found)
How can I instruct Composer to use my forwarded key?

A: I sorted this by adding the no-api option:
{
    "type": "vcs",
    "no-api": true,
    "url":  "git@github.com:myorganisation/myrepo.git"
}


text:
Q: implementing ajax using jquery i'm tried to implement ajax using jQuery.Its my first time to use ajax.so in a button click i need to display the current datetime. For this, i write the below code
//==============aspx page===============
<script type="text/javascript">

    $(document).ready(function (){
        var Button1 = $("#Button1");
        var Label1 = $("#Label1");
        Button1.click(function (){
          $.ajax({
                type: "POST",
                url: "/myownajax14/WebService/WebService1.asmx/GetDateTime",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#Label1").text(msg.d);
                    //alert('hi');
                    },
                error:alert('error');
            });

        });
    });

//================asmx.cs page===========
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    public string GetDateTime()
    {
        return DateTime.Now.ToString();
    }
}

My problem is,it doesn't give the answer..and it doesn't show any error.Have any mistake in this code?Please help me..

A: I too had a similar problem it's simple try this:
You need to specify type="button" attribute.

A: contentType: "application/json;" means that the client need the server to response a json type data.But the server response a string type one instead.
In the "success" block,the "msg" must be like '2010-10-10',so error happens in msg.d.
try the following for a string type data,or response a json type data in the server code such as {"y":2010,"m":10,"d":10}.
contentType: "application/text; charset=utf-8",
success: function (date) {
    $("#Label1").text(date);
}

A: Have you tried accessing the ASMX directly using a browser? This way, you can easily see what kind of response your ASMX is producing...