text:
Q: Is there a difference between Run As: Spring Boot App and Run As: Java Application? If I am using Spring Tool Suite or The Spring IDE plugin for eclipse, I can run a spring boot app 2 ways:
Run As:
    Spring Boot App
    Java Application

Both of these commands work and can fire up my spring boot app without an issue.  However, I wanted to understand the difference between the two different processes.  Is there actually a difference between them or do they work identically?

A: There are couple of differences, as someone already hinted in a comment. This article explains that you get some extra 'Bells and Whistles' in the launch configuration editor.
A second and perhaps more important difference is that since Boot 1.3 there is a JMX bean provided by Spring Boot App that allows STS to ask the app nicely to shut down. When you terminate the app from the IDE, for example by clicking the stop / restart button, STS uses this JMX bean to ask the boot app to shut down. This is a feature implemented in the "Run As Boot App" launcher, and so it doesn't take effect if you use "Run As Java App".
The Java launcher simply terminates the process associated with the launch using Java's Process.destroy() method. This is a more 'aggressive' way to kill the associated process and may not allow the app to cleanup stuff properly, for example cleanly closing database connnections.
So... in summary you get two things:

*

*Some extra boot-specific UI in the launch conf editor

*Graceful process termination for Boot 1.3 and later.


text:
Q: Can I run a XAML Unity App in 3D mode using the Mixed Reality I'm using the latest Unity version (2017.3.0f3) and check my player enable Window Mixed Reality. After building a new project from Unity with Build Type XAML, I see nothing but a black screen. When I use Build Type D3D, it works well.
Is there any problem with XAML type. Almost Mixed Reality tutorial on Microsoft, they recommend using D3D.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Random sampling R I am new to R and trying to exploit a fairly simple task. I have a dataset composed of 20 obs of 19 variabile and I want to generate three non overlapping groups of 5 obs. I am using the slice_sample function from dplyr package, but how do I reiterate excluding the obs already picked up in the first round?
library( "dplyr")
set.seed(123)
NF_1 <- slice_sample(NF, n = 5)

A: You can use the sample function from base R.
All you have to do is sample the rows with replace = FALSE, which means you won't have any overlapping. You can also define the number of samples.
n_groups <- 3
observations_per_group <- 5
size <- n_groups * obersavations_per_group
selected_samples <- sample(seq_len(nrow(NF)), size = size, replace = FALSE)

# Now index those selected rows
NF_1 <- NF[selected_samples, ]

Now, according to your comment, if you want to generate N dataframes, each with a number of samples and also label them accordingly, you can use lapply (which is a function that "applies" a function to a set of values). The "l" in "lapply" means that it returns a list. There are other types of apply functions. You can read more about that (and I highly recommend that you do!) here.
This code should solve your problem, or at least give you a good idea or where to go.
n_groups <- 3
observations_per_group <- 5
size <- observations_per_group * n_groups

# First we'll get the row samples.
selected_samples <- sample(
    seq_len(nrow(NF)),
    size = size,
    replace = FALSE
)

# Now we split them between the number of groups
split_samples <- split(
    selected_samples,
    rep(1:n_groups, observations_per_group)
)

# For each group (1 to n_groups) we'll define a dataframe with samples
# and store them sequentially in a list.

my_dataframes <- lapply(1:n_groups, function(x) {
    # our subset df will be the original df with the list of samples
    # for group at position "x" (1, 2, 3.., n_groups)
    subset_df <- NF[split_samples[x], ]
    return(subset_df)
})

# now, if you need to access the results, you can simply do:
first_df <- my_dataframes[[1]] # use double brackets to access list elements


text:
Q: Why does my 'git branch' have no master? I'm a git newbie and I keep reading about a "master" branch. Is "master" just a conventional name that people used or does it have special meaning like HEAD?
When I do git branch on the clone that I have, I only see 1 single branch - the one I'm on. No "master" at all. If I type git checkout master (as I see in alot of tutorials or guides), I get
error: pathspec 'master' did not match any file(s) known to git.

I'm just confused as to why my clone doesn't have a master that everyone seems to imply that it always exists.

A: Most Git repositories use master as the main (and default) branch - if you initialize a new Git repo via git init, it will have master checked out by default.
However, if you clone a repository, the default branch you have is whatever the remote's HEAD points to (HEAD is actually a symbolic ref that points to a branch name). So if the repository you cloned had a HEAD pointed to, say, foo, then your clone will just have a foo branch.
The remote you cloned from might still have a master branch (you could check with git ls-remote origin master), but you wouldn't have created a local version of that branch by default, because git clone only checks out the remote's HEAD.

A: I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add . and then git commit and the master branch will be created.
Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.

A: To checkout a branch which does not exist locally but is in the remote repo you could use this command:
git checkout -t -b master origin/master

A: master is just the name of a branch, there's nothing magic about it except it's created by default when a new repository is created.
You can add it back with git checkout -b master.

A: I actually had the same problem with a completely new repository. I had even tried creating one with git checkout -b master, but it would not create the branch. I then realized if I made some changes and committed them, git created my master branch.

A: In my case there was a develop branch but no master branch. Therefore I cloned the repository pointing the newly created HEAD to the existing branch. Then I created the missing master branch and update HEAD to point to the new master branch.
git clone git:repositoryname --branch otherbranch
git checkout -b master
git update-ref HEAD master
git push --set-upstream origin master

A: if it is a new repo you've cloned, it may still be empty, in which case:
git push -u origin master
should likely sort it out.
(did in my case.  not sure this is the same issue, thought i should post this just incase. might help others.)

A: It seems there must be at least one local commit on the master branch to do:
git push -u origin master

So if you did git init . and then git remote add origin ..., you still need to do:
git add ...
git commit -m "..."

A: If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'.  By using the command git status from your terminal you'd see which location you are.  In some cases, you'd see origin/main.
If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.
example:
git push heroku main

A: I had the same problem. I executed the "git init", but the main/master branch was not created. Possibly because I used a branch with another name and this one became the default.
The solution that worked for me was:

*

*I created the branch "main"

git checkout -b main

*I went to the option Settings->Branches of my directory and changed it to the new branch "main"

*With this change, Github itself notified me that my default branch (main) was behind my other branch and opened the window for me to confirm a PR applying the changes to the branch main. And following this, merging the pull request.


text:
Q: What does "biting one's nails" mean? It is puzzling. When I search online for "what is nail biting" all I get are pages explaining how to stop, not what it is.
Is it simply the act of biting the nails, or does it necessarily include a compulsive element to it? If someone trims their nails by biting, does it count? If they trim their nails, but don't bite their nails any time else, does it count?
Are all of the forms of "nail biting" mention equally as problematic? Is nail biting an issue in social acceptance?

A: "Nail biting" can be considered a sign of agitation. As far as OCD behavior, that is a question for psychology, rather than language use. As for connotation in a social context, it is not considered sanitary, in public, nor does it leave one's fingernails with a good appearance. However, toenail biting might be considered a mark of great agility and flexibility.

A: When used literally, which is common, "biting one's nails" refers to using one's physical teeth to bite one's physical nails, regardless of the reason or frequency. E.g. "Look, Sally is biting her nails" means "Look, Sally is using her teeth to cut/tear off the ends of her fingernails".
Therefore:

does it necessarily include a compulsive element to it?

No.

If someone trims their nails by biting, does it count? If they trim their nails, but don't bite their nails any time else, does it count?

Yes, that would still be called "biting one's nails".

In my portion of the English-speaking world, it isn't considered socially normal to trim one's nails by biting. It's expected to use a sharp instrument to do the job: most people use metal nail clippers, some might use some other tool such as scissors or a knife. Children who bite their nails are expected to grow out of it as they get older, and if they don't, it is usually seen as a problem that parents should work to solve. That is the reason why you see search results about how to stop, or help someone else stop biting their nails.
Whether either nail-biting or the societal norms about it are problematic or an issue is not a question about English usage.
Because nail-biting is associated with anxiety, "biting one's nails" also has a metaphorical usage meaning "feeling anxious" (e.g. "I was biting my nails about X" = "I was anxious about X").


text:
Q: run_inference_for_single_image(image, graph) - Tensorflow, object detection In reference to object_detection_tutorial.ipynb. I am wondering if its possible to run for all the images in a directory.
Rather than writing a for loop and running a "run_inference_for_single_image(image, graph)". Is there a way to run the inference on all the images in a directory or run the inference on multiple images.
link
  for f in files:
    if f.lower().endswith(('.png', '.jpg', '.jpeg')):
      image_path = files_dir + '/' + f
       .... // Read image etc.
      output_dict = run_inference_for_single_image(image_np, detection_graph)

This will create tf.session each time and i think its computationally expensive. Please correct me if i am wrong.

A: As you know, 'run_inference_for_single_image' method create each time.
If you wanna inference for multiple images, you should change code like,

*

*Method Call
images = []
for f in files:
  if f.lower().endswith(('.png', '.jpg', '.jpeg')):
    image_path = files_dir + '/' + f
    image =  .... // Read image etc.
    images.append(image)
    output_dicts = run_inference_for_multiple_images(images, detection_graph)

*run_inference_for_multiple_images
def run_inference_for_multiple_images(images, grapg):
  with graph.as_default():
    with tf.Session() as sess:
      output_dicts = []

      for index, image in enumerate(images):
        ... same as inferencing for single image

         output_dicts.append(output_dict)

   return output_dicts

This code will be performed without creating tf.session each time but once.

A: I found this tutorial from google - creating-object-detection-application-tensorflow. After looking into its github page --> object_detection_app --> app.py we only need to run detect_objects(image_path) function every single time we want to detect an object.

A: It is possible to run inference on batch of images depending on computational power of GPU and size of the images.
step 1: stacking all the test images in one array:
for image_path in glob.glob(PATH_TO_TEST_IMAGES_DIR + '/*.jpg'):
    image_np = io.imread(image_path)  #
    image_array.append(image_np)
image_array = np.array(image_array)

step 2: run inference on batches: (higher batch size might cause out of memory issues)
  BATCH_SIZE = 5
  for i in range(0, image_array.shape[0],BATCH_SIZE):
    output_dict = sess.run(tensor_dict, feed_dict={image_tensor: image_array[i:i+BATCH_SIZE]})

    print("number of images inferenced = ", i+BATCH_SIZE)
    output_dict_array.append(output_dict)

