text:
Q: Reusing a Javascript function? I have this simple read more JS function. I want to reuse it, what's the best practice for this? For example, below, I have two read more buttons but I have to copy paste the function and some number to it to use it. Not the cleanest way, what's a better way around this?

function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}

function myFunction2() {
  var dots = document.getElementById("dots2");
  var moreText = document.getElementById("more2");
  var btnText = document.getElementById("myBtn2");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
#more {display: none;}
#more2 {display: none;}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction()" id="myBtn">Read more</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction2()" id="myBtn2">Read more</button>

A: First, when repeating behavior you should refrain from attempting to use id attributes since (as you know) they must be unique. Additionally, it leads to naming things without much meaning (thing1, thing2 etc).
One technique is to use the class attribute.
Each event allows access to the target of the event. We can find the paragraph to effect using the previousElementSibling to find the
.
From there, we can use that node to query for the .dots and .more classes and change them as needed.
Since the button is the target of the event, we just change the button text directly.
EDIT: Thanks @Carston for the previousElementSibling hint.

function myFunction(e) {
  const paragraph = e.target.previousElementSibling;
  var dots = paragraph.querySelector('.dots');
  var moreText = paragraph.querySelector(".more");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    e.target.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    e.target.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
.more {display: none;}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction(event)">Read more</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction(event)">Read more</button>

A: You could use a function parameter to dynamically add a suffix to your ids :

function myFunction(suffix) {
  var dots = document.getElementById("dots" + suffix);
  var moreText = document.getElementById("more"  + suffix);
  var btnText = document.getElementById("myBtn"  + suffix);

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
#more {display: none;}
#more2 {display: none;}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction('')" id="myBtn">Read more</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction('2')" id="myBtn2">Read more</button>

Or 3 parameters corresponding to the ids :

function myFunction(dotsId, moreTextId, btnTextId) {
  var dots = document.getElementById(dotsId);
  var moreText = document.getElementById(moreTextId);
  var btnText = document.getElementById(btnTextId);

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}
#more {display: none;}
#more2 {display: none;}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction('dots','more','myBtn')" id="myBtn">Read more</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel...erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

<button onclick="myFunction('dots2','more2','myBtn2')" id="myBtn2">Read more</button>

A: use template literals like this:
function myFunction(number) {
  var dots = document.getElementById(`dots${number}`);
  var moreText = document.getElementById(`more${number}`);
  var btnText = document.getElementById(`myBtn${number}`);

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less";
    moreText.style.display = "inline";
  }
}

<button onclick="myFunction('')" id="myBtn">Read more</button>
<button onclick="myFunction2('2')" id="myBtn2">Read more</button>

A: I guess this answer was not really called for. In my opinion @RandyCasburn already nailed it. However, here is another version that works with even less html to put in place to create unfoldable sections.
By placing a  within a paragraph this section is marked to be "unfoldable". The first part of my script adds the three dots and a "Read more" button and makes the span's original content invisible.
The delegated click event handler then does all the work:

// prepare document once (put "..." and buttons in place):
document.querySelectorAll(".more").forEach(el=>{
  el.dataset.html=el.innerHTML;
  el.textContent="...";
  const btn=document.createElement("button");
  btn.className="morebtn";
  btn.textContent="Read more";
  el.closest("p").after(btn);
})

// delegated event attachment:
document.body.onclick=e=>{
 if (e.target.className==="morebtn"){
  const mor = e.target.previousElementSibling.querySelector(".more");
  [mor.innerHTML,mor.dataset.html]=[mor.dataset.html,mor.innerHTML];
  e.target.innerHTML = mor.textContent==="..."?"Read more":"Read less";
 }
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

And another paragraph with more nonsensical text that will only be shown completely, once the "Read more" button was hit.


text:
Q: Partial differential equations that involve an infinite "continuum" of variables: "Each point in space contributes additional degrees of freedom"? Page 11, Nonlinear Dynamics and Chaos, by Strogatz, says the following:

This is the domain of classical applied mathematics and mathematical physics where the linear partial differential equations live. Here we find Maxwell's equations of electricity and magnetism, the heat equation, Schrödinger's wave equation in quantum mechanics, and so on. These partial differential equations involve an infinite "continuum" of variables because each point in space contributes additional degrees of freedom. Even though these systems are large, they are tractable, thanks to such linear techniques as Fourier analysis and transform methods.

I'm wondering what is meant by the following:

These partial differential equations involve an infinite "continuum" of variables because each point in space contributes additional degrees of freedom.

"Each point in space contributes additional degrees of freedom"? We have three spacial dimensions, but since we're talking about an "infinite" continuum, I'm assuming he's referring to the infinite possible coordinates for these dimensions? I still don't understand why this infinite number of coordinates means that there are infinite variables? In mathematics, the number of variables has nothing to do with the number of possible coordinate combinations (which would be uncountably infinite, since there are an uncountably infinite number of real numbers).
Am I misinterpreting something here?
I would greatly appreciate it if people could please take the time to clarify this.

A: Partial differential equations solve for fields, that is, typically functions $\mathbb{R}^3\rightarrow \mathbb{R}$. How many scalar "variables" do you need to represent such a function?
What is the value of the field at point $(0,0,0)$ ? This is one variable.
What is the value of the field at point $(0,1,0)$ ? This is another variable.
What is the value of the field at point $(e,\sqrt{2},\pi)$ ? A third variable.
How many variables do we have in total, then? That would be the cardinality of the continuum, $\aleph_1$, hence a continuum of variables.

A: See the answer to this question. For completeness, the relevant bit:

For PDEs, the situation is much more complex. This is because, whereas an ODE defines a flow in an $n$-dimensional phase space, a PDE defines a flow in a function space. I'm skipping a lot of very important and interesting details here, but the important thing is that function spaces are infinite dimensional. To make the connection with the ODE case, take the example of the advection equation, given by
  $$
 c \frac{\partial u}{\partial t} + \frac{\partial u}{\partial x} = 0.
$$
  You can use the method of characteristics to write down the general solution to this PDE. The solution is given by
  $$
u(x,t) = f(x - c t),
$$
  where $f(x)$ is a function that plays the role of the initial condition, since $u(x,0) = f(x)$. So, you can pick any function $f(x)$ you like (again, skipping a couple of important and interesting details here), and you get a solution to the PDE. As there are, roughly speaking, infinitely many functions to choose from, you have infinitely many 'degrees of freedom' in picking an initial condition (initial function) for your PDE.
The order of the PDE mainly influences the particular function space it acts on, so the function space in which you can pick a function as initial condition. However, typically, all these function spaces are infinite dimensional -- in the sense that they are not finite-dimensional. The field of functional analysis addresses questions that arise in this context.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET website displaying Windows Server IIS welcome page I have created a new asp.net website and hosted it in IIS in a web server and its opening correctly in the webserver in IE but when I open it in my local windows computer I am getting the IIS welcome page. I am not able to understand how to fix this issue. Can anyone give me some suggestions. Other websites from the same server are working correctly as expected.
similar problem:
http://techspeeder.com/2016/10/28/server-2016-anywhere-access-shows-iis-instead-of-login-page/


text:
Q: Conigure Linux server to do lawful interception I have a server that makes the routing for my LAN (Linux, CentOS). I would like to have on it the possibility of lawful interception: I want to be able to see all network traffic that was done from my LAN (date, MAC, source IP, destination IP, protocols, ports, and some other stuff related to network connections). Is that already implemented in linux, or do I need to write my own software?
Any thoughts would be appreciated.

A: If you really want to see all the traffic on the network, there is really no substitute for a packet sniffer, such as tcpdump. That will record the full contents of every packet according to the rules you've specified, and can log it to a file.
You'll also need a lot of disk space, depending on how much traffic passes through and how much you want to keep.
If you're just interested in logging the start times of connections, and keeping it for a long time, it's probably better to take the approach of logging on firewall rules being hit.


text:
Q: Java 2D Game drawing performance I created a 2D game in java and am trying to get it to 60 fps with a resolution of 1920x1080 pixels. My game logic is performing fine in less than 1 millisecond. But the drawing takes up to over 10 milliseconds. This might be sufficient on my rather strong desktop (intel i5-4670K @ 3.40 Ghz), but on my laptop (intel i5-6300HQ @2.30 Ghz) the game is already slowing down quite a bit. The drawing is separated into two main steps:

*

*draw every component of the game onto a BufferedImage

*draw the BufferedImage in my extended JPanel class
The corresponding code is this:
@Override
public void run() {

    init();

    long startTime;
    long elapsedTime;
    long waitTime;

    while(running) {

        startTime = System.nanoTime();

        update();
        long updateTime = (System.nanoTime() - startTime) / 1000000;
        draw();
        long drawTime = (System.nanoTime() - startTime) / 1000000;
        drawToScreen();
        long drawscreenTime = (System.nanoTime() - startTime) / 1000000;

        elapsedTime = System.nanoTime() - startTime;
        waitTime = targetTime - elapsedTime / 1000000;
        if(waitTime < 0) {
            waitTime = 0;
        }

        try {
            Thread.sleep(waitTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

public void init() {

    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice device = env.getDefaultScreenDevice();
    GraphicsConfiguration config = device.getDefaultConfiguration();
    image = config.createCompatibleImage(1920, 1080, Transparency.TRANSLUCENT);

    g2d = (Graphics2D) image.getGraphics();
    running = true;
    gsm = new GameStateManager(this);
}

public void update() {
    gsm.update();
    Keys.update();
}

public void draw() {
    gsm.draw(g2d);
}

public void drawToScreen() {
    Graphics g = getGraphics();
    g.drawImage(image, 0, startDrawY, scaledWidth, scaledHeight, null);
    g.dispose();
}

Both the draw and drawToScreen methods take up to 5 milliseconds.
inside the draw method, the slowest parts are drawing the background image (1920x1080 image) and drawing the level (consisting of several 135x135 images), which both take a few milliseconds.
Now i have two questions: Is this draw-speed normal for large images like that? And if not what might I be doing wrong here or how can I improve the drawing-performance?

A: Java's core libraries are not meant for efficient graphics rendering, rather user interfaces.  JavaFX supports hardware acceleration.  If you require fine tuning of graphics, see LWJGL or LibGDX.  LibGDX has higher level abstractions, whereas LWJGL has bindings directly to the OpenGL, OpenGLES, and Vulkan API.
If you do not want to use these libraries, Java can have hardware acceleration enabled.  As far as I know, it is not enabled by default.  You will need to add the following argument to the JVM:
-Dsun.java2d.opengl=true
If you are just rendering an image, it will be fine to continue using a BufferedImage.  However, if you are editing the image frequently, consider looking at using a VolatileImage instead.
This is about the extent of my knowledge on speeding up Java2D games.  I would recommend looking at this question here.  The answerer seems very knowledgable, and goes more in depth than I do on the same topic.


text:
Q: Debian "sid"/Gnome: bash + browser cursor blink I'm struggling to make the cursor in bash stop blinking. Also, the cursor in Iceweasel has started blinking again, but, for some reason, a lot slower than in bash :) I got those problems since I upgraded to sid, so probably some configuration files were overwritten.
I tried everything in How to stop cursor from blinking - nothing worked, probably because that was about tty, not bash.
This did not work (that is, setting the flags worked, just didn't do anything to the cursors):
gconftool --search-key cursor_blink
 /desktop/gnome/interface/cursor_blink = false
 /schemas/desktop/gnome/interface/cursor_blink = false

This did work, but only to make the cursor visible and invisible, it didn't stop the blink:
tput cvvis

This did not work:
echo -n -e '\e[?17;14;224c'
printf '\033[?12l'

My PS1 looks like this (added \033[?17;0;127c):
PS1="\033[?17;0;127c\\[$(tput setaf 3)\\]\u \\[$(tput setaf 4)\\]\w: \\[$(tput sgr0)\\]"

This is already set to zero:
/sys/class/graphics/fbcon/cursor_blink

Any more ideas?


text:
Q: How to pass parameter from .run to .config? I work on my angularjs ui-route project.
in .run() core I put some variable in named clientid to $rootScope.
At some point I need to use stored variable in .config() core.
I know that I can't use $rootScope service in .config() core.
So my question is how to pass clientid variable from $rootScope to .config().Maybe I can use any another service?

A: Ofcourse, using $rootScope would be wrong decision. Because no one prefers to pollute global scope and there are other reasons as well. You could consider creating an constant called as settings and utilize that in wherever you needed in any angular components like .run block, config phase, service, provider, etc.
angular.module('mainModule').constant('settings', {
   clientId: 1123 //some inital value
})

Though you could override this value from your config phase.
angular.module('mainModule').config(['settings', configFn])

function configFn(settings){
    //routes registers here

    //other awesome stuf

    //set clientId here
    //Assuming your clientId will be available, no async operation.
    if(someValue === 1)
      settings.clientId = 'asd12';
    else
      settings.clientId = 'asd34';
}

Thereafter you can use that constant inside your run block
angular.module('mainModule').run(['settings', runBlock])

function runBlock(settings){
   console.log(settings);
}

Note: The reason behind selecting constant is, this flavor can be available as injectable in any angular components.


text:
Q: .read() returns "unicode object has no attribute read" in python with askopenfilename() I'm trying to make an import function for scrolledText in Python's Tkinter, but when reading the file, an AttributeError is raised. Code:
def open_command():
    openfile = tkFileDialog.askopenfilename()
    if openfile != None:
        contents = openfile.read()
        textPad.delete('1.0', END)
        textPad.insert('1.0', contents)
        openfile.close()

Error:
    contents = openfile.read()
AttributeError: 'unicode' object has no attribute 'read'

I want to clarify that 'textPad' refers to a 'ScrolledText' object.
Does anyone know why this is happening? at first I thought the error may be coming from encoding, so I encoded in UTF-8 but it still returned the same error. Thanks in advance!

A: tkFileDialog.askopenfilename() returns the file name not a file object. You'll want to do something like:
def open_command():
    filename = tkFileDialog.askopenfilename()
    if filename is not None:
        with open(filename) as f:
           contents = f.read()
        textPad.delete('1.0', END)
        textPad.insert('1.0', contents)

[If you're using Python 2.7 consider using Python 3 or change the above to open(filename, 'r')]


text:
Q: Angular FormGroup form control broken on reload I have the form to choose my image of my logo but when loading the page it is ok, value initiated and the form worke. but when i reload the page or the refresh is empty and broken.
<form [formGroup]="paramForm" (ngSubmit)="onSave()">
<mat-form-field>
  <mat-label>Logo</mat-label>
  <mat-select formControlName="fileUrl" >
    <mat-option *ngFor="let file of fileInfos | async" [value]="file.url">
       {{file.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

  <button type="submit"
          class="btn btn-outline-success mr-3 d-flex align-items-center justify-content-center"
          title="ok">

  </button>

    </form>

ngOnInit(): void {
    this.paramSiteService.getAllParam().pipe(take(1)).subscribe(paramSite => {
      this.paramBDD = paramSite[0];
    },
    error => console.log(error),
    () => {
      this.fileInfos = this.uploadService.getFiles();
      this.initForm();
    }
    );
  }
    public onSave() {
      if (this.paramForm.invalid) {
        return;
      } else {
        const formValue = this.paramForm.value;
        this.paramSiteService.putParam(this.paramBDD.id, formValue['fileUrl'])
          .subscribe(response => {
              window.location.reload();
            }, error => {
              console.log(error);
            }
          );
      }
    }
  private initForm() {
      this.paramForm = this.formBuilder.group({
      fileUrl: [this.paramBDD.logo.url, Validators.required],
      } );
  }

Works only one time

A: <form *ngIf="paramForm" [formGroup]="paramForm" (ngSubmit)="onSave()">
...
</form>

to solve the problem with FormGroup with async.


text:
Q: CSS don't change the font in some HTML docs In advance sorry for poor English.
Here is my situation.
I have two HTML documents which have style,size,color,alignment stored in CSS file.
I checked out,everything is linked properly,but font shows up properly in first document only,in second one it seems like there is no font set at all (shows default font).
Strange thing is that,when I change size in CSS file, it changes it in both HTML documents.(but not font).
Where is possible mistake?
EDIT:
I used dev tools in chrome and it shows me that connection between CSS file and HTML is OK.
Here the code:
1.HTML

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Список завдань</title>
    <link rel="stylesheet" type="text/css" href="https://pizzamaker.github.io/css/theme.css">
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab&subset=cyrillic-ext,latin' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Fredericka+the+Great' rel='stylesheet' type='text/css'>

<link rel="SHORTCUT ICON" href="https://pizzamaker.github.io/images/mark.png"/>

Tasks

    1
    Додайте всі натуральні числа до тисячі, які кратні 3 або 5.

        2
        Знайдіть суму всіх парних елементів ряду Фібоначчі, не більших чотирьох мільйонів.

    3
    Знайдіть найбільший дільник складеного числа, який є простим числом.

    4
    Знайдіть найбільший паліндром, отриманий сумою двох трьохзначних чисел.

    5
    Яке найменше число ділиться без остачі на всі числа від 1 до 20?

    6
    Яка різниця між сумою квадратів та квадратом суми?

    7

    Знайдіть 10001-ше просте число.

    8

    Знайдіть найбільшу суму з послідовності п'яти цифр в 1000-значному числі.

    9
    Здайдіть єдину трійку Піфагора {a, b, c}, для котрої a + b + c = 1000.

    10
    Порахуйте суму всіх простих чисел меньше двох мільйонів.

    11
    Найбільша множина чотирьох чисел в лінії таблиці 20х20?

    12
    Яке перше трикутне число, у якого більше п'ятиста дільників?

    13
    Знайдіть перші десять чесел суми наступних ста 50-значних чисел.

    14
    Знайдіть найдовшу послідовність з початковим елементом меньше мільйона.

    15
    Як багато маршрутів існує в таблиці 20х20, починаючи з лівого верхнього кута та закінчуючи правим нижнім?

    16
    Яка сума цифр числа 21000?

    17
    Скільки літер потрібно для написання усіх чисел від 1 до 1000 словами?

    18
    Знайдіть максимальну суму шляху з вершини трикутника до його основи.

    19
    Скільки  неділь випадають на перше число місяця в двадцатому столітті?

    20
    Знайдіть суму цифр в числі 100!.

2.HTML

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Завдання 1</title>
<link rel="stylesheet" type="text/css" href="https://pizzamaker.github.io/css/theme.css">
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab&subset=cyrillic-ext,latin' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Fredericka+the+Great' rel='stylesheet' type='text/css'>
<link rel="SHORTCUT ICON" href="https://pizzamaker.github.io/images/mark.png"/>

1

Якщо написати усі натуральні числа меньше 10, які є кратні 3 або 5, то отримаємо 3, 5, 6 і 9. Сума цих чисел - 23.

Додайте всі натуральні числа до тисячі, які кратні 3 або 5.

3.CSS
#nazwa {
    font-family:'Fredericka the Great',cursive;
    font-size:4.4em;
    text-align:center;
}

#middle {
    font-family:'Roboto Slab',serif;
    color:#000;
    margin-left:12em;
    margin-right:12em
}

strong {
    text-decoration:underline
}

#numbers {
    font-family:'Droid Serif',serif
}

h2 {
    font-family:'Roboto Slab',serif;
    color:#000;
    text-align:center
}

#header {
    position:absolute;
    top:0;
    right:0;
    left:0;
    height:150px;
    background-color:#fff;
    border-bottom-style:solid;
    background-image:url(https://pizzamaker.github.io/images/linedpaper.png)
}

#button {
    display:inline-block;
    padding:10px
}

#euler {
    margin-top:14em;
    padding:1px;

}

a:link {
    color:#000
}

a:visited {
    color:#000
}

a:hover {
    color:#000
}

a:active {
    color:#000
}

table {
    border-collapse:collapse
}

A: Your fonts are not being applied to the 1st HTMl file because it does not feature #middle, meaning the CSS is working fine.
To fix this, you simply need to add the appropriate id to the 1st HTML file like so:

Tasks

        TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT

On a related note, your 1st HTML file doesn't have tags around your main text. You will need to wrap your text with
s or similar, as you have in the 2nd HTML file. Consistency will save you 90% of errors, and speeds up solving them too!
Lastly, you don't need inline styles on your  tag to apply the background, you can do all that in your CSS like so:
body {
    background-image: url(https://pizzamaker.github.io/images/linedpaper.png);
}


text:
Q: If I post a form which has an element named "element1" and do not specify a value in a markup, does it post empty string or null? an input text element posts an empty string
I am wondering about a form tag which has the name "form1" and no assigned value.
by null I mean "not set".

A: It'll be an empty string. . . .

A: it depends on the particular element type.
You have to ask a question of far better quality to get certain answer.
I see no point in mentioning HTTP headers here though.

A: It posts an empty string (if that's relevant to the input type).  You can't post a null because HTTP doesn't have a native representation for the concept.  (You can post, for example, a JSON string that decodes to a null, but that's not the same thing.)
It's possible that what you meant by "posting a null" is posting a set of form key:value pairs that has no key corresponding to the element in question.  That's what happens if you disable the element; if a text input, for example, is not disabled and has no value set, a key:value pair gets posted for it where the value is an empty string.


text:
Q: Issues with personal listView Adapter I'm having some troubles using my own Adapter class for creating a ListView with delimiter. I'm a beginner in Android development so I really can't fix it alone.
I want to create a listview with the same layout as seen on this web site, and I also want my items to be alphabetically ordered.
So I create two Adapter, one for adding the delimiters, and the other one for handling the specific layout of each item.
The class ListeMusicContainer is an ArrayList sorted alphabetically by name.
Each one works perfectly fine separately, but when I try out both, I get a runtime error.
The error doesn't appear when the application starts, only when I try to scroll (so I guess I'm almost good).
I really don't why I get this error when scrolling. How can this be solved?
Here is the Adapter i use to create a ListView with delimiter
abstract public class MusicAdapter extends BaseAdapter{

abstract protected View getHeaderView(String caption, int index,
        View convertView, ViewGroup parent);
private List<Section> sections = new ArrayList<Section>();

private static int TYPE_SECTION_HEADER = 0;

public MusicAdapter() {
    super();
}

public void addSection(String caption, ItemAdapter adapter){
    sections.add(new Section(caption, adapter));
}

public Object getItem(int position){
    for (Section section : this.sections){
        if (position == 0){
            return section;
        }

        int size = section.adapter.getCount() + 1;
        if (position < size){
            return section.adapter.getItem(position - 1);
        }
        position -= size;
    }
    return null;
}

public int getCount(){
    int total = 0;

    for (Section section : this.sections){
        total += section.adapter.getCount() + 1;
    }
    return total;
}

public int getItemViewType(int position){
    int typeOffset = TYPE_SECTION_HEADER + 1;

    for (Section section : this.sections) {
        if (position == 0) {
            return (TYPE_SECTION_HEADER);
        }

        int size = section.adapter.getCount() + 1;

        if (position < size) {
            return (typeOffset + section.adapter
                    .getItemViewType(position - 1));
        }

        position -= size;
        typeOffset += section.adapter.getViewTypeCount();
    }

    return -1;
}

public boolean areAllItemsSelectable(){
    return false;
}

public boolean isEnabled(int position) {
    return (getItemViewType(position) != TYPE_SECTION_HEADER);
}

@Override
public View getView(int position, View convertView, ViewGroup parent){
    int sectionIndex = 0;

    for (Section section : this.sections){
        if (position == 0){
            return (getHeaderView(section.caption, sectionIndex, convertView, parent));
        }
        int size = section.adapter.getCount() + 1;

        if (position < size){
            return (section.adapter.getView(position - 1, convertView,
                    parent));
        }
        position -= size;
        sectionIndex++;
    }
    return null;
}

@Override
public long getItemId(int position){
    return position;
}

class Section {
    String caption;
    ItemAdapter adapter;

    Section(String caption, ItemAdapter adapter) {
        this.caption = caption;
        this.adapter = adapter;
    }
}
}

And here is the one I use for each item :
public class ItemAdapter extends BaseAdapter{

private ListeMusicContainer<Music> mList;
private LayoutInflater mInflater;

public ItemAdapter(Context context, ListeMusicContainer<Music> musics){
    mInflater = LayoutInflater.from(context);
    mList = musics;
}

@Override
public int getCount() {
    return mList.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null){
        convertView = mInflater.inflate(R.layout.list_item, null);

        holder = new ViewHolder();
        holder.nom = (TextView) convertView.findViewById(R.id.nomAlbum);
        holder.genre = (TextView) convertView.findViewById(R.id.genreAlbum);

        convertView.setTag(holder);
    }
    else{
        holder = (ViewHolder) convertView.getTag();
    }
    holder.nom.setText(mList.getItem(position).getNom());
    holder.genre.setText(mList.getItem(position).getGenre());

    return convertView;
}

static class ViewHolder{
    TextView nom;
    TextView genre;
}

}

Here is how i initialize my layout :
public class TestView extends ListActivity {
/** Called when the activity is first created. */

private ListView mListView;
private static String[] items;
private XmlDataParser mParser;
private ListeMusicContainer<Music> mList;

private MusicAdapter mAdapter = new MusicAdapter() {
    protected View getHeaderView(String caption, int index,
            View convertView, ViewGroup parent) {
        TextView result = (TextView) convertView;

        if (convertView == null) {
            result = (TextView) getLayoutInflater().inflate(
                    R.layout.header, null);
        }

        result.setText(caption);

        return (result);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mParser = new XmlDataParser();
    mList = mParser.parseXml(this);

    ListeMusicContainer<Music> groupe = new ListeMusicContainer<Music>();
    String currLetter = null;

    for (int i = 0; i < mList.size(); i++){
        if (!mList.getItem(i).getLabel().equalsIgnoreCase(currLetter) && currLetter != null){
            mAdapter.addSection(mList.getItem(i).getLabel().toUpperCase(), new ItemAdapter(this, groupe));
            groupe = new ListeMusicContainer<Music>();
            currLetter = mList.getItem(i).getLabel();
        }
        if (currLetter == null){
            currLetter = mList.getItem(i).getLabel();
        }

        groupe.addData(mList.getItem(i));
    }

    setListAdapter(mAdapter);

}
}

edit : in logcat, here is what I got in logcat when running the application :
I/ActivityManager(   42): Displayed activity com.view/.TestView: 1480 ms (total
1480 ms)
D/dalvikvm(  975): GC_EXTERNAL_ALLOC freed 1214 objects / 78504 bytes in 96ms
D/AndroidRuntime(  975): Shutting down VM
W/dalvikvm(  975): threadid=1: thread exiting with uncaught exception (group=0x4
001d800)
E/AndroidRuntime(  975): FATAL EXCEPTION: main
E/AndroidRuntime(  975): java.lang.NullPointerException
E/AndroidRuntime(  975):        at com.view.ItemAdapter.getView(ItemAdapter.java
:51)
E/AndroidRuntime(  975):        at com.view.MusicAdapter.getView(Music
Adapter.java:91)
E/AndroidRuntime(  975):        at android.widget.AbsListView.obtainView(AbsList
View.java:1294)
E/AndroidRuntime(  975):        at android.widget.ListView.makeAndAddView(ListVi
ew.java:1727)
E/AndroidRuntime(  975):        at android.widget.ListView.fillDown(ListView.jav
a:652)
E/AndroidRuntime(  975):        at android.widget.ListView.fillGap(ListView.java
:623)
E/AndroidRuntime(  975):        at android.widget.AbsListView.trackMotionScroll(
AbsListView.java:2944)
E/AndroidRuntime(  975):        at android.widget.AbsListView.onTouchEvent(AbsLi
stView.java:2065)
E/AndroidRuntime(  975):        at android.widget.ListView.onTouchEvent(ListView
.java:3315)
E/AndroidRuntime(  975):        at android.view.View.dispatchTouchEvent(View.jav
a:3766)
E/AndroidRuntime(  975):        at android.view.ViewGroup.dispatchTouchEvent(Vie
wGroup.java:897)
E/AndroidRuntime(  975):        at android.view.ViewGroup.dispatchTouchEvent(Vie
wGroup.java:936)
E/AndroidRuntime(  975):        at android.view.ViewGroup.dispatchTouchEvent(Vie
wGroup.java:936)
E/AndroidRuntime(  975):        at android.view.ViewGroup.dispatchTouchEvent(Vie
wGroup.java:936)
E/AndroidRuntime(  975):        at com.android.internal.policy.impl.PhoneWindow$
DecorView.superDispatchTouchEvent(PhoneWindow.java:1671)
E/AndroidRuntime(  975):        at com.android.internal.policy.impl.PhoneWindow.
superDispatchTouchEvent(PhoneWindow.java:1107)
E/AndroidRuntime(  975):        at android.app.Activity.dispatchTouchEvent(Activ
ity.java:2086)
E/AndroidRuntime(  975):        at com.android.internal.policy.impl.PhoneWindow$
DecorView.dispatchTouchEvent(PhoneWindow.java:1655)
E/AndroidRuntime(  975):        at android.view.ViewRoot.handleMessage(ViewRoot.
java:1785)
E/AndroidRuntime(  975):        at android.os.Handler.dispatchMessage(Handler.ja
va:99)
E/AndroidRuntime(  975):        at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(  975):        at android.app.ActivityThread.main(ActivityThrea
d.java:4627)
E/AndroidRuntime(  975):        at java.lang.reflect.Method.invokeNative(Native
Method)
E/AndroidRuntime(  975):        at java.lang.reflect.Method.invoke(Method.java:5
21)
E/AndroidRuntime(  975):        at com.android.internal.os.ZygoteInit$MethodAndA
rgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(  975):        at com.android.internal.os.ZygoteInit.main(Zygot
eInit.java:626)
E/AndroidRuntime(  975):        at dalvik.system.NativeStart.main(Native Method)

W/ActivityManager(   42):   Force finishing activity com.view/.TestView


text:
Q: How to wrap the row text in table? i have created the table by using TableModel and Table API in LWUIT. I did successfully , but While adding big text ( sentence like 'this is a sample program'), it won't wrap the text instead of displayed as text with dots ( Ex: this...). How to wrap the text in row?

A: Override the Table's createCell method and instead of returning a Label from that method return a TextArea. Set it to editable false and invoke setUIID("TableCell") on it so it will look like a table cell.


text:
Q: Spring : autowiring inside non spring class I have this HTTP listener subclass
public class MigificSessionListener implements HttpSessionListener {
    @Autowired
    @Qualifier("notificationThread")
    private NotificationThread notificationThread;

    @Override
    public void sessionDestroyed(HttpSessionEvent hse) {
          // here notificationThread value is null
    }
}

Value of notificationThread inside sessionDestroyed() is null.
How can i autowire sessionDestroyed inside this class ?

A: Your MigificSessionListener in not in your spring conext, spring even do not know it exists.
You can use WebApplicationContextUtils to get your spring context from ServletContext
WebApplicationContextUtils.getWebApplicationContext(sessionEvent.getSession().getServletContext())

A: Convert your non-Spring managed class MigificSessionListener into a Spring-managed one by annotating it with @Configurable.
For this annotation to be recognised you need <context:spring-configured/> in your Spring XML config or @EnableSpringConfigured if you are using Spring Java config.
The @Autowired or injection of other dependencies will then succeed.

A: You can enable Spring AOP with @EnableSpringConfigured and annotate your class with @Configurable. This let spring manage instances which are created outside the spring context with new. You will also need to enable either load-time weaving or compile-time weaving. This is documented in 9.8.1 Using AspectJ to dependency inject domain objects with Spring.
@Configuration
@EnableSpringConfigured
public class AppConfig {

}

@Configurable
public class MigificSessionListener implements HttpSessionListener {

    @Autowired
    @Qualifier("notificationThread")
    private NotificationThread notificationThread;

    //...

}


text:
Q: Cant get gravity to bottom on "overlay activity" I'm trying to create and overlay that displays on top of another activity, in the bottom. however i can't seem to get it to go to the bottom. It just stays in the middle, and has the height and width as the 2 buttons that are in it.
i have tried the solutions in this question:
Display new Activity on top of previous Activity
But that didn't do it.
So basically i'm down to this simple layout again:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical" android:background="#000" android:weightSum="0.6">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@drawable/greybutton"
        android:text="text1"
        android:textColor="#FFF"
        android:textSize="18dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:background="@drawable/greybutton"
        android:text="text2"
        android:textColor="#FFF"
        android:textSize="18dp"
        android:textStyle="bold" />
</LinearLayout>

And in the manifest:
    <activity android:name=".Overlay_share" android:screenOrientation="portrait" android:theme="@style/Theme.Transparent"></activity>

And in my styles:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@color/semitransparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
<color name="semitransparent">#00000000</color>
</resources>

Any help would be much appreciated.

A: Ok you can do this with a linear layout but i'd suggest a relative one.

*

*Change match_parent to fill_parent for your layout

*You need to specify android:gravity="bottom" for the buttons individually

*If you need the buttons to have equal weights, you should add another LinearLayout that wraps the buttons and specifies a weightSum and have the buttons specify individual layout_weight for the buttons.

So fill_parent, a nested LinearLayout for the buttons that specifies a weightSum and uses wrap_content, and specify layout_weight for the individual buttons. Or a RelativeLayout as i'll try to demonstrate below.
Here's how i'd suggest (personally)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="#000">

<RelativeLayout
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:paddingBottom="20dp"
    android:paddingRight="30dp"
    android:paddingLeft="30dp>
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:paddingRight="10dp"
    android:background="@drawable/greybutton"
    android:text="text1"
    android:textColor="#FFF"
    android:textSize="18dp"
    android:textStyle="bold" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:paddingLeft="10dp"
    android:layout_toRightOf="@id/button1"
    android:background="@drawable/greybutton"
    android:text="text2"
    android:textColor="#FFF"
    android:textSize="18dp"
    android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>

Or LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="#000">
<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:gravity="bottom"
    android:weightSum="2"
    android:paddingBottom="20dp"
    android:paddingRight="30dp"
    android:paddingLeft="30dp>
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:paddingRight="10dp"
    android:background="@drawable/greybutton"
    android:text="text1"
    android:layout_weight="1"
    android:textColor="#FFF"
    android:textSize="18dp"
    android:textStyle="bold" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:paddingLeft="10dp"
    android:layout_weight="1"
    android:background="@drawable/greybutton"
    android:text="text2"
    android:textColor="#FFF"
    android:textSize="18dp"
    android:textStyle="bold" />
</LinearLayout>
</LinearLayout>

Hopefully this at least gets you on the right track


text:
Q: validate text box input (for fasta format) before submission I want to validate a text box input on an HTML page whether it is in fasta format or not and if it only contains one sequence before submission of data.
I know PHP and little idea about JavaScript.
I don't think it is possible with php.

A: In order to validate it using JavaScript, you can use the following function:
/*
 * Validates (true/false) a single fasta sequence string
 * param   fasta    the string containing a putative single fasta sequence
 * returns boolean  true if string contains single fasta sequence, false
 *                  otherwise
 */
function validateFasta(fasta) {

    if (!fasta) { // check there is something first of all
        return false;
    }

    // immediately remove trailing spaces
    fasta = fasta.trim();

    // split on newlines...
    var lines = fasta.split('\n');

    // check for header
    if (fasta[0] == '>') {
        // remove one line, starting at the first position
        lines.splice(0, 1);
    }

    // join the array back into a single string without newlines and
    // trailing or leading spaces
    fasta = lines.join('').trim();

    if (!fasta) { // is it empty whatever we collected ? re-check not efficient
        return false;
    }

    // note that the empty string is caught above
    // allow for Selenocysteine (U)
    return /^[ACDEFGHIKLMNPQRSTUVWY\s]+$/i.test(fasta);
}

Source: http://www.blopig.com/blog/2013/03/a-javascript-function-to-validate-fasta-sequences/
Note, however, that you should perform the same check on the server side with php. The languages are very similar, and php provides everything you need.

A: This is the script that I modified as per my needs and it's working very well in mine case.
-----java script------
function validate(){

var seq = $("#protein_seq").val();

if (!seq) {

 alert("No input");

// check there is something first of all
    return false;
}

seq = seq.trim();

// split on newlines...
var lines = seq.split('\n');

// check for header
if (seq[0] == '>') {

    // remove one line, starting at the first position
    lines.splice(0, 1);
 if (lines[0] ==undefined) {

   alert("Please enter amino acid sequence in second line");
}
}
else{ alert("First line should start with '>' and amino-acid sequence in next line. Please refer to example data");
    //The seq string contains non-DNA characters
    return false;}

// join the array back into a single string without newlines and
// trailing or leading spaces
seq = lines.join('').trim();

//Search for charaters that are not G, A, T or C.
if (seq.search(/[^ACDEFGHIKLMNPQRSTUVWY\s]/i) != -1) {

    alert("Unspecified amino acid seq");
    //The seq string contains non-protein characters
    return false;

 }

---------html page-------------------------------------
 <form action="action.php" method="post" enctype="multipart/form-data" onSubmit="return validate()">
<textarea align=center type="text"  id='protein_seq' name="protein_seq" row='80' cols='100'></textarea>

<input id="button1" type="submit" class="myButton"  value="Submit" />


text:
Q: Get memory and CPU usage using PID? Under windows, given a PID:
1) How to get the exact memory in bytes and
2) The exact CPU usage
consumed by that application right now?

A: *

*See GetProcessMemoryInfo, and specifically the WorkingSetSize field of the out parameter.

*GetProcessTimes will let you know how much time your process has spent altogether in user & kernel space. It's up to you to calculate percentages, or whatever you want out of it.


text:
Q: What is the regular expression for numbers between 10000000 and 29999999? I am not a programmer, but I use a system that sometimes requires  regex knowledge. I need a custom field on a sign up form on my website. The custom field is only numbers between 10000000 and 29999999. How would I write the expression?

A: It'd be something like this:
^[12]\d{7}$
Regex Demo

*

*^ - Matches start of line. Ensuring the next match is the first character of the string.

*[12] - Checks if the first character is a 1 or 2.

*\d{7} - Ensures the next 7 characters are 0-9

*$ - Matches the end of the line. This helps ensures there's nothing after the 7th character that we matched prior.


text:
Q: get xml element value using url xml I am trying to get city data from the xml file.
Below one is a url of XML response from which I am getting a latitude and longitude value from the XML response/file.
http://maps.googleapis.com/maps/api/geocode/xml?address=Kenya&sensor=true
and this is my JavaScript code:-
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function load(){
        var reg = "Kenya";
                alert(reg);
                var xml;
                $.ajax({
                  url: "http://maps.googleapis.com/maps/api/geocode/xml?address="+reg+"&sensor=true",
                  async: false,
                  dataType:'xml',
                  success: function(data)
                {
                    xml=data;
                }
            });
                var lat = $(xml).find('lat:eq(0)').text();
                var lng = $(xml).find('lng:eq(0)').text();
                var radius = "100000";
                alert(lat);
                alert(lng);
                 $.ajax({
              url: "http://services.gisgraphy.com/geoloc/search?lat="+lat+"&lng="+lng+"&radius="+radius+"&format=json",
              async: false,
              dataType:'jsonp',
              success: function(data)
            {
                var asciiname = data.result[0].asciiName;
                console.log(asciiname);
            }
        });
            }
</script>
<body onload="load()">
</body>

with this I am trying to pass Region name in above url with lat and lang value.
http://services.gisgraphy.com/geoloc/search?lat=-0.0235590&lng=37.9061930&radius=100000.
With this url I am trying to get asciiName.
But it's not working and itss display nothing.
What I am doing wrong. Help me to solve my problem.
Thanks.

A: Here is your full code details. You're missing some variables like cntry_code and dataType in ajax call. If your question is solved then accept it.
<script>
    function getlg(){
            var cntry_code = 'IN';
            var reg = 'Rajkot';
            var xml;
            $.ajax({
                url: "http://services.gisgraphy.com//geocoding/geocode?address="+reg+"&country="+cntry_code+"&format=json",
                async: false,
                dataType:'jsonp',
                success: function(data){
                    var id = data.result[1].id;
                    console.log(id);
                    var lat = data.result[1].lat;
                    console.log(lat);
                    var lng = data.result[1].lng;
                    console.log(lng);
                    var radius = "100000";
                    $.ajax({
                          url: "http://services.gisgraphy.com/geoloc/search?lat="+lat+"&lng="+lng+"&radius="+radius+"&format=json",
                          async: false,
                          dataType:'jsonp',
                          success: function(data)
                          {
                                for(i=0;i<data.result.length;i++)
                                {
                                    var asciiname = data.result[i].asciiName;
                                    console.log(asciiname);
                                }
                          }
                    });
                }
            });
        }
</script>


text:
Q: What is the format of datetime in GET requests? Some requests to GitLab API, like listing Merge Requests (https://docs.gitlab.com/ee/api/merge_requests.html#list-merge-requests) allow for URL query parameters of datetime type (created_after and created_before params for this particular example).
I can't seem to find a format for the datetime param that would work. Timestamps (both with and without milliseconds) doesn't work, nor do the ISO format like 2017-06-29T11:00:00.000Z.
Maybe this query parameter doesn't work at all?

A: Found the reason: the created_before and created_after parameters, though listed and described in the official API documentation, are not yet included in any released version.
As of GitLab version 9.3.5 it's still listed under unreleased:
https://github.com/gitlabhq/gitlabhq/blob/master/changelogs/unreleased/12151-add-since-and-until-params-to-issuables.yml
https://github.com/gitlabhq/gitlabhq/commit/9fe6c2b2c2dd92831c93297021b41d6721e4b201

A: Try ISO8601 timestamps, therefore remove nanoseconds and include the timezone:
2017-06-29T11:00:00+00:00
Use for reference the ruby DateTime class as this one is used in Gitlab.
https://ruby-doc.org/stdlib-2.3.1/libdoc/date/rdoc/DateTime.html
The merge request API class of Gitlab:
https://gitlab.com/gitlab-org/gitlab-ce/blob/master/lib/api/merge_requests.rb

A: This is the time format that worked for me (Standard ISO-8601):
three_weeks_ago = (datetime.datetime.now(timezone.utc)- timedelta(days=21)).isoformat() .
mrs = request(f'/merge_requests?state=merged&created_after={three_weeks_ago}&per_page=100')

A: In Gitlab 12.6.4-ee (Enterprise Edition), ISO8601 datetime formats like "2020-02-12T00:08:15Z" and "2020-02-12T00:07:15+01:00" work, when URL-encoded. So "2020-02-12T00:08:15Z" -> "2020-02-12T00%3A08%3A15Z", and "2020-02-12T00:07:15+01:00" -> "2020-02-12T00%3A07%3A15%2B01%3A00". So a full (fake) URL example would be: https://gitlab.mycompany.com/api/v4/projects/myproject/merge_requests?updated_after=2020-02-12T00%3A07%3A15%2B01%3A00


text:
Q: Getting Semantic Grids scss foundation 4 to work I have 3 sections that collapse under the default breakpoint
but I do not know how to get it to collapse with my own css using scss.
default foundation grid that works well and collapses

...

...

...

I tried below out but but it doesn't seem to collapse

...

...

...

.container{
@include grid-row;

.div1 {
    @include grid-column(4);
}
.div2 {
    @include grid-column(4);
}
.div3 {
    @include grid-column(4);
}

}

A: its because you are writing the SCSS for grid-row wrong.
    @include grid-row();

Do NOT use @extend.  that is NOT how foundation4 is made to be used...  @extend just stuffs your styles into .row and .column and that is not what you want to do, instead you want to stick THOSE styles into your styles the reverse way using semantic code therefore you can change the code later in your SCSS and it updates later.
Here is the correct answer:
HTML

...

...

...

SCSS
.container{
@include grid-row();

.div1, .div2, .div3 {
    @include grid-column(12);

    @media #{$medium-up} {
       @include grid-column(4);
    }

    @media #{$large-up} {
           @include grid-column(4);
    }
}

}
Note: this is with foundation 5.  You must create breakpoints.  Your mobile breakpoint should have 12 columns if you want the whole view to collapse in mobile, or whatever you want.   This is the same as

if you want 4 columns for medium and up you write:

So to write that symantically without helper classes you write this:

and the SCSS code is:
.myclassname {
    @include grid-column(12);

    @media #{$medium-up} {
       @include grid-column(4);
    }
}

A: I was baffled by this, but then found out it is actually intended behavior. Here's a quote from the official Foundation grid documentation:

We kept media queries out of the code for our grid mixins. This will enable you to include the mixins inside of whatever breakpoint you'd like, putting you in complete control. If you want to create 10 breakpoints and shift the layout around between each one, by all means. If you want to use only the default breakpoints, we've got variables for that.

A: Use @extend instead.
    .container{
        @extend .grid;
        div{
            @extend .columns;
        }
    }
    .div1 {
        @extend .large-4;
    }
    .div2 {
        @extend .large-4;
    }
    .div3 {
        @extend .large-4;
    }

I made a couple of mixins that works well and I think that makes it easier:
https://gist.github.com/jofralogo/5324278


text:
Q: How to calculate the probability of an event when you don't know the initial probabilities? Say there are two coins: coin A is fair, but coin B always comes up heads.
A friend then flips one of the two coins, and you observe that the coin came up heads.
How do you calculate the probability that this was coin A, when you don't know if your friend chose the coin randomly or not?

A: If you don't know your friend's motivation for picking the coin, it's very difficult to come up with a theoretical probability.
You have to somehow identify your current probability that your friend picked the fair coin... in Bayesian probability this is called the "prior" - your assessment of the probability before you collected the data. In the situation you describe, this might have to be a subjective decision. There is extensive discussion of "uninformative priors" at the link provided.
Remember, that probability is based on the information that you have, and can change depending on what new information you collect.
For example, if your friend makes some knowing wink or comment, you might interpret this as a reason to change your prior probability.
If I have some reason to know that my friend would have picked coin A (like, she prefers tails), then I might assess the probability of coin A to be 1, or under other circumstances 0, or indeed anything in between.
Suggestion: Unless you have some reason to believe that your friend picked in a particular way, it might be sensible to set your prior as though your friend chose randomly (in that case, the posterior probability of coin A would be 1/3).
If your chosen prior probability that your friend picked coin A is set at $p$,
then the resulting posterior probability (after you observe a head) that your friend picked coin A will be $(0.5p)/(1-0.5p)$.
Typically, the 'heads' observation will revise your probability of coin A downwards from the probability you initially thought (unless $p=0$ or $p=1$).

A: Assuming that your friend chose the coin randomly, what we are looking for is what is the probability that your friend chose coin A given that when he flipped it he got a heads. Note that this can we written as $P(\text{coin A}|\text{heads})$. To solve this we use the well known $P(A|B)=\frac{P(A\cap B)}{P(B)}$. Therefore we get $P(\text{coin A}|\text{heads})=\frac{P(\text{coin A}\cap\text{heads})}{P(\text{heads})}$. Using a tree diagram we can find that the probability of choosing coin A and then getting a heads is $\frac{1}{4}$ while the probaility of getting heads is $\frac{3}{4}$. Therefore we get $P(\text{coin A}|\text{heads})=\frac{0.25}{0.75}=\frac{1}{3}$

A: You can never arrive at an exact answer - you can only guess at how your friend chooses the coin, and then see how likely your guess is to be true.
You might make the hypothesis that your friend always chose coin $B$.  In that case, the probability of getting a head would be $0.5$ - you might not think that was likely enough, but most hypotheses are rejected only when they predict that the observed behaviour will occur with probability at most $0.1$.
You might suppose that your friend chooses the coins at random.  In that case, the probability of getting a head would be $0.75$ - that seems likely enough.
The fact that the coin landed heads is, unfortunately, not enough to tell you anything about how your friend had chosen the coin.  If it had landed on tails, then you would know that your friend had chosen $B$, and you would know that she had not adopted the strategy 'always choose heads', and you could be reasonably confident that she had not adopted the strategy 'choose heads with probability $0.99$; otherwise, choose tails'.  Of course, in that case, you would know that your friend had chosen $B$, but...
So you really have nothing to work with.  What you need to do is to repeat the process a number of times, assuming that your friend uses the same strategy each time.
Suppose we wish to test the hypothesis that your friend chooses the coin randomly with probability $\frac{1}{2}$.  Get your friend to toss the coin $10000$ times.  Now we define the $95\%$ confidence interval for the number of heads under our hypothesis to be a range of values for the number of heads such that if our hypothesis is correct, there is a $0.95$ chance that the number of heads lies in that range.  A quick calculation (details of which I am happy to provide) shows that this interval is [7415,7585].  So if your friend tosses $7503$ heads, you can be reasonable confident in your hypothesis.  However, if she tosses $8703$, then you are probably wrong.
Suppose you have good reason to believe that your friend is choosing the coins randomly with probability $\frac{1}{2}$, and you observe her toss $7503$ out of $1000$ heads.  Then you have no evidence to reject your hypothesis, so you accept it.  Now suppose your friend tosses again and gets a head.  Using Emile's method, you know the probability she chose coin $A$ is $\frac{1}{3}$.


text:
Q: How to return value to index page from an included script page? index.php
<?php
$surl = "http://myweb.com/myfolder/include.php";
$me_arr  = array(array('method'=>'x', 'param1'=> 5, 'param2'=> 3),array('method'=>'y', 'param1'=> 2, 'param2'=> 2));
$json_data = json_encode($me_arr);
$strResult = include($surl."?me_Name=".$json_data);

echo $strResult;
?>

include.php
<?php
$method = (isset($_GET['me_Name']))?json_decode($_GET['me_Name'],true):'array()';

if(isset($method))
{
foreach (($method) as $extMethod)
{
$func = $extMethod['method'];
$param1 = $extMethod['param1'];
$param2 = $extMethod['param2'];

$func($param1,$param2,$z);
}
}
function x($x, $y, $z)
{
$z=$y+$x;
echo $z;
}
function y($x, $y, $z)
{
$z=$y+$x;
echo $z;
}
?>

This code works perfectly fine but I want to return the value of z to index.php not echo in include page . But return $z; doesn't work here, just give me the output 1 in index.php. Any way to solve this problem ?? Thanks in advance.

A: In you index.php page after inclusion you can use $z variable as like
<?php
$surl = "http://myweb.com/myfolder/include.php";
$me_arr  = array(array('method'=>'x', 'param1'=> 5, 'param2'=> 3),array('method'=>'y', 'param1'=> 2, 'param2'=> 2));
$json_data = json_encode($methodarr);
$strResult = include($surl."?me_Name=".$json_data);

echo $z; // Using variable from include page
?>


text:
Q: Magento 2 - Redirect to Account Dashboard During Checkout Funnel Login I have the setting checked to redirect a customer to their account dashboard after logging in and it works fine on regular pages, but I noticed that it has no effect when someone is on the checkout page and they log in during the checkout processes.
I need to redirect the customer to their dashboard when they are attempting to log in on the shopping cart page during the /checkout/cart/ funnel. Right now, it shows them their shipping options after logging in from the cart and allows them to continue the checkout process. Any solutions?

A: You have to override Ajax login (root_dir\vendor\magento\module-customer\Controller\Ajax\Login.php) controller and login.js(vendor\magento\module-customer\view\frontend\web\js\action\login.js) for ajax login redirect and need to add your conditions accordingly.
Step 1. Create/edit Your_Company/Your_Module/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Magento\Customer\Controller\Ajax\Login" type="Your_Company\Your_Module\Controller\Ajax\Login" />
</config>

Step 2. Overridden controller will reside in Your_Company\Your_Module\Controller\Ajax\Login.php
Now copy and paste the code from parent Ajax\Login.php
in execute method you will see
if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectRoute) {
    $response['redirectUrl'] = $this->_redirect->success($redirectRoute);
    $this->getAccountRedirect()->clearRedirectCookie();
}

Step 3. Now you have to insert your logic below this condition.
$response['redirectUrl'] = $this->_redirect->success($this->_url->getUrl("customer/account"));

This will set the response.redirectUrl for login.js(vendor\magento\module-customer\view\frontend\web\js\action\login.js) and here we got the real issue there is a code snippet you can check
if (redirectUrl) {
    window.location.href = redirectUrl;
} else if (response.redirectUrl) {
    window.location.href = response.redirectUrl;
} else {
    location.reload();
}

You just have to change it to
if (response.redirectUrl) {
    window.location.href = response.redirectUrl;
} else if (redirectUrl) {
    window.location.href = redirectUrl;
} else {
    location.reload();
}

To override login.js follow steps.
Step 4. Create file requirejs-config.js in You_Company\Your_Module\requirejs-config.js and write below code...
var config = {
    map: {
        '*': {
            'Magento_Customer/js/action/login': 'YourCompany_YourModule/js/login'
        }
    }
};

Step 5.
Copy login.js from vendor\magento\module-customer\view\frontend\web\js\action\login.js to YourCompany\YourModule\view\frontend\web\js\login.js
That's all.


text:
Q: Hibernate não Exclui Boa noite galera...
estou aprendendo Hibernate e tive um problema:
consegui inserir, recuperar os dados do BD... Tive um contratempo que corrigi adicionando a seguinte linha de comando nas configurações da execução (RUN):
--add-modules java.xml.bind

mas na hora de excluir tive este contratempo!
segue meu codigo:
package aplication;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import Dominio.Pessoa;

public class Programa {

    public static void main(String[] args) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("exemplo-jpa");
        EntityManager em = emf.createEntityManager();

        Pessoa p = em.find(Pessoa.class, 1);

        em.remove(p);

        System.out.println("Pronto!");
        em.close();
        emf.close();
    }

}

no BD tenho o registro, onde o Hibernate procura pelo ID 1 que é este registro abaixo:

1   -   algumacoisa@hotmail.com   -   alguem

quando rodo o programa ele nao elxclui e aparece 4 warnigs:

WARNING: An illegal reflective access operation has occurred WARNING:
  Illegal reflective access by javassist.util.proxy.SecurityActions
  (file:/C:/ws/AulaJPA/lib/javassist-3.20.0-GA.jar) to method
  java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
  WARNING: Please consider reporting this to the maintainers of
  javassist.util.proxy.SecurityActions
  WARNING: Use
  --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be
  denied in a future release

coloquei o comando mostrado no warning na configuração da execução:
--illegal-access=warn

ele retornou apenas um warning:

WARNING: Illegal reflective access by
  javassist.util.proxy.SecurityActions
  (file:/C:/ws/AulaJPA/lib/javassist-3.20.0-GA.jar) to method
  java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)

depois pesquisando melhor encontrei o mesmo erro e a resolução seria o seguinte comando:
--add-opens java.base/java.lang=ALL-UNNAMED

beleza... rodei, e não apareceu nenhum Warning, mas não apagou do meu BD!
estou usando JDK 10...
estou baixando a ultima versão estável do Hibernate que suporta versão JDK 8+ pra ver se não é incompatibilidade!
alguém saberia me dizer o que se passa?
valeu!!!

A: Tente acrescentar um em.flush(); após o em.remove(p);.
Quanto a essas warnings, elas são o resultado do conceito de modularização introduzida no Java 9. Muitos desenvolvedores de ferramentas que utilizam de reflection ficaram bem descontentes com essas mudanças que acabaram causando vários problemas inesperados. Apesar disso, pelo menos por enquanto, você não precisa se preocupar com essas warnings.


text:
Q: where to put swap ? partitioning a drive for ubuntu and spare ntfs space I have a spare hard drive.
 I am not setting up dual boot.
 I have ubuntu  on ext4 at the start of the drive.
and want to put a ntfs partition and a swap space
 should I put swap space between ubuntu and ntfs or at the end of drive?

A: It actually doesn't matter.
As long as you don't need to move Ubuntu or Windows, you're fine.
Just add it where you have free space. :)


