text:
Q: awk print line as is (with spaces) I am trying to modify a line based on a certain condition, and then print into a new file. Unfortunately, the file must be sensitive to a number of spaces between the columns. The typical line looks like this:
ATOM     301 H    UREA    24    5.966    3.408    1.877   1.00   0.00 UREA  N

Here is the command I use:
awk '{if ($4 == "UREA" && $2%2 == 1) sub("H","TH",$3);print $0;}' origin.dat > final.dat

Basically, I want awk to print exactly the same line (with the same number of spaces) but with a substituted third column. What it prints is:
ATOM 301 TH UREA 24 5.966 3.408 1.877 1.00 0.00 UREA H

I know I could use printf or a very long print statemnt, but with the number of columns the file has it can be cumbersome. Is there an elegant way to print a line after substitution as is? Thanks!

A: If you modify the positional parameters, Awk will reassemble the line. But if it's a file with fixed-width columns, you should be able to figure out which positions within the line to modify, so you don't need to modify the positional parameters.
This is not particularly elegant, but it preserves your spacing:
awk '$4 == "UREA" && $2%2 == 1 { print substr($0, 1, 13) "TH" substr($0, 15) }'

A: If you are using GNU awk (and possibly some other versions as well), there is support for using fixed-width fields instead of delimiter-based fields. Read through man awk for more information but your awk invocation would look something like:
awk 'BEGIN{FIELDWIDTHS="10 5 8 3 ..."}{....}'

Setting the FIELDWIDTHS variable at the beginning of the program, using a space-separated list of numbers, causes awk to split each line based on those values instead of on spaces (or other delimiters)...
EDIT: Here's an example using the original data, although I've had to guess on some of the field widths, because the question doesn't specify them, and I'm too lazy to count them, assuming what was typed is even exactly representative of the actual data... I've assumed that all spaces are trailing the preceding field, which may not actually be the case...
$ echo "ATOM     301 H    UREA    24    5.966    3.408    1.877   1.00   0.00 UREA  N" |\
  awk 'BEGIN{OFS=""; FIELDWIDTHS="9 4 5 8 100"} $4 ~ /^UREA/ && $2 % 2 {sub("H ", "TH", $3); print}'
ATOM     301 TH   UREA    24    5.966    3.408    1.877   1.00   0.00 UREA  N

A: When you access the third field, $3, the original formatting is lost. The following approach may have undesired consequences depending on the values in your other fields but one way to solve the problem is to perform the sub on the whole record:
awk '$4=="UREA" && $2%2{sub(/H/,"TH");print}' file

Remember that sub only performs one substitution, so there will only be side-effects if the first or second column can contain "H". Depending on your version of awk, you could make the regex more specific using word boundaries, for example. Note that I have used /H/ as the first argument to sub, rather than "H", as saves awk from converting the string to a regex.
As an aside, I've removed your usage of if as the structure of an awk program is condition { action }. I've also removed the == 1 from your condition as a number % 2 is either true (1) or false (0).
Output:
ATOM     301 TH    UREA    24    5.966    3.408    1.877   1.00   0.00 UREA  N

A: Modifying a field WILL cause the record to be recompiled using the OFS value as the separator. You need to modify the whole record instead using an RE interval:
$ awk '$4=="UREA" && $2%2{$0=gensub(/((\S+\s+){2})\S+/,"\\1TH","")}1' file
ATOM     301 TH    UREA    24    5.966    3.408    1.877   1.00   0.00 UREA  N

The above uses GNU awk for gensub(), \S, and \s.


text:
Q: Charset names: Are there any other commonly used "misspellings" of charsets such as "UTF8"? My first question on SO :-)
Background: I'm working on software that needs to filter HTTP traffic. While working on the part that needs to check the content of POST requests, the question has come up for how to interpret the received data with respect to the charset.
In order to know which charset names my code should accept in the "Content-Type" header I first looked for an exhaustive list of charset names and found this: http://www.iana.org/assignments/character-sets
(Of course that list is way too long to support them all and I will select a small subset that is relevant in my case.)
Question: From the list I take it that "UTF8" (without dash) is not a IANA-defined name of a charset, however it seems that it is still used sometimes anyway and most servers/browsers will understand it. Are there any more such cases of commonly understood charset names which are not listed by IANA that my filter should be able to understand?
Generally: Is there a "more complete" list somewhere?
More specifically: Are there any aliases for the US-ASCII charset that are not listed by IANA?

A: Masato Kinugawa (@kinugawamasato) made lists of acceptable charset names for each web browser. See http://l0.cm/encodings/list/ .
For example, the charset names that treated as alias of US-ASCII in Chrome are:

*

*windows-1252

*ansi_x3.4-1968

*ascii

*cp1252

*cp819

*csisolatin1

*ibm819

*iso_8859-1

*iso_8859-1:1987

*iso88591

*iso8859-1

*ISO-8859-1

*iso-ir-100

*l1

*latin1

*us-ascii

*x-cp1252

As described in the site, you can also test the behavior of your browser by your self in http://l0.cm/encodings/check/ .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Box-shadow of button is wider than the button itself Hope somebody can help me. I've added custom css to a button but the shadow displayed is wider than the button itself:
This is how it looks:

This is the css:
.dip-button-dark-bg {
    border-radius: 5px !important;
    box-shadow: 2px 2px 2px #484848 !important;
}

Can someone tell me what I should add? I've been searching for a solution for 2 hours now and have become pretty desperate.


text:
Q: How to make ref in component link to component data? I am using https://github.com/r3code/vue-vis-network
I am getting error: Cannot read property 'hasChildNodes' of undefined
My component code is:
<template>
    <el-container >
            <el-main>
                <network ref="network" :nodes="nodes" :edges="edges" :options="options"> </network>
                <button @click="get_data">GetData</button>
            </el-main>
  </el-container>
</template>

<script>
    export default {
        components: { Notification },
        data () {
            return {
              nodes: [],
              edges: [],
              options: []
            }
        },

        methods:
        {
          get_data()
          {
            axios.get(base_url + '/graph')
               .then((response) => {
                this.nodes = response.data.nodes;
                this.edges = response.data.edges;
                }).catch((error) => {   console.log(error); });
          }
        },
    }
</script>

index.js:
Vue.component('network', new vueVisNetwork.Network);

I suppose that there is problem that it's attempt to access to data placed in #app. How I can say him that he should use data declared in component?
Actual data example:
  nodes : [
    {id: 1, label: 'Fooo"', group: "company"},
    {id: 2, label: 'Baaar', group: "owner"},
  ],

  edges : [
    {from: 1, to: 2},
  ],

possible related issue https://github.com/crubier/react-graph-vis/issues/57


text:
Q: HTTP Status 500 - /WebContent/olaMundo.xhtml Not Found in ExternalContext as a Resource I'm trying access a page .xhtml using JSF 2.0 and Apache Tomcat-8.0.6 but I'm getting the error of the title. The "olaMundo.xhtml" is in the folder MyProject/WebContent/olaMundo.xhtml. Any idea about what is wrong? This problem is different of the same other of here because in this case the code was running perfect before, and suddenly died :(, and my folders were perfects.
olaMundo.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html">
  <h:head>
    <title>Argentum</title>
  </h:head>

  <h:body>
      <h:outputText Ola Mundo/>
  </h:body>
</html>

Stacktrace:
java.io.FileNotFoundException: /WebContent/olaMundo.xhtml Not Found in ExternalContext as a Resource
at com.sun.faces.facelets.impl.DefaultFaceletFactory.resolveURL(DefaultFaceletFactory.java:224)
at com.sun.faces.facelets.impl.DefaultFaceletFactory.resolveURL(DefaultFaceletFactory.java:265)
at com.sun.faces.facelets.impl.DefaultFaceletFactory.getMetadataFacelet(DefaultFaceletFactory.java:201)
at com.sun.faces.application.view.ViewMetadataImpl.createMetadataView(ViewMetadataImpl.java:114)
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:227)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:111)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:508)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)


text:
Q: should i query or should i use url variables? Stack: nextjs (yes, I'm using SSR), Hasura, reactjs
I have 2 pages, one of them queries and displays a table that contains users. Another page is for printing the said table using window.print().
So basically, the said 2 pages use the same data.
I am thinking of 2 ways to tackle this:

*

*On the 2nd page, use the same query as I have on the first page
(which sounds redundant and not efficient)

*Pass the data from the 1st page on the 2nd page's URL (which is will
make the URL dirty but it sounds faster)


text:
Q: a variant of history.pushstate() javascript in php or jQuery I have this piece of javascript which gives me the opportunity to change the displayed url. The problem is that if I refresh after going to a page it doesn't find the page because the url has changed. Which makes alot of sense because javascript is client side. (see code below)
history.pushState("", "", "example");

I would like to know if this can be done server sided instead of client sided like with PHP or jQuery for instance?


text:
Q: Deleting Multer uploads object after processing Express I am trying to delete the file object that is created and stored in the uploads folder.
Here is my config options for multer:
const path = require('path')
multerConfigOpt = {
    dest: 'uploads/',
    fileFilter:  function(req, file, cb) {
        var ext = path.extname(file.originalname)
        console.log(ext);
        if (ext === '.pdf' || ext === '.doc' || ext === '.docx' || ext === '.txt') {
            console.log("true!");
            cb(null,true)
        } else {
            cb(null, false)
        }
    }
}

module.exports = multerConfigOpt

After processing the files that was submitted by a user via a HTML Form I would like to delete it. When I try and do the following:
    await fs.unlink(this.file.path, (err) => {
        if (err) {
            console.log(err);
        }
    })

However I get the following error:
Error: EPERM: operation not permitted,

these files that are store in the uploads folder do not have an extension. I believe they are just binary files that were created by multer.
Below is an example of the file that is in the uploads folder path.

All I do with the file is send it as an attachment through email using nodemailer
if (this.file && this.isJobSeeker) {
    mailOptions.attachments = [{
        filename: 'resume.pdf',
        content:  fs.createReadStream(this.file.path)
    }]
}

How can I delete these files?
Thank you for the help.