make sure dimensions of image_tensor and image_array match. In this example image_array is (?, height, width, 3)
some tips:

*

*You would want to load the graph only once as it takes few seconds to load.

*I observed that using skimage.io.imread() or cv2.imread() is pretty fast in loading images. These functions directly load images as numpy arrays.

*skimage or opencv for saving images are faster than matplotlib.


text:
Q: Adding a piped input to an array during a while read So my web host adds a malware.txt file in my account if there is any. The file has a line with the path to file ending with a : for each line.
I am trying to use awk to print the path from this file and pipe the output into adding into an array. But it's not adding for some reason because when I print nothing happens. If I manually add an element to the array it prints.
Please help me understand how I am wrong.
#!/bin/bash

# Add list of infected files to an array
declare -A malware_listing=()
awk -F":" '/home/{print $1}' ~/malware.txt | while read file ; do malware_listing+=( ${file} ) ; done ;

# Print list of infected files
for i in "${malware_listing[@]}" ; do echo $i ; done ;
~


text:
Q: How to extract string with one regex? I need some help with regex. I have 3 types of headings

*

*1.1.1.1 Abc

*B.1.1.1 Abc

*B. Abc
And I want to select like to select them like this

*

*1.1.1.1

*B.1.1.1

*B
Thank you

A: Here is a regex pattern whose matches seem to work for what you expect:
^.*?(?=\.? [A-Za-z]{3}$)

The lookahead will cause the pattern to stop matching when it sees an optional dot, followed by a space, then followed by three characters and the end of the line.
Demo

A: Try groups

var examples = [
  "1.1.1.1 Abc",
  "B.1.1.1 Abc",
  "B. Abc"
];

for(var k in examples) {
  k = examples[k];
  document.write(k.replace(/(.*)Abc/,'$1')+"<br>");
}

A: Try pattern: ([\dA-Z]\.)+[\dA-Z]?
([\dA-Z]\.)+ will match ne or more uppercase letter or digits followed by a dot.
[\dA-Z]? will match zero or one occurence of uppercase letter or digits followed by a dot.
Demo

A: Try this regex:
^[0-9\.A-Z\/]*?(?=\.?\s)


text:
Q: Tips and sequence to troubleshooting ICs on PCB I have PCB that has a pretty sophisticated IC on it (Ethernet switch). Some of the boards work fine but some do not. The reason is that IC doesn't seem to work. There is even no clock on clocking inputs from the crystal and I think that it means that the IC is damaged. My questions are:

*

*Are there some tips how to debug ICs on the PCB, I mean check if the IC is operational or damaged.

*What can cause IC damage on the PCB, can it only be electrostatic discharge or maybe there are some common mistakes in the PCB design.
There matter is that I have a pretty big amount of that PCBs (~20) and half of them are not operational because the IC doesn't seem to work and I want to find the cause but don't no how...


text:
Q: Opening media from google maps custom marker So I'm working on a custom google maps tour type application and I'm wondering how to get media to popup when I click a link within a google maps marker.  Ideally this is what I would like to happen:
1. User clicks on marker and the normal white box comes up like on real Google Maps.
2. Within that text box I would like to have a button that will launch media that I have stored on a SQL server somewhere. This media could be audio, pictures, or video.
The code I have so far is below. If anyone could let me know how to do this, or point me in the right direction that would be awesome!
Thanks
<!doctype  html>

    <title>HuskyWalk Application Demo</title>
    <meta name="viewport" conmtent="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

Maps provided by Google Maps

I know there is going to need to be some stuff in the onMarker_Clicked() method most likely, I'm just not sure what.

A: You'll want to use an InfoWindow and call its open() method from the click event handler.
See also the section in the google maps developer guide https://developers.google.com/maps/documentation/javascript/overlays#InfoWindows


text:
Q: Return/print amount of digits in a sentence OR an error message I'm new to the site and to python so I hope I'm giving all the required information. I've already searched for this question but none of the solutions seem to work for me.
I'm trying to create a function that reads some text and returns the amount of digits it contains. For example:
"It is 2012" , should return "Text has 4 digits"
If there are no digits, it should return a different message such as:
"It is Monday" , should return "Text does not contain digits"
So I wrote this:
def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit() == False:
            print ("Text does not contain digits")

        else:
            sum += 1

    print("Text has", sum, "digit(s)")

txt = str(input("Write some text: "))
(CountNumbers(txt))

The functions seem to be OK however, the prints turn out wrong, for example:
Write some text: 65
Text has 2 digit(s) #this is ok, but...

When I only input text:
Write some text: sd
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 0 digit(s)

When I input text and numbers (but text first):
Write some text: sd 564
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 3 digit(s)

I know my error lies in the blocks, (I think), but I haven't figured out a way because when I use return, it stops before it finished to read the text. I've tried about 20+ different things, please help me !
Thank you !!
P.S. I need this to work as a .py and not just in the IDLE (Python Shell) window, that's why I'm writing the blocks like this.

A: The issue is you are printing the "Text does not contain digits" message every time you encounter a non-digit character. Try moving that print statement to after the loop when you know how many characters there are:
def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit():
            sum += 1

    if sum > 0:
        print("Text has", sum, "digit(s)")
    else:
        print ("Text does not contain digits")

txt = str(input("Write some text: "))
(CountNumbers(txt))

Edit: A couple more points towards good Python code:

*

*As noted in the comments of your question, by convention, functions/methods in Python are named in lower case with underscores, i.e., count_numbers not CountNumbers.

*Pedantic mode: you are counting the digits in the string, not numbers, so it should really be named count_digits for clarity.

*There is a built-in Python function called sum. It is considered bad practice to shadow this function by having a variable of the same name. I'd rename your sum variable to count.

