text:
Q: Playing a video with gstreamer on a Raspberry Pi 3 with Raspbian Stretch I tried playing videos on Raspbian stretch with gstreamer but failed. I started installing gst-omx and tried the following pipelines:
gst-launch-1.0 videotestsrc ! videoconvert ! glimagesink
-> ERROR: from element /GstPipeline:pipeline0/GstGLImageSinkBin:glimagesinkbin0/GstGLImageSink:sink: Failed to connect to X display server

gst-launch-1.0 --gst-debug=3 uridecodebin uri=file:///opt/test/file.mp4 ! autovideosink
and
gst-launch-1.0 --gst-debug=3 playbin uri=file:///opt/test/file.mp4
-> gldisplay gstgldisplay_x11.c:88:gst_gl_display_x11_new: Failed to open X11 display connection with name, '(null)'

It seems like GStreamer is looking for an X display server. But I don't want to use one.
Did anyone get it running on a Raspbian Stretch? It seemed to work on Wheezy.

A: Finally got it working with this gist: https://gist.github.com/moritzvieli/417de950209a24a4f7a57ce1bb5bfeb7
I had to build gstreamer from the sources. This is how i configured the base plugins:
./configure --prefix=/usr \
--disable-gtk-doc --disable-examples \
--disable-opengl --enable-gles2 --enable-egl --disable-glx \
--disable-x11 --enable-wayland --enable-dispmanx \
--with-gles2-module-name=/opt/vc/lib/libbrcmGLESv2.so \
--with-egl-module-name=/opt/vc/lib/libbrcmEGL.so

After this, I always got EGL_NOT_INITIALIZED error, because gstreamer was picking the wrong shared libraries. This could be fixed temporarly with this hack:
sudo ln -fs /opt/vc/lib/libbrcmEGL.so /usr/lib/arm-linux-gnueabihf/libEGL.so.1
sudo ln -fs /opt/vc/lib/libbrcmGLESv2.so /usr/lib/arm-linux-gnueabihf/libGLESv2.so.2

I still have to figure out a proper solution. Maybe uninstall the egl mesa libraries.


text:
Q: excel count rows where column B OR C OR D is higher than X There is a table:
excel table

And I need excel to count me rows that that at least one of the size measure are over 40. In other words:

COUNT B.1994 IF length is > 40 OR width is > 40 OR height is > 40

And it should return in this case 3 rows.
Thank you in advance!

A: =SUM((A2:A5="B.1994")*(((B2:B5>40)+(C2:C5>40)+(D2:D5>40))>0))

press CTRL+SHIFT+ENTER to enter it as an array formula.

A: With data like:

In E2 enter:
=IF(AND(A2="B.1994",MAX(B2:D2)>40),1,0)

and copy down.  Then in another cell:
=SUM(E2:E5)

(The key point is that if any of the elements in a row is greater than 40, then the MAX() of those elements must also be greater than 40)

A: =SUM(IF(MMULT(--($B$2:$D$5>40),{1;1;1})>0, 1, 0)*--($A$2:$A$5="B.1994"))

Ctrl-Shift-Enter (Array formula)

Edit: new requirement:
=SUM(IF(MMULT(--($B$2:$D$5>40),{1;1;1})>1, 1, 0)*--($A$2:$A$5="B.1994"))
The if condition tests if the matrix multiplication totals greater than 1. The original version tested if greater than 0.
Last Edit for requirement:
=SUM(IF(($E$2:$E$5>5)+(MMULT(--($B$2:$D$5>85),{1;1;1})>0)+(MMULT(--($B$2:$D$5>40),{1;1;1})>1)+--($B$2:$B$5*$C$2:$C$5*$D$2:$D$5>3600), 1, 0)*--($A$2:$A$5="B.1994"))

A: =COUNTIFS(range1,critera1,range2,critera2)

The COUNTIFS function applies criteria to cells across multiple ranges and counts the number of times all criteria are met.
If your data starts in cell A1 it would look something like:
=COUNTIFS(B2:B5,">40",C2:C5,">40",D2:D5,">40")

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you obscure an Email Address in ExactTarget? I would like to send subscribers to a link that passes their email address as a url query parameter. Is there a way in ExactTarget to obscure the email address so it cannot be easily read in the url? For example instead of:
http://www.website.com?e=email@address.com
It would look something like
http://www.website.com?e=xSeffWrf3gtH
where the value of e = email@address.com.

A: You can use the Base64Encode() function in ET to encode it and then decode it on the target page using the Base64Decode() function.
Check out this post.  It has a code sample.
EDIT: (Snip from other post)
First page:
%%[
    SET @processingPageURL = MicrositeURL(NNX, "attr1", "value1", "attr2", "value2")
    SET @preferenceCenterURL = MicrositeURL(NNZ, "processingURL", Base64Encode(Replace(@formURL, "=", "_")))
]%%
To the preference center

Target page:
%%[
    SET @formURL = RequestParameter("processingURL")
    SET @formURL = Base64Decode(Replace(@formURL, "_", "="))
]%%
<form action="%%=RedirectTo(@formURL)=%%" method="POST">

A: If you need something more secure, try EncryptSymmetric/DecryptSymmetric.  This is more secure than the Base64 solution, but significantly more complex.  The documentation is too extensive to be posted here, but do have a look at the links.
EncryptSymmetric(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10)

Encrypts plain text data using the supplied algorithm and encryption
  values. You can supply either a value or a valid external key for the
  password, initialization vector, and Salt. You can also use the
  external keys if you have previously created keys in the Key
  Management section of the user interface. Otherwise, the function
  generates a password using the password parameter or stored value, the
  Salt parameter or stored value, and the IV parameter or stored value.
  If you do not pass or reference an initialization vector, the function
  uses the password parameter or stored value as the initialization
  vector. All output provided by this function uses base 64 encoding.
This function treats Salt and IV values (either directly provided or
  looked up by key) as hex strings, with each pair of characters
  repesenting a single byte in the larger strings. Do not attempt to use
  these values as a cipher string, as you cannot successfully encrypt
  those strings using this function.


text:
Q: making a specific section tag 100% width and height of window I have the following structure:

Header

Des

   Link

Header

Des

   Link

I want section#first to be width 100% and height 100% no matter what size the window is and then when the anchor tag is clicked i want section#second to do the same making each section effectively its own page.
Ive tried adding width: 100% and height: 100% to each section but i think js is required to achieve this? can anyone advise me on how this can be achieved?
Kyle

A: Using width: 100%; should effectively keep the div at the width of the window, but the height is a little tricky.
One technique is to use javascript to maintain the height.  Here's an example.
function handleResize(){
    $("#first").height($(window).height());
}

This will set the height on page load, but as the page is resized it won't update.
To handle the resizing you can bind to the resize event.
$(window).bind('resize', handleResize);

You might also need to consider some other events, for example: onorientationchange is an event fired by the iPad when it is rotated.
These code samples use jQuery for simplicity, but it's not required.
To have the two pages alternate, you can do something like:
function handleResize(selector){
    $(selector).height($(window).height());
}
function handleShrink(selector){
    $(selector).height(0);
}
$("#pageTwoLink").click(function(){
    handleShrink("#first");
    handleResize("#second");
}
$("#pageOneLink").click(function(){
    handleShrink("#second");
    handleResize("#first");
}

Of course, this could be drastically cleaned up, if you provide some more information about the exact specification.

A: Great! No javascript required! its like 2 sections of easy css:
  section#first{
    background:darkkhaki;
  }
  section#second{
    background:darkseagreen;
  }

  section#first:target,section#second:target{
    width:100%;
    height:100%;
  }

DEMO: http://jsbin.com/emeyag/edit

A: By setting the position property to fixed, you allow the two sections to exist in the same spot.
section{ position:fixed; top:0;bottom:0;left:0;right:0;}

Then you can use javascript to change which one is visible:
$('a').click(function(){
  $(this).closest('section').hide();
  $($(this).attr('href')).show();
});