text:
Q: One sided Corner radius using UIBezierPath bezierPathWithRoundedRect: getting distorted corners. Can anyone help to achieve good corners? One sided Corner radius using UIBezierPath bezierPathWithRoundedRect: getting distorted corners.

Used the following code,
UIBezierPath *maskPath1 = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(view.bounds, 0.5, 0.5) byRoundingCorners:corners cornerRadii:CGSizeMake(6.0, 6.0)];
CAShapeLayer *maskLayer1 = [[CAShapeLayer alloc] init];
maskLayer1.frame = view.bounds;
maskLayer1.path  = maskPath1.CGPath;
maskLayer1.strokeColor = view.layer.borderColor;
maskLayer1.lineJoin = kCALineJoinRound;
view.layer.mask = maskLayer1;
view.layer.masksToBounds = YES;
[view setNeedsDisplay];

the corner radius getting distorted after applied.
Side note : Also the border between the views getting thicken when I add the border width to the views, since the border of view getting merged. Any solution or workaround for this is more helpfull.


text:
Q: Pick image from library and compress windows phone 8.1 In this code first I am picking image from windows phone photo library and then compressing it so that I can upload it. But I am facing some problem in compressing as when I use FlushAsync in BitmapEncoder, the orginal final is not overwritten and exception occurs. Here is my code
Picking image from library
ImagePath = string.Empty;
                    FileOpenPicker filePicker = new FileOpenPicker();
                    filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                    filePicker.ViewMode = PickerViewMode.Thumbnail;

                    // Filter to include a sample subset of file types
                    filePicker.FileTypeFilter.Clear();
                    filePicker.FileTypeFilter.Add(".bmp");
                    filePicker.FileTypeFilter.Add(".png");
                    filePicker.FileTypeFilter.Add(".jpeg");
                    filePicker.FileTypeFilter.Add(".jpg");
                    filePicker.PickMultipleFilesAndContinue();
                    view.Activated += viewActivated;