*There is no need to surround a function call in parentheses (it doesn't do any harm, apart from making it look bad IMHO).

With these changes, your code becomes:
def count_digits(txt):
    count = 0

    for n in txt:
        if n.isdigit():
            count += 1

    if count > 0:
        print("Text has", count, "digit(s)")
    else:
        print ("Text does not contain digits")

txt = str(input("Write some text: "))
count_digits(txt)

A: I just solved your codes problems:
def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit():
            sum += 1

    if sum:
        print("Text has", sum, "digit(s)")
    else:
        print ("Text does not contain digits")

CountNumbers(input("Write some text: "))

A: Early returns are quite alright and can greatly simplify the code:
def CountNumbers(txt):
    for n in txt:
        if not n.isdigit():
            print ("Text does not contain digits")
            return

    print("Text has", len(txt), "digit(s)")

txt = str(input("Write some text: "))
(CountNumbers(txt))

This function returns as soon as a non-digit character appears, or prints the length of the input string (which is made of nothing but digits).
You could also write that with a "generation expression" like:
def CountNumbers(txt):
    if all(char.isdigit() for char in txt):
        print("Text has", len(txt), "digit(s)")
    else:
        print ("Text does not contain digits")

txt = str(input("Write some text: "))
(CountNumbers(txt))

Now, Python functions more typically return values and let the calling code act on it. This version returns the strings and lets the "main" part of your program print the results. It also renames the function to all lowercase (Python usually uses capitalized names for classes):
def countnumbers(txt):
    if all(char.isdigit() for char in txt):
        return "Text has %d digit(s)" % len(txt)
    else:
        return "Text does not contain digits"

txt = str(input("Write some text: "))
print(countnumbers(txt))

Hmmm, not too shabby! But Python also has nifty conditional expressions like:
def countnumbers(txt):
    return ("Text has %d digit(s)" % len(txt)
        if all(char.isdigit() for char in txt)
        else "Text does not contain digits")

txt = str(input("Write some text: "))
print(countnumbers(txt))

Finally, maybe you'll want to make that into a proper module so other code can use it. Wrap the interactive part of your program like this and it will only execute if you're running it like a command line script, but not if your importing it as a module:
def countnumbers(txt):
    return ("Text has %d digit(s)" % len(txt)
        if all(char.isdigit() for char in txt)
        else "Text does not contain digits")

if __name__ == '__main__':
    txt = str(input("Write some text: "))
    print(countnumbers(txt))

If I were writing that function as part of a production system, that's pretty close to how it'd look. Notice that the logic is identical to your first attempt. The biggest difference is that this version lets Python do most of the work.

A: A slightly more pythonic reworking of the original. Personally, I find the 'list comprehension' form a little easier to read (unless it's nested):
def count_digits(txt):
    count = len([c for c in txt if c.isdigit()])

    if count > 0:
        print ("Text has", count, "digit(s)")
    else:
        print ("Text does not contain digits")


text:
Q: How to create a report in SSRS by using another report? I Had report stateLow.rdl in my project solutions. I need to add one more report to solution named as stateHigh.rdl. The second report structure looks like stateLow.rdl with different datasets. Do I need to develop the structure from scratch or I can use existing report?

A: What I do is just make a copy of the report you want to clone (stateLow.rdl) using Windows Explorer or whatever and rename it to the new name (stateHigh.rdl). Then in Visual Studio, right-click the Reports folder in the Solution Explorer, select Add -> Existing item... and add the new report then edit it with my changes.


text:
Q: Properties of the vector space $V^-$ defined by "refusing" to multiply the complex vector space $V$ by anything other than real scalars. I$\def\nc#1#2{\newcommand{#1}{#2}}\nc{\vm}{V^-\!}\nc{\v}{V}\nc{\f}{\mathbb{F}}\nc{\fn}{\f^n\!}$ am reading "Finite Dimensional Vector Spaces" by Halmos and several times he mentions the space denoted by $\vm$ which, for any complex vector space $\v$ of dimension $n$, is found by only multiplying vectors in $\v$ by real scalars.
My question is two fold.
An exercise asks the dimension of this vector space $\vm$. I figure that the basis for $\v$ will be the same as the basis for $\vm$ so the dimension must be $n$. I also suppose an isomorphism can be established with $\fn$ which allows us to take $\fn$ as a real vector space with dimension $n$. Is this reasoning correct?
My second question asks why this vector space $\vm$ could be considered important. I have a feeling it is more than a contrived example. Does anyone have any input?
Thank you.

A: Let $V$ be a $\Bbb C$-vector space with $\Bbb C$-basis
$$
\{v_1,\dotsc,v_n\}
$$
Then for every $v\in V$ there exist unique $\alpha_1,\dotsc,\alpha_n\in\Bbb C$ such that
$$
v=\alpha_1\cdot v_1+\dotsb+\alpha_n\cdot v_n
$$
But now there are unique $a_k,b_k\in\Bbb R$ such that $\alpha_k=a_k+ib_k$. Hence for every $v\in V$ there exist unique $a_1,\dotsc,a_n,b_1,\dotsc,b_n\in\Bbb R$ such that
$$
v=a_1\cdot v_1+\dotsb+a_n\cdot v_n+b_1\cdot iv_1+\dotsb+b_n\cdot iv_n\tag{1}
$$
Can you use equation (1) to find a basis (and hence compute the dimension) of $V^-$?

A: We will have
$$\dim V^-=2\dim V$$ we can think of this as $$[V^-:\mathbb{R}]=[V:\mathbb{C}][\mathbb{C}:\mathbb{R}]$$
The example is not contrived since this situation occurs all the time in algebra and representation theory.


text:
Q: Parse query results array returning nill objective c I'm trying to fetch objects from parse however I'm getting a nil array even after the findObjectsInBackgroundWithBlock.

The Question class does exist if you're wondering.
So my question is, why is my array nil even though there are objects in my Question class?


text:
Q: android.view.InflateException: Error inflating class android.support.design.widget.NavigationView В Android Studio создал проект по шаблону Navigation Drawer Activity при отладке вылетает ошибка в onCreate MainActivity:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

В xml nav_view:
<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

nav_header_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/logo_act"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Flower Deliver"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Just Deliver It" />

</LinearLayout>

Чем это вызвано?
Если minSdk = 15
И Sdk устройства = 15


text:
Q: Microsoft ORCA Answer File I am editing a .MSI file and one of the properties is email. Is there a way to pull the users email address automatically so during the install they do not have to enter it?

A: No, it's not possible to automatically retrieve the user's email address during the installation of an MSI file. This is because MSI files are used to install software on a computer, and they do not have access to personal information about the user.
If you want to collect the user's email address during the installation process, you will need to include a field in the installation wizard that prompts the user to enter their email address. You can then store this information in a property of the MSI file, which can be used by the installed software or stored in a configuration file for later use.
One way to do this is to use a custom action in the MSI file to prompt the user for their email address and store it in a property. You can use a custom action to display a dialog box or other user interface element that prompts the user for their email address and then use the MSI API to store the value in a property.


text:
Q: R extracting structured data between multiple html tags I have downloaded my facebook data. It contains a htm file with all my contacts. I would like to read it in with R, and create a contact.csv.
The usual structure is:

Firstname Lastname

contact: email@email.com

contact: +123456789

but some contacts may miss the phone number

Firstname Lastname

contact: email@email.com

while some miss the email

Firstname Lastname

contact: +123456789

The csv should have the structure Firstname Lastname; email; tel number
I have tried:
library(rvest)
library(stringr)

html <- read_html("contact_info.htm")
p_nodes <- html %>% html_nodes('tr')
p_nodes_text <- p_nodes %>% html_text()
write.csv(p_nodes_text, "contact.csv")

Which creates me the csv, but unfortunately merges names with "contact:" and does not create separate columns and does not allow to have "NA" for missing either phone numbers or emails.
How could I enhance my code to accomplish this?
Thanks

A: You can use regexpr to identify the email & the telephon number :
xml1 <- '
Firstname Lastname

contact: email@email.com

contact: +123456789

'
xml2 <- '
Firstname Lastname

contact: email@email.com

'
xml3 <- '
Firstname Lastname

contact: +123456789

'
docs <- c(xml1,xml2,xml3)

library(rvest)

df <- NULL

for ( doc in docs) {
 page <- read_html(doc)
 name <- page %>% html_nodes("tr td:first-child") %>% html_text()
 meta <- page %>% html_nodes("span.meta li") %>% html_text
 ind_mail <- grep(".{1,}\\@.{1,}\\..{1,}",meta)
 if(length(ind_mail)>0) mail <- meta[ind_mail] else mail <- "UNKWN"
 ind_tel <- grep("[0-9]{6,}$",meta)
 if(length(ind_tel)>0) tel <- meta[ind_tel] else tel <- "UNKWN"
 res <- cbind(name,mail,tel)
 df <- rbind(df,res)
}

Hope that will helps ,
Gottavianoni


text:
Q: Flask + Gunicorn + Pyrogram I try create python app with Flask, Gunicorn and Pyrogram
This is one of code examples:
import flask
from flask import request
from pyrogram import Client, idle

session_str="Looong session key"

app = flask.Flask(__name__)
pyro = Client('my_account', in_memory=True, session_string=session_str)

@app.route('/api/v1/is_alive')
def isAlive():
    return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}

@app.route('/api/v1/get_me', methods=['GET'])
def getMe():
    with pyro:
         data = pyro.get_me()
         return str(data)

if __name__ == '__main__':
    pyro.start()
    app.run(debug=False,host='0.0.0.0')

I got one of error:

attached to a different loop
ConnectionError("Client has not been started yet")
ConnectionError("Client is already connected")

App starting with this command:
gunicorn wsgi:app --bind 0.0.0.0:8000 -w 2 --threads 2 --access-logfile -
I tried run :
@app.route('/api/v1/get_me', methods=['GET'])
def getMe():
         data = pyro.get_me()
         return str(data)

if __name__ == '__main__':
    app.run(debug=False,host='0.0.0.0')

@app.route('/api/v1/get_me', methods=['GET'])
def getMe():
         data = pyro.get_me()
         return str(data)

if __name__ == '__main__':
    pyro.start()
    app.run(debug=False,host='0.0.0.0')

Working without error example:
@app.route('/api/v1/get_me', methods=['GET'])
def getMe():
         pyro.start()
         data = pyro.get_me()
         return str(data)

if __name__ == '__main__':
    app.run(debug=False,host='0.0.0.0')

but i need insert pyro.start() on each route((
How to start pyrogram one time???


text:
Q: How can I write "Event1 'or' Event2" inside on method from flutter_bloc? That's my code for PostsBloc:
class PostsBloc extends Bloc<PostsEvent, PostsState> {
  final _dataService = DataService();

  // Constructor
  PostsBloc() : super(LoadingPostsState()) {
    on<LoadPostsEvent>((event, emit) async {
      emit(LoadingPostsState());

      try {
        final posts = await _dataService.getPosts();
        emit(LoadedPostsState(posts: posts));
      } catch (e) {
        emit(FailedToLoadPostsState(error: e));
      }
    });
  }
}

So, I want to use the same method with new event, just without emitting LoadingPostsState() like this:
 PostsBloc() : super(LoadingPostsState()) {
    on<LoadPostsEvent || PullToRefreshEvent>((event, emit) async {
      if(event == LoadPostsEvent){
        emit(LoadingPostsState());
      }

      try {
        final posts = await _dataService.getPosts();
        emit(LoadedPostsState(posts: posts));
      } catch (e) {
        emit(FailedToLoadPostsState(error: e));
      }
    });
  }

A: What you want is the is operator:
if (event is LoadPostsEvent)

However you run into another problem:
on<LoadPostsEvent || PullToRefreshEvent>

this is not a thing. I believe you have two options:
Either make a new event X and have LoadPostsEvent and PullToRefreshEvent extend it, like this:
class LoadEvent extends PostsEvent { ... }

class LoadPostsEvent extends LoadEvent { ... }
class PullToRefreshEvent extends LoadEvent { ... }

on<LoadEvent>((event, emit) {
  if (event is LoadPostsEvent)
});

or, in order to minimize code repetition, declare this event handler as a function
on<LoadPostsEvent>(_loadEvent);
on<PullToRefreshEvent>(_loadEvent);

...

void _loadEvent(PostsEvent event, Emitter<PostsState> emit) {

...

}


text:
Q: Should I programmatically add subviews in init or ViewDidLoad, and why? I've been browsing some answers here and I get two different suggestions:

*

*add in init. Example in this answer

*add in ViewDidLoad. Suggested in this answer
Which one is the current best practice? The second answer seems to be older (2010), so I wonder if it's an old, no-longer-suggested, practice?

A: For a non-XIB-based view controller, the correct place is in -loadView. -loadView is responsible for initializing a view controller's view property, including any subviews. The system will call this method at the appropriate time. You must assign something to the view controller's view property inside this method:
 - (void)loadView
{
    UIView *view = ...;
    // create additional views here

    self.view = view;
}

If you have a XIB-based view controller, the documentation says not to override -loadView. In this case, you should do additional view initialized work in -viewDidLoad.

A: No, never do such stuff in init.
I viewDidLoad or even viewWillAppear, never in init because your view might not be there at the time, it kept happening to me when I was starting out that I was setting some string to a UILabel which wasn't there and made the app crash, but this worked in the simulator because it is so much faster than an actual device like iPhone 3.
Same with resetting data and closing off delegates and such should not be set in dealloc. Dealloc might not get called when you think it will. You should set such operations inside viewWillDissapear or viewWillUnload.


text:
Q: React Native: RNUILib 5.30.0 in React-Native 0.65.1 wont build due to error Background: I am trying to setup RNUILib on a react-native project but it wont build.
I followed the instructions from the official guide.

Environment: Android/Windows
Here's my dependencies:
@react-native-community/blur : 3.6.0
@react-native-community/datetimepicker : 3.5.2
@react-native-community/masked-view : 0.1.11
@react-native-community/netinfo : 6.0.1
@react-native-picker/picker : 1.16.7
@react-navigation/drawer : 6.1.4
@react-navigation/native : 6.0.2
react: 17.0.2
react-native: 0.65.1
react-native-gesture-handler : 1.10.3
react-native-reanimated : 2.3.0-alpha.2
react-native-safe-area-context : 3.3.0
react-native-screens : 3.6.0
react-native-ui-lib : 5.30.0

Error log from react-native run-android command:
Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Could not find com.eightbitlab:blurview:1.6.3.
     Searched in the following locations:
       - https://dl.google.com/dl/android/maven2/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
       - https://repo.maven.apache.org/maven2/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
       - file:/C:/Users/vfvic/.m2/repository/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
       - file:/D:/_react-native/CBTracker2/node_modules/react-native/android/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
       - file:/D:/_react-native/CBTracker2/node_modules/jsc-android/dist/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
       - https://www.jitpack.io/com/eightbitlab/blurview/1.6.3/blurview-1.6.3.pom
     Required by:
         project :app > project :react-native-community_blur

As I have mentioned, I have performed all the steps in the Setup guide, including the linking of @react-native-community/blur.

A: Apparently, this is due to com.eightbitlab:blurview being only available from jcenter which is required by react-native-community_blur.
I've added jcenter() in my build.gradle file and it's now working fine.
allprojects {
    repositories {
        jcenter()
        google()
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        maven { url 'https://www.jitpack.io' }
    }
}

A: late but hope it will help someone, update android/build.gradle like below
allprojects {
    repositories {
        ....rest

        jcenter() {
            content {
                includeModule("com.eightbitlab", "blurview")
            }
        }
    }
}

A: According officials, just try https://github.com/Kureev/react-native-blur/issues/444


text:
Q: Error when running MYSQL code--Super confused I get this error when trying to compile in sqlfiddle- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 9
If I take Line 9 out it does the same, I'm not sure how to fix this.
I'm pretty new to this, can I run these commands from the community edition of MySQL?
If I run the customer table by itself it works, I add the Pizza table it's fine, but when I add the OrderInformation table is where I start getting that error. I've gone through the code a few times, is there something I'm missing when it comes to the orderinformation table? I'm Stuck.
CREATE TABLE Customer
(
CustomerID     int                 NOT NULL   AUTO_INCREMENT,
FirstName      varchar(45)   NOT NULL,
LastName       varchar(45)  NOT NULL,
StreetAddress  varchar(45)  NOT NULL,
City                    varchar(45)  NOT NULL,
State                 varchar(2)   NOT NULL,
ZipCode            varchar(5)     NOT NULL,
HomePhone    INT(11)  ,
MobilePhone   INT(11) ,
OtherPhone     INT(11),
PRIMARY KEY (CustomerID)
);

CREATE TABLE Pizza
(
PizzaID          INT                   NOT NULL   AUTO_INCREMENT,
PizzaName   VARCHAR(45) NOT NULL,
Description    VARCHAR(90),
UnitPrice        DECIMAL           NOT NULL,
PRIMARY KEY (PizzaID)
);

CREATE TABLE OrderInformation
(
OrderID             int          NOT NULL,
CustomerID      int          NOT NULL  AUTO_INCREMENT,
OrderDate        date       NOT NULL,
PRIMARY KEY (CustomerID, OrderID),
FOREIGN KEY(CustomerID) REFERENCES  Customer (CustomerID),

);

CREATE TABLE OrderItem
(
OrderID     INT              NOT NULL,
Quantity   SMALLINT(5),
PizzaID   INT               NOT NULL,
PRIMARY KEY (OrderID, PizzaID),
FOREIGN KEY(PizzaID) REFERENCES Pizza (PizzaID),
FOREIGN KEY(OrderID) REFERENCES  OrderInformation (OrderID)
);

A: Your problem is that you left a comma , where it shouldn't be here:
CREATE TABLE OrderInformation
(
OrderID             int          NOT NULL,
CustomerID      int          NOT NULL  AUTO_INCREMENT,
OrderDate        date       NOT NULL,
PRIMARY KEY (CustomerID, OrderID),
FOREIGN KEY(CustomerID) REFERENCES  Customer (CustomerID), --<--------- here
);

Remove it and you should be fine.
There is also another problem I noticed.
On the OrderItem table you tried to add a foreign key constraint to OrderInformation table, but you only specified one field. The OrderInformation table has two fields as primary key so every table that has a constraint to it should also have both columns.
Also, make no sense to have CustomerID int NOT NULL AUTO_INCREMENT, column as AUTO_INCREMENT in OrderInformation table. It should just be a foreign key constraint. Given your database model.


text:
Q: Why I am getting android.os.NetworkOnMainThreadException with AsyncTask? I am getting android.os.NetworkOnMainThreadException while I have wrote the code of networking operation in AsynkTask. is there any other reason for throwing this exception?
Here is my Code:
public class Background_confirmation extends AsyncTask<Void, Integer, Void> {
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            progressDialog = ProgressDialog.show(Confirmation.this,
                    "Please wait...", "Retrieving data ...", true);
            try {
                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost(
                        "http://68.121.167.160/sip_chat_api/create_account.php?useralias="
                                + useralias + "&cntname=" + cntcode + "");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                    is = entity.getContent();

            } catch (Exception e) {
                e.printStackTrace();
            }
            if (backgroung_flag == 1) {

            } else {
                if (is != null) {
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(is, "UTF-8"));
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();

                        result = sb.toString();
                    } catch (Exception e) {
                        Log.e("log_tag",
                                "Error converting result " + e.toString());
                    }
                }

            }
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                // progressDialog.setCancelable(true);
            }
            super.onPostExecute(result);
        }

    }