text:
Q: Product Hilbert Spaces that require completion? My lecturer said that to make the Hilbert space $(H\oplus H',⟨\cdot,\cdot⟩ )$ we need to (1) make the cartesian product $H \oplus H' = H\times H'$, (2) give it an inner product, and - the confusing part to me - (3) complete the resulting space.
I don't see when this would be required, as the inner product is already continuous, and I can't think of any elements we need to add in say $\mathbb{R}^d$ or $\bigoplus_{n∈ \mathbb{Z}}\operatorname{span}\{e^{2π inx}\} = L^2([0,1]/\sim, \mathbb{C})$ if we don't complete the space.
What product/direct sum of Hilbert spaces $H_i$ would require completion?

A: I agree that, if you make the direct sum of a finite number of Hilbert spaces, then you do not need to complete anything. Indeed, the finite product of complete metric spaces is also complete. However, things change quite a little bit when you switch to infinite products: indeed, the algebraic direct sum of an infinite family of vector spaces consists not on the whole cartesian product (on which it is unclear how to define an inner product), but rather on the elements of it that are zero except for a finite number of entries. For example, the algebraic direct sum of countable copies of $\mathbb{R}$ is
$$
\bigoplus_{\mathbb{N}}^{\text{algebraic}} \mathbb{R}=\left\{ (x_n)_{n\in\mathbb{N}} \ :\ x_n=0\ \text{for all sufficiently big }n\right\}.$$
You make this into a pre-Hilbert space by defining an inner product on it in this way:
$$
\left( (x_n), (y_n)\right) = \sum_{n\in \mathbb{N}} x_ny_n,
$$
(here you need the fact that sequences vanish eventually: otherwise you would get a possibily-non-convergent infinite series here). Finally, taking the completion you get the space usually known as $\ell^2$.


text:
Q: setPreferencesFromResource vs addPreferencesFromResource This question is more academic than procedural.  My preference screen displays and works fine, but while looking up various examples of the proper implementation of AppCompatPreferenceActivity, I discovered people handle loading the XML setting's resource differently in their sample code.
I am only using a single, simple settings setup, all within a single PreferenceScreen and category, but PreferenceFragmentCompat seems to still be the most appropriate and versatile way to go, leaving more options open for the future.  I may or may not add more settings and or categories later.
My question is just this, given the parameters above, are there any benefits or disadvantages in using one call over the other (setPreferencesFromResource vs addPreferencesFromResource).
I've have tried both:
public class PreferenceFragmentCustom extends PreferenceFragmentCompat
{
  @Override
  public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
  {
    setPreferencesFromResource(R.xml.app_preferences, rootKey);
  }
}

and
public class PreferenceFragmentCustom extends PreferenceFragmentCompat
{
  @Override
  public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
  {
    addPreferencesFromResource(R.xml.app_preferences);
  }
}

but, they both seem to work the same (remember, I am not swapping different preference fragments in and out and may or may not in the future).
Again, given the circumstances cited above, I'm asking if there is any reason to choose one method of loading the XML setting's resource over the other (setPreferencesFromResource vs addPreferencesFromResource).
Thank you in advance.

A: they do different things, look at the docs
addPreferencesFromResource : Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.
setPreferencesFromResource: Inflates the given XML resource and replaces the current preference hierarchy (if any) with the preference hierarchy rooted at key.
so basically if you have an app where you want the user to see changed preferences after he does something or even changes a setting then you should use setPreferences to achieve the change.
if your app is big and there are various functionalities each with their own settings then addPreferences can help you in not having to write the entire preference xml at once but rather let it grow organically each functionality having its own preference xml fragment
these are just two examples where the distinctions between the functionality of these two methods might come in handy but I am sure there are many more.
If in your case you dont really care and you only have one preference fragment I guess it really does not matter. tchnically I guess setPreferences would be the "more correct" one but both methods are part of the same library and, as you said, to some extent their functionality overlaps  so who cares XD


text:
Q: Mips Merge Sort I am trying to code a mergesort program using Mips but it is getting caught in an infinite loop and I can't seem to get it to work.
.text
.globl main

main:
addi $sp, $sp, -4
sw   $ra, 0($sp)
la   $a0, array
li   $a1, 3
li   $a2, 43
la   $a3, helper

jal  mergesort      #go through mergesort

move $a0, $v0       #move result to address $a0
li   $v0, 4     #print  out array
syscall

lw   $ra, 0($sp)
addi $sp, $sp, 4
jr   $ra

li   $v0, 10        #finish program
syscall

mergesort:
addi $sp, $sp, 4    #save variables
sw   $ra, 0($sp)
sw   $s0, 4($sp)
sw   $a1, 8($sp)
sw   $a2, 12($sp)
sw   $s1, 16($sp)
sw   $s2, 20($sp)
sw   $s3, 24($sp)
sw   $s4, 28($sp)
sw   $s5, 32($sp)
sw   $s6, 36($sp)
sw   $s7, 40($sp)

slt  $t0, $a1, $a2  #comparing low < high
li   $t1, 1
bne  $t0, $t1, quit #if false finish program

add  $s0, $a1, $a2      #s0 = mid (mid = (high+low)/2)
sll  $s0, $s0, 1

j    mergesort_1    #first recursion
j    mergesort_2    #second recursion
j    merge      #start merge

mergesort_1:
move $a2, $s0       #mid = high
jal  mergesort      #go through mergesort with new parameters

mergesort_2:
add  $s0, $s0, 1    #low = mid+1
move $a1, $s0
jal  mergesort      #go through mergesort with new parameters
merge:
add  $s1, $s1, $a1  #s1 = i = low
add  $s3, $s3, $a1  #s3 = k = low
add  $s2, $s0, 1    #s2 = l = mid+1

add  $s4, $a0, $s1  #s4 = a[i]
srl  $s4, $s4, 2

add  $s5, $a0, $s2  #s5 = a[j]
srl  $s5, $s5, 2

add  $s6, $a3, $s3  #s6 = c[k]
srl  $s6, $s6, 2

while1:
slt $t0, $s0, $s1   #i <= mid
bne $t0, $zero, while2
slt $t1, $a2, $s2
bne $t1, $zero, while2  #j <= high
            #if either fails go to next while loop

add  $s4, $a0, $s1  #s4 = a[i]
srl  $s4, $s4, 2
add  $s5, $a0, $s2  #s5 = a[j]
srl  $s5, $s5, 2

slt  $t2, $s4, $s5  #a[i] < a[j]
addi $t3, $t3, 1
beq  $t2, $t3, if_1     # if condition is true go through if statement

move $s6, $s5       #else, c[k] = a[j]
addi $s3, $s3, 1    #increment
addi $s2, $s2, 1

jal  while1     #go through while loop again

if_1:
add  $s6, $a3, $s3  #s6 = c[k]
srl  $s6, $s6, 2

move $s6, $s4       #c[k] = a[i]

addi $s3, $s3, 1    #increments
addi $s1, $s1, 1

jal  while1     #go through while loop again

while2:
slt  $t0, $s0, $s1  # if i > mid, end while loop
bne  $t0, $zero, while3

add  $s4, $a0, $s1  #s4 = a[i]
srl  $s4, $s4, 2
add  $s6, $a3, $s3  #s6 = c[k]
srl  $s6, $s6, 2

move $s6, $s4       #c[k] = a[i]

addi $s3, $s3, 1    #increments
addi $s1, $s1, 1

jal  while2     #go through while loop again

while3:
slt  $t0, $a3, $s2  # if j > high end while loop
bne  $t0, $zero, for_init

add  $s5, $a0, $s2  #s5 = a[j]
srl  $s5, $s5, 2
add  $s6, $a3, $s3  #s6 = c[k]
srl  $s6, $s6, 2

move $s6, $s5       #c[k] = a[j]

addi $s3, $s3, 1    #increments
addi $s2, $s2, 1

jal  while3     #repeat while loop

for_init:
move $s1, $zero     #set parameters for for loop
add  $s1, $s1, $a1  #i = low

for:
slt  $t0, $s3, $s1  #if i > k end for loop
bne  $t0, $zero, quit

add  $s7, $a3, $s1  #s7 = c[i]
srl  $s7, $s7, 2

add $s4, $a0, $s1   #s4 = a[i]
srl $s4, $s4, 2

move $s4, $s7       #a[i] = c[i]

addi $s1, $s1, 1    #increment

jal  for        #repeat

quit:
lw   $s7, 40($sp)   #load values
lw   $s6, 36($sp)
lw   $s5, 32($sp)
lw   $s4, 28($sp)
lw   $s3, 24($sp)
lw   $s2, 20($sp)
lw   $s1, 16($sp)
lw   $a2, 12($sp)
lw   $a1, 8($sp)
lw   $s0, 4($sp)
lw   $ra, 0($sp)

addi $sp, $sp, 48   #return to main
jr   $ra

.data
array:  .word 56,3,46,47,34,12,1,5,10,8,33,25,29,31,50,43
helper: .word 0:50

It was working yesterday, but for some reason I can't get it to work today and I have no idea what changed.


text:
Q: how to monitor every ui frame draw time when develop on android i am looking for a solution to monitor ui performance. When user touch screen,the view will update.and i want to know the time duration of this action cost

*

*how to monitor ui performance on android?

*can i  monitor every ui frame draw time?

It seems that there is no API;


text:
Q: Batch file `start` command fails if `cmd` not called A .bat script that launches a program stopped working today on Windows 10 Pro 21H1.
Investigating, the batch file contains start "" "%~dp0winnfsd" -log %2 -pathFile %3 -id %4 %5 which filled in is:
start "" "C:\Users\Peter\.vagrant.d\gems\2.6.7\gems\vagrant-winnfsd-1.4.0\bin\winnfsd" -log on -pathFile "C:/Users/Peter/.vagrant.d/nfspaths" -id 0 0

When this is executed from a batch file or command prompt, today it gives the error:
The filename, directory name, or volume label syntax is incorrect.

Press Enter or Esc to exit...

If I remove start "" and run the command from the command prompt it works:
"C:\Users\Peter\.vagrant.d\gems\2.6.7\gems\vagrant-winnfsd-1.4.0\bin\winnfsd" -log on -pathFile "C:/Users/Peter/.vagrant.d/nfspaths" -id 0 0

And after reading https://stackoverflow.com/a/8351295/119750 I modified the batch file to contain this and it works:
start cmd /c call "C:\Users\Peter\.vagrant.d\gems\2.6.7\gems\vagrant-winnfsd-1.4.0\bin\winnfsd.exe" -log on -pathFile "C:/Users/Peter/.vagrant.d/nfspaths" -id 0 0

I don't understand what's going on here or why the first has stopped working.

*

*Why would the first command not work/stop working?

*Why does calling cmd make a difference?


text:
Q: ERROR: Cannot find symbol -- How do I get my class to compile when it depends on a class in a subfolder? Inside my package alignmentparser I have a class named Subject where I have a string I want to convert to a JSON object. After researching how I might achieve this, I found the package JSON-java, which I downloaded and placed into my package as a subdirectory named JSON.
My classes' package statements state package alignmentparser;. I updated the package statements in each file in the JSON subdirectory to package alignmentparser.JSON;.
Now I can't get my TestRunner class (which depends on Subject) to compile. I get these error messages:
./alignmentparser/Subject.java:85: error: cannot find symbol
JSONObject json = new JSONObject(sb.toString());
      ^   symbol:   class JSONObject   location: class Subject
./alignmentparser/Subject.java:85: error: cannot find symbol
JSONObject json = new JSONObject(sb.toString());
      ^   symbol:   class JSONObject   location: class Subject

What can I do to get past these error messages?
EDIT: Here is the whole code, just in case there are errors I don't know about.
Subject.java
package alignmentparser;

import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.util.regex.*;

public class Subject {
  private String id;
  private String sequence;
  // Position on subject where alignment with query begins, inclusive
  private int start;
  // Position on subject where alignment with query ends, inclusive
  private int end;

  public Subject(String accessNum, int hitFrom, int hitTo, String seq) {
    id = accessNum;
    sequence = seq;
    start = hitFrom;
    end = hitTo;
    getEntireSubject();
  }

  // Getters
  public String getSequence() {
    return sequence;
  }
  public int getStart() {
    return start;
  }
  public int getEnd() {
    return end;
  }

  // Fetches accession number from NCBI
  // https://www.ncbi.nlm.nih.gov/books/NBK25498/#chapter3.Application_2_Converting_access
  private void getEntireSubject() {
    try {
      // e post to Entrez
      String link = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?db=nucleotide&id=" + id;
      URLConnection connection = new URL(link).openConnection();
      connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
      connection.connect();
      BufferedReader r  = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

      String webEnv = "";
      String queryKey = "";
      // Put together string to be scanned to find patterns
      StringBuilder sb = new StringBuilder();
      String line;
      while ((line = r.readLine()) != null) {
        sb.append(line);
      }
      String result = sb.toString();
      // Specify patterns to search for
      String queryKeyRegEx = "<QueryKey>(\\d+)<\\/QueryKey>";
      String webEnvRegEx = "<WebEnv>(\\S+)<\\/WebEnv>";
      // Create Pattern objects
      Pattern queryKeyPattern = Pattern.compile(queryKeyRegEx);
      Pattern webEnvPattern = Pattern.compile(webEnvRegEx);
      // Create Matcher objects
      Matcher queryKeyMatcher = queryKeyPattern.matcher(result);
      if (queryKeyMatcher.find()) {
        queryKey = queryKeyMatcher.group(1);
        System.out.println(queryKey);
      }
      Matcher webEnvMatcher = webEnvPattern.matcher(result);
      if (webEnvMatcher.find()) {
        webEnv = webEnvMatcher.group(1);
        System.out.println(webEnv);
      }

      // e fetch to Entrez
      link = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nucleotide&query_key="+queryKey+"&WebEnv="+webEnv+"&usehistory=y";
      connection = new URL(link).openConnection();
      connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
      connection.connect();
      r  = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

      sb = new StringBuilder();
      while ((line = r.readLine()) != null) {
        sb.append(line);
      }
      JSONObject json = new JSONObject(sb.toString());
      System.out.println(json);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

TestRunner.java
package alignmentparser;

import java.util.*;

class TestRunner {
  private String query = "ATCCTGTCTGTGTTAGGAG-AGTCTACTTC-TTAACNGAGGGATTCANTNTTTCCTGCANAGGCGGCCGTCNATGAANACCCTGTTTGTGGACAGCTACNGNGAGATGCTTTTNTTTCTGCAGTCACTGTTCATGCTGGCCACCGTGGTGCTGTACTTCANCCACCTCAAGGAGTATGTGGCTTCCATGGTATTCTCCCTGGCCTTGGGCTGGNCCAACATGCTCTACTACNCCCGCGGTTTCCAGCAGANGGGCATCTATGCCGTCATGATANANAANATGATCCTGAGAGACCTGTGCCGTTTCATGTTTGTCTACGTCGTCTTNTTGTTCGGNTTTTCCACAGCGGNGGTGACGCTGATTGAAGACGGNAANAATGACTCCCTGCCGTCTGAGTCCACGTCGCACAGGNGGNGGGGGCCTGCCTGCANGCCCCCCGATAGCTCCTACAACAGCCTGTACTCCACCTGCCTGGAGCTGTTCAAGTTCACCATCGGCATGGGCGACCTGGANTTCACTGANAACTATGACTTCAAGGCTGTCTTCATCATCCTGCTGCTGGCCTATGTAATTCTCACCTACATCCTCNTGCTCAACATGCTNATCGCCCTCNTGGGTGAGACTGTCAACAAGATCGCACAGNNAGAGCAAGAACATCTGGAANCTGCAGAGAGCCATCACCATCCTGNACACGGAGAAGAGCTTCCTTAAGTGCATGAGGAAGGCCTTCCGCTCAGGCAAGCTGCNTGCANGTGGGGTACACACCTGATGGCAAGGACGACTACCGG";
  private String midline = "||||||||||||||||||| |||||||||| ||  | |||||||||| | ||||||||| ||||||||||| ||||| ||||||||||||||||||||| | ||||||||||| |||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||||||| |||||||||||||||||| |||||||||||||||||||||| | || ||||||||||||||||||||||||||||||||||||||| ||||||| |||||||| ||||||||||||| ||||||||||||||||||||| || |||||||||||||||||||||||||||||||||||| || ||||||||||||||| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| |||||||| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||| ||||||||| |||||||||||||||||||||||||||||  ||||||||||||||||||| |||||||||||||||||||||||| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||| |||| ||||||||||||||||||||||||||||||||||||";
  private Subject subj = new Subject("NM_080704", 1710, 2495, "ATCCTGTCTGTGTTAGGAGGAGTCTACTTCTTTTTCCGAGGGATTCAGTATTTCCTGCAGAGGCGGCCGTCGATGAAGACCCTGTTTGTGGACAGCTACAGTGAGATGCTTTTCTTTCTGCAGTCACTGTTCATGCTGGCCACCGTGGTGCTGTACTTCAGCCACCTCAAGGAGTATGTGGCTTCCATGGTATTCTCCCTGGCCTTGGGCTGGACCAACATGCTCTACTACACCCGCGGTTTCCAGCAGATGGGCATCTATGCCGTCATGATAGAGAAGATGATCCTGAGAGACCTGTGCCGTTTCATGTTTGTCTACATCGTCTTCTTGTTCGGGTTTTCCACAGCGGTGGTGACGCTGATTGAAGACGGGAAGAATGACTCCCTGCCGTCTGAGTCCACGTCGCACAGGTGGCGGGGGCCTGCCTGCAGGCCCCCCGATAGCTCCTACAACAGCCTGTACTCCACCTGCCTGGAGCTGTTCAAGTTCACCATCGGCATGGGCGACCTGGAGTTCACTGAGAACTATGACTTCAAGGCTGTCTTCATCATCCTGCTGCTGGCCTATGTAATTCTCACCTACATCCTCCTGCTCAACATGCTCATCGCCCTCATGGGTGAGACTGTCAACAAGATCGCACAGG-AGAGCAAGAACATCTGGAAGCTGCAGAGAGCCATCACCATCCTGGACACGGAGAAGAGCTTCCTTAAGTGCATGAGGAAGGCCTTCCGCTCAGGCAAGCTGC-TGCAGGTGGGGTACACACCTGATGGCAAGGACGACTACCGG");

  public static void main(String[] args) {
    TestRunner analyzer = new TestRunner();
    analyzer.identifyMismatches();
    analyzer.identifyResidue(547);
  }

  /**
  * Identifies the residue encoded by the codon at the specified codon count.
  */
  private void identifyResidue(int pos) {
    HashMap<String, ArrayList<String>> codons = assembleCodonMap();

    // Set base position of first codon in the CDS (to be retrieved from GenBank later)
    int posOfCDS = 276;
    // Adjust given codon count to account for any difference between CDS / query length
    // NOTE: Subtract 3 to account for conversion between codon count and base count
    int adjustedPos = (pos * 3) - (subj.getStart() - posOfCDS) - 3;
    System.out.println(adjustedPos + subj.getStart());

    if (adjustedPos < 0) {
      System.out.println("Codon " + pos + " is not viewable in this alignment.");
      //System.out.println("You can view codons " + (posFirstCodon + 1) + " through " + ((2495 - 276) / 3));
    }

    // Get codon
    String found = "";
    for (int i = 0; i < query.length(); i += 3) {
      if (i == adjustedPos) {
        found = query.substring(i, i + 3);
        System.out.println(found + " at " + (i + subj.getStart()));
      }
    }

    // Identify residue that codon translates to
    for (String codon : codons.keySet()) {
      if (codons.get(codon).contains(found)) {
        System.out.println("Residue is " + codon);
      }
    }
  }

  private HashMap<String, ArrayList<String>> assembleCodonMap() {
    ArrayList<String> ala = new ArrayList<String>();
    ala.add("GCT");
    ala.add("GCC");
    ala.add("GCA");
    ala.add("GCG");
    ArrayList<String> arg = new ArrayList<String>();
    arg.add("CGT");
    arg.add("CGC");
    arg.add("CGA");
    arg.add("CGG");
    arg.add("AGA");
    arg.add("AGG");
    ArrayList<String> asn = new ArrayList<String>();
    asn.add("AAT");
    asn.add("AAC");
    ArrayList<String> asp = new ArrayList<String>();
    asp.add("GAT");
    asp.add("GAC");
    ArrayList<String> cys = new ArrayList<String>();
    cys.add("TGT");
    cys.add("TGC");
    ArrayList<String> gln = new ArrayList<String>();
    gln.add("CAA");
    gln.add("CAG");
    ArrayList<String> glu = new ArrayList<String>();
    glu.add("GAA");
    glu.add("GAG");
    ArrayList<String> gly = new ArrayList<String>();
    gly.add("GGT");
    gly.add("GGC");
    gly.add("GGA");
    gly.add("GGG");
    ArrayList<String> his = new ArrayList<String>();
    his.add("CAT");
    his.add("CAC");
    ArrayList<String> ile = new ArrayList<String>();
    ile.add("ATT");
    ile.add("ATC");
    ile.add("ATA");
    ArrayList<String> leu = new ArrayList<String>();
    leu.add("TTA");
    leu.add("TTG");
    leu.add("CTT");
    leu.add("CTC");
    leu.add("CTA");
    leu.add("CTG");
    ArrayList<String> lys = new ArrayList<String>();
    lys.add("AAA");
    lys.add("AAG");
    ArrayList<String> met = new ArrayList<String>();
    met.add("ATG");
    ArrayList<String> phe = new ArrayList<String>();
    phe.add("TTT");
    phe.add("TTC");
    ArrayList<String> pro = new ArrayList<String>();
    pro.add("CCT");
    pro.add("CCC");
    pro.add("CCA");
    pro.add("CCG");
    ArrayList<String> ser = new ArrayList<String>();
    ser.add("TCT");
    ser.add("TCC");
    ser.add("TCA");
    ser.add("TCG");
    ser.add("AGT");
    ser.add("AGC");
    ArrayList<String> thr = new ArrayList<String>();
    thr.add("ACT");
    thr.add("ACC");
    thr.add("ACA");
    thr.add("ACG");
    ArrayList<String> trp = new ArrayList<String>();
    trp.add("TGG");
    ArrayList<String> tyr = new ArrayList<String>();
    tyr.add("TAT");
    tyr.add("TAC");
    ArrayList<String> val = new ArrayList<String>();
    val.add("GTT");
    val.add("GTC");
    val.add("GTA");
    val.add("GTG");

    HashMap<String, ArrayList<String>> codons = new HashMap<String, ArrayList<String>>();
    codons.put("alanine", ala);
    codons.put("arginine", arg);
    codons.put("asparagine", asn);
    codons.put("aspartic acid", asp);
    codons.put("cysteine", cys);
    codons.put("glutamine", gln);
    codons.put("glutamic acid", glu);
    codons.put("glycine", gly);
    codons.put("histidine", his);
    codons.put("isoleucine", ile);
    codons.put("leucine", leu);
    codons.put("lysine", lys);
    codons.put("methionine", met);
    codons.put("phenylalanine", phe);
    codons.put("proline", pro);
    codons.put("serine", ser);
    codons.put("threonine", thr);
    codons.put("tryptophan", trp);
    codons.put("tyrosine", tyr);
    codons.put("valine", val);

    return codons;
  }

  /**
  * Prints out mismatches in the alignment of subject and query.
  * Base positions are referenced from subject.
  */
  private void identifyMismatches() {
    // Loops through each character in the midline
    for (int i = 0; i < midline.length(); i++) {
      // If character is a space, denoting a mismatch
      if (midline.charAt(i) == ' ' && query.charAt(i) != 'N') {
        // Print out the characters at the same position in subject & query
        System.out.println(subj.getStart() + i);
        System.out.println(subj.getSequence().charAt(i) + ">" + query.charAt(i));
      }
    }
  }
}

EDIT 2: Screenshot of my folder structure.

A: Firstly, unless you are planning to modify the source code for JSON-java, you don't really need to include the project as source code. Just modify your project dependency to include the JSON-java jar artifact or include it in your classpath so that the necessary classes can be found by the run time.
Secondly, if you really want to include the project as source code and compile it yourself, you still don't need to change the package structure of the project. You can compile it and build the artifact (jar) outside your application.
Thirdly, if you still want to include the project as source code in your own package, you need to modify the package declaration of each and every class within this project. It looks like you have already tried it. But to make sure you have, for example changed the package name of the class JSONObject from org.json to alignmentparser.org.json? Also, when you want to use one or more of these JSON-java classes in your own code, you need to import those classes. E.g. import org.json.JSONObject. I see in your code sample (Subject.java), that you are not doing it. Once you have fixed the package renaming and included the necessary class import statements, you should not get any compiler error.


text:
Q: Security implications of textarea direct to DOM I have a requirement to paste text from a textarea into the DOM as a preview area, much like the one you get on Stackoverflow when you make a comment etc.
I allow users to insert any and all html tags, including javascript tags. I know this will allow embedded javascript and flash content etc, but I then remove all of this server side so no other user will see, they just see plain text.
However are there any security issues in letting the user insert these things in there own page?
My guess is there isn't otherwise tools like firebug would be a security risk, but I'm not sure.

A:
However are there any security issues in letting the user insert these things in there own page?

I can't see any - the DOM is freely manipulable in the client's browser, anyway. Whether they do it using a tool like Firebug or your JavaScript function, doesn't matter.
As long as the data isn't shown unfiltered in other users' browsers, I think you're safe doing this.

A: Actually in rare set of circumstance, it might be an issue. It highly depends on how this particular feature works, but I can imagine making first use of CSRF to 'post' in the preview area some malicious javascript/ajax, and use that to steal cookies, change account password or whatever tickles your fancy.
So the attack would go something like this; I send a user a link to a 'legitimate' website. On that website there is a hidden payload (eg via img tag in case of GET, or hidden iframe with auto-submitting form for POST) which silently redirects the user to your website with the XSS payload, which then will be executed by the user through the injection in the preview area, for instance logging user's cookies, without him ever knowing.
Again it all depends how your preview feature works, and if you for instance use form tokens etc., but the point is that it in fact could be an issue.


text:
Q: Can't connect to sql from php with ip So i have this script for connection to sql server.
//SET CONNECTION TO MSQL
$serverName = "";
$uid = "user";
$pwd = "password";
$databaseName = "database";

//BUILD CONNECTION ARRAY
$connectionInfo = array( "UID"=>$uid,
                         "PWD"=>$pwd,
                         "Database"=>$databaseName);

/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);

//TEST CONNECTION
if( $conn ) {
echo "Connection established.
";

}else{
     echo "Connection could not be established.
";
     die( print_r( sqlsrv_errors(), true));
}

I have this script localy on the server and remote.
My mission is to be able to connect remotely.
So if i try $serverName = "SRV\SQLEXPRESS"; and runt this localy i gott message: Connection established.
If i change the server name for the local ip and test it locally i got this message:

Connection could not be established.
Array ( [0] => Array ( [0] => 08001 [SQLSTATE] => 08001 [1] => 2 [code] => 2 [2] => [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server

I have been talking to the network administration and they say that the port is open and the firewall accepts connections both locally and remote.
If i try to connect remotely i got the message that tha odbc driver cannot be found.
So what seems to be the problem, and what should i do to find it? What can i test?
EDIT
As suggested in the comments i tried:
$serverName = "tcp:192.168.0.242, 51484";

And it worked. I dont know why that port is beeing used? sql configuration manager says 1433 is used?
Remote connection to public ip still tells me that odbc driver is missing?!

A: As @preben said in the comments, this was solved by adding "tcp" to the serverName.
$serverName = "tcp:192.168.0.242, 51484";


text:
Q: 2 Internet Explorer (32 bit) processes taking up CPU I am running Windows 8.1 N Pro x64 and there are 2 Internet Explorer processes that must be for 32 bit. It stays there even if Internet Explorer is closed. I tried ending the processes but they just come back. I run a x64 Internet Explorer. How can I stop those processes?

A: With your more complete description of the "issue", it's easy to answer: that's normal operation of IE: one instance for the frame window, and additional instances for each tab.
See How to determine which IE tabs goes to which IEXPLORE.EXE process... for a more complete description, but basically, when you look at the Command Line used to start each instance, you'll see:
"C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE": frame window
"C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE" SCODEF:m CREDAT:x /prefetch:2 : tab 1
"C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE" SCODEF:n CREDAT:y /prefetch:2 : tab 2
where m & n is the process id (PID) of the parent process and x and y are random integers.


text:
Q: How add image in Apple Local/Push notification message? In some iOS games i see images in local/push notifications: hearts, smiles, ...
How i can get this feature?
At this time i already using a en.lproj and Localizable.strings. May be the solution there?
Thanks

A: I would guess it is not really a "image" in the meaning of a pixel graphic
but a character from the Emojii keyboard you can add to any text on your iPhone.
And then it is the same question as here Sending Emoji in Push Notifications via PHP on iOS .


text:
Q: How to get onChildClick, groupPosition and childPosition from ExpandableListView in android? I'm really unsure as of how to get the groupPosition and the childPosition from the ExpandableListView. I tried using a switch and case, but that doesn't work it doesn't seem to recognize the groupPosition. So how can I get the groupPosition and childPosition?
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    // Set up our adapter
    mAdapter = new MyExpandableListAdapter();
    setListAdapter(mAdapter);
    registerForContextMenu(getExpandableListView());

    getExpandableListView().setOnChildClickListener(new OnChildClickListener()
    {
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
        {
            switch(groupPosition & childPosition)
            {
            case 2 & 2:
                Intent asariIntent = new Intent(Codex.this, CodexAsari.class);
                Codex.this.startActivity(asariIntent);
                break;

            case 1 & 0:
                Intent protheanIntent = new Intent(Codex.this, CodexProthean.class);
                Codex.this.startActivity(protheanIntent);
                break;

            case 1 & 1:
                Intent rachniIntent = new Intent(Codex.this, CodexRachni.class);
                Codex.this.startActivity(rachniIntent);
                break;
            }
            return false;
        }
    });
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    menu.setHeaderTitle("Sample menu");
    menu.add(0, 0, 0, "Sample action");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();

    String title = ((TextView) info.targetView).getText().toString();

    int type = ExpandableListView.getPackedPositionType(info.packedPosition);
    if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
        int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
        int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
        Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,
                Toast.LENGTH_SHORT).show();
        return true;
    } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
        int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
        Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
        return true;
    }

    return false;
}

public class MyExpandableListAdapter extends BaseExpandableListAdapter
{
    public String[] groups = { "Aliens: Council Races", "Aliens: Extinct Races", "Aliens: Non-Council Races", "Aliens: Non-Sapient Creatures", "Citadel and Galactic Government", "Humanity and the Systems Alliance", "Known Associates" };
    private String[][] children = {
            { "Asari", "Salarians", "Turians" },
            { "Protheans", "Rachni" },
            { "Batarians", "Collectors", "Drell", "Elcor", "Geth", "Hanar", "Keepers", "Krogan", "Praetorians", "Quarians",
                "Reapers", "Reapers: Indoctrination", "Sovereign", "Volus", "Vorcha" },
            { "Husks", "Thresher Maws", "Varren" },
            { "Citadel", "Citadel Council", "Citadel Space", "Spectres" },
            { "Councilor Donnel Udina: Anderson Chosen Councilor", "Councilor Donnel Udina:  Undina Chosen Councilor", "Earth: Mass Effect", "Earth: Mass Effect 3", "First Contact War", "Systems Alliance", "Rise of the Alliance: Renegade", "Rise of the Alliance: Paragon" },
            { "Steven Hackett", "David Anderson", "Udina Chosen Councilor", "Dr. Liara T'Soni", "EDI", "Garrus Vakarian", "Kaidan Alenko", "Ashley Williams", "Tali'Zorah", "Dr. Mordin Solus", "Jacob Taylor", "Jeff 'Joker' Moreau", "Miranda Lawson", "Dr. Karin Chakwas" }
    };

    public Object getChild(int groupPosition, int childPosition) {
        return children[groupPosition][childPosition];
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    public int getChildrenCount(int groupPosition) {
        return children[groupPosition].length;
    }

    public TextView getGenericView() {
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 64);

        TextView textView = new TextView(Codex.this);
        textView.setLayoutParams(lp);
        textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
        textView.setPadding(36, 0, 0, 0);
        return textView;
    }

    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
            View convertView, ViewGroup parent) {
        TextView textView = getGenericView();
        textView.setText(getChild(groupPosition, childPosition).toString());
        return textView;
    }

    public Object getGroup(int groupPosition) {
        return groups[groupPosition];
    }

    public int getGroupCount() {
        return groups.length;
    }

    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
            ViewGroup parent) {
        TextView textView = getGenericView();
        textView.setText(getGroup(groupPosition).toString());
        return textView;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public boolean hasStableIds() {
        return true;
    }

}

public int childPosition()
{
    return 0;
}

A: I gotta say, i've never seen a case statement looking like that. Perhaps you could try the following and see if you get any different results:
getExpandableListView().setOnChildClickListener(new OnChildClickListener() {
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        switch(groupPosition) {
        case 1:
            switch (childPosition) {
            case 0:
                Intent protheanIntent = new Intent(Codex.this, CodexProthean.class);
                Codex.this.startActivity(protheanIntent);
                break;
            case 1:
                Intent rachniIntent = new Intent(Codex.this, CodexRachni.class);
                Codex.this.startActivity(rachniIntent);
                break;
            }
        case 2:
            switch (childPosition) {
            case 2:
                Intent asariIntent = new Intent(Codex.this, CodexAsari.class);
                Codex.this.startActivity(asariIntent);
                break;
            }
        }
        return false;
    }
});