Decoding and compressing image
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
        if (args != null)
        {
            try
            {
            if (args.Files.Count == 0) return;
            view.Activated -= viewActivated;
            userLoginResponse = await DataManager.GetLoginResponseAsync();
            for (int no = 0; (no < args.Files.Count && no < 4); no++)
            {
                StorageFile storageFile = args.Files[no];
                var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

                var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
                await bitmapImage.SetSourceAsync(stream);
                var decoder = await BitmapDecoder.CreateAsync(stream);
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
                var data = pixelData.DetachPixelData();

                BitmapPropertySet propertySet = new BitmapPropertySet();
                BitmapTypedValue qualityValue = new BitmapTypedValue(1.0, Windows.Foundation.PropertyType.Single);
                propertySet.Add("ImageQuality", qualityValue);
                BitmapEncoder be = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
                be.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, 480, 480, 50, 50, data);
                await be.FlushAsync();

Can anyone please suggest a solution to this problem.
Thanks in advance

A: I used the Nokia Imaging SDK to accomplish this. Just add the SDK to your solution using NuGet.
Then include
using Lumia.Imaging;

in your code file. After that you can use the following code to read the Image data from a StorageFile and compress it to a byte[] which you can then upload to your Server:
byte[] compressedImageBytes = null;
IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read); // "file" being the StorageFile from your FileOpenPicker
if (file.Name.ToLower().EndsWith(".jpg") || file.Name.ToLower().EndsWith(".jpeg"))
{
    using (StreamImageSource source = new StreamImageSource(fileStream.AsStreamForRead()))
    {
        IFilterEffect effect = new FilterEffect(source);
        using (JpegRenderer renderer = new JpegRenderer(effect))
        {
            renderer.Quality = 0.7; // higher value means better quality
            IBuffer buffer = await renderer.RenderAsync();
            Windows.Security.Cryptography.CryptographicBuffer.CopyToByteArray(buffer, out compressedImageBytes);
        }
    }
}}