And i am calling this class in OnCreate()
new Background_confirmation().execute();

But it always goes in Catch block and gives me this exceptions LogCat
Any suggestion and idea will be Appreciated.
Thanks

A: You've used wrong AsyncTask method to place Your network related code. Please, move it to doInBackground, because onPreExecute takes place on main thread. So, exception occurred. Details are here.

A: public class Background_confirmation extends AsyncTask<Void, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(Confirmation.this, "Please wait...", "Retrieving data ...", true);

        }

        @Override
        protected String doInBackground(Void... params) {

            try {
                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost("http://68.121.167.160/sip_chat_api/create_account.php?useralias=" + useralias + "&cntname=" + cntcode + "");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                e.printStackTrace();
            }
            if (backgroung_flag == 1) {

            } else {
                if (is != null) {
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();

                        result = sb.toString();
                    } catch (Exception e) {
                        Log.e("log_tag", "Error converting result " + e.toString());
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                // progressDialog.setCancelable(true);
            }
        }
    }

Your code should change like above. Things you have to consider

*

*Connectivity should code inside doInBackground()

*If you want to get the result of the doInBackground(), you have to take it in onPostExecute()

*That means you have to return a String value in doInBackground() where your third parameter of AsyncTask class should be String too (which is not in Wayne's answer)

In your code, you are calling a InputStream that we cannot see except in the "else" part. If you are using only that InputStream, make sure code always reach the else part.

A: Put all your network request code in doInBackground.
onPreExecute and onPostExecute will run on UI Thread (main thead) so you will get an exeption if you request network on these 2 methods.
public class Background_confirmation extends AsyncTask<Void, Integer, Void> {
    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(Confirmation.this,
                "Please wait...", "Retrieving data ...", true);

    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(
                    "http://68.121.167.160/sip_chat_api/create_account.php?useralias="
                            + useralias + "&cntname=" + cntcode + "");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
                is = entity.getContent();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (backgroung_flag == 1) {

        } else {
            if (is != null) {
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is, "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();

                    result = sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag",
                            "Error converting result " + e.toString());
                }
            }

        }
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
            // progressDialog.setCancelable(true);
        }

    }

}


text:
Q: Map function Inside an Array In javascript I know the number one rule of coding is to never repeat yourself ,
My code works perfectly but
How do I go about mapping this  realYears[0] so I can dynamically retrieve the array data inside it without having to repeat the steps 7 times
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Total People in IS', 'Backlog With Growth Rate', 'Backlog With Current Delivery Pace'],
      realYears[0],
      realYears[1],
      realYears[2],
      realYears[3],
      realYears[4],
      realYears[5],
      realYears[6],
      realYears[7]
    ]);

realYears[] contains
0: (4) ["2020", NaN, NaN, NaN]
1: (4) ["2021", 210000, 25000, 24000]
2: (4) ["2022", 220000, 28000, 24500]
3: (4) ["2023", 200000, 28500, 25000]
4: (4) ["2024", 190000, 29000, 25500]
5: (4) ["2025", 250000, 31000, 26000]
6: (4) ["2026", 245000, 32000, 26500]
7: (4) ["2027", 245000, 34000, 27500]

So Basically I'm mapping each array row

A: You may be looking for ES6 spread operator.

const array1 = ["E1", "E2", "E3"];

let yourArray = ["your Entry", ...array1];

console.log(yourArray);

In your case, it would be:
var data = google.visualization.arrayToDataTable([
      ['Year', 'Total People in IS', 'Backlog With Growth Rate', 'Backlog With Current Delivery Pace'],
      ...realYears
    ]);


text:
Q: Parsing bytes recieved from a keyboard I am currently working with understanding the keyboard entries received by the computer or OS, which here is Linux.
I wrote a small program to see all the entries from the keyboard, and all I could understand was that each message is 24 bytes long and each key press seems to be recorded within 3 such messages.
I could not find a way to understand what the entry meant exactly.
As an example:

*

*My Entry

helloworld^C