A: Try overriding getChildView() in your MyExpandableListAdapter class. getChildView gets called whenever a child is touched on (or when its checkbox is checked or unchecked--I don't remember which, or if there's a difference). Within that method you have access to groupPosition and childPosition. See Working with children in ExpandableListActivity for more information.


text:
Q: Handling multiple GraphQL subscription events in React This has been driving me mad and I can't seem to find anyone else with the same problem, which probably means that I'm missing something fundamental.
I'm using AWS Amplify and have a GraphQL endpoint upon which I'm subscribing to a few events (update, create, delete) in a React project. I have a table bound to my list object that holds my data.
When multiple events come in, my state gets all messed up due to it being asynchronous and my table ends up missing a whole chunk of data. I've tried using useReducer to see if that makes a difference but it doesn't. I feel like I need a way to queue the subscription events and then use them, which makes me wonder if this is not standard practice or I'm missing something fundamental.
This is my reducer.
const reducer = (state, action) => {
   switch (action.type) {
      case "ADD":
         return { ...state, productList: action.payload };
      case "UPDATE":
         //update code
      case "DELETE":
         //delete code
      default:
         return state;
   }
};

My initial load and setup within the component
   const [state, despatch] = useReducer(reducer, { productList: [] });

   useEffect(() => {
      fetchData()
         .then((result) => {
            despatch({ type: "ADD", payload: result });
         })
         .catch((err) => console.log(err));

      setupSubscriptions();
      return () => unsubscribe();
   }, []);