if (compressedImageBytes != null)
{
    //you can upload or safe the byte-array of the compressed image
}

A: You are trying in your application to select photos from a photo library of Windows Phone, compress them and write back to the library Windows Phone?
I know from your application you can only choose to read pictures from the photo library for Windows Phone. In this way, you cannot change the original  image on your Windows Phone photo library.

A: Though it is late but I think the problem is using stream object multiple time. first you are using the stream to create the BitmapImage and after than using stream to create decoder and after this using the stream again in bitmap encoder.
The funny thing is in Windows phone 8.1 stream object getting null after first time use. so you can clone stream object before using it. in your case you can clone 2 times for decoder & encoder like
var streamDecoder= steam.Clone(); var streamEncoder = stream.Clone(). and use them in your decoder and encoder. I think the problem will be fixed like this.


text:
Q: Store content offline until connection is established I am hoping for some help regarding an offline iPad application.
I have a form within the app that the user fills in, this form then links to a PHP script online. Obviously you can't run the script until you are on line. Is there any way at all of clicking the form submit button, if there is a connection it will connect to and run the PHP and if there is no connection it will automatically run the php in the background when a connection becomes available.
I have tried a number of different searches but have still been unsuccessful.
Thank you in advance!

A: It most likely is possible to solve this problem with JavaScript, but that's not so straightforward. Since you are dealing with an iOS app where it is possible to check network connection status and listen for changes, you probably should create a service that receives the form data within your app. That service should store the data locally, find out when your target server is accessible and send it.
UPDATE:
If you are dealing with a web-app, the way to go for it still to implement a service in JavaScript that uses timed events (i.e. setTimeout() or setInterval()) to check connection status. Upon submitting the form, prevent the default behaviour so the form is not submitted traditionally. Instead, store the data locally in sessionStorage or localStorage and when your service finds the target server available, read the locally stored data and send it via AJAX.