*The output

    ffffffd3 31 5d 5d 0 0 0 0 ffffff98 3d c 0 0 0 0 0 4 0 4 0 28 0 7 0
    ffffffd3 31 5d 5d 0 0 0 0 ffffff98 3d c 0 0 0 0 0 1 0 1c 0 0 0 0 0
    ffffffd3 31 5d 5d 0 0 0 0 ffffff98 3d c 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc2 5d 9 0 0 0 0 0 4 0 4 0 b 0 7 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc2 5d 9 0 0 0 0 0 1 0 23 0 1 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc2 5d 9 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 2c 5b a 0 0 0 0 0 4 0 4 0 b 0 7 0
    ffffffd4 31 5d 5d 0 0 0 0 2c 5b a 0 0 0 0 0 1 0 23 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 2c 5b a 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc8 ffffffd9 a 0 0 0 0 0 4 0 4 0 8 0 7 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc8 ffffffd9 a 0 0 0 0 0 1 0 12 0 1 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc8 ffffffd9 a 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffe7 16 c 0 0 0 0 0 4 0 4 0 8 0 7 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffe7 16 c 0 0 0 0 0 1 0 12 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffe7 16 c 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffac 11 e 0 0 0 0 0 4 0 4 0 f 0 7 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffac 11 e 0 0 0 0 0 1 0 26 0 1 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffac 11 e 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc9 ffffffcf e 0 0 0 0 0 4 0 4 0 f 0 7 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc9 ffffffcf e 0 0 0 0 0 1 0 26 0 0 0 0 0
    ffffffd4 31 5d 5d 0 0 0 0 ffffffc9 ffffffcf e 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 4c ffffffca 0 0 0 0 0 0 4 0 4 0 f 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 4c ffffffca 0 0 0 0 0 0 1 0 26 0 1 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 4c ffffffca 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 4d ffffffc7 1 0 0 0 0 0 4 0 4 0 f 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 4d ffffffc7 1 0 0 0 0 0 1 0 26 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 4d ffffffc7 1 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffab 0 4 0 0 0 0 0 4 0 4 0 12 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffab 0 4 0 0 0 0 0 1 0 18 0 1 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffab 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffb4 fffffffd 4 0 0 0 0 0 4 0 4 0 12 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffb4 fffffffd 4 0 0 0 0 0 1 0 18 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffb4 fffffffd 4 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffbc ffffffbb 5 0 0 0 0 0 4 0 4 0 1a 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffbc ffffffbb 5 0 0 0 0 0 1 0 11 0 1 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffbc ffffffbb 5 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffc2 ffffffb8 6 0 0 0 0 0 4 0 4 0 1a 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffc2 ffffffb8 6 0 0 0 0 0 1 0 11 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffc2 ffffffb8 6 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffa8 ffffffb5 7 0 0 0 0 0 4 0 4 0 12 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffa8 ffffffb5 7 0 0 0 0 0 1 0 18 0 1 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffa8 ffffffb5 7 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffa3 73 8 0 0 0 0 0 4 0 4 0 12 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffa3 73 8 0 0 0 0 0 1 0 18 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 ffffffa3 73 8 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 79 70 9 0 0 0 0 0 4 0 4 0 15 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 79 70 9 0 0 0 0 0 1 0 13 0 1 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 79 70 9 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 fffffff8 6d a 0 0 0 0 0 4 0 4 0 15 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 fffffff8 6d a 0 0 0 0 0 1 0 13 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 fffffff8 6d a 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 c ffffffec a 0 0 0 0 0 4 0 4 0 f 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 c ffffffec a 0 0 0 0 0 1 0 26 0 1 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 c ffffffec a 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 fffffffa ffffffa9 b 0 0 0 0 0 4 0 4 0 f 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 fffffffa ffffffa9 b 0 0 0 0 0 1 0 26 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 fffffffa ffffffa9 b 0 0 0 0 0 0 0 0 0 0 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 17 ffffffa7 c 0 0 0 0 0 4 0 4 0 7 0 7 0
    ffffffd5 31 5d 5d 0 0 0 0 17 ffffffa7 c 0 0 0 0 0 1 0 20 0 1 0 0 0
    ffffffd5 31 5d 5d 0 0 0 0 17 f

*The code I used

#include"json.h"

    int main(char* argc, char* argv[]){
        FILE* fp = fopen("/dev/input/event8","r");
        FILE* fp2 = fopen("log.txt","w");
        char ch;
        int n = 0;
        char repr[10];
        while(1){
            ch = fgetc(fp);
            if(n==24){
                fputc('\n', fp2);
                n = 0;
            }
            sprintf(repr, "%x", ch);
            fputs(repr, fp2);
            fputc(' ', fp2);
            n++;
        }
    }

A:
I could not find a way to understand what the entry meant exactly.

The device node that your program is reading from,
        FILE* fp = fopen("/dev/input/event8","r");

is a special type of file that is known as an input event interface.
Reading from that file will return data organized as
struct input_event {
        struct timeval time;
        unsigned short type;
        unsigned short code;
        unsigned int value;
};

Besides the key/event code and key value, the data includes a timestamp time.
The GNU C Library provides two data types specifically for representing an elapsed time.
They are used by various GNU C Library functions, and you can use them for your own purposes
too. They're exactly the same except that one has a resolution in microseconds, and the other,
newer one, is in nanoseconds.

Data Type: struct timeval

    The struct timeval structure represents an elapsed time. It is declared in sys/time.h
    and has the following members:

    time_t tv_sec
        This represents the number of whole seconds of elapsed time.

    long int tv_usec
        This is the rest of the elapsed time (a fraction of a second), represented as
        the number of microseconds. It is always less than one million.

The event types and event codes are described here.
Try using the utility evtest instead of your program to get a feel for the event interface.
E.G. sample output for pressing & releasing the A key:
Event: time 1566419656.576267, -------------- SYN_REPORT ------------
Event: time 1566419662.463531, type 4 (EV_MSC), code 4 (MSC_SCAN), value 1e
Event: time 1566419662.463531, type 1 (EV_KEY), code 30 (KEY_A), value 1
Event: time 1566419662.463531, -------------- SYN_REPORT ------------
Event: time 1566419662.615625, type 4 (EV_MSC), code 4 (MSC_SCAN), value 1e
Event: time 1566419662.615625, type 1 (EV_KEY), code 30 (KEY_A), value 0

Be sure that you understand raw keyboard output, i.e. scancodes.
On a PC the keyboard hardware generates scancodes so that every keypress (and release) can be detected.
It is up to software to translate and remap the keypresses, e.g. to ASCII code or ANSI escape sequences.


text:
Q: Query with WITH clause and COUNT subquery In the query below, I don't get the results i would expect. Any insights why? How could i reformulate such query to get the desired results?
Schema (SQLite v3.30)
WITH RECURSIVE
  cnt(x,y) AS (VALUES(0,ABS(Random()%3)) UNION ALL SELECT x+1, ABS(Random()%3) FROM cnt WHERE x<10),
  i_rnd as (SELECT r1.x, r1.y, (SELECT COUNT(*) FROM cnt as r2 WHERE r2.y<=r1.y) as idx FROM cnt as r1)
SELECT * FROM i_rnd ORDER BY y;

result:
| x   | y   | idx |
| --- | --- | --- |
| 1   | 0   | 3   |
| 5   | 0   | 6   |
| 8   | 0   | 5   |
| 9   | 0   | 4   |
| 10  | 0   | 2   |
| 3   | 1   | 4   |
| 0   | 2   | 11  |
| 2   | 2   | 11  |
| 4   | 2   | 11  |
| 6   | 2   | 11  |
| 7   | 2   | 11  |

expected result:
| x   | y   | idx |
| --- | --- | --- |
| 1   | 0   | 5   |
| 5   | 0   | 5   |
| 8   | 0   | 5   |
| 9   | 0   | 5   |
| 10  | 0   | 5   |
| 3   | 1   | 6   |
| 0   | 2   | 11  |
| 2   | 2   | 11  |
| 4   | 2   | 11  |
| 6   | 2   | 11  |
| 7   | 2   | 11  |

In other words, idx should indicate how many rows have y less or equal than the y of row considered.

A: I would just use:
select cnt.*,
       count(*) over (order by y)
from cnt;

Here is a db<>fiddle.
The issue with your code is probably that the CTE is re-evaluated each time it is called, so the values are not consistent -- a problem with volatile functions in CTEs.


text:
Q: Expectation of a normal random variable when conditioning on a correlated normal random variable being above a threshold Suppose $X$ and $Y$ are correlated with correlation coefficient $\rho$. They are jointly normal with means $\mu_X$ and $\mu_Y$ respectively. Then what is $E[X | Y \geq T]$? Feel free to add additional assumptions if necessary.
In the case where $X = Y$, we can use the formula here: https://en.wikipedia.org/wiki/Truncated_normal_distribution#One_sided_truncation_(of_lower_tail)[4].

A: The same expectation can be written in terms of standard normal RVs, with the same correlation coefficient:
$$\mathbb E[X|Y\geq t] = \sigma_x \mathbb E\left[\frac{X-\mu_x}{\sigma_x} \bigg| \frac{Y-\mu_y}{\sigma_y} \geq \frac{t-\mu_y}{\sigma_y}\right] + \mu_x = \sigma_x\mathbb E[X'|Y'>t']+\mu_x$$
Then, we can use the formula given in the wikipedia:
$$\mathbb E[X' | Y' > t']=\mathbb E[X' | Y'\geq t']=\rho \frac{\phi(t')}{1-\Phi(t')}$$
and, plug in. $\phi(z)$ and $\Phi(z)$ are the PDF and CDF of standard normal RV, respectively.

A: As a closed form solution has already been proposed, here is a relatively simple numerical algorithm to arrive at an answer as well.

*

*Generate a random uniform deviate between 0 and 1.

*Use this value in a software supplied Normal random deviate inversion algorithm to create a Normal deviate, say $Y_i$, for a Normal distribution with associated mean = $μ_y$ and sigma = $σ_y$.

*If $Y_i$ ≥ t, keep the sample point, otherwise return to Step 1.

*Compute $E[X|Y = Y_i ]$ per the well known formula $\mathbb E[X | Y_i ] = \mu_x + ρ\frac{\sigma_x}{\sigma_y}(Y_i -\mu_y) $. Source see, for example, this education reference.

*Repeat starting at Step 1 for a large number of iterations.

*Finally, calculate the average of all values obtained in Step 4.
Note, one can easily adjust Step 3 in this Monte Carlo simulation approach to handle more complex cases (like a range).


text:
Q: How To Check the input for a possible close match from A DB OK i will write as clear as possible
it's an e-commerce web site and there is a lot of goods
so i have a searching form that send's the input to a php script via jquery's post
method(ajax) now what i want to do is to check if the input (from the form) is equal
or close to one of the word's in my DB but i cant write a regexp for every single word so is
there a solution ???
for example if the client want to see our offers for pentuim 4 and he wrote peniuom it should tell that "do you mean pentuim"
i hope that i can get an answer now

A: You could just send the user input to a LIKE query and get the database to do the search work - they are pretty good at that :-)
If there are no results for an exact match then you could pass the search terms through a spell-checker first or use a fuzzy search.
How do I do a fuzzy match of company names in MYSQL with PHP for auto-complete? might also help.