My subscriptions
   function setupSubscriptions() {
      subscriptionOnCreateProduct = API.graphql(graphqlOperation(onCreateProduct)).subscribe({
         next: (e) => {
            const product = e.value.data.onCreateProduct;
            despatch({ type: "ADD", payload: product });
         },
      });
...

An finally my render
return (
...
{state.productList.map((product) => (
  // Display my data
))}

A: In my frustration, I posted this in haste.
I needed to setup different action types for the initial load and when a subscription event adds a new item.
My reducer now looks like this...
const reducer = (state, action) => {
   switch (action.type) {
      case "INIT_LOAD":
         return { ...state, productList: action.products };
      case "ADD":
         return { ...state, productList: [...state.productList, action.product] };
      case "UPDATE":

      ...

      default:
         return state;
   }
};


text:
Q: How do I fetch a json response from ionic-native HTTP get method? I'm studying Ionic and I've started working with some APIs and now I'm having some trouble using the CountryAPI (https://fabian7593.github.io/CountryAPI/). I'm using the GET method to receive a json with informations of all the countries that have "united" in their names. Here's my code:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import firebase from 'firebase'
import { HTTP } from '@ionic-native/http'

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  public resultados: any

  constructor(public navCtrl: NavController, public http: HTTP) {
    this.mget()
  }

  sair(){
    firebase.auth().signOut().then(() => this.navCtrl.setRoot('login'))
  }

  mget(){

    let url = 'http://countryapi.gear.host/v1/Country/getCountries?pName=united'

    this.http.get(url, {}, {}).then( data => {

      console.log(data.data); // data received by server

      let results = JSON.parse(data['_body']).results

    })
  }

}

when I console.log the data received it's all ok and beautiful in a json format, but it's not possible to subscribe for the ionic-native http.get method and if I try something like
for(let i = 0; i < news.length(); i ++){
      console.log(news[i])
      this.noticias.push({
        name: news[i].name,
        nativeName: news[i].nativeName
      })
    }

is no good, it accuses that news.length() is not a function.
I need to fetch all the data in a vector so I can display it in a list with ion-list in my app.

A: To Fetch the JSON data from country API you should add the provider like this:
ionic g provider countryService

and then hit the API like the below code in countryService.ts
  // ******************************** listing API ***********************************
  load() {

    console.log(' RestServiceProvider Load Method fro listing');
    if (this.data) {
      return Promise.resolve(this.data);
    }

    // don't have the data yet
    return new Promise(resolve => {
      this.http.get("http://countryapi.gear.host/v1/Country/getCountries?pName=united")
        .map(res => res.json().response)
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        });
    });
  }