text:
Q: How to nudge a graph to the right without altering the total surface it covers I have a document collection with size 1000, they all have 1 feature, a vector with 5 elements. The total sum of the 5 elements equals 100. So for example I can have a document with feature: [10,15,40,20,15].
Each vector element equals a sentiment, ranging from very negative to very positive.
The results I get for the 1000 text documents come out a little on the negative side,
so I am trying to nudge them all a little to the right without altering the total sum.
For example [10,15,40,20,15] should, after applying the formula, result to [7,13,32,40,8].
How can I manage this?
Thanks in advance!

A: As I understand, you want the first (left) elements of that vector to get smaller, and the right part to get bigger, right?  This can be accomplished by adding something like [-10,-5,0,5,10] to each vector.

A: If the issue is that the corpus is genuinely more negative than you'd like it to be, then how about pre-prending to each document, just before the analysis:
I am a happy bunny!

And if that isn't enough, then also add in:
The sun is shining beautifully in Happy Bunny Land today!!

If the issue is that your analysis is producing a more negative result than what you believe is the correct answer, then fiddle with the weights (if using a weighted approach); if not using a weighted word approach, and you have a list of positive and negative words, then review those lists for the document context and either remove some negative words, or add in some more words to the positive list.


text:
Q: How to catch HttpAntiForgeryException in ASP.NET MVC I'm using the AntiForgeryToken in my ASP.NET MVC forms. If I deactivate cookies in my browser and send the from, I'd get following error message:
A required anti-forgery token was not supplied or was invalid.
How can I prevent this message from showing? I would prefer redirecting the user to another page.
I've activated customErrors and included this HandleError in my controller:
[HandleError(ExceptionType=typeof(HttpAntiForgeryException), View="Index")]
public class MyController : Controller
{
...
}