text:
Q: How to append Nginx IP to X-Forwarded-For in Kubernetes Nginx Ingress Controller I''m wondering "How to append Nginx IP to X-Forwarded-For"
I added snippet in Ingress annotation.
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ing
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      proxy_set_header X-Forwarded-For "$remote_addr, $server_addr";

But it seems to double set in nginx.conf.
    proxy_set_header X-Forwarded-For        $remote_addr;
...
    proxy_set_header X-Forwarded-For "$remote_addr, $server_addr";

So my backend server will get two X-Forwarded-For
Anyone knows "How to disable the proxy_set_header part generated by Nginx Ingress Controller"?
        proxy_set_header X-Request-ID           $req_id;
        proxy_set_header X-Real-IP              $remote_addr;

        proxy_set_header X-Forwarded-For        $remote_addr;

        proxy_set_header X-Forwarded-Host       $best_http_host;
        proxy_set_header X-Forwarded-Port       $pass_port;
        proxy_set_header X-Forwarded-Proto      $pass_access_scheme;

        proxy_set_header X-Scheme               $pass_access_scheme;

A: The accepted answer is not working for me. You just need to add the below annotation to the ingress object;
nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Forwarded-For $http_x_forwarded_for";

for testing;
❯ curl -I https://example.com/path/here

HTTP/1.1 200 OK
cache-control: no-cache, no-store, max-age=0, must-revalidate
Date: Sat, 13 Mar 2021 08:52:02 GMT
expires: 0
pragma: no-cache
vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers
X-Forwarded-For: 88.888.8.8
Connection: keep-alive

A: Your configuration snippet is not being doubled, actually what is happening is that proxy_set_header X-Forwarded-For        $remote_addr; is already set by default when you deploy NGINX Controller in your cluster.
In order to disable this default setting, you need to use a custom template.
By doing this, you can have a nginx.conf free of proxy_set_header X-Forwarded-For        $remote_addr; so you can set it as you need using the annotation you have described.

A: Just for people with a similar problem who end up here, an alternative (perhaps cleaner) solution, if you're deploying ingress-nginx controller using Helm is to set both compute-full-forwarded-for and use-forwarded-headers to true in your values.yml. No need for additional configurations in the Ingress (like the one in the question).


text:
Q: Fullcite with Optex bibliography system I've been searching in the documentation, but haven't found a way to print, in the text, the complete reference of an entry. It would work just like the \fullcite command from Biblatex, which prints the entry in the text itself:
\fullcite[olsak] = Olšák, Petr. OpTEX – A new generation of Plain TEX. TUGboat. TEX Users Group, 2020, Vol. 41, No. 3, pp. 348–354.
In other words, when one calls it in the text it prints the full reference. I find it useful for syllabi. (It works somewhat like the verbose style in biblatex.)

A: I've created a new OpTeX trick 0092 which implements \fullcite. You have to read the data from .bib file first at beginning of your document using
\readbib (simple) op-biblist

and then \fullcite[label] expands to the bibliographic record. It is far from ideal because bib system in OpTeX was borrowed completely from old OPmac and there is dependency on librarian package with not fully expandable macros. The plan is to rewritten this part of OpTeX in order to leave the librarian dependency and use Lua code for reading .bib files. But this is only plan, not realized in coming weeks.


text:
Q: How to display clickable features from Geoserver over Google Maps v3 Base? Please forgive what I am sure is a very noob question, but I need to do some research into the best way to achieve this and I am a beginner to GIS.
My employer has a Geoserver instance set up which can serve up files in all manner of formats. Is it possible to plot one of these onto Google Maps v3 in such a way as to make the feature's properties available to an information pop-up?
My development server is not on the same domain as the Geoserver, but the Geoserver serves up files publicly.
I have tried using GeoJSON but this seems to rely on the Geoserver and web server being on the same domain, otherwise cross site scripting protection prevents the connection - this works fine as long as I download the GeoJSON into a text file and store it on the web server but the source database will be regularly updated so the mapping needs to be dynamic.
I've tried using a KML layer, but nothing displays at all when I use this method replacing the KML file URL with my own Geoserver's KML file url.
I think this must not be a weird question as having a map with features that pop up info when you click them seems to be a fairly common thing, so can someone advise me where to start?
e.g. What is the best format to use to serve up dynamically updated data from Geoserver? Is it possible to display this kind of info on Google Maps? I believe that this needs to be a web feature service in order to plot vector objects rather than image-based maps - how would you handle this kind of request?

A: You need to implement a WebGIS application which base layer is provided by Google Maps and which main feature layer is provided by your employer GeoServer instance. For this purpose you may use the excellent open source library OpenLayers. In its home site you can find tutorials and examples which can help you to implement your application. Alternatively you may use maps provided by OpenStreetMap or other open data services in your application.
Web browsers prevent applications from performing AJAX requests to domains different from domain serving the application. Therefore this will prevent your application to reach data provided by the GeoServer instance. For avoiding this limitation you may enable cross-origin resource sharing (CORS) in the GeoServer instance. You can find more information about CORS in this web site.

A: Since google maps would just be a reference layer served under your own data hosted on geoserver you need to build an application that queries and returns text field data to a text box, the layer you are serving from your local hosted data, the Google data is really just a graphic background to your map window is not related to your data base but through synchronization of a nonreferenced raster hosted by google, about the only data you might get from google data would be lat lon and a hundred geo referenced points within query limits restricted by google through a developer contract.

A: What is your frontend tool ? If you use for example Leaflet, you can use the google map as background, WMS layer from geoserver as "foreground" and script like
https://gist.github.com/rclark/6908938
to get detailed information about the clicked item (you can modify the geoserver to return for example HTML table or JSON data, if you prefer to work with them in some script way, display specific popup and so on)


text:
Q: How to style buttons in Ruby on Rails Button is as follows:
    <%= render 'follow_form' if signed_in? %>

In follow_form:
    <%= render 'follow' %>

In follow.html.erb:
    <%= form_for current_user.relationships.build(:followed_id => @user.id),
         :remote => true do |f| %>

<%= f.hidden_field :followed_id %>

<%= f.submit "Watch" %>

    <% end %>

How would I style that with CSS?

A: Try :
<%= f.submit "Watch" , :style => 'padding-top: 14px', :class => 'class_name' %>

A: You can simply pass parameters to the f.submit helper, including a class and/or ID, to enable the button to be styled by CSS.  For example, you could put this in the ERB:

<%= f.submit "Watch", :class => "button" %>

and then have a CSS class that applies to that, for example:
.button{
  color: #bbbbbb;
  width: 200px;
  height: 100px;
  /*add any other properties you want to style*/
}


text:
Q: PDFBox insert images inline with TEXT I am using PDFBox for the first time to generate a PDF. I have a text document which consists of a series of about 40 multi-choice questions generated by my java program. Some of the questions have associated small images which need to be inserted above the question.
For this reason I am converting the text document to a PDF and hope to insert the images on that.
I have managed to insert an image into the PDF document but it underlay's the text like a background.
I want to place the images in line with the text (as in word format text box, inline).
It seems the insert image classes need an absolute position which will depend on the position of the text.
How can I know where to draw my image?
for info PDFBox 2.0.7.jar
import ExamDatabase.ReadInputFile;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.PDFontFactory;//???look up
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType3Font;
import org.apache.pdfbox.pdmodel.font.PDSimpleFont;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDInlineImage;

/**
 *
 * @author Steve carr
 */
public class HelloWorldPdf1_1_1
{
    //runs

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException
    {

        ReadInputFile fileI = new ReadInputFile();// read plain text file text file
        ArrayList<String> localList = fileI.readerNew();

        // Create a document and add a page to it
        try (PDDocument document = new PDDocument())
        {
            PDPage page = new PDPage();
            document.addPage(page);

            // Create a new font1 object selecting one of the PDF base fonts
            PDFont font1 = PDType1Font.HELVETICA;//TIMES_ROMAN;
            PDFont font2 = PDType1Font.TIMES_ROMAN;
            PDFont font3 = PDType1Font.COURIER_BOLD;

            try (PDPageContentStream contentStream = new PDPageContentStream(document, page))
            {

                //Creating PDImageXObject object
                PDImageXObject pdImage = PDImageXObject.createFromFile("C:/PdfBox_Examples/CARD00.GIF", document);

                //**creating the PDPageContentStream object
                //PDPageContentStream contents = new PDPageContentStream(document, page);
                //**Drawing the image in the PDF document
                contentStream.drawImage(pdImage, 100, 500, 50, 70);//1ST number is horizontal posn from left

                //****TEXTTEXTTEXTTEXT
                // Define a text content stream using the selected font1, moving the cursor and drawing the text "Hello World"
                contentStream.beginText();

                contentStream.setFont(font1, 11);

                contentStream.newLineAtOffset(0, 0);
                contentStream.setCharacterSpacing(0);
                contentStream.setWordSpacing(0);
                contentStream.setLeading(0);
                contentStream.setLeading(14.5f);// this was key for some reason

                contentStream.moveTextPositionByAmount(100, 700);// sets the start point of text

                System.out.println("localList.size= " + localList.size());//just checking within bounds during testing

                String line;
                int i;

                for (i = 0; i < 138; ++i)
                {
                    System.out.println(localList.get(i));
                    line = localList.get(i);

                    contentStream.drawString(line);
                    contentStream.newLine();
                }

                contentStream.endText();
                //******************************************************
                // Make sure that the content stream is closed:
                contentStream.close();
            }

            // Save the results and ensure that the document is properly closed:
            document.save("Hello World.pdf");
        }
    }
}

result output with text written on top of image:

A: As per this pdf box fix: https://issues.apache.org/jira/browse/PDFBOX-738, transparency is preserved only when rgba is set.so if transparency is preserved it will look as inline with the other text rather than an overlay, so this could be a solution for your first part of the problem ie the overlay issue.
And this example helps you find how to compute the width occupied by a specific text and thus to calculate where to place the image next after the text:
https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/DetermineTextFitsField.java?revision=1749360&view=markup