A: The createReadStream function in fs also may take a buffer as an input, however, it seems that fs.createReadStream() converts that buffer to a string which ultimately must contain a file path (which seems like an important detail they should've mentioned in the docs).
Multer has a feature where instead of storing the file on your disk, you can have the file as an in-memory buffer.
You may try:
const multerMemoryStorage = multer.memoryStorage();

multerConfigOpt = {
    storage: multerMemoryStorage,
    fileFilter:  function(req, file, cb) {
        var ext = path.extname(file.originalname)
        console.log(ext);
        if (ext === '.pdf' || ext === '.doc' || ext === '.docx' || ext === '.txt') {
            console.log("true!");
            cb(null,true)
        } else {
            cb(null, false)
        }
    }
}

Then, if you're taking req.file in this.file in your processing function, you can do the following:
Using the stream module in nodejs, we can convert the buffer into a readable stream, which is the base class of fs.ReadStream.
const stream = require('stream')
const getNewReadableStreamFromBuffer = (inputBuffer) => {
    const readable = new stream.Readable.from(inputBuffer);

    return readable;
}
if (this.file && this.isJobSeeker) {
    mailOptions.attachments = [{
        filename: 'resume.pdf',
        content: getNewReadableStreamFromBuffer(this.file.buffer)
    }]
}

The file need not be deleted, because it's never saved to disk. And since nodejs is garbage collected, the buffer should be cleared from memory.
NOTE: Multer docs mention in a warning that in this approach, you must ensure that your server has enough memory to keep in-memory buffers of uploaded files, as some files may be quite large. If your files are small enough, it will work smoothly.


text:
Q: Is there any way to resume a chat in dialogflow cx? I'm trying to build a chatbot with DialogFlow CX. We have an existing chatbot built on DF ES where with the help of contexts we have implemented a resume chat feature, which enables our end users to come back to the chat anytime and continue from where they left off. So currently we are building out the exact same bot in CX and we are facing challenges in recreating the resume chat flow.
So any help regarding how to to do this will be really helpful.
Thanks in advance

A: Dialogflow CX conversation (session) can be described and visualized as a state machine, configured to collect information or parameters from the end-user. This information is relevant to the conversation state on that page. Please be noted that for each conversational turn, the current page will either stay the same or transition to another page. This also applies for resuming or continuing the current state of the conversation.
Here are possible ways to continue/resume a conversation by passing previously collected customer data from a previous conversation into a new conversation:

*

*You can create a custom implementation using a webhook wherein a function will store the parameter and forms you collected and use that to continue the chat from where the user left off during a conversation flow or a session. In the webhookResponse you can set the fulfillment_response, target_page fields and session_info field to update and send back the stored parameters you collected from the previous conversation.
Here's an example of how to pass the session parameter, target page and fulfillment response from your webhook response:
{
   sessionInfo: {
       parameters: {
           param1: {
             value: "sample1"
           }
       }
   },
  targetPage: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>/pages/<Page ID>,
  fulfillment_response: {
       messages: [{
         text: ["This is where you left"],
       }]
   }
}

*You can use APIs or Client Libraries  to set the queryParams.parameters and queryParams.currentPage in the detectIntent method.
Here's a sample reference using REST API to set the QueryParameters of the detectIntent method request body:
 {
    queryParams: {
        parameters: {
              param1: {
                value: "sample1"
              },
    currentPage: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>/pages/<Page ID>,
        }
     }

 }


text:
Q: Code compiles with std::string even when the syntax appears bad and contains multiple '+' operator Why this code compiles without any error?
std::string s = std::string("Look at plus plus... ") + + "... Strange!\n";

Is it a standard code or generosity of g++ (v4.9)?
In fact y'day I had seen a crash happening which was pointing to std::string in the same region of code where these "wrong syntax" was present. Possibly this could be the culprit.


text:
Q: Effect of shortening length of pendulum on angular amplitude
A simple pendulum has a point like bob of mass $m$ and a light inextensible string.
Suppose, by means of some arrangement, we shorten the string extremely slowly,
so that at any instant, the ratio of length to rate at which it changes is much greater
than the period of the pendulum. Suppose the length of the string is $L$ and the
angular amplitude (assumes to be small) is $\theta$. Now, at this moment, the length of the
string is changed by $\Delta L(<0)$ , what would be the corresponding change in angular
amplitude $\theta$.

I believe the amplitude would increase (based on horrible imagination so I might be wrong). I am unable to convincingly work out this problem. I am having difficulty in incorporating the fact that "at any instant, the ratio of length to rate at which it changes is much greater than the period of the pendulum."
Could anyone please give an elementary approach(highlighting the mathematics) or a hint of some kind?
Edit: I tried analysing the forces on the bob using polar coordinates as I could see terms like $\dot r$ and $\dot \theta$. But I couldn't make significant progress towards the original question.
(I am not familiar with the Lagrangian as yet.)

A: If the string (fixed at the top) passes through a hole in a movable mounted rod, and you move the rod downward (when the string is straight), then you have done no work on the pendulum and its maximum  kinetic or potential energy do not change.  The maximum height of swing will  not change, but with a shorter string, the angle of swing will increase.  If you pull the string up through the hole, you are doing work on the pendulum. It will swing to a greater height, but the bottom position is also rising. I'm guessing the maximum angle will be the same as in the previous situation.

A: Let us assume that when you shorten the pendulum you are not doing any work on the bob.We know that that total energy of a pendulum is equal to the potential energy possessed by it at the highest point.Also the Maximum height reached by the pendulum is $l(1-cos\theta)$ where l is effective length and $\theta$ is the angular amplitude. So total mechanical energy of pendulum can be written as $mgl(1-cos\theta)$ . So when you reduce l,  $ \theta$ increases such that $cos\theta$ decreases and $1-cos\theta$ increases keeping total mechanical energy same.So when you reduce l Angular amplitude increases.But you cannot reduce l indefinitely because a point will be reached when angular amplitude will be as high as $\pi$ which is the maximum possible angular amplitude. Let this limiting value of l be $l_{limiting}$.
Now the question arises : What happens when you reduce effective length such that it becomes less than $l_{limiting}$.Well in that case the total mechanical energy won't change (since we haven't done any work on the bob) but potential energy at the maximum height i.e  at angular displacement of $\pi$ with respect to vertical will be less than Total mechanical energy so the body will have some kinetic energy at this point i.e It will execute motion in vertical circle.(Refer to diagrams provided);
Here's the math:
initial Mechanical energy = $mgl_1(1-cos\theta)$
Final mechanical energy = $mgl_2(1-cos\phi)$
But since work done = 0 ,  Initial mechanical energy = Final mechanical energy
$mgl_1(1-cos\theta)$  =  $mgl_2(1-cos\phi)$
where $l_1$ is initial length , $l_2$ is final length , $\theta$ is initial angular amplitude and $\phi$ is final angular amplitude .
Solving this equation we can calculate the value of $\phi$.
If $l_2$ < $l_1$ then $\phi$ > $\theta$
Let me know if this was clear enough.


text:
Q: how to store select/option inside a foreach in a database? I have a foreach for questions, inside that foreach I print the questions and below I place a select/option
@foreach ($questions as $index => $question)

{{$question->title}}

{{$question->id}}

        <select wire:model="answers" name="question" id="question">
            <option value="" selected></option>
            <option value="yes">YES</option>
            <option value="no">NO</option>
        </select>
@endforeach

output foreach
I am trying to save all the answers in a database table, in the select I put a wire:model="answers" linked to an array inside the component public $answers=[]; to capture the answers
How can I capture all the answers of the selects, and then store all in the database?

A: got it, you need to remove any unnecessary attribute and in the select you need to pass the $index to the array wire:model="answers.{{$index}}"


text:
Q: java.lang.OutOfMemory with large high-resolution images I'm developing an Android app which uses multiple large images in several of its activities. Each image is around 1280x800 and I load about 2-4 of these images for each Activity. I realize that these images are very large in terms of the memory that is allocated to each individual app on a device, but how can I display them at their original resolution without running into a java.lang.OutOfMemory error? I need these images to be displayed at their full size on a screen (scaling is done automatically by xml when the screen is smaller than the image). I saw several solutions involving shrinking down images into thumbnails and storing those into memory, but wouldn't that cause the image to lose it's original size/resolution? Thanks for your help!

A: There are a few things you can do about this.
The first thing that comes to mind is that 1280x800 is (probably) your entire screen, so you should only need to display one at a time. Don't hold the others in memory while you do that.
Still a 1280x800 image at 4 bytes per pixel is only 4MB, and tablets seem to all offer 48MB of heap these days. You should be able to hold a few in memory if you need to. If you're running out of memory, it's possible you're leaking. If you watch in DDMS, does your memory usage continue to grow as you change activities?
A common source of leaks is the bitmaps themselves. Be sure to call Bitmap#recycle when you're done with them.
If it really comes down to it, and you cannot fit into the heap space provided, you can also try adding android:largeHeap="true" to the application tag in your manifest. This will request the system offer you more heap space - up to 256MB on some devices. This should be a  last resort, though, as it will vary by device, and be completely ignored on some (the original Kindle Fire comes to mind).
You can see just how much total heap space you have with Runtime.getRuntime().maxMemory();. See this answer for a more detailed explanation. It's trickier to see just how much you're using, but there is a description here if you want to tackle that beast.
Finally, there may be a better way to load your images than specifying them in xml. Be sure to read this developer guide page. Even if you must leave them in xml, I have seen marked improvement in memory usage by splitting the image assets into the drawable-hdpi, drawable-mdpi, etc. directories rather than just dumping them in drawable.

A: This article describes pretty well how to create a heap dump and analyze it using Eclipse MAT. This will help you find the most likely suspects for memory leaks pretty quickly.
Again I point you to this great link I found from another SO Question that has tutorials of how to properly over come the problem.

A: Image needs to scaled before loading the image using BitmapFactory or related methods.
public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        } else {
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    }
    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

whole thing is explained in Android developer site, Loading Large Bitmaps Efficiently


text:
Q: Converting latitude/longitude to full range referential I have a list of latitudes and longitudes expressed as follow:
-1 <= latitude <= 0
0 <= longitude <= 1