For getting the name of the country you should call this method in your HomePage  like this:
  this.countryService.load().then(data => {
        this.country= data;
      });

show name in UI by using html of HomePage class :
 <ion-list>
        <ion-item *ngFor="let countrylist of country">

User Id: {{countrylist.name}}

{{countrylist.nativeName}}

        </ion-item>
      </ion-list>


text:
Q: Discord.js doesn't see what emoji is reacted So I have been struggling for the past couple of days on how to make this work.
I am trying to make it so when someone submits somebody it will ask for confirmation and then console.logs that. but it doesn't do anything when I press the check.
  // aca!evidence [URL] [ign/name]
  const checkChannel = client.channels.find("name", "testbotchannel");
  const ign = args[1];
  const link = args[2];
  const filter = (reaction, user) => reaction.emoji.name === '✅';

  if(!ign) {
    message.channel.send(`Please define a username`);
  } else if (!link) {
    message.channel.send(`Please define a URL`);
  } else {
    message.reply(`Thanks for submitting! We will review this asap!`)
    .then(msg => {
        msg.delete(10000)
      });
    checkChannel.send(`${message.author} submitted ${ign} (${link})`).then(async message => {
      await message.react("✅")
      await message.react("❎")
      message.awaitReactions(filter)
      .then(() => console.log(`Collected`))
      .catch(console.error)
    });
  }

A: I think what you want instead of .awaitReactions(...) is .createReactionCollector(...). Using this method, you can create an event that responds to each reaction on a message, using the 'collect' event.
Here's an example from the docs, fitted to your code after the line with checkChannel.send(...)
message.react('✅')
.then(mReaction => message.react('❎') )
.then(mReaction => {
    const collector = message.createReactionCollector(reactionFilter, { time: 15000 });
    collector.on('collect', r => console.log(`Collected ${r.emoji.name}`));
    collector.on('end', collected => console.log(`Collected ${collected.size} items`));
})
.catch(console.log);

P.S. I don't use the await library, but i'm sure you can adapt this for your needs. Let me know if you have any questions


text:
Q: Pairing up Django backend with frontend Here's my problem.
I have a small javascript game, which I am trying to pair with Django backend, to store highscores in sessions, maybe implement a highscore board, login, etc. in future. Just as a practice of interaction between front/backend.
So far I have the game running in javascript, and my plan is this: upon getting a score, it sends an ajax (jQuery) request to django, telling django to increment the score. Now here's few questions I have in mind:

*

*Is it possible to render the highscore to template with Django/DTL? Score is set at 0, and each time a player scores, ajax-call to django backend will increment the score by one, and render it in template without refreshing the page. (Also compare it to highscore in sessions, and overwrite it if the new score is higher)
To my understanding, it requires a page refresh, which is not what I want.

*Should I increment the score in frontend with JS, and after a game ends, send the score to django backend to compare it with the one in sessions etc etc.

*Can javascript access values of django view? JSON maybe?
I'm still hesitating if I am heading to the right direction, so if you guys could just point me to the right direction. What would be the best way to implement this?