The HandleError is ignored.
Has anyone got a solution?

A: It works fine for me :)
I notice you've specified the error view as "Index" - is it possible there's an error in this view that only shows up in this error situation? HandleErrorAttribute will be displaying this "Index" view without executing the action itself - if your Index action method is setting objects in ViewData that the View relies on to work, then the error won't be handled properly and you'll get the ugly yelllow page.
If that doesn't fix it, have you tested error handling on other errors to make it works? Some things that can cause errors to not be handled:

*

*Custom errors aren't on in your web.config

*An error in your view

*An error in the master page that the view uses.

A: I think the point of the anti-forgery token is to just deter requests made on behalf of an authenticated user by another website. So if you can legitimately access the form without cookies, that means you can access it without being authenticated so there shouldn't be any need to protect it from CSRF attacks.
I hope someone corrects me if I'm wrong though.


text:
Q: Rolling sum in R df <- data.frame(x = seq(1:10))

I want this:
df$y <- c(1, 2, 3, 4, 5, 15, 20 , 25, 30, 35)

i.e. each y is the sum of previous five x values. This implies the first
five y will be same as x
What I get is this:
df$y1 <- c(df$x[1:4], RcppRoll::roll_sum(df$x, 5))

  x  y y1
  1  1  1
  2  2  2
  3  3  3
  4  4  4
  5  5 15
  6 15 20
  7 20 25
  8 25 30
  9 30 35
  10 35 40