Those coordinates represent POIs on a fantasy map displayed using the Leaflet JavaScript library using the coordinate system EPSG:3857 (Web Mercator)
I need to map those coordinates to the full range of possible latitudes/longitudes (-90/+90 and -180/+180) in order to display them properly using the iOS MapKit framework.


text:
Q: Does this clockwise method work for polygons? public class SimplePolygon {

protected int n; // number of vertices of the polygon
protected Point2D.Double[] vertices; // vertices[0..n-1] around the polygon
                                // boundary

protected SimplePolygon(int size) {
    n = size;
    this.vertices = new Point2D.Double[size];
}

protected SimplePolygon() {
    n = 0;
}

public static SimplePolygon getNewPoly(Point2D.Double[] vertex) {
    int size = vertex.length; // TODO: replace this line with your code
    SimplePolygon p = new SimplePolygon(size);
    // TODO: populate p.vertices[0..size-1] from input file
    for(int i = 0; i < vertex.length; i++){
        Point2D.Double[] pArray = p.vertices;
        pArray[i] = vertex[i];
    }
    return p;
}

public int getSize() {
    return n;
}

public Point2D.Double getVertex(int i) throws IndexOutOfBoundsException {
    Point2D.Double u = null;
    try{
        u = vertices[i];
    }catch(IndexOutOfBoundsException e){
        e.printStackTrace();
    }
    return u;
}

public static double delta(Point2D.Double a, Point2D.Double b,
        Point2D.Double c) {
    double val = (a.getX()*b.getY()*1) + (a.getY()*1*c.getX())
            + (1*b.getX()*c.getY()) - (a.getY()*b.getX()*1)
            - (a.getX()*1*c.getY()) - (1*b.getY()*c.getX());

    return val;
}

Hi, I am trying to implement the "delta" method, but I have no way in telling if it's correct. The method says it returns "twice the signed area of oriented triangle." The instructions given were a little iffy on how we're suppose to calculate
I saw the matrix and a little bit of research showed cross product would work, but now I feel I would need to create a helper method that would determine if the three points are clockwise, counter clockwise, or colinear, which I have some idea on how to do. I just need help in determining if my delta method is correct.


text:
Q: How do I remove a character from array element? I have an array like this:
["ee", "3/4\"", "22\"", "22\""]

and I'd like to either remove the commas, \" or replace that with &#34 so that the array looks like this:
["ee", "3/4", "22", "22"]

or this:
["ee", "3/4&#34", "22&#34", "22&#34"]

The reason is that I'm trying to pass that array from Ruby to JavaScript, but I keep getting an "Unterminated string constant error" and I just can't figure out a way around it!
This is what I'm using to pass the info to JavaScript:
cut_list="from_ruby_cut(\""+c[1]+"\")"

A: To replace each element in an array with a modified version, such as replacing the unwanted character, you can use the map! function. Inside the block, use gsub to replace the unwanted " character.
array = ["ee", "3/4\"", "22\"", "22\""]

array.map!{ |element| element.gsub(/"/, '') }
array
#=> ["ee", "3/4", "22", "22"]

array.map!{ |element| element.gsub(/"/, '&#34') }
array
#=> ["ee", "3/4&#34", "22&#34", "22&#34"]

However, you may also be able to solve your problem by using c[1].inspect instead of c[1] when building your JavaScript string. If you use inspect, it'll print the string with the enclosing quotes included, and the backslash to escape the quote inside the string.

A: To modify the arrays the way you want use map and gsub.
a = ["ee", "3/4\"", "22\"", "22\""]
a.map{|e| e.gsub(/"/,'')}
=> ["ee", "3/4", "22", "22"]

or
a.map{|e| e.gsub(/"/,'&#34')}
=> ["ee", "3/4&#34", "22&#34", "22&#34"]

However, I am not sure this is the best way to accomplish your end goal.


text:
Q: How to use a Surface pro as a microphone for my desktop? I'm currently using my Surface pro 4 as a second screen by using the connect to a wireless display functionality, is it possible to also use it as a microphone?

A: You would have to connect the audio output (higher than microphone level) to the microphone input of the other device. I think you might be able to do it, but it may not be worth the effort.
You would have to attenuate and then balance the audio output because microphone input is measured in millivolts.
An inexpensive microphone would be much better.

A: Not 100% sure but it would involve to connect the headphone output to the line input (not mic input) of the PC using a jack connector (mono to mono or mono to stereo?).
Plus you can route the signal using the Windows software Cable.
A headset might serve you better (but that wasn't what you were asking).


text:
Q: Using mysql statement to join tables and return maximum values instead of PHP maths In PHP with MySQL I am trying to write queries to pull certain required reports with Joined Tables.I have read though so many SQL scripting manuals, and would normally do this type of thing by pulling filtered records from db tables into PHP, and doing the math gymnastics there. Unfortunately this is inefficient so I am looking for the right SQL query to point me in the right direction. This is my situation.
I have mysql tables: events and payments, they are linked by a single ID column (events.event_id = payments.payment_event_id)
I need to get a recordset containing only the 5 events with the most associated payments. Then I would like a result array containing this original event detail arrays along with an integer which is their ticket payment count.
Ideally the result array structure would look like this:
$result_events--
|0||0|payment count(53)
|0||1|$full event array

|1||0|Payment Count (34)
|1||1|$full event array

EDIT:
After talking to people I thought I would spell out what I am after. I need a 2 column resultset, left column is event_id (from events table) and right hand column is total amount of payments for that event (ie the number of 'payment' rows which match this event id. So out of huge random tables of events and payments, I would like to be left with one like this:
| Event_id | total Payments |

but ordered by the payment column. I know I'm asking the earth :)

A: If you want to get the 5 most common payments for an event and get just those 5 details, you can do a subquery to get the event_ids where you group the payment_event_ids, then order the count descending top to bottom and take the top 5 results.
Then you take those ID's and get the event details that match those ids
SELECT
  *
FROM
  events
WHERE
  event_id IN (
    SELECT
      payment_event_id
    FROM
      payments
    GROUP BY payment_event_id
    ORDER BY count(*) DESC
    LIMIT 5
  );

Optionally you can also get all the payment details with a join, but you'll get more than 5 rows returned this way
SELECT
  *
FROM
  events
JOIN
  payments
ON
  events.event_id = payments.payment_event_id
WHERE
  events.event_id IN (
    SELECT
      payment_event_id
    FROM
      payments
    GROUP BY payment_event_id
    ORDER BY count(*) DESC
    LIMIT 5
  );

A: Simple query, only thing left for you to do is select the columnnames you need from both tables:
$q = "SELECT events.columname, payments.columnname FROM events
      INNER JOIN payments ON events.event_id = payments.payment_event_id
      ORDER BY payments.payment_count DESC
      LIMIT 5";


text:
Q: Buildozer failed to execute the last command while I was trying to build,push and automatically run the apk on my device using buildozer android debug deploy run it shows these errors:
# Check configuration tokens

# Ensure build layout

# Check configuration tokens

# Preparing build

# Check requirements for android
# Install platform
# Apache ANT found at /home/sahil/.buildozer/android/platform/apacheant-1.9.4
# Android SDK found at /home/sahil/.buildozer/android/platform/android-sdk-21
# Android NDK found at /home/sahil/.buildozer/android/platform/android-ndk-r9c
# Check application requirements
# Check garden requirements
# Compile platform
# Distribution already compiled, pass.
# Build the application #21
# Package the application
 # Command failed: /usr/bin/python2.7 build.py --name demo --version 1.2.0 --package org.test.myapp --private /home/sahil/kivy/.buildozer/android/app --sdk 14 --minsdk 8 --orientation landscape debug
#
# Buildozer failed to execute the last command
# If the error is not obvious, please raise the log_level to 2
# and retry the latest command.
# In case of a bug report, please add a full log with log_level = 2

I checked it out in documentation and also on internet but did not find anything about it.
AND I am just making a simple Hello World application:
#version.regex
#__version__= '1.0'

from kivy.app import App
from kivy.uix.label import Label

class SimpleApp(App):
    def build(self):
        return Label(text="Hello World")

if __name__=="__main__":
    SimpleApp().run()

Thanks!

A: Probably you are running an updated version of cython, all major release start form 0.21 and up, you have to downgrade cython to 0.20 ( sudo pip install cython==0.20 ) then removing .buildozer folder ( rm -Rf .buildozer ) and then rebuilding with 'buildozer android debug'

A: First raise the log level = 2 in buildozer.spec,then it will show all logs and error clearly. Here in .buildozer/android/platform/python-for-android/dist/myapp/python 2.7 build.py was missing. To fix this issue run this command buildozer android clean and then rebuild it using buildozer android debug or automatically run using buildozer android debug deploy run.


text:
Q: How to reorder time on the y-axis so midnight is in the center I am graphing day (x-axis) by time in minutes (y-axis) using geom_raster to create an actogram. I want the y-axis to start at 12 noon and go down to midnight and then back up to noon (12pm, 11am, 10am, 9am, 8am, 7am, 6am, 5am, 4am, 3am, 2am, 1am, 0, 11pm, 10pm, 9pm, 8pm, 7pm, 6pm, 5pm, 4pm, 3pm, 2pm, 1pm 12pm), so midnight will be in the center. I have absolutely no idea how to do this.
I have tried to turn the data into a factor and order it:
x <- seq(11.55, 0, -0.05)
y <- seq(23.55, 12.00, -0.05)
z <- c(x,y)

but the problem is I have a lot of duplicate values because I am working with 24 days worth of data...
This is my code without rearranging the y-axis:
ggplot(LIA_20, aes(x = date, y = time))+
  geom_raster(data = LIA_20, aes(fill = Sv_mean))+
  scale_fill_gradientn(colours = matlab.like(100), na.value = "white",
                       limits = c(-140, -70))+
  scale_x_continuous(expand = c(0,0), limits = c(2, 23), breaks = 3:22)+
  scale_y_discrete(expand = c(0,0))+

  coord_fixed(ratio = 0.00005)+
  theme(panel.background = element_blank(),
        legend.position = "bottom")+
  labs(x = "Day (May 2018)", y = "Time of day, UTC", fill = "Sv (dB)")+
  guides(fill = guide_colourbar(title.position = "bottom",
                                title.hjust = 0.5))


text:
Q: Django Annotate - Concat from last created ManyToMany Object Fields class User(models.Model):
    name=CharField()

class Address(models.Model):
    user= Foreignkey(user, related_name="Addresses")
    buildingname=CharField()
    subbuildingname=CharField()
    town=CharField()
    ...

I have a models like top and want to extract data as list below.
{
    [
        ['USERNAME1', 'A XYZBUILDING 14 Drain St. '],
        ['USERNAME2', 'C XXXBUILDING 13 Drain St. '],
        ['USERNAME3', 'B ZZZBUILDING 12 Drain St. '],
        ...
    ]

}

Also as a workaround, this is a closest thing to the answer but i could not make it finish
without looping every user or
without executing raw sql in extra method's select field.
I want to achive this with Django ORM.
address_subquery = Address.objects.filter(user__id=F('pk')).order_by('created')
User.objects.filter(**my_custom_filters).annotate(
    subbuildingname_str=Subquery(address_subquery.values('subbuildingname')[:1], output_field=CharField()),
    street_str=Subquery(address_subquery.values('street')[:1], output_field=CharField()),
    buildingname_str=Subquery(address_subquery.values('buildingname')[:1], output_field=CharField()),
    buildingnnumber_str=Subquery(address_subquery.values('buildingnnumber')[:1], output_field=CharField()),
).annotate(
    address_text_str=Concat(
        'subbuildingname_str', Value(' '),
        'buildingname', Value(' '),
        'buildingnumber', Value(' '),
        'street_str',
        output_field=CharField(),
        default=""
    )
).values_list('name', 'address_text_str')

A: Actually you are doing wrong in subquery, you have to write subquery like this :-
from django.db.models import OuterRef

address_subquery = Address.objects.filter(user=OuterRef('pk')).order_by('created')

You can refer from here https://docs.djangoproject.com/en/3.2/ref/models/expressions/#subquery-expressions


text:
Q: How to automate db deployments in visual studio 2010? I'm trying to put together an automated deployment strategy for my company's .NET application. We are using TFS/VS 2010, along with IIS for application hosting and msbuild for continuous integration & deployment. The application consists primarily of two components:
* A webapp
* A database
Our branching strategy, for the moment, is single-stream. That is, we have one big 'ol trunk, and for now we can assume that it will remain that way.
We've figured out how to get msbuild to deploy the webapp to IIS, so that's cool. Now I'm trying to figure out the best strategy for handling deployment of the database component. Right now, database deployment is entirely manual: our db architect builds the db on his machine periodically, examines the auto-generated migration script, and then manually writes pre/post deployment scripts. Then, he runs the whole deployment and sends an email to everyone.
This is not an ideal solution: the automated nightly webapp deployment works great, except when the dba fails to coordinate his manual db deployment work. This results in a lot of headaches for all parties. Thus, I'm trying to figure out how feasible an auto-deployment of the db will be.
I understand how to make msbuild deploy a database. However, the bigger problem seems to be properly managing pre/post deployment scripts.
With all this in mind, can anyone point me to best practices in this kind of a situation? I've done a lot of config mgmt in the past, but am new to managing a project with a database component.

A: we use the Visual Tool VSDBCMD to compare 2 databases and generating update sql scripts
http://msdn.microsoft.com/en-us/library/dd193283.aspx


text:
Q: Four iframes, two side by side I have four iframes. I want them displayed as follows:
1 | 2
3 | 4

This is my code:
<!doctype html>

The
 does not have the effect I expect. I get the four iframes on one line, side-by-side (each picture is an iframe):

How to "break" after two iframes ?

A: Using Float and Width
CSS code
.box {
    float:left;
    width: 50%;
}
iframe {
    width:100%;
}

HTML code

A: The most simple way would be to replace the float: left style with display: inline-block. Doing it this way, you could also get rid of the .clear class as well. What float is doing is it's getting rid of any proper "breaking" and making all elements "float", whether they belong there or not.
Also, I'd suggest changing your
 tags to
, since they're acting as dividers anyway.
Edited CSS:

A: As Hidden Hobbes stated in comments section, adding clear class along with third box class will do the trick, like:

Additionally, you can also do it by using the box class to the parent of the div where iframe present, like:

Hope this helps.


text:
Q: protected virtual destructor in pybind11 I want to bind with the class from third party library. The class have some pure virtual functions but the destructor is protected and virtual.
In order to bind the class, I have to write a derived class that overrides the pure virtual functions (https://pybind11.readthedocs.io/en/stable/advanced/classes.html)
so the code is like this
class Parent {
  public:
    virtual void foo() = 0;
  protected:
    virtual ~ Parent() //Dtor
    {
    }
};

class PyParent : public Parent
{
  public:
    void foo () override {
        PYBIND11_OVERLOAD_PURE(
            void,
            Parent,
            foo
        );
    }
};

void init(py::module & m) {
    py::class_<Parent, PyParent> p(m, "p");
}

However, since the destructor of the base class is declared as protected, the following errors are thrown
error: 'virtual Parent::~Parent()' is protected
         virtual ~ Parent() //Dtor

I can not modify the base class since it's a third party library.
Any idea to bind the class with pybind11?

A: std::unique_ptr and std::shared_ptr are smart pointers supported by pybind out of box. Both of them require destructor to be public.
The simplest solution would be to write intermediate class with public destructor and expose it with pybind11.
...
class DeletableParent : public Parent{
public:
  ~DeletableParent() override = default;
};
...
py::class_<DeletableParent, PyParent> p(m, "p");

So all your Python classes will inherit from DeletableParent
If all you want to do is to make Parent-derived classes on Python side, this solution is fine.
If you want to expose a C++ Parent-derived-class which doesn't have DeletableParent as one of it's bases you will find difficulties in exposing such diverged inheritance relations.
Another option is to write your own smart pointer which does not call destructor of holded pointer. But it looks like straight road to memory leaks.
Update:
I overlooked that this particular issue is already covered in pybind11 doc:
https://pybind11.readthedocs.io/en/stable/advanced/classes.html#non-public-destructors


text:
Q: How to create an INetAdress constructor I have this code:
  import java.net.InetAddress;
  import java.net.UnknownHostException;

  public class NsLookup {

 private InetAddress inet = null;

 public void resolve(String host) {
   try {
     inet = InetAddress.getByName(host);

     System.out.println("Host name : " + inet.getHostName());
     System.out.println("IP Address: " + inet.getHostAddress());
  }
   catch (UnknownHostException e) {
     e.printStackTrace();
   }
 }

 public static void main(String[] args) {
   NsLookup lookup = new NsLookup();
   lookup.resolve(args[0]);
 }
}

But I am trying to add a constructor to the class that initialises the InetAddress object, separating it from the resolve() method but unclear how to, any suggestions?

A: What you need is a simple constructor which accepts host name in the form of a String and initialises the InetAddress object for the same, which could be easily done as completed below :
  import java.net.InetAddress;
  import java.net.UnknownHostException;

  public class NsLookup {

    private InetAddress inet = null;

    // you need to define this extra constructor
    public NsLookup(String host){
    try{
       inet = InetAddress.getByName(host);
    }
    catch(UnknownHostException uhe){
      uhe.printStackTrace();
    }
    }
    // constructor ends here

    // Also you don't need to remove the argument received by the resolve()
   // so that one could resolve other hostnames too.

    public void resolve(String host) {
     try {
        inet = InetAddress.getByName(host);
        System.out.println("Host name : " + inet.getHostName());
        System.out.println("IP Address: " + inet.getHostAddress());
     }
     catch (UnknownHostException e) {
        e.printStackTrace();
     }
    }

 public static void main(String[] args) {
        NsLookup nsl = new NsLookup("YOUR-HOSTNAME");
        // add your rest code here
 }
}


text:
Q: Python default character encoding handling I've seen several post related to this, but no clear answer. Let's say I want to print the string s=u'\xe9\xe1' in a terminal which only supports ASCII (e.g., LC_ALL=C; python3). Is there any way to configure the following as default behaviour:
import sys
s = u'\xe9\xe1'
s = s.encode(sys.stdout.encoding, 'replace').decode(sys.stdout.encoding)
print(s)

I.e., I want to the string to print something - even garbage - rather than raising an exception (UnicodeEncodeError). I'm using python3.5.
I would like to avoid writing this for all of my strings which may contain UTF-8.

A: You can do one of three things:

*

*Adjust the error handler for stdout and stderr with the PYTHONIOENCODING environment variable:
export PYTHONIOENCODING=:replace

note the :; I didn't specify the codec, only the error handler.

*Replace the stdout TextIOWrapper, setting a different error handler:
import sys
import io

sys.stdout = io.TextIOWrapper(
    sys.stdout.buffer, encoding=sys.stdout.encoding,
    errors='replace',
    line_buffering=sys.stdout.line_buffering)

*Create a separate TextIOWrapper instance around sys.stdout.buffer and pass that in as the file argument when printing:
import sys
import io

replacing_stdout = io.TextIOWrapper(
    sys.stdout.buffer, encoding=sys.stdout.encoding,
    errors='replace',
    line_buffering=sys.stdout.line_buffering)

print(s, file=replacing_stdout)


text:
Q: Why does QGIS keep freezing? About a year ago I installed the newest version of QGIS, but it kept freezing after  a few minutes of use, so I uninstalled it and installed 2.18 because it was supposed to be more stable. It seemed to work at the time. Not until the last few weeks have I really started to use QGIS intensively, and now it has started freezing again. I haven't been doing anything complicated, just creating polygons and editing their attributes. It doesn't seem to matter exactly what i'm trying to do, after a certain time or number of clicks the whole thing just freezes and won't function no matter how long I wait.
I've seen similar questions, but without any definitive answers. I'm running Windows 10 on an MSI 72. The computer should definitely be fast enough, I never had a problem with ArcGIS or AutoCAD. I haven't installed any plugins, and I don't see how it could be a problem with the data as I'm creating it in QGIS and it doesn't matter if I'm editing the data or just trying to zoom in/out.


text:
Q: Various Colours In The Same Table Cell, Possible? I have a request to display a string in various colours in a table cell, that is one portion of a string in one colour and the rest in another colour (either the background or the text). I have found an article on changing the cell background colour, but not a portion of a cell. That is close to the requirement, but don't meet the requirement.
The only possible solution, I can think of, is to use the Text type which can be set with various colours after splitting a string into two parts. But, how to use the Text type data with the TableView setup as the following?
aColumn.setCellValueFactory(p -> new SimpleStringProperty(...) );
...
aTalbeView.setItems(FXcollections.observableArrayList(...));

I am still new to JavaFX. Is it doable? If so, how shall I approach a solution?
A mock up table is attached below.

A: The cellValueFactory is used to tell the cell what data to display. To tell the cell how to display its data, use a cellFactory. The two are more or less independent.
So you can do
aColumn.setCellValueFactory(p -> new SimpleStringProperty(...));

and then something like:
aColumn.setCellFactory(tc -> new TableCell<>() {
    private final String[] palette = new String[] {
        "#1B9E77", "#D95F02", "#7570B3", "#E7298A",
        "#66A61E", "#E6AB02", "#A6761D", "#666666" };
    private TextFlow flow = new TextFlow();

    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setGraphic(null);
        } else {
            flow.getChildren().clear();
            int i = 0 ;
            for (String word : item.split("\\s")) {
                Text text = new Text(word);
                text.setFill(Color.web(palette[i++ % palette.length]);
                flow.getChildren().add(text);
                flow.getChildren().add(new Text(" "));
            }
            setGraphic(flow);
        }
    }
});

This assumes each cell has multiple words (separated by whitespace) and colors each word a different color. You can implement the different colors any way you like; this shows the basic idea.

A: The approach used in this answer

*

*An additional range parameter is added to the backing model to indicate the highlight range for text in the cell.

*The cellValueFactory uses a binding statement to allow the cell to respond to updates to either the text in the cell or the highlight range.

*Labels within an HBox are used for the cell graphic rather than a
TextFlow as labels have more styling options (e.g. for text
background) than text nodes in TextFlow.

*Using multiple labels within the cells does change some of the eliding behavior of the cell when not enough room is available in the column to include all text, this could be customized by setting properties on the HBOX or label to configure this behavior how you want.

*CSS stylesheet for styling is included in the code but could be
extracted to a separate stylesheet if desired.

*I didn't thoroughly test the solution, so there may be logic errors around some of the boundary conditions.
Screenshots
Highlighted a subset of text within a cell in a non-selected row:

Highlighted a subset of text within a cell in a selected row:

Example code
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class HighlightedTextTableViewer extends Application {

    private static final String CSS_DATA_URL = "data:text/css,";
    private static final String HIGHLIGHTABLE_LABEL_CSS = CSS_DATA_URL + // language=CSS
            """
            .highlightable {
                -fx-font-family: monospace;
                -fx-font-weight: bold;
            }

            .highlight {
                 -fx-background-color: cornflowerblue;
                 -fx-text-fill: white;
            }
            """;

    private static final String HIGHLIGHTABLE_STYLE_CLASS = "highlightable";
    private static final String HIGHLIGHTED_STYLE_CLASS = "highlight";

    @Override
    public void start(Stage stage) {
        TableView<Field> table = createTable();
        populateTable(table);

        VBox layout = new VBox(
                10,
                table
        );
        layout.setPadding(new Insets(10));
        layout.setPrefHeight(100);

        stage.setScene(new Scene(layout));
        stage.show();
    }

    private TableView<Field> createTable() {
        TableView<Field> table = new TableView<>();

        TableColumn<Field, String> nameColumn = new TableColumn<>("Name");
        nameColumn.setCellValueFactory(
                p -> p.getValue().nameProperty()
        );

        TableColumn<Field, Field> valueColumn = new TableColumn<>("Value");
        valueColumn.setCellValueFactory(
                p -> Bindings.createObjectBinding(
                        p::getValue,
                        p.getValue().valueProperty(), p.getValue().highlightRangeProperty()
                )
        );
        valueColumn.setCellFactory(param -> new HighlightableTextCell());

        //noinspection unchecked
        table.getColumns().setAll(nameColumn, valueColumn);

        return table;
    }

    public static class HighlightableTextCell extends TableCell<Field, Field> {
        protected void updateItem(Field item, boolean empty) {
            super.updateItem(item, empty);

            if (item == null || empty || item.getValue() == null) {
                setGraphic(null);
            } else {
                setGraphic(constructTextBox(item));
            }
        }

        private Node constructTextBox(Field item) {
            HBox textBox = new HBox();
            textBox.getStylesheets().setAll(HIGHLIGHTABLE_LABEL_CSS);
            textBox.getStyleClass().add(HIGHLIGHTABLE_STYLE_CLASS);

            int from = item.getHighlightRange() != null ? item.getHighlightRange().from() : -1;
            int valueLen = item.getValue() != null ? item.getValue().length() : -1;
            int to = item.getHighlightRange() != null ? item.getHighlightRange().to() : -1;

            if (item.highlightRangeProperty() == null
                    || from >= to
                    || from > valueLen
            ) { // no highlight specified or no highlight in range.
                textBox.getChildren().add(
                        createStyledLabel(
                                item.getValue()
                        )
                );
            } else {
                textBox.getChildren().add(
                        createStyledLabel(
                                item.getValue().substring(
                                        0,
                                        from
                                )
                        )
                );

                if (from >= valueLen) {
                    return textBox;
                }

                textBox.getChildren().add(
                        createStyledLabel(
                                item.getValue().substring(
                                        from,
                                        Math.min(valueLen, to)
                                ), HIGHLIGHTED_STYLE_CLASS
                        )
                );

                if (to >= valueLen) {
                    return textBox;
                }

                textBox.getChildren().add(
                        createStyledLabel(
                                item.getValue().substring(
                                        to
                                )
                        )
                );
            }

            return textBox;
        }

        private Label createStyledLabel(String value, String... styleClasses) {
            Label label = new Label(value);
            label.getStyleClass().setAll(styleClasses);

            return label;
        }
    }

    private void populateTable(TableView<Field> table) {
        table.getItems().addAll(
                new Field("Dragon", "93 6d 6d da", null),
                new Field("Rainbow", "0c fb ff 1c", new Range(3, 8))
        );
    }

}

class Field {
    private final StringProperty name;
    private final StringProperty value;
    private final ObjectProperty<Range> highlightRange;

    public Field(String name, String value, Range highlightRange) {
        this.name = new SimpleStringProperty(name);
        this.value = new SimpleStringProperty(value);
        this.highlightRange = new SimpleObjectProperty<>(highlightRange);
    }

    public String getName() {
        return name.get();
    }

    public StringProperty nameProperty() {
        return name;
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public String getValue() {
        return value.get();
    }

    public StringProperty valueProperty() {
        return value;
    }

    public void setValue(String value) {
        this.value.set(value);
    }

    public Range getHighlightRange() {
        return highlightRange.get();
    }

    public ObjectProperty<Range> highlightRangeProperty() {
        return highlightRange;
    }

    public void setHighlightRange(Range highlightRange) {
        this.highlightRange.set(highlightRange);
    }
}

record Range(int from, int to) {}

Alternative using TextField
An alternative to the HBox for displaying highlighted text would be to use a TextField (non-editable), which allows a selection to be set (via APIs on the text field), however, I did not attempt a solution with a TextField approach.  A TextField may allow a user to drag the mouse to select text (perhaps could be disabled if desired by making the field mouse transparent).
Related Questions (uses TextFlow)

*

*Highlight text in TableView with TextFlow

*JavaFX TableView with highlighted text

*JavaFX: setting background color for Text controls


text:
Q: Property 'value' does not exist on type FormEvent in TypeScript I am struggling to type my lookup for all the input elements inside a submitted form.
  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    const inputs = e.target.getElementsByTagName('input') as HTMLInputElement; //TS2339: Property 'getElementsByTagName' does not exist on type 'EventTarget'.
  };
  return (
        <form onSubmit={submit}>
          <input type="date" name="date" placeholder="e.g. 10/11/1984" />
        </form>
    </>
  );

Full TS error
/var/www/src/Pages/NewClaim/index.tsx
TypeScript error in /var/www/Pages/NewClaim/index.tsx(47,27):
Property 'getElementsByTagName' does not exist on type 'EventTarget'.  TS2339

    45 |     e.preventDefault();
  > 46 |     const inputs = e.target.getElementsByTagName('input') as HTMLInputElement;
       |                           ^
    48 |     const newClaimData = await createClaim();

A: Your casting is a little off–see the snippet below.
getElementsByTagName also returns a HTMLCollection so cannot cast to a single HTMLInputElement
export default function App() {
  const submit = async (e: FormEvent) => {
    e.preventDefault();

    const inputs = (e.target as HTMLFormElement).getElementsByTagName("input") as HTMLCollection;
    console.info(inputs[0]);

    // the element
    const startDate = inputs[0] as HTMLInputElement;
    console.info(startDate);

    // also an option
    const formData = new FormData(e.target as HTMLFormElement);
    console.info(formData.get("start-date"));
  };

  return (
    <form onSubmit={submit}>
      <input type="date" name="start-date" placeholder="e.g. 10/11/1984" />
      <input type="date" name="end-date" placeholder="e.g. 10/11/1984" />
      <button type="submit">Submit</button>
    </form>
  );
}


text:
Q: Consuming a VB.NET web service from PHP I'm relatively new to PHP, and totally new to VB.NET / Web Services / SOAP / XML, and i'm having trouble to make my PHP communicate with the VB.NET web service.
This is my PHP script:
<?php
    $client = new SoapClient("http://10.0.0.2/wsteste/Service1.asmx?wsdl");
    $param = array("usuario" => "name", "senha" => "test");
    $response = $client->__soapCall("HelloWorld", $param);
    print_r($response);
?>

And here is the VB.NET asmx.
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class Service1
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld(ByVal usuario As String, ByVal senha As String) As String
        Return usuario & " - " & senha
    End Function

End Class

And here is what printed on the browser:
stdClass Object ( [HelloWorldResult] => - )
It was supposed to return name - test, wasn't it?

A: I think that the PHP SOAP Client is passing the parameters without the names. So usuario nor senha means nothing to the HelloWorld method.
I would try something like
$client->HelloWorld(array("usuario"=>"name", "senha"=>"test"));

Haven tested though.
EDIT
From this question Call asp.net web service from PHP with multiple parameters
Pass your params like this
$params->usuario = 'name';
$params->senha = 'test';
$client->HelloWorld($params);


text:
Q: Get a value from Javascript I want to get the value that I entered in the prompt, and save it in a variable to use it to update a DB later .. I try this but is does not work !!
@{
    var fileName = "";
    var db = Database.Open( "GP" );
    var sqlupdate = "Update rc_Files set fileName=@0 Where fileID= 5";
    db.Execute(sqlupdate, fileName);
 }

<html lang="en">
  <body>
    <script>
        function myFunction() {
             newName = prompt("Please enter new file name :");
             if (newName != null)
             {
                 @fileName = newName;
             }
        }
    </script>
  </body>
</html>

A: JavaScript is client side language. You can't updated db with it. You can send request to your server side script, which will update something in datatable.
You can find example of doing this here or just use google.

A: Try this code:
$(document).ready(function() {
    var fileName = '';
    var newName = prompt('Please enter a new file name');
    if(newName != null) {
       fileName = newName;
        console.log(fileName);
    }
});

Its getting the value you entered through javascript.
Demo here

A: From your question is not clear what is your goal.
If you want to store a value in your page waiting to use it when the page is posted, you could use a hidden input field.
In my example the value inputed when the page is loaded is stored until the user clicks the submit button:
@{
    if(IsPost){
        var fileName = Request["fileName"];
        var db = Database.Open("GP");
        var sqlupdate = "Update rc_Files set fileName=@0 Where fileID= 5";
        db.Execute(sqlupdate, fileName);
    }
}

<html lang="en">
    <head>
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
    <body>
        <form method="post">
            <input type="hidden" name="fileName" id="fileName" value="" />
            <input type="submit" />
        </form>
        <script>
            $(document).ready(function () {
                var newName = prompt('Please enter a new file name');
                $('#fileName').val(newName);
            });
        </script>
    </body>
</html>

Else, if you want to update your database without submitting your page, you should use Ajax. This article could help you: Posting Data With jQuery AJAX In ASP.NET Razor Web Pages.


text:
Q: pull/push from gitlab results in Permission denied (publickey) I'm using both git bash and VS code to connect to my gitlab repository. Everything was working fine until I created a new repo and tried to clone it locally via git bash.
The error I received was:
git@gitlab.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

I've tried changing the permissions of the ./ssh folder and the public key, adding an ssh to agent, none of those worked.
Executing ssh -Tv <user name>@gitlab.com shows the following output:
OpenSSH_8.2p1, OpenSSL 1.1.1f  31 Mar 2020
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to gitlab.com [172.65.251.78] port 22.
debug1: Connection established.
debug1: identity file /c/Users/user/.ssh/id_rsa type 0
debug1: identity file /c/Users/user/.ssh/id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.8
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.8 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002
debug1: Authenticating to gitlab.com:22 as 'user'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /c/Users/user/.ssh/known_hosts:7
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey in after 134217728 blocks
debug1: pubkey_prepare: ssh_get_authentication_socket: Bad file descriptor
debug1: Will attempt key: /c/Users/user
/.ssh/id_rsa RSA SHA256:rNZDTqdiVzM9+qjPlPV9wpd5Eg0t0tKKMonz+Q6+yGo
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /c/Users/user/.ssh/id_rsa RSA SHA256:rNZDTqdiVzM9+qjPlPV9wpd5Eg0t0tKKMonz+Q6+yGo
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
<user name>@gitlab.com: Permission denied (publickey).

A:
I've tried changing the permissions of the ./ssh folder and the public key, adding an ssh to agent, none of those worked.

First, make sure you have registered the content of id_rsa.pub to your GitLab SSH keys profile page.
If it still does not work, try and regenerate that key, without passphrase (fo testing, and ruling out any ssh-agent issue, which is used only for caching passphrase)
ssh-keygen -m PEM -t rsa -P ""

Make sure your Git for Windows is up-to-date (2.27).
Make sure to set GIT_SSH= (meaning to unset GIT_SSH, which should not refers to putty.exe).


text:
Q: jquery mobile popup not working? im using jquery mobile. im trying to create a popup. I found this simpel code that should work. http://jquerymobile.com/branches/popup-widget/docs/pages/popup/index.html
I tried the code in the example
Tooltip

    This is a completely basic popup, no options set.

but when I put this in my own code the div will still display and when I click on the button it goes to an other page, instead of a popup. Can someone help me?

A: Well ... I've gotten it to work (sample code below, sorry for the muddled string I couldn't get it to display in the code blocks otherwise) ... but I'm wondering how YOU found this page??  This doesn't seem to be part of the latest jQuery Mobile release candidate ... so my guess is that it's not working for you because your JS and CSS references aren't pointing to the files that actually contain the corresponding code?
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>JQM popup test</title>
        <link rel="stylesheet"
            href="http://jquerymobile.com/branches/popup-widget/css/themes/default/jquery.mobile.css"/>

        Tooltip

This is a completely basic popup, no options set.

Other

Random

Text

A: It seems popups are scheduled for 1.2 release (see this page on github).
I think the "branches" in the url page indicates that this page is from the unreleased dev branch of jQuery mobile. If you look at the docs page for the 1.1 release, this feature is not documented.
It can be added to 1.0 by adding either the jquery.mobile.popup.js and css from the previous github link or use the web-ui-fw project which includes the popup widget and other widgets.
I use web-ui-fw to have popups with jQuery mobile 1.1; this plugin uses "popupwindow" instead of "popup" for the data-rel and data-role


text:
Q: Concatenate two matrices in C I'm trying to concatenate the same matrix in C, and the only idea that crossed to my mind is addition, but it doesn't work. For example, if I have: {1,1;2,2}, my new matrix should be {1,1,1,1;2,2,2,2}. I want to double the number of rows. I Googled, but I didn't find anything.
Here is my code:
 matrix2=realloc(matrix1,sizeof(int*)*(row));
 int i,j;
 for(i=0;i<row;i++){
   for(j=0;j<col;j++){
    matrix2[i][j]=matrix1[i][j]+matrix1[i][j];
   }
 }

A: Use the psuedocode I provide below. Note that for any C before C99, you cannot instantiate arrays with int matrix[2*W][H] (if W and H are not #defines)
Given matrix1 and matrix 2 of equal W,H
make matrix3 of 2*W,H
for h to H
    for i to W
        matrix3[h][i] = matrix1[h][i]
        matrix3[h][i+W] = matrix2[h][i]

Making the matrix will require 1 malloc per row, plus 1 malloc to store the array of row pointers.
Note how you will need 2 assignments in the loop instead of the one you had before. This is because you are setting in two places.

A: You sound like you have a background with higher level languages like matlab.  In C the plus operator does not concatenate matrices.  This will add the values in the matrices and store the new value into the new matrix.

A: Here we are copying the input matrix into a new matrix twice
for(int i = 0; i < m; i++){for(int j = 0; j < n;j++)
{  mat2[i][j] = mat[i][j];}}
for(int i = 0 ; i < m ; i++){for(int j = n; j < (2*n) ; j++){   mat2[i][j] = mat[i][j-n];}}


text:
Q: How can we force Isabelle to reveal to us what rule it's applying in the background in Isar when a proof starts? I was trying to prove:
lemma
  shows "¬ ev (Suc 0)"

I did:
lemma
  shows "¬ ev (Suc 0)"
proof (rule notI)
  assume "ev (Suc 0)"
  then show False
  proof

and it gave me really pretty goals:
proof (state)
goal (2 subgoals):
 1. Suc 0 = 0 ⟹ False
 2. ⋀n. ⟦Suc 0 = Suc (Suc n); ev n⟧ ⟹ False

that could probably make my proof readable.
It seems it applied some sort of cases in the background. But when I wrote cases the proof finished immediately instead of showing the above rule inversion cases explicitly. See:
lemma
  shows "¬ ev (Suc 0)"
proof (rule notI)
  assume "ev (Suc 0)"
  then show False
  proof (cases)

which shows:
proof (state)
goal:
No subgoals!

which means I can just place a qed.
How can I figure out exactly what (introduction?) rules Isar is doing automatically in Isabelle?

A: As noted in the comment to your question, in your case, proof boils down to proof rule. The rule method (without any parameters) applies some fitting introduction/elimination rule. You can find out which one it is using the rule_trace attribute:
    using [[rule_trace]] apply rule

(or you could have done declare [[rule_trace]] globally somewhere above or note [[rule_trace]] in your Isar proof)
This says
    proof (prove)
    goal (2 subgoals):
     1. Suc 0 = 0 ⟹ False
     2. ⋀n. Suc 0 = Suc (Suc n) ⟹ ev n ⟹ False
    rules:
        ev ?a ⟹ (?a = 0 ⟹ ?P) ⟹ (⋀n. ?a = Suc (Suc n) ⟹ ev n ⟹ ?P) ⟹ ?P

so it doesn't give you the name, unfortunately. But it is clear that this rule must come from the inductive command, because you didn't prove it yourself. If you do a print_theorems command right after the inductive command, you find that this is the theorem ev.cases, which is also the one that the cases method uses (except that the cases method also does some postprocessing simplification of the goal, as mentioned here).
The inductive command registers the ev.cases rule as an elim? rule, which means that the automation will not use it, but if you do something like apply rule, it will be considered.


text:
Q: JSLint: Read Only error when setting console even though it's set as writable global Consider the following code:
/*global console:true */
(function () {
    "use strict";

    //set console for browsers without debugger
    if (!console) {
        console = {
            log: function() {}
        };
    }
});

This will throw an error:
Error:
Problem at line 7 character 9: Read only.

console = {

Problem at line 7 character 9: Stopping. (3% scanned).

Yet, console has been set as a writeable global, thus it should not be read only.
Any suggestions on how to circumvent or solve this issue?
Thanks.

A: I copied your code and tried it into www.jslint.com, had to change two small things but it gives me no errors  now (added one space after "function" and added the self invokation) :
/*global console:true */
(function () {
    "use strict";

    //set console for browsers without debugger
    if (!console) {
        console = {
            log: function () {}
        };
    }
}());

Where did you try it?

A: If you're using the jslint.com website, and you have the Assume console, alert, ... box checked, try unchecking it.


text:
Q: email logo is the same for self emails I am using magento 2.3.3.
I configured the new logo. When I create a new customer account the email sent to the customer contains the new logo, but the email copy sent to me has always the luma logo.
I tried to delete all the luma images in the directories but still got the luma logo.
The header.html contains src="{{var logo_url}}". I don't know where to set the right logo for email sent to myself.

A: There are an issue in magento 2.3.3 transnational email logo upload. You can fixed this issue by this below process. The you can upload the logo from there and you problem will be solved. I am also faced the same issue but now it is solved.
First you have to go to this below page by
Admin login => Content => Design => Confgiuration => Click on edit your Main Website => then scroll and you get this below section.
This image upload field is wrong. This is file upload field not image and also not working.

You have to create this above field like this below image upload field

Now the below code is to convert the field:
Create /app/code/Vendor/Module/etc/module.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="0.0.1" schema_version="0.0.1">
        <sequence>
            <module name="Magento_Email"/>
        </sequence>
    </module>
</config>

Then overwrite the page:
From :
/vendor/magento/module-email/view/adminhtml/ui_component/design_config_form.xml
To:
/app/code/Vendor/Module/view/adminhtml/ui_component/design_config_form.xml
And change code with this below code
<?xml version="1.0" encoding="UTF-8"?>

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="other_settings">
        <fieldset name="email">
            <settings>
                <level>1</level>
                <collapsible>true</collapsible>
                Transactional Emails
            </settings>
            <field name="email_logo" formElement="imageUploader">
                <settings>
                    <notice translate="true">To optimize logo for high-resolution displays, upload an image that is 3x normal size and then specify 1x dimensions in the width/height fields below.</notice>
                    Logo Image
                    <componentType>imageUploader</componentType>
                </settings>
                <formElements>
                    <imageUploader>
                        <settings>
                            <allowedExtensions>jpg jpeg gif png</allowedExtensions>
                            <maxFileSize>2097152</maxFileSize>
                            <uploaderConfig>
                                <param xsi:type="string" name="url">theme/design_config_fileUploader/save</param>
                            </uploaderConfig>
                        </settings>
                    </imageUploader>
                </formElements>
            </field>
            <field name="email_logo_alt" formElement="input">
                <settings>
                    <validation>
                        <rule name="validate-no-html-tags" xsi:type="boolean">true</rule>
                    </validation>
                    <dataType>text</dataType>
                    Logo Image Alt
                    <dataScope>email_logo_alt</dataScope>
                </settings>
            </field>
            <field name="email_logo_width" formElement="input">
                <settings>
                    <notice translate="true">Necessary only if an image has been uploaded above. Enter number of pixels, without appending "px".</notice>
                    <validation>
                        <rule name="validate-digits" xsi:type="boolean">true</rule>
                    </validation>
                    <dataType>number</dataType>
                    Logo Width
                    <dataScope>email_logo_width</dataScope>
                </settings>
            </field>
            <field name="email_logo_height" formElement="input">
                <settings>
                    <notice translate="true">Necessary only if an image has been uploaded above. Enter image height size in pixels without appending "px".</notice>
                    <validation>
                        <rule name="validate-digits" xsi:type="boolean">true</rule>
                    </validation>
                    <dataType>number</dataType>
                    Logo Height
                    <dataScope>email_logo_height</dataScope>
                </settings>
            </field>
            <field name="email_header_template" formElement="select">
                <settings>
                    <notice translate="true">Email template chosen based on theme fallback, when the "Default" option is selected.</notice>
                    <dataType>text</dataType>
                    Header Template
                    <dataScope>email_header_template</dataScope>
                </settings>
                <formElements>
                    <select>
                        <settings>
                            <options class="Magento\Config\Model\Config\Source\Email\Template\Header"/>
                        </settings>
                    </select>
                </formElements>
            </field>
            <field name="email_footer_template" formElement="select">
                <settings>
                    <notice translate="true">Email template chosen based on theme fallback, when the "Default" option is selected.</notice>
                    <dataType>text</dataType>
                    Footer Template
                    <dataScope>email_footer_template</dataScope>
                </settings>
                <formElements>
                    <select>
                        <settings>
                            <options class="Magento\Config\Model\Config\Source\Email\Template\Footer"/>
                        </settings>
                    </select>
                </formElements>
            </field>
        </fieldset>
    </fieldset>
</form>

Then run
bin/magento setup:upgrade
bin/magento cache:flush
Give permission to the pub, generated, var folder
And then upload your logo from there and send email to check email logo.


text:
Q: jQuery selectors with meta-characters I'm having problem selecting an element with an id like this <li ="0f:Bactidol_Recorder.mp4">.
I tried using the function that escapes meta-characters with two backslashes below from this jquery link but still can't select the element
Function:
function jq(myid) {
   return '#' + myid.replace(/(:|\.)/g,'\\$1');
}

Example:
$(jq('0fb:Bactidol_Recorder.mp4')).empty()

Output:
$(#0fb\\:Bactidol_Recorder\\.mp4).empty();

A: EDIT: Your original code works fine. (jQuery 1.4.2)
You could write
$('*[id="0fb:Bactidol_Recorder.mp4"]')

However, it'll be slower.
The fastest way to do this would be to write
$(document.getElementById("0fb:Bactidol_Recorder.mp4"))


text:
Q: Not all JSON entries are returned in ng-repeat Im learning angularjs. So far I have managed to get a table to populate using a standard ng-repeat directive within a single controller. I am using a JSON file stored on github. Result.
However, I have 1 problem.  The JSON file has 15 objects(?) and each object has 14 attributes.
The json is valid according to JSONlint. A snippet of the json is below
[
    {
        "Room_ID": "1",
        "OldRoom": "room1oldname",
        "NewRoom": "room1newname",
        "floor": "First Floor",
        "facilities": "Y",
        "NoSeats": "4",
        "PC": "1",
        "flipchart": "N",
        "conferencePhone": "N",
        "phone": "Y",
        "whiteboard": "N",
        "projector": "N",
        "waterFountain": "N",
        "NoOfProjectorScreens": "0"
    },
    {
        "Room_ID": "2",
        "OldRoom": "Room2Oldname",
        "NewRoom": "Room2Newname",
        "floor": "First Floor",
        "facilities": "N",
        "NoSeats": "4",
        "PC": "0",
        "flipchart": "N",
        "conferencePhone": "N",
        "phone": "N",
        "whiteboard": "N",
        "projector": "N",
        "waterFountain": "N",
        "NoOfProjectorScreens": "0"
    }
]

Originally it looked like all items with names containing spaces weren't being returned. For example "water fountain" was not returned, but "whiteboard" was.  I changed all the entries to remove spaces and rechecked the validity of the json but no dice.
Ive tried returning data from various sample apis and haven't had any trouble other than this particular json source.
I also tried the $index by x but not sure I did this correctly or if its what i needed since each entry in JSON has its own unique ID.
I presume it must be something to do with the JSON itself otherwise no other results would be returned from this or any other source file.
I presently get 15 rows of data (1 per room), but some of the columns are blank.
I have only been doing this a week, apologies if I have some of the semantics incorrect.
Thank you for your time.
Long time lurker, new time asker
EDIT: Hi, apologies for the delay. I can't add a plunker as I don't know how to use it.  But I am only using two files so I will post the code below.
Index.html and controller.js
Controller.js code
angular
.module("roomviewer", [])

.controller("MainController", function($scope, $http) {

var onUserComplete = function(response){
    $scope.user = response.data;
};

var onError = function(reason){
    $scope.error = "oh no";
};

    $http.get("https://gist.githubusercontent.com/cnrowland/78f5d20bd175028e1051/raw/42246133908e126f2c53303d97a10fff9d43ff07/roomMaster.json")
.then(onUserComplete, onError);

});

Index.html code
<!DOCTYPE html>

<meta charset="utf-8">
<title>Room Viewer</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">

       <button type="button" class="navbar-toggle"
         data-toggle="collapse" data-target="#nav-toggle">

 </button>
       Room Viewer

See All Rooms

Filter Rooms

    <form class="navbar-form navbar-right" role="search">
        <input type="text" class="form-control"
        placeholder="Search">
    </form>

          Room ID
          New Room
          Old Room
          Location
          Facilities
          No of PCs
          Flipchart
          Conference Phone
          Telephone
          Whiteboard
          Water Fountain
          Projector
          No. of Projector Screens

          {{user.Room_ID}}
          {{user.NewRoom}}
          {{user.OldRoom}}
          {{user.floor}}
          {{user.facilities}}
          {{user.PC}}
          {{user.flipchart}}
          {{user.conferencePhone}}
          {{user.phone}}
          {{user.whiteboard}}
          {{user.waterFountain}}
          {{user.projector}}
          {{user.NoOfProjectorScreens}}


text:
Q: How to connect to HBase table using spark without scanning entire table and get specific known row keys data I am having a massive number of row keys,  need to get data of those row keys without scanning entire table or loading entire table into spark as table is very big

A: You may try to use gimel library, according to md file filter are pushed down to Hbase.
What is gimel?

    Gimel is a Big Data Abstraction framework built on Apache Spark & other open source connectors in the industry.
    Gimel provides unified Data API to read & write data to various stores.
    Alongside, a unified SQL access pattern for all stores alike.
    The APIs are available in both scala & python (pyspark).

HBase md file
In this md file you will find some examples, maybe they are similar to you use case
    gsql("set gimel.hbase.columns.mapping=personal:name,personal:age")
val df = gsql("select * from udc.Hbase.ClusterName.default.test_emp where rowkey='1-MAC'")
df.show

df.explain
== Physical Plan ==
*(1) Filter isnotnull(rowkey#181)
+- *(1) Scan HBaseRelation(Map(catalog -> {"table":{"namespace":"default", "name":"test_emp", "tableCoder":"PrimitiveType"},
"rowkey":"rowkey",
"columns":{
"rowkey":{"cf":"rowkey", "col":"rowkey", "type":"string", "length":"50"},
"name":{"cf":"personal", "col":"name", "type":"string"},
"age":{"cf":"personal", "col":"age", "type":"string"}
}
}
    ),None) [rowkey#181,name#182,age#183] PushedFilters: [IsNotNull(rowkey), *EqualTo(rowkey,1-MAC)], ReadSchema: struct<rowkey:string,name:string,age:string>

A: There are many HBase-Spark libraries, but many of them are old and they are not mantained. So I prefer old reliable methods.
Try the following.
I have 'word_counts' HBase table, with 'counts' column family.
In my case there is 'counts:count' column which is Long.
I will use newAPIHadoopRDD method and HBase access by hbase-mapreduce library
Let's start (I am using Apache Spark 3.1.3, but it should work for any Spark version)
spark-shell --master yarn --packages org.apache.hbase:hbase-client:2.2.7,org.apache.hbase:hbase-common:2.2.7,org.apache.hbase:hbase-mapreduce:2.2.7

My code is as follows:
import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.hbase.client.Result
import org.apache.hadoop.hbase.io.ImmutableBytesWritable
import org.apache.hadoop.hbase.mapreduce.TableInputFormat
import org.apache.hadoop.hbase.util.Bytes
import org.apache.spark.sql.SparkSession
import org.apache.hadoop.hbase.filter.PrefixFilter
import org.apache.commons.codec.binary.Base64
import org.apache.hadoop.hbase.protobuf.ProtobufUtil
import org.apache.hadoop.hbase.client.Scan

// This function converts a Scan object to a string representation
// that can be passed to HBase as a configuration value
def convertScanToString(scan: Scan) = {
  val proto = ProtobufUtil.toScan(scan)
  Base64.encodeBase64String(proto.toByteArray)
}

// Create a new Scan object and set a PrefixFilter
// to only return rows with keys that start with "s"
val scan = new Scan()
val filter = new PrefixFilter(Bytes.toBytes("s"))
scan.setFilter(filter)

// Create a new HBase configuration and set the input table,
// zookeeper quorum, and scan
val conf = HBaseConfiguration.create()
conf.set(TableInputFormat.INPUT_TABLE, "word_counts")
conf.set("hbase.zookeeper.quorum", "zookeeper-host")
conf.set(TableInputFormat.SCAN, convertScanToString(scan))

// Create an RDD using the HBase configuration and the TableInputFormat
val rdd = spark.sparkContext.newAPIHadoopRDD(conf, classOf[TableInputFormat], classOf[ImmutableBytesWritable], classOf[Result])

// Convert the RDD to a DataFrame and set the column names
val df = rdd.map(x => {
  val rowKey = Bytes.toString(x._2.getRow)
  val columnValue = Option(x._2.getValue(Bytes.toBytes("counts"),
       Bytes.toBytes("count"))).map(value =>
       Bytes.toLong(value).toString).getOrElse("")
  (rowKey, columnValue)
}).toDF("row_key", "column_value")

If you are interested only with particular key you can use the following
import org.apache.hadoop.hbase.client.{Get, Result}
import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
import org.apache.spark.sql.SparkSession

val hbaseConf = HBaseConfiguration.create()
hbaseConf.set("hbase.zookeeper.quorum", "zookeeper-host")
val tableName = TableName.valueOf("word_counts")
val connection = ConnectionFactory.createConnection(hbaseConf)
val table = connection.getTable(tableName)

val get = new Get(Bytes.toBytes("s"))
val result: Result = table.get(get)

val value = Bytes.toString(result.getValue(Bytes.toBytes("counts"), Bytes.toBytes("count")))

println(s"Value for key 's' is: $value")

table.close()
connection.close()


text:
Q: To set focus on Anchor Tag on enter Key press I have used Anchor tags in my code as mentioned below:

                    Home

                    Contact

On enter key press it opens specific page/link but Default Tab Navigation starts from URL.
What I want is that during TAB Navigation when it selects particular link then on Enter key press specfic page/link will open and focused
should remain on that link/Anchor Tag. Currently it moves and start default Navigation from URL.
I have used this CSS Code:
/* To set keyboard focus on Tab press*/
a:focus
{
    outline: 1px dotted black;
}

Can please anyone assist me to fix this?

A: Okay, I'm hoping that I understand your problem correctly. I think you want a navigation link to stay focused after a user presses enter to navigate through that link. For example, a user is on the homepage, tabs to focus on a 'contact us' link, then presses enter. After navigation to the new page is complete, you want the contact link to remain in focus.
HTML:

  Home
  Contact

JS:
//attach event listener to #nav (doesn't work in IE8)
document.getElementById('nav').addEventListener("keydown", storeLinkId, false);

//function stores ID attribute of target link
//into session storage if enter is pressed
function storeLinkId(e) {
  if (!e) e = window.event;
  var keyCode = e.keyCode || e.which;

  if (keyCode == '13') {
    console.log("storing " + e.target.id);
    sessionStorage.setItem('tabbed-link', e.target.id);
    }
 }

 //if there is a linkid in session storage
 if (sessionStorage.getItem('tabbed-link')) {
   //get the id from session storage
   var linkId = sessionStorage.getItem('tabbed-link');
   //focus on the link with the matching id attribute
   document.getElementById(linkId).focus();
   //delete the linkid from session storage
   sessionStorage.removeItem('tabbed-link');
 }

If you used this method, you would have to include this code on every page of your site. Here's a working example.
Edited: Cleaned up code and added jsFiddle link

A:

                    Home

                    Contact

$(function(){
 $('#home').focus();
})

check this code

A: If I understand correctly... Try adding target="_blank" to anchors
Example:
...


text:
Q: how do I route Asterisk dials from serverA to serverB? I'm trying to make an Asterisk server connect to a SIP provider (which offers PSTN origination and termination). I've been reading the great Definitive Guide, but am having a conceptual problem with this illustration:

Once Asterisk has determined how to handle the channel, it will pass
  call control to the correct context in the dialplan. The context
  parameter in the channel configuration file tells the channel where it
  will enter the dialplan (which contains all the information about how
  to handle and route the call).

The "telephone", in this case a softphone, is defined in sip.conf with easy to understand syntax.  A corresponding context in extensions.conf has the line:
exten => 101,1,Dial(Sip/000FFFF0002)

and the syntax of this seems to mean, to my understanding, to Dial the 000FFFF0002 hardphone.
Now, when it comes to dialing through a SIP provider, this just isn't covered as well, at least for me.
This seems to be crucial line:
exten => _6XXX,1,Dial(SIP/${EXTEN}@serverB)

Which, in my dialplan, is reflected as:
exten => _91999NXXXXXX,2,Dial(${TESTSIPTRUNK}/${EXTEN:2},,To)

yet the "dial" never seems to go to the other server -- in this case, a SIP provider.  I don't understand the mechanics of what's happening.  How do I even figure how or why it's not getting out, and, instead, returns " I am sorry that's not a valid extension..." from invalid.gsm playing.
The full log, the channels and extensions are in gists.  I'm more asking conceptually, what's supposed to be happening?  I appreciate that the calls are supposed to go through ServerB, in this case a SIP provider, but otherwise don't quite understand how to ensure that this actually happens.
see also:
asterisk peer with SIP provider through proxy

A: It answers you

it's not a valid extension

because it cannot find this extension in the given context. Maybe there is an error in what you're dialing vs what you got in the extension.conf
For example, it looks like you're dialing number starting with 91987 when in your extensions.conf I see only pattern to handle numbers starting with 91999. Are you sure there is a exten for 91987?


text:
Q: Python "list index out of range" error in list iteration What am I doing Wrong?
"list index out of range" on line 7
Sorry for russian letters in code, it's my hometask.
Help me please.
import sys
morze = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
ralphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' #Russian alphabet 0-32
doc = "Вот цитата для тебя : Встретив двусмысленность , отбрось искушение угадать . С наилучшими пожеланиями , Андрей ." #doc = open('text.txt')
print('Не поддерживается правильное отображение знаков препинания. Ставьте знаки через пробел.') #Attention
for line in doc:
    line = line.lower() #Downcase
    for word in line.split(' '):
        ln = len(word) #Length of word
        if ln == 1 and word in ralphabet: #One-letter words
            letternumber = ralphabet.find(word)
            sys.stdout.write(morze[letternumber] + ' ')
        elif ln == 1: #Symbols
            ...
        elif ln != 1 and not (word[0] in alphabet): #Symbols error
            sys.stdout.write('[ERROR]')
        elif ln != 1: #Long words
            shift = ln - 1
            if shift > 10:
                shift = 10
            for letter in word:
                letternumber = ralphabet.find(letter) + 1 - shift
                for digit in str(letternumber):
                    sys.stdout.write(morze[digit] + ' ')
            sys.stdout.write('| ')
        sys.stdout.write('| ')

input() #PAUSE

A: You are using the index of the word to find something in the morze list if you print(letternumber,len(morze)) you can see exactly why you get the error:
  (31, 10)
   ^    ^

The length of ralphabet is 66 and the length of morze is 10 so that is not going to work.
You might also want to change these two lines:
 elif ln > 1 and word[0] not in alphabet:  #Symbols error
            sys.stdout.write('[ERROR]')
 elif ln > 1:  #Long words

0 is also != 1 but word[0] is not going to work .
You are also calling str on  letternumber then trying to pass a string as an index:
       for digit in str(letternumber):
             sys.stdout.write(morze[digit] + ' ')
                                       ^
                                       string = error

You could use:
  for digit in range(letternumber):
         sys.stdout.write(morze[digit] + ' ')

But again if  letternumber = ralphabet.find(letter) + 1 - shift is greater than 10 you would get an error.