text:
Q: Ruby on Rails: I cannot create a new user When I sent to the terminal with $ curl -X POST '{"user": {"name": "hogehoge", "email": "hogehoge@gmail.com", "icon_url": "hogehoge", "location": "hogehgoe", "password": "hogehoge"}}' localhost:3000/v1/users on my application directory for creating a new user, I had an error.
{
  "status": 400,
  "error": "Bad Request",
  "exception": "#<ActionController::ParameterMissing: param is missing or the value is empty: user>",
  ・・・
  ・・・
  ・・・
}

at the server log
Started POST "/v1/users" for 127.0.0.1 at 2018-12-11 16:55:56 +0900
Processing by V1::UsersController#create as JSON
  Parameters: {"name"=>"hogehoge", "email"=>"hogehoge@gmail.com", "icon_url"=>"hogehoge", "location"=>"hogehoge", "password"=>"[FILTERED]"}
Completed 400 Bad Request in 1ms

ActionController::ParameterMissing (param is missing or the value is empty: user):

app/controllers/v1/users_controller.rb:52:in `user_params'
app/controllers/v1/users_controller.rb:20:in `create'

I thought user_params was satisfied with correct parameters, but it didnot.
This is my user_controller.rb
module V1
  class UsersController < ApiController
    before_action :set_user, only: [:show, :update, :destroy]
    skip_before_action :authenticate_user_from_token!, only: [:show, :index, :create]

    # POST /users
    def create
      @user = User.new(user_params)

      if @user.save
        render json: @user, serializer: V1::UserSerializer
      else
        render json: @user.errors, status: :unprocessable_entity
      end
    end

    private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def user_params
      params.require(:user).permit(:name, :email, :location, :icon_url, :password)
      p params
    end
  end
end

why did HTTP sent to me with 400 bad status code?

As you said, I sent to the terminal with this JSON params to localhost:3000/v1/users.
{
 "user":
    {
    "name": "hogehoge",
    "email": "hogehoge@gmail.com",
    "icon_url": "hogehoge",
    "location": "hogehoge",
    "password": "hogehoge"
    }
}

but now HTTP status sent 500 internal server error to me.
This is a new error code.
Started POST "/v1/users" for 127.0.0.1 at 2018-12-11 17:33:50 +0900
Processing by V1::UsersController#create as JSON
  Parameters: {"user"=>{"name"=>"hogehoge", "email"=>"hogehoge@gmail.com", "icon_url"=>"hogehoge", "location"=>"hogehoge", "password"=>"[FILTERED]"}}
<ActionController::Parameters {"user"=><ActionController::Parameters {"name"=>"hogehoge", "email"=>"hogehoge@gmail.com", "icon_url"=>"hogehoge", "location"=>"hogehoge", "password"=>"hogehoge"} permitted: false>, "format"=>:json, "controller"=>"v1/users", "action"=>"create"} permitted: false>
Completed 500 Internal Server Error in 34ms (ActiveRecord: 2.0ms)

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