In summary, I need y but I am only able to achieve y1

A: 1) enhanced sum function Define a function Sum which sums its first 5 values if it receives 6 values and returns the last value otherwise.  Then use it with partial=TRUE in rollapplyr:
Sum <- function(x) if (length(x) < 6) tail(x, 1) else sum(head(x, -1))
rollapplyr(x, 6, Sum, partial = TRUE)
##  [1]  1  2  3  4  5 15 20 25 30 35

2) sum 6 and subtract off original Another possibility is to take the running sum of 6 elements filling in the first 5 elements with NA and subtracting off the original vector.  Finally fill in the first 5.
replace(rollsumr(x, 6, fill = NA) - x, 1:5, head(x, 5))
##  [1]  1  2  3  4  5 15 20 25 30 35

3) specify offsets A third possibility is to use the offset form of width to specify the prior 5 elements:
c(head(x, 5), rollapplyr(x, list(-(1:5)), sum))
## [1]  1  2  3  4  5 15 20 25 30 35

4) alternative specification of offsets  In this alternative we specify an offset of 0 for each of the first 5 elements and offsets of -(1:5) for the rest.
width <- replace(rep(list(-(1:5)), length(x)), 1:5, list(0))
rollapply(x, width, sum)
## [1]  1  2  3  4  5 15 20 25 30 35