A: I think it's bad practice to continuously ping the server like that. Especially considering that with something like a game, a lot of things can be changing very quickly. Your best bet is to keep track of what's going on in the front end, and then ping the server as needed to send or request information, query the database, etc (in other words, go with number 2, except you won't need to "compare" it with what's going on in the session, you'd simply be saving the finished game information to your database.)
All in all it depends on the complexity of the game and how you decide to structure it.

A: I don't think you need Django to re-render the page with each update of the score.
Instead, you could have a view render the page when it receives a GET request (returning the HTML of the page) and have jQuery send off AJAX POST requests to a different endpoint (or the post method of a class-based view) with each change of the game state.
If you do that, you can instead just have the endpoint return something like JsonResponse({"success": True, "msg": "High score updated"}). Back on the client side, you can update the score upon receiving that response.
The jQuery might look something like this:
// Remember to use CSRF protection and update CSRF headers accordingly to avoid 403 errors
var newScore = "4000";
$.ajax({
  method: 'POST',
  url: '/api/updateScore',
  data: {
    gameID: '12345',
    newScore: newScore,
  }).done(function(response){
    if(response.success){
        $("#scorebar").html(newScore);
    }
    else{
      // Error handling
    };
  });

And on the Django side, it could be something like
# views.py
class GameView(View):

  def get(self, request, *args, **kwargs):
    return render(request, 'gameboard.html')

  def post(self, request, *args, **kwargs):
    game_id = int(request.POST['gameID']
    game = get_obj_or_404(Game, id=game_id)
    game.score = int(request.POST['newScore'])
    game.save()
    return JsonResponse({
      'success': True,
      'msg': 'Game saved',
    })


text:
Q: Google Mobile Vision Low Image Quality I try to take photo from camera with mobile vision library but taken image's qualities are low (Resolution 240x320)
I don't know where I should modify this feature(I guess it is related with CameraSource) and I'm not sure I should modify or not.
Here is my Capture Function (found from here : How Capture Picture while mobile vision api - face tracking )
public void takePicture(){

        cameraSource.takePicture(null, new CameraSource.PictureCallback() {
            private File imageFile;

            @Override
            public void onPictureTaken(byte[] bytes) {
                try {
                    // convert byte array into bitmap
                    Bitmap loadedImage = null;
                    Bitmap rotatedBitmap = null;
                    loadedImage = BitmapFactory.decodeByteArray(bytes, 0,
                            bytes.length);

                    Matrix rotateMatrix = new Matrix();
                    rotateMatrix.postRotate(0);
                    rotatedBitmap = Bitmap.createBitmap(loadedImage, 0, 0,
                            loadedImage.getWidth(), loadedImage.getHeight(),
                            rotateMatrix, false);

                    File dir = new File(
                            Environment.getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES), "MyPhotos");

                    boolean success = true;
                    if (!dir.exists())
                    {
                        success = dir.mkdirs();
                    }

                    if (success) {
                        java.util.Date date = new java.util.Date();

                        imageFile = new File(dir.getAbsolutePath()
                                + File.separator
                                + new Timestamp(date.getTime()).toString()
                                + "Image.jpg");

                        pictureName = imageFile.getName();
                        Log.i("Picture Name ", pictureName);
                        imageFile.createNewFile();

                        Toast.makeText(MainActivity.this, "Image Saved", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getBaseContext(), "Image Not saved",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();

                    // save image into gallery
                    rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);

                    FileOutputStream fout = new FileOutputStream(imageFile);
                    fout.write(ostream.toByteArray());
                    fout.close();
                    ContentValues values = new ContentValues();

                    values.put(MediaStore.Images.Media.DATE_TAKEN,
                            System.currentTimeMillis());
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                    values.put(MediaStore.MediaColumns.DATA,
                            imageFile.getAbsolutePath());

                    MainActivity.this.getContentResolver().insert(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                    //saveToInternalStorage(loadedImage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

Here is CameraSource creation:
        cameraSource = new CameraSource.Builder(getApplicationContext(), detector)
                .setFacing(CameraSource.CAMERA_FACING_BACK)
                .setRequestedPreviewSize(1280, 1024)
                .setRequestedFps(2.0f)
                .setAutoFocusEnabled(true)
                .build();

Should I modify anything or add something in here?
Thanks for help.

A: I fix this problem with changing these two lines:
 rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);

I changed format to PNG
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);

And changed these attributes of camerasource when I create the variable
.setRequestedPreviewSize(1920, 1024)
 .setRequestedFps(3.0f)


text:
Q: Validate params in Rails In my Rails app I want to validate the filter and post_type params.
Both are optional, but if they are present they must have a value and must have a value that matches one in an array of valid values.
In my controller I have two methods for checking them:
def validate_filter
  if params.has_key?(:filter)
    if params[:filter].present?
      if ['popular', 'following', 'picks', 'promoted', 'first-posts'].include?(params[:filter])
        return true
      else
        return false
      end
    else
      return false
    end
  else
    return true
  end
end

def validate_post_type
  if params.has_key?(:post_type)
    if params[:post_type].present?
      if ['discussions', 'snaps', 'code', 'links'].include?(params[:post_type])
        return true
      else
        return false
      end
    else
      return false
    end
  else
    return true
  end
end

And then in my main controller method I do:
def index
    raise ActionController::RoutingError.new('Not Found') unless validate_filter && validate_post_type
    ...

So this means post_type= and post_type=cam would return a 404 but post_type=snaps would return true.
Is there a better way to validate that the params passed are valid but for both empty and if the key itself exists. Using just blank? and present? is not enough in this scenario.

A: I would probably move this logic to the model, but if you really want it in the controller you could simplify it.
def validate_filer
  return true unless params.has_key?(:filter)
  ['popular', 'following', 'picks', 'promoted', 'first-posts'].include?(params[:filter])
end

A: You can do this in before_action callback of the controller.
before_action :validate_params, only: [:index]

def validate_params
  return false unless params[:filter].present? && params[:post_type].present?
   params_include?(:filter, %w(popular following picks promoted first-posts))
   params_include?(:post_type, %w(discussions snaps code links))
end

A: In a case of an API I would consider letting the client know, that there is a validation error rather than just saying 404.
How about using ActiveModel::Validations?
class MyParamsValidator
  include ActiveModel::Validations

  AVAILABLE_FILTERS    = %w(popular following picks promoted first-posts)
  # this might come from an enum like MyModel.post_types
  AVAILABLE_POST_TYPES = %w(discussions snaps code links)

  attr_reader :data

  validates :filter, inclusion: { in: AVAILABLE_FILTERS }, allow_blank: true
  validates :post_type, inclusion: { in: AVAILABLE_POST_TYPES }, allow_blank: true

  def initialize(data)
    @data = data
  end

  def read_attribute_for_validation(key)
    data[key]
  end
end

class MyController < ApplicationController
  before_action :validate_params, only: :index

  def validate_params
    validator = MyParamsValidator.new(params)

    return if validator.valid?

    render json: { errors: validator.errors }, status: 422
  end
end

You can find more info about a nested case with some tests here.

A: Perhaps a small helper method:
def validate_filter
  params_include?(:filter, %w(popular following picks promoted first-posts))
end

def validate_filter
  params_include?(:post_type, %w(discussions snaps code links))
end

def params_include?(key, values)
  !params.key?(key) || values.include?(params[key])
end

It is not clear from your question where that params are coming from, if they are query parameters or part of the path. If they are part of the path you might consider using routing constraints in your routes.rb


text: Q: The video doesn't play audio in android build in unity I put a videoPlayer component in scene. the video clip is 360 video file and the audio output mood is direct.  it's playing well on game view and IOS device but Android device. so anyone can help me? i'm grateful.screenshot of the video player Component


text:
Q: Alternative to GetRecordInfoFromGuids - Get IRecordInfo without typelib being registered GetRecordInfoFromGuids requires the typelib to be registered, but I don't want to register my typelib (project requirements) because I use it with:
#import "ComService.tlb"

How can I get the IRecordInfo without using GetRecordInfoFromGuids?

A: I think you can use the GetRecordInfoFromTypeInfo function.
The first parameter of this function is a pointer to the ITypeInfo interface.
You can manually load the typelib with the LoadTypeLibEx function and find the required ITypeInfo pointer.

A: One option is to use Registration-Free COM.  You can define COM registrations in your binary's manifest files instead of it being in the registry.  I've used UDTs in this scenario and it works great.  See this walkthrough:
http://msdn.microsoft.com/en-us/library/ms973913.aspx


text:
Q: "Back to the Future" - tense problem So I was watching an episode of the TV show Big Bang Theory and the characters where talking about tenses in regard to the movie Back to the Future II. They said this:

Leonard: If future Biff goes back to 2015 right after he gives young Biff the Almanac, he could get back to the 2015 with Marty and Doc in it. Because it wasn't until his 21st birthday that 1955 Biff placed his first bet.
Sheldon: But whoa, whoa. Is placed right?
Leonard: What do you mean?
Sheldon: Is placed the right tense for something that would've happened in the future of a past that was affected by something from the future?
Leonard: [thinks] Had will have placed?
Sheldon: That's my boy.

My question is:
Is this grammatically correct to say Had will have placed in this situation?
I think it was called the back to the future episode.

A: This is mainly a joke. There isn't a real tense in English to say "something that would've happened in the future of a past that was affected by something from the future," probably because no one has ever encountered such a situation. There's no grammatically correct way to combine tenses in this way.
If I had to make an actual "correct" sentence for this, I would say something like, "But it wasn't until his 21st birthday that 1955 Biff would have placed his first bet in that timeline." But again, there aren't really any rules in grammar about how to talk about time travel. If there were, maybe we had will could have used them.

A: Here's our scenario:

*

*Past A leads into Future A

*Future A changes its past into Past B

*Past B leads into Future B

*We're in Present C

So we're talking about a hypothetical future that won't happen. Which means we can use the conditional perfect tense, 'would have'.

Because it wasn't until his 21st birthday that 1955 Biff would've placed his first bet.


text:
Q: How to manipulate a string representing a raw number (e.g. 130000.1293) into a formatted string (e.g. 130,000.13)? In apps script I want to obtain formatted 'number' strings. The input is an unformatted number. With an earlier answer posted by @slandau, I thought I had found a solution by modifying his code (see code snippet). It works in codepen, but not when I am using apps script.
1. Does anyone know what went wrong here?
2. I noticed this code works except when entering a number ending in .0, in that case the return value is also .0 but should be .00. I would like some help fixing that too.
Thanks!
I have tried to look for type coercion issues, but wasn't able to get it down. I am fairly new to coding.
function commaFormatted(amount)
{
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2);
    var preD = a[1]/(Math.pow(10,a[1].length-2));
    var d = Math.round(preD);
    var i = parseInt(a[0]);
    if(isNaN(i)) { return ''; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while(n.length > 3)
    {
        var nn = n.substr(n.length-3);
        a.unshift(nn);
        n = n.substr(0,n.length-3);
    }
    if(n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if(d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}

console.log(commaFormatted('100000.3532'))

The expected result would be 100,000.35.
I am getting this in the IDE of codepen, but in GAS IDE is stops at the .split() method => not a function. When converting var a to a string = I am not getting ["100000", "3532"] when logging var a. Instead I am getting 100000 and was expecting 3532.

A: Based on this answer, your function can be rewritten to

function commaFormatted(amount)
{
  var inputAmount;
  if (typeof(amount) == 'string') {
    inputAmount = amount;
  } else if (typeof(amount) == 'float') {
    inputAmount = amount.toString();
  }
  //--- we expect the input amount is a String
  //    to make is easier, round the decimal part first
  var roundedAmount = parseFloat(amount).toFixed(2);
  //--- now split it and add the commas
  var parts = roundedAmount.split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join(".");
}

console.log(commaFormatted(100000.3532));
console.log(commaFormatted('1234567.3532'));


text:
Q: how to get checkbox event from grid?
how i can get sum of balance amount of checked row?
I am not able to get event of checkbox and then column's value of that particular row.
Please help me out.

A: I got my Ans by my own
var grid = $("#amount_detail").data("kendoGrid");
            grid.tbody.on("change", ".ob-paid", function (e) {
              var row = $(e.target).closest("tr");
              var item = grid.dataItem(row);
              var balance_amount = item.balance_amount;
              item.set("checkbox", $(e.target).is(":checked") ? 1 : 0);

              if($(e.target).is(":checked")==1){
                      var t = ($("#tot_balance").val() * 1)+(balance_amount * 1);
                      $("#tot_balance").val(t);
              }
              else{
                  var t = ($("#tot_balance").val() * 1)-(balance_amount * 1);
                  $("#tot_balance").val(t);
              }

A: I created a prototype on jsbin for you to check out. This should contain all of the necessary components to do what you're asking for. I am assuming the Kendo UI grid has an ID, so you would want to replace the selector that I have used with your grid's ID. However, the concept is essentially what you're looking for.
Assuming you have a grid with the id myTable, you would be able to do something like this:

                Select

               Action

               Action

                Name

                Unique ID

                Format

                Job #

                Total Amount

                Balance Amount

                <input type="checkbox" class="check" />

                <input type="button" value="Make Payment" />

                <input type="button" value="Change Details" />

                John Doe

                12345

                AIR CAN

                Random Number 11122

                1500

                2340

                <input type="checkbox" class="check" />

                <input type="button" value="Make Payment" />

                <input type="button" value="Change Details" />

                Jane Doe

                56789

                LCL CAN

                Random Number 14562

                1300

                1000

                <input type="checkbox" class="check" />

                <input type="button" value="Make Payment" />

                <input type="button" value="Change Details" />

                Jim Bob

                82352

                AIR CAN

                Random Number 985613

                600

                800

You're JavaScript might look something like this:
$(document).ready(function(){
    //Store the totals here.
    var totals = [];
    //Handle checkbox click.
    $('#myTable input:checkbox').on('click', function(){
        var sum = 0;//For adding the sum
        //Get the cell with the balance in it.
        var number = $(this).parentsUntil('tbody').find('.balance').text();
        //Handle if checked
        if ($(this).is(':checked')){
            $(this).parentsUntil('tbody').addClass('highlight');
            totals.push(parseInt(number));
        }else{//Handle if not checked
            $(this).parentsUntil('tbody').removeClass('highlight');
            var idx = totals.indexOf(parseInt(number));
            totals.splice(idx, 1);
        }
        for (var n = 0; n < totals.length; n++){
            sum += totals[n];
        }
        $('#total').text(sum > 0 ? sum : "");
    });
});

Please see the prototype for clarification on use and for a live demo of the code.
Hope this helps. :)


text:
Q: Rails JSON parse unexpected token escapced chars I have a string that has been escaped, I want to parse this into JSON but I keep getting errors using rails
{\"content\":{\"Soass__text_plain__abc_of_study\":\"Some of Study\",\"Dodeeedd\":
...........
........lots more of the string then comes some \u002d1 etc

Parse error on line 160:
...              "id": \u002d1
JSON::ParserError: 399: unexpected token at '{"spacer":"http://s.c.xxx.yyyy.com/scds/common/u/img/spacer.gif","i18n_get_discovered_upload":"\u003cstrong\u003eGet discovered\u003c/strong\u003e for your work! Add your videos, images, documents...","bg_promo_1":

How can I JSON parse this?

A: You can build your json with hashes or with arrays, its more simple and clean
hash_of_values = {'foo' => 1, 'bar' => 2}
array_of_values = [hash_of_values]

And then :
JSON.parse(hash_of_values) => "{\"foo\":1,\"bar\":2}"
JSON.parse(array_of_values) => "[{\"foo\":1,\"bar\":2}]"


text:
Q: Why does my factorial function always return 1? I'm learning C and came up with this one-line factorial function using a ternary operator on the return, but it always returns 1.
#include <stdio.h>

int factorial(int n){
    return  (n > 1) ? factorial(n -1) : 1;
}

int main() {
    for(int i = 0; i < 10; i++){
        printf("%d factorial is %d\n",i,factorial(i));
    }
    return 0;
}

You can see the code returns 1 for values 0 through 9 in this link:
https://code.sololearn.com/c7uSnfxw92sl/#c

A: You forgot to multiply by n
int factorial(int n){
    return (n > 1) ? n * factorial(n -1) : 1;
}

A: That is very easy since we can use the substitution rules. Eg.
factorial(10);                    // ==
(10 > 1) ? factorial(10 - 1) : 1  // ==
(9 > 1) ? factorial(9 - 1) : 1    // ==
(8 > 1) ? factorial(8 - 1) : 1    // ==
(7 > 1) ? factorial(7 - 1) : 1    // ==
(6 > 1) ? factorial(6 - 1) : 1    // ==
(5 > 1) ? factorial(5 - 1) : 1    // ==
(4 > 1) ? factorial(4 - 1) : 1    // ==
(3 > 1) ? factorial(3 - 1) : 1    // ==
(2 > 1) ? factorial(2 - 1) : 1    // ==
(1 > 1) ? factorial(1 - 1) : 1    // ==
1

Your function is broken. It does not multiply n with the result of factorial(n - 1). You could also do it with an accumulator for it to become tail recursion, but you cannot just replace it with factorial(n - 1) since it will not compute the same as factorial(n).


text:
Q: What does the cast pointer do in this code? This function is supposed to convert an integer value to 32-bit float representation in hex.  But I don't understand what the 3rd line actually does.  Can anyone elaborate on that?
void convert_to_IEEE754( int value, char* ieee754_str ) {
  float ieee754_value = (float) value / 1000;  // value is pre-multiplied by 1000
  byte* array = (byte*) &ieee754_value;
  sprintf( ieee754_str, "%02x%02x%02x%02x", array[3], array[2], array[1], array[0] );
}

A: This cast:
byte* array = (byte*) &ieee754_value;

converts the value &ieee754_value to the type byte *, so that it can be assigned to the variable array. Without the cast the expression &ieee754_value has type float * and such a value cannot be assigned to a variable of type byte *. Thus the cast is necessary.
The array pointer is then used to read the bytes making up the value.
This is not a recommended technique, it's better to use a union for this:
union {
  float ieee754_value;
  byte  bytes[4];
} tmp = { .ieee754_value = (float) value / 1000 };

then access the bytes through tmp.bytes.


text:
Q: How to resolve the domain name I created on domain.com in alibaba cloud SAS? I have created a SAS in Alibaba cloud with ghost template as the image for SAS. I have also created a domain name on domain.com and now I am trying to configure the domain name to the ghost app running on SAS. But when I add the domain name the Resolution Status for this domain still shows as Unresolved. The below error message is displayed on the top of the console.

Domain name, which uses Alibaba Cloud DNS, can be resolved here directly. Other domain should be resolved manually with corresponding DNS service provider.

I have also added the domain name on Alibaba Cloud DNS so I am not sure why this is still not getting resolved. Any help will be much appreciated.

A: Contact your registrar to establish an A record that maps your domain name to the IP address of Alibaba Cloud SAS (Simple Application Server).
Refer:
https://www.alibabacloud.com/help/doc-detail/59080.htm


text:
Q: How big can be the images in the drawable folders? How big can be the images in the drawable folders? I've searched in net but I couldn't find any precise answer. Please help

A: Why so!
Anyways it depends on the device used (SD Card). Larger image can effect the size of app too. So may be you have to look for what max size an Android app can have.
The answer still is, Device Dependent!
If you try to download (install) app with larger size you may get a failure:
Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]

This is a thread describing this issue.


text:
Q: Format SDcard as ext4 for birth time I am using a GoPro Hero 4 to record groundtruth videos. I need to collect the exact time the video has been created (down to miliseconds).
In ext4, there is a field of birthtime ( or ctime, btime). Could I format the SD card to ext4, and stat the birth time later?


text:
Q: corner cube within a cube I want to draw a cube within a cube using tikz, so that the inner cube is a an inner corner, like the drawing below.

I'd like the inner cube to be shaded and for its size to be adjustable, but generally small. In addition, I'd like for space to label all axes, this is a conceptual drawing so no need for tick marks.

A: run with xelatex:
\documentclass{article}
\usepackage{pst-solides3d}
\begin{document}
\psset{lightsrc=viewpoint,viewpoint=50 60 25 rtp2xyz,Decran=50}
\begin{pspicture}[showgrid=false](-3,-3)(3,3)
\psSolid[object=cube,a=4,action=draw]
\psSolid[object=cube,a=1,fillcolor=yellow,action=draw**](-1.5,1.5,-1.5)
\end{pspicture}

\end{document}

A: from the solution
\documentclass[border=5mm,tikz]{article}
\usepackage{mwe}
\usepackage{tikz}
\usetikzlibrary{positioning,calc}

\usepackage{xcolor}
\begin{document}
\newcommand{\Depth}{2}
\newcommand{\Height}{2}
\newcommand{\Width}{2}

\newcommand{\ccube}[5]{
\coordinate (O) at (#1);
\coordinate (A) at (0,#2,0);
\coordinate (B) at (0,#2,#3);
\coordinate (C) at (0,0,#3);
\coordinate (D) at (#4,0,0);
\coordinate (E) at (#4,#2,0);
\coordinate (F) at (#4,#2,#3);
\coordinate (G) at (#4,0,#3);

\draw[blue,fill=yellow!30,opacity=#5] (O) -- (C.center) -- (G) -- (D) -- cycle;% Bottom Face
\draw[blue,fill=blue!30,opacity=#5] (O) -- (A) -- (E) -- (D) -- cycle;% Back Face
\draw[blue,fill=red!10,opacity=#5] (O) -- (A) -- (B) -- (C) -- cycle;% Left Face
\draw[blue,fill=red!20,opacity=#5] (D) -- (E) -- (F) -- (G) -- cycle;% Right Face
\draw[blue,fill=red!20,opacity=#5] (C) -- (B) -- (F) -- (G) -- cycle;% Front Face
\draw[blue,fill=red!20,opacity=#5] (A) -- (B) -- (F) -- (E) -- cycle;% Top Face}
}

\begin{tikzpicture}

\coordinate(O) at (0,0,0);

\ccube{O}{2}{2}{-2}{0.8}
\ccube{O}{5}{5}{-5}{0.2}

\draw ($(C) +(0,-0.5)$) -- node[below,sloped]{label 1} ($(O)+(0,-0.5)$);
\draw ($(C) +(0,-0.5)$) -- node[below,sloped]{label 2} ($(G)+(0,-0.5)$);
\draw ($(A) +(0.5,0)$) -- node[sloped,above]{label 3} ($(O)+(0.5,0)$);
%% Following is for debugging purposes so you can see where the points are
%% These are last so that they show up on top
\foreach \xy in {O, A, B, C, D, E, F, G}{
    \node at (\xy) {\xy};
}
\end{tikzpicture}
\end{document}


text:
Q: Can we prove that some non-cardinal ordinals are regular? Usually the notion of cofinality is used for cardinals, though there seems to be no problem defining it for non-cardinal limit ordinals also: the cofinality of a limit $\alpha$ is the least $\gamma$ such that there is a less than $\gamma$ sequence of ordinals less than $\gamma$ such that the $\operatorname{sup}$ of the sequence is $\alpha$. But running through some examples leaves me wondering whether the notion is interesting: $\operatorname{cf} (\omega \cdot n) = \omega$, and $\operatorname{cf}(\epsilon_0) = \omega$, since $\omega, \omega^\omega, \omega^{\omega^\omega}, \dots$ is a confinal sequence.
My question is, can we prove that some non-cardinal ordinals are regular? More particularly, are there any countable ordinals that can be proven regular?

A: The answer is no. Every regular ordinal is a cardinal.
The reason is simple, if $\alpha$ is not a cardinal, then it has a bijection with some smaller $\gamma$. This bijection is a sequence of order type $\gamma$ which is cofinal in $\alpha$. Therefore the cofinality of $\alpha$ is at most $\gamma<\alpha$.
If you want this sequence to be strictly increasing you can inductively thin out the sequence resulting from the bijection, at each step either you have finished and have an order type smaller than $\gamma$ or you will have a strictly increasing sequence of order type $\gamma$. Either way, we have $<\alpha$.


text:
Q: Gromov-Witten invariants I'm a mathematician studying Schubert calculus, and I'm out to compute the Gromov-Witten invariants of the complete flag manifold. Well, I actually already know how to compute them, but only in a way that involves cancellation, and the goal is to masterfully cancel everything and have only a formula that describes what's left.
I've heard this has some relationship to quantum field theory. I know very little physics other than what an enthusiast would read in a popular science book, but I do have some interest in the relationship of the problem I will spend my life failing to solve (far easier problems have been unsolved for 136 years) to reality. If anyone could give a brief overview of why physicists care about Gromov-Witten invariants I would appreciate it.


text:
Q: Adding a list to my x-bar does not work I want to add list to an x-bar. So im doing:
 data_total <- read.csv2("graph_medewerkers.csv", header = T) #grab excel
 data <- data_total$PERCNG #getting one column
 head(data) =>

 [1] 4.74  8.71  7.01

 qcc(data, type="xbar.one", center = 2)

This however gives me the following error:
 Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] :
 non-numeric argument to binary operator
 In addition: Warning message:
 In mean.default(statistics) :
 argument is not numeric or logical: returning NA

I dont really understand whats going wrong. Cause when I do:
data <- c(4.74, 8.71, 7.01) and then
qcc(data, type="xbar.one", center = 2)

It does work. Any thoughts on whats is triggering the error? There are no numeric values in my set....


text:
Q: Knex(with Expressjs) and postgresSQL: String is automatically double quoted in SQL by knex I have a issue when I try to pass a value in a SQL using knex.
app.get('/home/:topbarMenuPath', (req, res)=> {
  const { topbarMenuPath } = req.params;

  var toStringQuery =
  db.select('tm1.menu_name','tm1.seq','tm1.menu_path','tm1.menu_id')
  .from('tb_menu as tm1')
  .join('tb_menu as tm2', function() {
    this.on('tm1.parent_menu_id', '=', 'tm2.menu_id')
      .andOn('tm2.menu_level', '=', 1)
      .andOn('tm1.menu_level', '=', 2)
      .andOn('tm2.menu_path','=',topbarMenuPath)
  }).toString()
  ;
  console.log('toStringQuery',toStringQuery);
});

If I pass ':topbarMenuPath' as 'hello', the console.log output would be shown below:
select "tm1"."menu_name", "tm1"."seq", "tm1"."menu_path", "tm1"."menu_id"
from "tb_menu" as "tm1"
inner join "tb_menu" as "tm2" on "tm1"."parent_menu_id" = "tm2"."menu_id"
and "tm2"."menu_level" = 1
and "tm1"."menu_level" = 2
and "tm2"."menu_path" = "hello"

It seems that Postgres cannot recognize the double quote "hello", it shows an error when I try to send the SQL to Postgres.
The error:
{
    "length": 166,
    "name": "error",
    "severity": "ERROR",
    "code": "42703",
    "position": "251",
    "file": "d:\\pginstaller_12.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_relation.c",
    "line": "3359",
    "routine": "errorMissingColumn"
}

Is there any way that I can get a SQL with single quote hello like below?
and "tm2"."menu_path" = 'hello'

instead of
and "tm2"."menu_path" = "hello"

A: Yes, from the docs:

If you need to use a literal value (string, number, or boolean) in a join instead of a column, use knex.raw.

knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin']))
Outputs:
select * from `users` inner join `accounts` on `accounts`.`type` = 'admin'

For you, that means .andOn('tm2.menu_path', '=', knex.raw('?', [topbarMenuPath]))


text:
Q: How to send complex array to asp.net mvc controller with JSONP How can i SEND complex type object with array inside it using JSONP
 var product= {categories:[ {id:1,text:"cat 1"},{id:2,text:"cat 2"}],id:43,price:3535};
 $.getJSON(url ,product, function (data) {

 //i can get the data from the server but i cant pass the complex array to the server
 });

and on asp.net mvc server:
    public JsonpResult Create(Product product)
    {
        string thisisok = product.id;
        string needthis = product.categories[0].text;
        return new JsonpResult { Data = true };
    }

how should i pass the complex json using the "getjson" method,
i cant use ajax request because its need to be cross domain

A: Well I had a similar issue; I wanted to pass an array of objects to the controller using jsonp and always I received it as null! (I mean, by GET method and with a callback feature to cross the domain)
Lets suppose I have a complex class: SearchCriteria
public class SearchCriteria
{
    public string destination {get; set;}
    public string destinationTitle { get; set; }
    public string departure { get; set; }
    public string month { get; set; }
    public string nights { get; set; }
    public string cruiseline { get; set; }
}

And I want to pass an array of SearchCriteria to my Controller.
I found the solution creating an attribute:
public class JsonpFilter : ActionFilterAttribute
{
    public string Param { get; set; }
    public Type JsonDataType { get; set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
        {
            string inputContent = filterContext.HttpContext.Request.Params[Param];
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var result = serializer.Deserialize(inputContent, JsonDataType);
            filterContext.ActionParameters[Param] = result;
        }
    }
}

In the controller:
 [JsonpFilter(Param = "criterias", JsonDataType = typeof(SearchCriteria[]))]
 public JsonpResult getResultSet(SearchCriteria[] criterias)
 {
     foreach (SearchCriteria sc in criterias)
     {
         // TODO (normalize criteria, etc..)
     }
     return Jsonp(new { content = RenderPartialViewToString("getResults", criterias)});
 }

In the client script when I call the method:
// Populate the Array of objects

var criteria = new Array();
for (var i = 0; i < 4; i++) {
    criteria.push({ "destination": $("#DestinationValue" + i).val(),
                    "departure": $("#PortValue" + i).val(),
                    "month": $("#Month" + i).val(),
                    "nights": $("#Nights" + i).val(),
                    "cruiseline": $("#CruiselineValue" + i).val()});
}

// Call the controller; note i do not specify POST method and I specify "callback" in order to enable jsonp that cross the domain.

$.ajax({
  url: "getResultSet?callback=?",
  dataType: 'json',
  data: {"criterias" : JSON.stringify(criteria)},
  contentType: 'application/json; charset=utf-8',
  success: function (data) {
              // call return from the controller
           }
});

I hope this could help someone.

A: If you need to return JSONP from your server, why are you returning JSON from your controller action? This being said the JSONP implementation of jQuery relies on adding <script> tags to the DOM and as you know a <script> tag sends a GET request to fetch the resource. That's a limitation of jQuery's JSONP implementation.
But firstyou need to have your server return JSONP. You could write a custom ActionResult that will return JSONP:
public class JsonpResult : ActionResult
{
    private readonly object _obj;

    public JsonpResult(object obj)
    {
        _obj = obj;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var serializer = new JavaScriptSerializer();
        var callbackname = context.HttpContext.Request["callback"];
        var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj));
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(jsonp);
    }
}

and then in your controller action return this result:
public ActionResult Create(Product product)
{
    ...
    return new JsonpResult(new { success = true });
}

and then a client could consume this action but using a GET request (and all the limitations this has such as sending complex objects as the one you have shown):
$.getJSON('http://example.com/products/create', product, function(result) {
    alert(result.success);
});

If you need to send complex objects I think that the best would be to setup a server side script on your domain that will serve as a bridge between your domain and the remote domain and then send a $.ajax request to your script.


text:
Q: how to flush batch data to sink in apache flink I am using apache flink(v1.10.0) to compute RabbitMQ message, the sink the result to MySQL, now I am compute like this:
   consumeRecord.keyBy("gameType")
                .timeWindowAll(Time.seconds(5))
                .reduce((d1, d2) -> {
                    d1.setRealPumpAmount(d1.getRealPumpAmount() + d2.getRealPumpAmount());
                    d1.setPumpAmount(d1.getPumpAmount() + d2.getPumpAmount());
                    return d1;
                })
                .addSink(new SinkFunction<ReportPump>() {
                    @Override
                    public void invoke(ReportPump value, Context context) throws Exception {
                        // save to mysql
                    }
                });

But now the sink method only get one row in each invoke, if one of rows in this batch failed,I could not rollback the batch operate.Now I want to get batch of one window and sink to database once, if failed, I rollback the insert and Apache Flink's checkpoint.This is what I trying to do now:
consumeRecord.keyBy("gameType")
                .timeWindowAll(Time.seconds(5)).reduce(new ReduceFunction<ReportPump>() {
                    @Override
                    public ReportPump reduce(ReportPump d1, ReportPump d2) throws Exception {
                        d1.setRealPumpAmount(d1.getRealPumpAmount() + d2.getRealPumpAmount());
                        d1.setPumpAmount(d1.getPumpAmount() + d2.getPumpAmount());
                        return d1;
                    }
                })
                .apply(new AllWindowFunction<ReportPump, List<ReportPump>, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<ReportPump> values, Collector<List<ReportPump>> out) throws Exception {
                        ArrayList<ReportPump> employees = Lists.newArrayList(values);
                        if (employees.size() > 0) {
                            out.collect(employees);
                        }
                    }
                })
                .addSink(new SinkFunction<List<ReportPump>>() {
                    @Override
                    public void invoke(List<ReportPump> value, Context context) throws Exception {
                        PumpRealtimeHandler.invoke(value);
                    }
                });

but the apply function give tips: Cannot resolve method 'apply' in 'SingleOutputStreamOperator'. How to reduce it and get list of the batch data and flush to database only once?

A: SingleOutputStreamOperator does not have an apply method, because apply can be emit only after windowing.
What you miss here is:
.windowAll(GlobalWindows.create())

between the reduce and the apply, it'll aggregate all the reduced results to one global window that contain list of all the reduces results, than you'll can make collect for one list instead multiple batchs against the database.

I dont know if your result is a good practice, because you'll lose the parallelism of apache flink.
You should read about the TableApi and the JDBC sink, maybe it'll help you. (more information about it here: https://ci.apache.org/projects/flink/flink-docs-stable/dev/table/connect.html#jdbc-connector).


text:
Q: Classifying categories on Yahoo! Answer now I have a seemingly easy but challenging task.I need to develop a data set of questions,and I classify the questions into two categories:

*

*Factoid questions: "who is the current president of France."

*Free questions: "Can you rate the cameras below for me,please?"

now I need to know the percentage of both categories on Yahoo! answer so that I could maintain my data set accordingly,but I don't know a good way of doing this statistic.Doing manually seems really impossible,does anyone have an idea?I would be really grateful,thanks.

A: You mean, recognize one from the other? Automatically, without any categorization from the site's end? That's probably going to be impossible.
I think the best you can do is compare some metrics. "Free" questions will probably tend to have more contributions with more text; they would be more heavily discussed if Y!Answers had a discussion system... "Factoid" questions may start with "What is..." more often ... and so on.
Maybe fetch 100 random questions, do a manual check and write down the percentages.


text:
Q: My graphics card won't work after Windows Logo, with drivers installed even in VGA mode, but works in Safe Mode. Is my GPU toast? Short description (readability and 150 char title limit):
I had a power blackout+brownout recently. The picture on screen would not show. Upon further investigation, the monitor would turn on ONLY in safe mode, until I uninstalled the driver. Drivers were reinstalled, and the monitor turns off after "Starting Windows". Otherwise, it can boot into Windows. I have uninstalled (and cleaned) all the drivers before reinstall of older ones.
Is the GPU bad?
To reiterate, the following events took place:

*

*power goes out for over a minute

*a few seconds after lights go out, thunder rolls

*power browns out again or goes out briefly (I was in another room, I could only see the lights dimming to zero for a brief moment)

*thunder rolls again

Next:

*

*when I turned my computer back on, the picture didn't seem to display

*

*it should be noted here this was a "salvaged" Samsung Syncmaster, which entire company apparently has notoriously buggy and/or defect-ridden power supplies (Google it up, esp. LED TV), often trapping themselves in OFF mode, or eternally flashing standby lights.

*Thus the deeper problem was not immediately evident. Due to the power outage,
the The monitor was refusing to turn on (this monitor has to be kept on--I have even disassembled it to look for bad capacitors, per an EEVBlog post).

*Switched bad monitor for my old one. It became clear:

*blue power LED showed yellow AFTER the POST--sometimes the computer would even restart in a loop after the Windows Logo.

Further research was done (I read and skimmed a statistically large enough sample of the relevant threads on the Internet), and took the following actions:
1) Boot into Safe Mode (with networking) -- this was the only and surefire way to get in.
2) Changed resolutions to something the good monitor might scale to, since the "bad" one was 1920x1200 > 1680x1050 of the good one.
3) Restarted with various resolution settings, removing VGA, updating or changing driver to at least 2 different versions including the working one I had installed a year ago (AMD has been updating it sometimes).
4) Removed device in DM, "deleted" driver in checkbox, ran DDU, and ran AMD cleanup utility, in safe mode.
5) Restarted, monitor works. Install driver, monitor turns off.
Conclusions:
1) NO graphics driver I installed made a difference. The computer either reset in a loop or made it to a the login screen with no video signal, but full sound and USB microphone feedback.
2) Installing the monitor driver and ICM profile in safe mode did not change anything, either.
3) The screen turns off as soon as the "Starting Windows" logo disappears, every time.
4) With no driver installed, I can boot into "regular" mode with a picture. Otherwise, the screen only works in Safe Mode.
Is my GPU toast? Or should I try uh, piggybacking another ATX supply to use the 6-pin connector?
This is on an HP-branded Tyan K8WE derivative OEM board used in an (old) workstation. The power supply is a Delta DPS-750CB that has been abused by a relative turning the circuit breaker off in anger, retaliation, etc. Both monitor and PSU were connected behind the ostensibly-functional Surge Master (1kJ prot. or so?) at the time of the lightning strike(s).

A: If you've tried all the GPU outputs, and all of them exhibit the same behavior, there are a couple possibilities.

*

*Your PCIe slot is toast - test by using the GPU in a different machine or PCIe slot or a different GPU in the same machine same slot

*Your GPU is simply toast. I had an XFX HD 6870 that exhibited the exact same behavior.

If your GPU is toast, there's no way to save it. It's a chip problem. It's possible you could reflow the chip, but it's unlikely you'll be able to save it.
Buy a GTX 1060 and enjoy the performance boost.