app/controllers/v1/users_controller.rb:20:in `create'

A: Your View
You are not passing any hash having key user in your params,
  Parameters: {"name"=>"hogehoge", "email"=>"hogehoge@gmail.com", "icon_url"=>"hogehoge", "location"=>"hogehoge", "password"=>"[FILTERED]"}

If you are creating your user by form by form_for, it will look like,
  Parameters: { "user" => { "name"=>"hogehoge", "email"=>"hogehoge@gmail.com", "icon_url"=>"hogehoge", "location"=>"hogehoge", "password"=>"[FILTERED]" } }

You are passing user params by input tag for sure. So how you are supposed to use strong parameters!

A: It looks like you left debug code in your #user_params so it won't return the right object:
# Only allow a trusted parameter "white list" through.
def user_params
  params.require(:user).permit(:name, :email, :location, :icon_url, :password)
  p params
end


text:
Q: Xamarin.Forms Shell Tabbar goes up when keyboard open in Android and iOS I have used xamarin shell tabbar and create one chat screen but when keyboard appears Tabbar also goes up.
I have tried all possible ways but not getting success please help me.

A: Try to set Soft Keyboard Input Mode to Resize:
App.Current.On<Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);


text:
Q: tvOS: YouTube Player with subtitles I implemented a tvOS App that allows to browse YouTube playlists and play their videos. On web I simply can enable subtitles. But via the api this doesn't seem to be supported. Is the no flag on YouTube to render subtitles in the stream?
How do I achieve this?


text:
Q: When using Samba, how do I stop programs from deleting and recreating a file when I edit it? I have a Raspberry Pi that I've set up as a home file server. It's running Ubuntu Server 21.04 and Samba Version 4.13.3-Ubuntu.
Here's the relevant part of my /etc/samba/smb.conf file:
[NAS]
    comment = Samba Share for Us
    path = /media/4TB-NAS/Samba/
    browsable = yes
    read only = no
    valid users = @samba-users
    create mask = 0664
    directory mask = 0775
    force group = samba-users
    vfs objects = recycle
    recycle:repository = /media/4TB-NAS/Samba/.recycle
    recycle:keeptree = yes
    recycle:versions = no
    recycle:touch = yes
    recycle:exclude_dir = .recycle

[Guest]
    comment = MediaShare for Guests
    path = /media/4TB-NAS/Samba/MediaShare/
    guest ok = yes
    browsable = yes
    read only = yes

Here's the problem: Whenever I connect to my Samba share NAS from my desktop and edit (and save) a TXT file using Pluma or an ODT file using LibreOffice Writer, I think those programs actually delete the old file and then save a new copy of it. How do I stop that from happening? (Or at least hide that behavior from Samba and it's Recycle Bin feature?)
I noticed this happening because we have two users who use this Samba share. If one user creates a file, they will be that file's owner. However, if the other user then edits that file, they will actually become the new owner of the file. I've actually found this issue documented online: https://www.samba.org/samba/docs/old/Samba3-HOWTO/AccessControls.html#id2615338 (look for the heading at the bottom titled "MS Word with Samba Changes Owner of File"). This issue (changing file owners) on its own isn't a big deal for me. With the create mask, directory mask, and force group lines in my smb.conf file, I can work around the changing ownership easily enough.
However, this problem is a bigger pain when it comes to my Samba Recycle Bin. Every time I edit a file, the old version is sent to Samba's Recycle Bin! I don't want my Samba Recycle Bin crowded with old versions of files that I did not delete.
How can I solve this problem? Any help or insights would be much appreciated! (= Thank you!


text:
Q: Certain website's url does not change after login e.g. facebook.com stays facebook.com after login? My website URL is www.xyz.com after login I redirect it to home page then my URL looks like www.xyz.com/home but I want to stay as www.xyz.com even after login...
How to do it? Most of the websites like facebook, twitter does it.
How to create the access file for it?

A: There is no special trick here. Any URL can be loaded when you're logged out, and then loaded again when you're logged in.
If your application assumes that everyone who goes to /home is logged in, it's clearly insecure. If /home can tell whether the user is logged in, so can /.
An application can do what it likes with that information - it doesn't have to redirect to a different page if the user is in the "wrong" state, it can just serve different content.


text:
Q: How to add DataGridViewLinkColumn property to dynamically generated columns in DataGridView? Developing In: c# winforms without any Database Connections
Description: In my DataGridView, columns were dynamically generated.At some point some of the columns need to be DataGridViewLinkColumn property. I was tried in many ways but didn't achive this.
I hope someone from here would help me :)
Thanks In Advance.

A: Try this:
       DataGridViewLinkColumn links = new DataGridViewLinkColumn();

        links.HeaderText = "Hello";
        links.UseColumnTextForLinkValue = true;
        links.Text="http://microsoft.com";
        links.ActiveLinkColor = Color.White;
        links.LinkBehavior = LinkBehavior.SystemDefault;
        links.LinkColor = Color.Blue;
        links.TrackVisitedState = true;
        links.VisitedLinkColor = Color.YellowGreen;

        dataGridView.Columns.Add(links);

A: You will need to switch off AutoGenerateColumns, then generate each column yourself.
Setup the normal columns as type DataGridViewTextBoxColumn, then for the columns which need to be Linked columns set them up as type DataGridViewLinkColumn.


text:
Q: Is it possible to keep tomb stones after tables compaction? I understand that entries get marked with tombstones when a deletion in requested in C*. This way, a soft deletion is performed and it is made effective during compaction:

In addition to consolidating SSTables, the compaction process merges
  keys, combines columns, discards tombstones, and creates a new index
  in the merged SSTable.

Is it possible to avoid tombstones discard in order to keep them stored for ever? I know that would be against efficiency. I just wonder if it is possible.

A: You can use a higher gc_grace_seconds value in your table properties to increase the time until tombstones will be effectively deleted.


text:
Q: Selection Sort in ArrayList of Integers w/o Collections.sort I need to code my own method selection sort WITHOUT the Collections.sort() in Java. This is my current code, and I can't seem to figure out how to actually swap positions in the list. Any help would greatly be appreciated!
        ArrayList<Integer> ListOfNumbers = new ArrayList(8);

        ListOfNumbers.add(9);
        ListOfNumbers.add(19);
        ListOfNumbers.add(2);
        ListOfNumbers.add(1231);
        ListOfNumbers.add(89);
        ListOfNumbers.add(17);
        ListOfNumbers.add(3);
        ListOfNumbers.add(1);

        for(int i=0; i<ListOfNumbers.size(); i++)
        {
          int CurrentMinimum = i;

          for (int j=i+1; j<ListOfNumbers.size(); j++)
          {
            if(ListOfNumbers.get(j) < ListOfNumbers.get(i))
            {
              CurrentMinimum = j;
            }
            if (CurrentMinimum != i)
            {
              int temp;
              temp = i;
              i = CurrentMinimum;
              CurrentMinimum = temp;
              System.out.println(ListOfNumbers);
            }
          }
        }

A: You can use the set method in List Interface to swap the values.
set(int index, E element)

Basically do the following:
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);

A: Permute index a with index b in array list al :

*

*temp = al.remove(a)

*al.add(a, al.remove(b)) ////// updated

*al.add(b,temp)

Hope it will help.
EDIT1 : more precisely :
You have got a problem in your sort algorithm :
/* find the next minimum */
for(int j=i+1; j<ListOfNumbers.size(); j++)
{
    if(ListOfNumbers.get(j) < ListOfNumbers.get(CurrentMinimum)) // <<<<<
    {
         CurrentMinimum = j;
    }
}

/* then, if necessary, permute */
temp = ListOfNumbers.remove(i);
ListOfNumbers.add(i, ListOfNumbers.remove(CurrentMinimum-1)); // -1 because of previous remove
ListOfNumbers.add(CurrentMinimum,temp);

A: you can  use
 List<Integer> ListOfNumbers = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Collections.swap(ListOfNumbers, 0, 3);


text:
Q: pyqt gui as an object of a main class rather than the main class itself. How do I connect callback to a method in the main class? basically I have three classes:

*

*MainClass

*GUI

*Foo

In this simple example MainClass should just execute some code in the class Foo whenever the button of the class GUI is pressed.
I know that a simple solution to this would be that you could use the GUI class itself as the main class and have the buttons callback function in the same class.
But I have so many functions, I want to seperate the GUI stuff and the code which should be executed when a GUI event occurs.
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
import sys

class MainClass:
    def __init__(self) -> None:
        self.foo = Foo()

        app = QApplication(sys.argv)
        MainWindow = QMainWindow()
        ui = GUI()
        ui.setupUi(MainWindow)
        MainWindow.show()
        app.exec()

    def process_from_gui(self):
        #execute this when the button is clicked
        self.foo.bar()

class Foo:
    def bar(self):
        #do some stuff

class GUI():
    def setupUi(self, MainWindow):
        self.centralwidget = QWidget(MainWindow)
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.clicked.connect(self.button_callback)
        self.pushButton.setText("test button")

    def button_callback(self):
        pass
        #call method in MainClass

m = MainClass()

I hope I made myself clear and thanks in advance for your answers!

A: If i understand you correctly you could do something like that
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
import sys

class MainClass:
    def __init__(self) -> None:
        self.foo = Foo()

        app = QApplication(sys.argv)
        MainWindow = QMainWindow()
        ui = GUI()
        ui.setupUi(MainWindow,self)
        MainWindow.show()
        app.exec()

    def process_from_gui(self):
        # execute this when the button is clicked
        self.foo.bar()

class Foo:
    def bar(self):
        print("something")

# do some stuff

class GUI():
    def setupUi(self, MainWindow,MainClass):
        self.MainWindow = MainClass
        self.centralwidget = QWidget(MainWindow)
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.clicked.connect(self.button_callback)
        self.pushButton.setText("test button")

    def button_callback(self, MainWindow):
        self.MainWindow.process_from_gui()  # your method in MainClass

if __name__=="__main__":
    m = MainClass()


text:
Q: Spinner NullPointerException my problem is that my method visListe() will not work when add it to Spinner... it works when i add it to onCreate, but when added it to spinner it gave me error :
LOGCAT
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: no.hit.kvisli.heiverden, PID: 30934
java.lang.NullPointerException
        at no.hit.kvisli.heiverden.MainActivity$1.onClick(MainActivity.java:69)
        at android.view.View.performClick(View.java:4633)
        at android.view.View$PerformClick.run(View.java:19330)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)

CODE
public class MainActivity extends ActionBarActivity
implements BasicDialogFragment.OnNameEnteredListener {
public static final String P1 = "melding";

private EditText input = null;
private Button listeKnapp = null;
private TextView visTekst = null;
double l;
double t;
double r;
double LB;
double AB;
int antTerminer;
Spinner spinner1;
private static final String[] VERDIER =
                          {"Serielån", "Annuitetslån"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //input        = (EditText) findViewById(R.id.skrivTekst);
    listeKnapp   = (Button) findViewById(R.id.liste_button);
    final EditText laan = (EditText)findViewById(R.id.laanInput);
    final EditText aar = (EditText)findViewById(R.id.aarInput);
    final EditText termin = (EditText)findViewById(R.id.terminInput);
    final EditText rente = (EditText)findViewById(R.id.renteInput);
    final Spinner valgSpinner = (Spinner) findViewById(R.id.spinner1);

    LB = Double.parseDouble(laan.getText().toString());
    l = Double.parseDouble(aar.getText().toString());
    t = Double.parseDouble(termin.getText().toString());
    r = Double.parseDouble(rente.getText().toString());

    AB = LB / (l*t) ;
    double RB = r/t;
    antTerminer = (int) (t*l);

    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, VERDIER
    );
    valgSpinner.setAdapter(spinnerAdapter);

    listeKnapp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(spinner1.getSelectedItem().toString().equals("Serielån")){
            visListe();
            }
            if(spinner1.getSelectedItem().toString().equals("Annuitetslån")){

            }
        }
    });

}

private String[] getListe(){
    String[] listeTabell = new String[antTerminer];
    for(int rad=0;rad<listeTabell.length;rad++) {
        double RB = Math.round(LB * (r / t) / 100);
        LB -= (int) AB;

        listeTabell[rad] = " Dette er termin nr : " + (rad + 1)  +
                            " Terminbeløp: " + ((int)(AB+RB)) +
                            " Avdrag: " + (int)AB +
                            " Rente: " + RB +
                            " Restgjeld: " + LB;

    }
    return listeTabell;
}
private void visListe() {
    Intent i = new Intent(MainActivity.this, ListeDemo.class);
    Bundle b = new Bundle();
    b.putStringArray("no.hit.jon.liste", getListe());
    i.putExtra("no.hit.jon.listeBundle", b);
    startActivityForResult(i, 0);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode==0 && resultCode== Activity.RESULT_OK) {
        String valgtTekst = data.getStringExtra("ValgtText");
        int pos = data.getIntExtra("ValgtPosisjon", -1);
        visTekst.setText("Du valgte linje " + pos + " : " + valgtTekst);
    }
}

private void startDialog() {
    BasicDialogFragment bdf = new BasicDialogFragment();
    bdf.show(getFragmentManager(), "basic");

}

public void OnFragmentInteractionListener(String nameEntered){
    visMinTekst();
}

private void visMinTekst() {
    visTekst.setText(input.getText());
    Toast melding = Toast.makeText(getApplicationContext(),
            input.getText(), Toast.LENGTH_SHORT);
    melding.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

My code worked perfectly before spinner and i have used spinner by this way before without any problems, so im confused and not sure where to look for the problem.
PS. i want spinner to run my method visListe() to be more specific :)

A: where you findViewById for spinner1 ?
you should change it by this valgSpinner I think.
if(valgSpinner.getSelectedItem().toString().equals("Serielån")){
        visListe();
}
if(valgSpinner.getSelectedItem().toString().equals("Annuitetslån")){

}

A: You declare spinner1 here
Spinner spinner1;

but I never see you initialize it anywhere. You do, however, initialize another Spinner here
final Spinner valgSpinner = (Spinner) findViewById(R.id.spinner1);

so you get a NPE in onClick() when you try to access spinner1. It looks like you have your variable names mixed up. Change it to
 listeKnapp.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(valgSpinner .getSelectedItem().toString().equals("Serielån")){
        visListe();
        }
        if(valgSpinner .getSelectedItem().toString().equals("Annuitetslån")){

        }
    }
});

to use the variable you initialize and get rid of the useless variable spinner1.

A: I am guessing the Issue is not the Spinner but rather the Array in Line 69 (as it sais), which gets "antTerminer" entries.


text:
Q: Extending Classes in Javascript
Possible Duplicate:
How do I create an abstract base class in JavaScript?

Is it possible to use OOP practices in javascript and create classes and extend abstract classes?

A:
Is it possible to use OOP practices in javascript

Yes.

and create classes

No, JavaScript doesn't have classes. It is pretty easy to implement them, though, if your design needs them. However, in most cases, if you need classes in JavaScript, you're probably doing something wrong and should rethink your design (or your choice of language, but that is part of the design).

and extend abstract classes?

Since there are no classes: no. But again, you can build them yourself, if you need them. And also again, if you find you need them, you are probably doing something wrong.
By the way: what do classes have to do with OOP practices? Hint: it's OOP, not COP!

A:
Is it possible to use OOP practices in javascript

In JavaScript you can inherit from objects.
var Base = {
  ...
};

var Extension = Object.create(Base, {
  ...
});

create classes

There is no notion of class. There is only a notion of prototypical inheritance and a prototype relationship.

extend abstract classes?

Depends, define abstract
Article about ES5 OO


text:
Q: how to make the in-line math equation as shown in the figure beautifully arranged in text?
When discussing and explaining some math equations,  I sometimes prefer to use in-line equations (created by use $ ... $ in the text) in the text environment, as shown ONLY in the last two lines.
However, you have seen that the long in-line equation
$f(x_i,\eta_i,m)=|x_i|+\log(\frac{2}{\eta_i})(\frac{|x_i|}{3mp_i}+|x_i|\sqrt{(\frac{1}{3mp_i})^2+\frac{2}{\log(2/\eta_i)}(\frac{1}{mp_i}-\frac{1}{m})})$

is ugly arranged in text, with very big space. Do you have any method to  let this in-line equation (automatically) have a norm space between each term, and at the same time, the extra part of this long equation can (automatically) start from the next line? Thanks in advance.

A: Not using inline math here would be the normal advice!
Or set the sentence in a \raggedright (or \begin{flushleft}) as that is what you want it to do: allow lines to be short without stretching them to fit.


text:
Q: PowerShell processing of large CSV very slow - Is there a better way? Using Powershell and am working through a foreach loop. One of the steps inside the loop is to find a match in a csv file -
import-csv ".\RateCard.csv" | where-object{$($Item.'From Number') -match "^\+?($($_.Destination))\w*$"}

The foreach loop is processing around 100,000 records for a month time period and completes within a few minutes without the csv lookup. After adding the csv lookup I can see its taking about 5-10 seconds for each lookup. The csv file has 40,000 rows and about 10 columns.
While I understand that client side processing is going to be slower, and that I should probably look at using SQL, I wondered if there is a faster way to do this. I thought of using a stream reader but couldn't work out how I could do a match lookup.
Any suggestions would be greatly appreciated.

A: As mjolinor suggested, move your Import-CSV outside the ForEach loop:
$RateCard = importcsv ".\ratecard.csv"
ForEach($Item in $Items){
    if($RateCard.Destination -contains $Item.'From Number'){
        Do Stuff
    }
}

I just added a If/Then function to check if your Item's From Number is found in the CSV's Destination field.