Note
The scheme for filling in the first 5 elements seems quite unusual and you might consider using partial sums for the first 5 with NA or 0 for the first one since there are no prior elements fir that one:
rollapplyr(x, list(-(1:5)), sum, partial = TRUE, fill = NA)
## [1] NA  1  3  6 10 15 20 25 30 35

rollapplyr(x, list(-(1:5)), sum, partial = TRUE, fill = 0)
## [1]  0  1  3  6 10 15 20 25 30 35

rollapplyr(x, 6, sum, partial = TRUE) - x
## [1]  0  1  3  6 10 15 20 25 30 35

A: A simple approach would be:
df <- data.frame(x = seq(1:10))
mysum <- function(x, k = 5) {
  res <- rep(NA, length(x))
  for (i in seq_along(x)) {
    if (i <= k) { # edited ;-)
      res[i] <- x[i]
    } else {
      res[i] <- sum(x[(i-k):(i-1)])
    }
  }
  res
}
mysum(df$x)
# [1]  1  2  3  4  5 15 20 25 30 35

A: mysum <- function(x, k = 5) {
  res <- x[1:k]
  append<-sapply(2:(len(x)+1-k),function(i) sum(x[i:(i+k-1)]))
  return(c(res,append))
}
mysum(df$x)


text:
Q: View size and owner on folders, within a folder Anyone know how to view all the folders within an directory with size, folder/file, owner?
The only command I know of is du -hs *
But that shows all the subfolders aswell and does not show owner.
For example,
I would like to get the info size, folder/file, owner of the folder/file under "/my/path/".
Any know of command which could provide me with this info?
Br
Hultman

A: Here I've got a simple snippet for you
#!/usr/bin/env bash

unset fname owner size i

for f in "$@"
  do
    fname[i]="$f"
    owner[i]=$(stat -c %U "$f")
    size[i++]=$(stat -c %s "$f")
  done

for i in "${!fname[@]}"
  do
    printf "User %s owns %s and the size is %d Kbytes\n" "${owner[i]}" "${fname[i]}" $((${size[i]} / 1024))
  done

Make the script executable or run it like  bash script_name [path]
chmod u+x script_name

And run it
./script_name /my/path/*

A: You could try the find command:
find /my/path -maxdepth 1 -type d -printf "%u %g   " -exec du -h --max-depth=0 {} \;

should locate all directories (filter -type d) one level below the starting point /my/path (option -maxdepth 1). It will then

*

*use the -printf option to print owner and group, and then

*invoke du --max-depth=0 on each directory found ({}) to print the name and total size directly behind the output of the preceding -printf option, using the -exec mechanism.


text:
Q: Exchange data between android devices of one user without cloud programming i want to program an application that connects different android devices of one user. If happens an event on one device, the other one should be notified (eg. a toast for testing).
Is there a service in the world of google that handles the backend for me, without programming my own server/cloud-app?
An example would be timely from google where i can change the clock on my mobile and seconds later the new value ist available on my tablet.
Thanks

A: Yes there is a service, that can be used for sending notification to another phone. Here is an official link.
Google Cloud Messaging for Android
And this is an example
Android Device to Device Messaging using GCM via HTTP


text:
Q: Programmatically implement Mac long-press accent popup The application I'm working on uses a custom text editor. The problem is that it therefore doesn't employ the Mac's now-standard long-press key accent popup, i.e., holding down 'A' will produce "aaaaaaaaa" instead of the "à á â ä..." window.
Anyone know if it's possible to programmatically call/otherwise implement that accent popup?

A: Properly handling key events so that they interact properly with the system is discussed in the Creating a Custom Text View section of the Cocoa Text Architecture Guide. You should also familiarize yourself with the Handling Key Events chapter of the Cocoa Event Handling Guide (although it's a bit outdated; in particular, it refers to the deprecated NSTextInput protocol which has been replaced by NSTextInputClient).
The basic gist is that you should send key events through either -[NSTextInputContext handleEvent:] or -[NSResponder interpretKeyEvents:], implement action methods on your view, and also have your view class adopt and implement the NSTextInputClient protocol.
You acquire a reference to the appropriate NSTextInputContext object from the inputContext property of NSView.
Sending the key events through one of those handler methods is how that press-and-hold feature gets activated. The NSTextInputClient protocol methods are how it ultimately interacts with your text view's document model. When the user selects a character from the popover, the feature uses that protocol to actually replace the initial character with the final one.
This will also allow your text view to handle Asian input methods.


text:
Q: Using Numpy on IronPython 64 Bit Is it possible at all to use numpy on IronPython 64-bit?  I've made an attempt to use the packages distributed by Enthought but they do not work.
Any suggestions on this?  Are there any projects currently working on getting numpy to work with 64-bit IronPython?


text:
Q: RegEx - Changing a value I have this text:
    <script type="text/javascript" id="wordpress_grazit_script">
            var dbnurls = [];
            var dbnanchors = [];
            dbnurls.push('url');
            dbnanchors.push('anchor');
            var script = document.createElement("script");
            script.setAttribute("src", dbn_protocol+"path to js");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("id", "grazit_script");
            document.getElementById("my-id").parentNode.appendChild(script);
    </script>

and I need to replace dbn_protocol+"path to js" with something else.
I have tried to use this match pattern but it matches all the way to the last );
    "script\\.setAttribute\\([\"']src[\"'],(.*[^\\);])(\\);)(.*)"

I need to spcify that I need this regex in c# .net
Thank you

A: You could match only as from the dbn_protocol (and use @ symbol when defining the regex so you don't have to do a bunch of double escapes):
var regex = new Regex(@"dbn_protocol\+""[^""]+""");

ideone example.
Using the quotes will prevent the regex from matching more than path to js.

A: If in javascript you can do it like this:
var result = yourScriptString.replace(
    /(script\.setAttribute\("src",)(.*)(\))/,
    " $1'" + someUrl + "'$3");

See this jsfiddle for details.

A: If you only want to replace dbn_protocol+"path to js",there are several ways to achieve this,first you can directly replace dbn_protocol+"path to js" with something new using
string.Replace(string searchterm,string replacementterm);

but as you mentioned you want the stuff in regex,so try the method below,it returns a new string(which is a new script section with dbn_protocol+"path to js" replaced).This should satisfy you as it's done using regex;
Regex r = new Regex(@"dbn_protocol\+""[^""]+""");
string newscript=r.Replace("your script's text","the replacement string");
//newscript is the script text that you need.

One more thing i would like to point if you need to change this absolutely once,then why you chose doing it in code while you could easily do it by hand.
Hope it works.

A: Thank you Chris for your answer. The problem was what you said. The regex was taking greedy and going all the way to the last match. I put the '?' and it all worked.
Thank you


text:
Q: D-Bus GLib bindings—unable to get code off the ground I've been playing with GLib's D-Bus bindings, trying to get something (anything) working, with very limited success. I've been trying to get Ross Burton's example code to compile and run, but keep hitting new and exciting difficulties.
Can you help debug this code, or failing that, point me at some example of D-Bus GLib code that does work?
Since Ross' code is out-of-date, I've replaced the line
dbus_g_object_class_install_info (G_OBJECT_CLASS (echo_class), &dbus_glib_echo_object_info);

with
dbus_g_object_type_install_info (G_OBJECT_TYPE (echo_class), &dbus_glib_echo_object_info);

per his comments on that article, but made no other changes other than to update the include directories to match the setup on my box.
When running the server executable, though, I get the following error:
** (process:11747): CRITICAL **: dbus_g_object_type_install_info: assertion `G_TYPE_IS_CLASSED (object_type) || G_TYPE_IS_INTERFACE (object_type)' failed

The stack trace at this point, according to gdb, is
#0  0x0000003b5f40b440 in dbus_g_object_type_install_info () from /usr/lib64/libdbus-glib-1.so.2
#1  0x0000003b5722909c in g_type_class_ref () from /lib64/libgobject-2.0.so.0
#2  0x0000003b57229798 in g_type_create_instance () from /lib64/libgobject-2.0.so.0
#3  0x0000000000400f16 in main (argc=<value optimized out>, argv=0x7fff156497d8) at EchoObject.c:111

I'm not sure what's going wrong, or what the next steps should be in debugging. I'd like to get some basic code sending and receiving D-Bus method call messages, so I can see how things should work to use in my application.
I'm using D-Bus 0.73.
Update: Given the lack of success on my part, and the lack of response here, I'm currently looking at abandoning D-Bus and finding some other IPC mechanism.
Update 2: In the end, I went with a Unix named sockets approach, which is doing exactly what I need it to do in a total of 280 lines of code (plus test code).

A: In the following line
dbus_g_object_type_install_info (G_OBJECT_TYPE (echo_class), &dbus_glib_echo_object_info);

you need to use the G_OBJECT_CLASS_TYPE() macro instead of G_OBJECT_TYPE().
This is because echo_class is an instance of EchoClass, which is a "class structure" in the GObject world. The G_OBJECT_TYPE() is for "object structures", which would be the Echo structure in the aforementioned example.
I know this answer is way to late for @me_and, but maybe someone else will find it useful.

A: dbus-glib is pretty ... nasty to use, and it's basically unmaintained at this point. You're probably better off using its upcoming replacement, GDBus, which will be included in the next stable GLib release. Check out the Lowlevel D-Bus support and Highlevel D-Bus support sections of the documentation for more details.