text:
Q: PhoneGap app did build; now errors For some reason my PG app has stopped building. Literally nothing has changed - I simply tried to rebuild it. It used to work; now it doesn't.
The error is:

What went wrong: Execution failed for task ':processDebugResources'.
com.android.ide.common.process.ProcessException: Failed to execute
  aapt

Here's the relevant part of the log output:

FAILED
BUILD FAILED
Total time: 0.985 secs
FAILURE: Build failed with an exception.

*

*What went wrong: Execution failed for task ':processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

Try: Run with --stacktrace option to get the stack trace. Run with
  --info or --debug option to get more log output. Error: /project/gradlew: Command failed with exit code 1 Error output: Note:
  Some input files use or override a deprecated API. Note: Recompile
  with -Xlint:deprecation for details.
  /project/build/intermediates/manifests/full/debug/AndroidManifest.xml:25:23-35:
  AAPT: No resource found that matches the given name (at 'icon' with
  value '@mipmap/icon').
       /project/build/intermediates/manifests/full/debug/AndroidManifest.xml:22:
  error: Error: No resource found that matches the given name (at 'icon'
  with value '@mipmap/icon').
FAILURE: Build failed with an exception.
What went wrong: Execution failed for task ':processDebugResources'.
  com.android.ide.common.process.ProcessException: Failed to execute
  aapt
Try: Run with --stacktrace option to get the stack trace. Run with
  --info or --debug option to get more log output.
      at ChildProcess.whenDone (/project/cordova/node_modules/cordova-common/src/superspawn.js:169:23)
      at emitTwo (events.js:106:13)
      at ChildProcess.emit (events.js:191:7)
      at maybeClose (internal/child_process.js:877:16)
      at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)

I've read other posts and tried some things suggested, but so far nothing is halping. This post advised adding a line to the assemblyinfo.cs files, but I'm getting the same result.
I have no idea what most of the log output above means. Can anyone see what's going wrong!?


text:
Q: $_POST method showing undefine variable How to solve this i don't add data using by $_Post Method, but without $_POST method showing undefine variable?
if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){

        //Getting values
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $age = $_POST['age'];

        //Creating an sql query
        $sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";

        //Importing our db connection script
        require_once('connect.php');

        //Executing query to database
        if(mysqli_query($con,$sql)){
            echo 'Employee Added Successfully';
        }else{
            echo 'Could Not Add Employee';
        }

        //Closing the database
        mysqli_close($con);
    }

A: You need to define your variables to something if $_POST is not set.
So code would look something like this:
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] ? "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$age = isset($_POST['age']) ? $_POST['age'] : "";
//if isset $_POST['age'] then assign it to $_POST['age'] else assign it to ""

if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){

        //Creating an sql query
        $sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";

        //Importing our db connection script
        require_once('connect.php');

        //Executing query to database
        if(mysqli_query($con,$sql)){
            echo 'Employee Added Successfully';
        }else{
            echo 'Could Not Add Employee';
        }

        //Closing the database
        mysqli_close($con);
    }

Bonus:
You code can be easily injected. Use prepared statements to avoid this.
$sql = "INSERT INTO info (firstname,lastname,age) VALUES (?,?,?)"; // question marks are placeholders to bind values to
$stmt = $con->prepare($sql); // prepare query
$stmt->bind_param("sss", $firstname, $lastname, $age); // bind values to your query
if($stmt->execute()){ // if success
    echo 'Employee Added Successfully';
}else{
    echo 'Could Not Add Employee';
}

You can learn more about it here

A: Try changing this one:
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";

To this one:
$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('".$firstname."','".$lastname."','."$age."')";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java-JDBC-MySQL Error I'm trying to get my java program to talk to a MySQL DB.
So i did some reading and downloaded MySQL Connector/J. I've extracted it into my home  directory ~. Here are the contents.
user@hamster:~$ ls
LoadDriver.class  LoadDriver.java  mysql-connector-java-5.1.18-bin.jar

The contents of LoadDriver.java are
user@hamster:~$ cat LoadDriver.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!

public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

The contents are the same from http://dev.mysql.com/doc/refman/5.1/en/connector-j-usagenotes-basic.html#connector-j-usagenotes-connect-drivermanager with the only change that the Exception is being printed to console in the catch block.
I compile it as follows
leonard@hamster:~$ javac LoadDriver.java

When I try to execute it, the following is the ouput.
leonard@hamster:~$ java LoadDriver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

This output is consistent with the executing command, but when trying to run it with the prescribed CLASSPATH method I run into the following issue.
leonard@hamster:~$ java -cp /home/leonard/mysql-connector-java-5.1.18-bin.jar LoadDriver
Exception in thread "main" java.lang.NoClassDefFoundError: LoadDriver
Caused by: java.lang.ClassNotFoundException: LoadDriver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: LoadDriver. Program will exit.

Am I missing something? How do I get MySQL's own code samples running.

A: You need to have both the jar, and the current directory, on the classpath.
java -cp .:/home/leonard/mysql-connector-java-5.1.18-bin.jar LoadDriver


text:
Q: When i perform poptorootview controller the first view controllers textfield being blank When i perform poptorootview controller the first view controllers textfield should be blank
so i have to create that some value that not be blank like username textfield must be shown saved username


text:
Q: Why does shinyapps fail to deploy when it requires edgeR or limma Bioconductor packages? I am having trouble deploying an app which requires edgeR and limma packages, via shinyapps.io. The app is running locally without any problem and I can deploy any other app which doesn't require limma and edgeR. However, I am receiving the following error during deployment of the app using edgeR:
An error has occurred
The application failed to start.

Attaching package: 'DT'
The following objects are masked from 'package:shiny':

dataTableOutput, renderDataTable

Loading required package: edgeR
Warning in library(package, lib.loc = lib.loc,
character.only = TRUE, logical.return = TRUE,  :
there is no package called 'edgeR'

Error in value[[3L]](cond) : unable to find required package 'edgeR'
Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted"

> devtools::session_info()
Session info -----------------------------
setting  value
version  R version 3.3.0 (2016-05-03)
system   x86_64, mingw32
ui       RStudio (0.99.879)
language (EN)
collate  English_Australia.1252
tz       Australia/Sydney
date     2016-05-15

Packages -----------------------------

package       * version  date       source
BiocInstaller   1.22.2   2016-05-12 Bioconductor
bitops          1.0-6    2013-08-17 CRAN (R 3.3.0)
curl            0.9.7    2016-04-10 CRAN (R 3.3.0)
devtools        1.11.1   2016-04-21 CRAN (R 3.3.0)
digest          0.6.9    2016-01-08 CRAN (R 3.3.0)
git2r           0.14.0   2016-03-13 CRAN (R 3.3.0)
htmltools       0.3.5    2016-03-21 CRAN (R 3.3.0)
httpuv          1.3.3    2015-08-04 CRAN (R 3.3.0)
httr            1.1.0    2016-01-28 CRAN (R 3.3.0)
memoise         1.0.0    2016-01-29 CRAN (R 3.3.0)
mime            0.4      2015-09-03 CRAN (R 3.3.0)
packrat         0.4.7-1  2016-03-28 CRAN (R 3.3.0)
R6              2.1.2    2016-01-26 CRAN (R 3.3.0)
Rcpp            0.12.4   2016-03-26 CRAN (R 3.3.0)
RCurl           1.95-4.8 2016-03-01 CRAN (R 3.3.0)
RJSONIO         1.3-0    2014-07-28 CRAN (R 3.3.0)
rsconnect       0.4.1.11 2016-05-15 Github (rstudio/rsconnect@2419667)
rstudioapi      0.5      2016-01-24 CRAN (R 3.3.0)
shiny         * 0.13.2   2016-03-28 CRAN (R 3.3.0)
shinyapps     * 0.4.1.8  2016-05-15 Github (rstudio/shinyapps@4dd3a9d)
withr           1.0.1    2016-02-04 CRAN (R 3.3.0)
xtable          1.8-2    2016-02-05 CRAN (R 3.3.0)

appDependencies() also does not display edgeR package as you can see from below:
> appDependencies()
package version source
1           DT     0.1   CRAN
2           R6   2.1.2   CRAN
3         Rcpp  0.12.4   CRAN
4       digest   0.6.9   CRAN
5    htmltools   0.3.5   CRAN
6  htmlwidgets     0.6   CRAN
7       httpuv   1.3.3   CRAN
8     jsonlite  0.9.20   CRAN
9     magrittr     1.5   CRAN
10        mime     0.4   CRAN
11     packrat 0.4.7-1   CRAN
12       shiny  0.13.2   CRAN
13      xtable   1.8-2   CRAN
14        yaml  2.1.13   CRAN

But as far as I've read from other forums, this is not necessarily the cause of the problem.
I reckon I am having the same issue as in this post.
I'd appreciate if someone can help with this issue.
P.S. limma package also generates the same problem.


text:
Q: Showing both Windows installations in grub (single Windows EFI partition) I hope this is the right place to ask this question!
I have a machine in which I have three OSs installed: two Windows 10 and Ubuntu.
The two windows 10 systems have been installed on the same drive, share the same EFI partition, and appear as a single entry in my grub. When I select that entry, I get to the Windows boot menu, in which I have to choose if I want to boot one or the other version.
My grub menu looks like this (picture taken from the internet)

My windows boot menu looks like this, only with Windows1 and Windows2 as options instead (picture taken from the internet)

If I select version  1 I get directly to the desktop without issues, but if I select version 2 the machine reboots and I have to go through the grub menu all over again. When I was using version 1 more often this wouldn't be a problem, but lately I am using version 2 a lot more: I now need to make sure I'm switching to windows in the grub twice and select version 2 in the windows boot menu, which is quite cumbersome.
Now, since there's a single Windows EFI partition, I can't seem to make both installations visible in the grub, and would like to know if there's some way of fixing my problem! The output for the windows entry in the grub is the following:
insmod part_gpt
insmod fat
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root  5A8C-8F53
else
  search --no-floppy --fs-uuid --set=root 5A8C-8F53
fi
chainloader /EFI/Microsoft/Boot/bootmgfw.efi

I know that Windows does something like setting a parameter or similar in order to get to windows version 2, as I need to choose the grub entry twice but on the second boot it skips the windows boot menu.
This is my GParted view of the Windows drive:

I hope I was clear, happy to add more details if needed!


text:
Q: Validation POST request by OAuth1.0a in Django I'm using Django 3.0.7 and i need to validate the incoming POST request from my partner server by HMAC-SHA1 or OAuth1.0a and if it validated send response {"OK":"200"}.
My views.py looks like this:
def api_create_blog_view(request):

    blog_post = BlogPost(author=request.user)

    if request.method == 'POST':
        serializer = BlogPostSerializer(blog_post, data=request.data)
        data = {}
        if serializer.is_valid():
            serializer.save()
            return Response({"response_code":"OK"})
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

There are a lot of topics how to do it, but i can't get how to do it in my case.

A: I answered your other question, I think this is what you really want. You want to create an OAuth 1.0 provider, but you don't need to issue client id and secrets.
Here is the documentation on create an OAuth 1.0 provider: https://docs.authlib.org/en/latest/django/1/index.html


text:
Q: Python - get column iterator from a file (without reading the whole file) My main goal is to calculate median(by columns) from a HUGE matrix of floats. Example:
a = numpy.array(([1,1,3,2,7],[4,5,8,2,3],[1,6,9,3,2]))

numpy.median(a, axis=0)

Out[38]: array([ 1.,  5.,  8.,  2.,  3.])

The matrix is too big to fit in the Python memory (~5 terabytes), so I keep it in a csv file.
So I want to run over each column and calculate median.
Is there any way for me to get column iterator without reading the whole file?
Any other ideas about calculating the median for the matrix would be good too. Thank you!

A: If you can fit each column into memory (which you seem to imply you can), then this should work:
import itertools
import csv

def columns(file_name):
   with open(file_name) as file:
       data = csv.reader(file)
       columns = len(next(data))
   for column in range(columns):
       with open(file_name) as file:
           data = csv.reader(file)
           yield [row[column] for row in data]

This works by finding out how many columns we have, then looping over the file, taking the current column's item out of each row. This means, at most, we are using the size of a column plus the size of a row of memory at one time. It's a pretty simple generator. Note we have to keep reopening the file, as we exhaust the iterator when we loop through it.

A: I would do this by initializing N empty files, one for each column.  Then read the matrix one row at a time and send each column entry to the correct file.  Once you've processed the whole matrix, go back and calculate the median of each file sequentially.
This basically uses the filesystem to do a matrix transpose.  Once transposed, calculating the median of each row is easy.

A: There's probably no direct way to do what you're asking with a csv file (unless I've misunderstood you). The problem is that there's no meaningful sense in which any file has "columns" unless the file is specially designed to have fixed width rows. CSV files aren't generally designed that way. On disk, they're nothing more than a giant string:
>>> import csv
>>> with open('foo.csv', 'wb') as f:
...     writer = csv.writer(f)
...     for i in range(0, 100, 10):
...         writer.writerow(range(i, i + 10))
...
>>> with open('foo.csv', 'r') as f:
...     f.read()
...
'0,1,2,3,4,5,6,7,8,9\r\n10,11,12,13,14,15,16,17,18,19\r\n20..(output truncated)..

As you can see, the column fields don't line up predictably; the second column starts at index 2, but then in the next row, the width of columns increases by one, throwing off the alignment. This is even worse when input lengths vary. The upshot is that the csv reader will have to read the entire file, throwing out the data you don't use. (If you don't mind that, then that's the answer -- read the whole file line by line, throwing out the data you won't use.)
If you don't mind wasting some space and know that none of your data will be longer than some fixed width, you could create a file with fixed-width fields, and then you could seek through it using offsets. But then, once you're doing that, you might as well start using a real database. PyTables seems to be the favorite choice of many for storing numpy arrays.

A: You can use bucketsort to sort each of the columns on disk without reading them all into memory. Then you can simply pick the middle value.
Or you can use the UNIX awk and sort commands to split and then sort your columns before you select the median.


text:
Q: IIS 7.5/ASP.NET MVC App - error serving JS Greetings,
I'm new to working w/ IIS in general, so I hope I'm asking the right question in the right place with the right amount of information. Here goes:
On a Windows 7 64-bit (IIS 7.5) box, I have a ASP.NET MVC application. It works fine on another dev's box that is very similar in configuration. It's setup to use the "Classic .NET App Pool" which in turn is setup to "Enable 32-bit Applications" This is a requirement as we communicate w/ some legacy 32 bit ActiveX controls.
I added the MVC wild card mappings and verified it was set to the .NET v2.xxx 32bit aspnet_isapi.dll.  (The one in Framework, not Framework64).
If I set a breakpoint in the global.asax.cs, I get my breakpoint when running/debugging, but the app is refusing to serve any .js files. When using FireFox w/ Firebug, the Net tab shows 404 Not Found for every requested .js file. All .css are served correctly.
This causes the application to fail, of course. With the exception of the properties set above, IIS is setup "out of the box"
Any ideas/things to try?
Thanks in advance!

A: Turns out to be a case noob-ness and frustration...
The web.config had and environment setting that was incorrectly set on my machine but never used to point to the JS files. Another dev implemented it and I didn't notice.
Lesson learned (again) is to take a break and approach w/ a fresh mind.
Thanks to all who read this.


text:
Q: A Select All (filetered/unfiltered) rows button in Jquery Datatables plugin How do I create a select all checkbox in the jquery datatable plugin I am using in my application. Is there a plugin for this feature in the datatbles. I am not able to find any such thing in my search.
$("#button_select_all").click(function () {

                $(allSamplesTable.fnGetFilteredNodes()).find(':checkbox').each(function () {
                    $this = $(this);
                    $this.attr('checked', 'checked');

                   for (var i = 0; i < _sampleTableExports.length; i++) {
                        if (_sampleTableExports[i]["Id"] == $(this).val()) {
                            _sampleTableExports.splice(i, 1);
                            return true;
                        }
                   }
                   _sampleTableExports.push({ "Name": $(this).attr("name"), "Id": $(this).val() });
                });

            });


text:
Q: Tkinter - Scrollbar does not resize when number of labels inside a frame changes I am trying to create a GUI where left hand side is a Listbox (contained inside a frame f2) that displays employee ID's and right side is another frame second_frame (contained inside canvas and outer frame f3) that shows transaction details of each selected employee in the form of labels.
Each employee can have multiple transactions. So, The number of labels had to be dynamic, i.e. for first selected item in listbox, there could be two labels and for second selected item in listbox, it could be hundred. For every selection, I am calling two functions to destroy old labels and create new labels. While the code works fine, I am having trouble resizing the scrollbar according to the selected listbox entry. I am new to Tkinter, Please advise. Below is my code.
Also note, the test() function when called from outside any function displays the scroll bar, but does not display anything when called from within any function.
# -*- coding: utf-8 -*-
from tkinter import *

'''def test():
    for i in range(0,50):
        for j in range (0,7):
            Label(second_frame, text=f'{i}{j}', width=20).grid(row=i, column=j, pady=5,padx=5)
'''
# --- function ---
def destroy_frame():
    #f1.grid_forget()
    print("destroying frame")
    for label in second_frame.winfo_children():
        label.destroy()

def create_frame(val):
    print("creating new frame")
    for i in range(0,val):
        for j in range (5):
            Label(second_frame, text=f'{i} {j} ', relief=GROOVE, width=10).grid(row=i, column=j, pady=5,padx=5)

def on_selection(event):
    # here you can get selected element
    print('previous:', listbox.get('active'))
    print(' current:', listbox.get(listbox.curselection()))

    # or using `event`
    print('(event) previous:', event.widget.get('active'))
    print('(event)  current:', event.widget.get(event.widget.curselection()))

    print (listbox.get(listbox.curselection()))

    if (listbox.get(listbox.curselection()) == "Eid 1"):
        destroy_frame()
        create_frame(100)

    elif (listbox.get(listbox.curselection()) == "Eid 2"):
        destroy_frame()
        create_frame(200)

    print('---')

root = Tk()
root.geometry('800x500')

#Create base Frames
f1 = Frame(width=800, height=50, bg="yellow", colormap="new")
f1.grid(row=0, columnspan=2)
f1.grid_propagate(False)

f2 = Frame(width=200, height=425, bg="light blue", colormap="new")
f2.grid(row=1, column=0)
f2.grid_propagate(False)

f3 = Frame(width=600, height=425, bg="light green", colormap="new")
f3.grid(row=1, column=1)
f3.grid_propagate(False)

#Create header Label
l1_f1 = Label(f1, text="Employee Purchase Entries:", bg="yellow")
l1_f1.grid(row=0, column=0)

#Create Listbox
listbox = Listbox(f2, bg="light blue", width=40, height=400)
listbox.grid(row=0, column=0)

#Add Scrollbar to ListBox
list_scrollbar = Scrollbar(f2)
list_scrollbar.grid(row=0, column=1, sticky=NSEW)

#Enter Listbox Data
listbox.insert(1, 'Eid 1')
listbox.insert(2, 'Eid 2')

listbox.bind('<<ListboxSelect>>', on_selection)

#configure the Listbox and Scrollbar
listbox.config(yscrollcommand  = list_scrollbar.set)
list_scrollbar.config(command = listbox.yview)

#Create a Canvas
my_canvas = Canvas(f3, width=580, height=425, bg="light green")
#my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
my_canvas.grid(row=0, column=0)

#Add a Scrollbar to the canvas
my_scrollbar = Scrollbar(f3, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.grid(row=0, column=1, sticky=NSEW)

#configure the canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e : my_canvas.configure(scrollregion = my_canvas.bbox("all")))

#Create another frame inside the canvas
second_frame = Frame(my_canvas)

#Add the new frame to a window in the canvas
my_canvas.create_window((0,0), window=second_frame, anchor="nw")

#test()

root.mainloop()

A: Your canvas isnt trigger the configure event when you add widgets to your frame. Instead your frame is been triggerd.
So you need to put this line:
second_frame.bind('<Configure>', lambda e : my_canvas.configure(scrollregion = my_canvas.bbox("all")))

after creating second_frame


text:
Q: How to add show/hide action in rails forms only in the view template I'm new to rails and using to devise for authentication, what i want to accomplish is user privacy.
Meaning in edit form i want to add a toggle switch action for example 'Email field' to give the user the ability to show/hide fields in his profile but the form still displayed in the edit view.
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  <%= f.error_notification %>

Settings

            <%= link_to 'Personal information', "/users/edit", class: "nav-link text-dark font-weight-bold" %>
            <%= link_to 'Account settings', "/account/settings", class: "nav-link text-dark font-weight-bold" %>
            <%= link_to 'Password settings', "/account/passwords", class: "nav-link text-dark font-weight-bold" %>
            <%= link_to 'Security', "/account/security", class: "nav-link text-dark font-weight-bold" %>

              First name:

              <%= f.input :first_name, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "First name"} %>

              Last name:

              <%= f.input :last_name, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Last name"} %>

          Biography

              About:

              <%= f.input :about, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Write in few lines something about yourself and what you are passionate about"} %>

          Career

              Company:

              <%= f.input :company, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Where do you work?"} %>

              Job title:

              <%= f.input :job_title, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Current working position?"} %>

              School / University:

              <%= f.input :school, label: false, input_html: { class: "form-control w-100 border-top-0 border-right-0 border-left-0 rounded-0", placeholder: "Name of school or university"} %>

              <%= f.button :submit, "Update", class: "btn btn-primary btn-sm btn-block" %>

<% end %>

i made a custom devise registration controller
app/controllers/registations_controller.rb

class RegistrationsController < Devise::RegistrationsController

  def update
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)

    resource_updated = update_resource(resource, account_update_params)
    yield resource if block_given?
    if resource_updated
      set_flash_message_for_update(resource, prev_unconfirmed_email)
      bypass_sign_in resource, scope: resource_name if sign_in_after_change_password?
      respond_with resource, location: after_update_path_for(resource)
    else
      clean_up_passwords resource
      set_minimum_password_length
      session[:return_to] ||= request.referer
      redirect_to session.delete(:return_to), alert: resource.errors.full_messages[0]

    end
  end

  def settings
      @user = current_user
      if @user
          render :settings
      else
          render file: 'public/404', status: 404, formats: [:html]
       end
  end

  def passwords
    @user = current_user
    if @user
      render :passwords
    else
      render file: 'public/404', status: 404, formats: [:html]
    end
  end

  def security
    @user = current_user
    if @user
      render :security
    else
      render file: 'public/404', status: 404, formats: [:html]
    end
  end
end

app/controllers/users_controller.rb

class UsersController < ApplicationController
  before_action :authenticate_user!
  def show
    @user = current_user
  end
end

routes.rb

Rails.application.routes.draw do
  get 'users/show'
  root 'pages#home'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html

  devise_for :users, controllers: { registrations: "registrations" }
  resources :user, only: [:show]
  devise_scope :user do
    get 'accounts/settings', to: 'registrations#settings', as: :settings
    get 'accounts/passwords', to: 'registrations#passwords', as: :passwords
    get 'accounts/security', to: 'registrations#security', as: :security
  end
end

A: You'll want to do 3 things:

*

*Add a button with an onclick handler that allows the user to click on it to hide/show the field

*Add an ID to the div you are using to show the attribute

*Create a javascript function to show/hide that div

So add the button outside the div you are hiding and include the onclick
<%= button_tag "Hide/Show", :onclick => "hideInput()" %>

Then add the ID to the div you are hiding. In your case, do something like this. You can use any ID you want. Mine is just an example.

 <%= @user.email %>

Then you want to add the hideInput function in your javascript file. Preferably in assets/javascripts/[file_name]
function hideInput() {
  var emailDiv = document.getElementById("emailDisplayed");
  emailDiv.style.display === "block" ?  emailDiv.style.display = 'none' : emailDiv.style.display = 'block';
}

Now when the user clicks on the button, it will hide/show your div that contains the user email.


text:
Q: How to read line of code that includes numpy? Sorry for the weird question, but I am reviewing the code and can not understand the meaning of the line of code.
I have a NumPy array with (23345,23345,4) dimensions and let's call it X.
What does this line mean:
I2[I2>10000] = 10000

A: This means replace elements in the array that are larger than 10k by just 10k.


text:
Q: Input stopping threads from running I want to run a program that can ask for input and run threads at the same time.
For example:
import threading

def get_input():
  while True:
    var = input('prompt> ')
    do_stuff

#main loop
while True:
  input_thread = threading.Thread(target=get_input)
  input_thread.start()
  do_stuff_that_doesn't_work

So the problem above would be that it asks for input(prompt>) and while it's asking for input, do_stuff_that_doesn't_work won't work.
I've seen people get by this before but I don't know how to do it.

A: You shouldn't be creating a thread inside your while loop.  Try this code...
import threading
import time

run = True
def get_input():
    global run
    while run:
        var = input('prompt> ') #python 3 only
        print('Input was ', var)
        if 'q' == var:
            run = False

input_thread = threading.Thread(target=get_input)
input_thread.start()

print('Type q to exit')
ctr = 0
while run:
    ctr += 1
    time.sleep(0.1)
print('Exiting with ctr: ', ctr)


text:
Q: Checking the resource parameter in a C# method I guess this would look a bit stupid, but I'm trying to find an easy way of doing this.
I have a bunch of SQL scripts in different files, which I have added as text file resources in my .net project. I pass each of these resource strings to an ExecuteScript method which gets the script executed in the database, with the help of a predefined connection string. It goes like this:
ExecuteScript(Resources.Script1);
ExecuteScript(Resources.Script2);
ExecuteScript(Resources.Script3);

private void ExecuteScript(string script)
{
    connectionString = // Get connection string from config file
    // Rest of the code to execute the script.
}

Now the problem arises when I would want to use different connection strings for different scripts. For example: I would like to use a connectionString1 for executing Resources.Script1, connectionString2 for Resources.Script2.
How do I do this in my ExecuteScript method itself? Is there a way to find the resource's name after it enters the method? Or should I define separate connection strings explicitly?

A: You could use a more complex type as parameter.
ExecuteScript(Resources.Script1);
ExecuteScript(Resources.Script2);
ExecuteScript(Resources.Script3);

private void ExecuteScript(ScriptContext scriptContrxt)
{
    connectionString = // Get connection string from config file
    // Rest of the code to execute the script.
}

Define a new class ScriptContext with two properties like this:
public class ScriptContext
{
     // may be create a constructor and make the setter private.
     public string script { get; set; }
     public ConnectionString ConnectionString { get; set; }
}

Than you can use for every script another connection string.

A: You can't achieve this unless the name of the resource or the connectionString is contained within the script.
I would go for something like this:
ExecuteScript(Resources.Script1, Resources.ConnectionString1);

Or, as alternative:
private void ExecuteScript(int index)
{
    var connectionString = Resources.ResourceManager.GetString(string.Format("ConnectionString{0}",index));
    var script = Resources.ResourceManager.GetString(string.Format("Script{0}",index));
// Rest of the code to execute the script.
}


text:
Q: Speed up Geotools Vector Grid processing I am using Geotools Vector Grid on a FeatureSource (shapefile) that been projected to "AUTO:42001". Units for the map are then in one meter increments. When the FeatureSource is a large country (like India) and the grid size is set to 10km it can take around 10 minutes to generate a grid covering the country. If I set the grid size smaller the generation time can be even larger (I tried a 1km grid and it did not complete when I left it running overnight).
Is this length of time typical for the Vector Grid, or am I doing something wrong?
Is there any way to speed up the generation of the grid?
My source data is the "ne_50m_admin_0_countries.shp" file from https://www.naturalearthdata.com/downloads/50m-cultural-vectors/50m-admin-0-countries-2/
I read the file in and select the country I want using a Query, convert to the local project and the run the GridBuilder.
File file = new File("./ne_50m_admin_0_countries.shp");
FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource worldMapSource = dataStore.getFeatureSource();

// Select India
Filter filter = CQL.toFilter("NAME = 'India'");
Query queryIndia = new Query(worldMapSource.getSchema().getTypeName(), filter);

FeatureCollection<SimpleFeatureType, SimpleFeature> collectionIndia = worldMapSource.getFeatures(queryIndia);
SimpleFeatureSource indiaSource = DataUtilities.source(collectionIndia);

// Project india map to local projection
SimpleFeatureSource india_LOCAL = GeoProjectionHelper.convertToLocalProjection(indiaSource);

// Set the grid size (WGS84 1.0 = 1 degree ; AUTO Local 1.0 = 1 meter) and create a bounding envelope
// that is neatly aligned with the grid size
double squareWidth = 10000.0; // 10km  (10km ~ 10min to generate)
SimpleFeatureSource indiaGrid_LOCAL = GridBuilder.getIntersectingGrid(india_LOCAL, squareWidth);

public class GridBuilder {

   public static SimpleFeatureSource getIntersectingGrid(SimpleFeatureSource featureSource, double squareWidth) throws IOException {
    ReferencedEnvelope gridBounds = Envelopes.expandToInclude( featureSource.getBounds(), squareWidth);

    // Create a feature type
    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName("grid");
    tb.add(
        GridFeatureBuilder.DEFAULT_GEOMETRY_ATTRIBUTE_NAME,
        Polygon.class,
        gridBounds.getCoordinateReferenceSystem());
    tb.add("id", Integer.class);
    SimpleFeatureType TYPE = tb.buildFeatureType();

    // Build the grid the custom feature builder class
    GridFeatureBuilder builder = new IntersectionBuilder(TYPE,  featureSource);

    return Grids.createSquareGrid(gridBounds, squareWidth, -1, builder);
  }
}

public class IntersectionBuilder extends GridFeatureBuilder {
  final FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2();
  final GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();

  final SimpleFeatureSource source;
  int id = 0;

  public IntersectionBuilder(SimpleFeatureType type, SimpleFeatureSource source) {
    super(type);
    this.source = source;
  }

  public void setAttributes(GridElement el, Map<String, Object> attributes) {
    attributes.put("id", ++id);
  }

  @Override
  public boolean getCreateFeature(GridElement el) {
    // filter based on grid element geometry
    Filter filter = ff2.intersects(ff2.property("the_geom"), ff2.literal(el.toGeometry()));
    boolean result = false;

    try {
      result = !source.getFeatures(filter).isEmpty();
    } catch (IOException ex) {
      throw new IllegalStateException(ex);
    }

    return result;
  }
}

public class GeoProjectionHelper {

    public static SimpleFeatureSource convertToLocalProjection(SimpleFeatureSource inputFeatureSource) throws IOException {

        // extract the original CRS
        CoordinateReferenceSystem origCRS = inputFeatureSource.getFeatures().getSchema().getCoordinateReferenceSystem();

        // find centre coordinate of input
        Coordinate inputCentre = inputFeatureSource.getBounds().centre();

        // find local projection
        CoordinateReferenceSystem auto = origCRS;
        SimpleFeatureCollection outputFeatureCollection = inputFeatureSource.getFeatures();
        if (!(origCRS instanceof ProjectedCRS)) {

            String code = "AUTO:42001," + inputCentre.x + "," + inputCentre.y;

            try {
                auto = CRS.decode(code);
                System.out.println(auto.toString());

            } catch (FactoryException e) {
                e.printStackTrace();
            }

            outputFeatureCollection = new ReprojectingFeatureCollection(inputFeatureSource.getFeatures(), auto);
        }

        // wrap back to SimpleFeatureSource
        return DataUtilities.source( outputFeatureCollection );
    }

A: There are some key classes missing from your question, so this may not reflect exactly what your issue is but in my tests the majority of the execution time (5.5 sec) is writing out the shapefile of 108237 polygons.
Setup time 0.687
producing a 327.0 by 331.0 grid (108237.0)
grid time 0.662
writing time 5.562

Here's how I implemented the getIntersectingGrid class:
public static SimpleFeatureSource getIntersectingGrid(ReferencedEnvelope gridBounds, double squareWidth)
      throws IOException, NoSuchAuthorityCodeException, FactoryException, TransformException {

    double x = gridBounds.getMedian(0);
    double y = gridBounds.getMedian(1);
    // reproject to local crs, respecting axis order
    double lon;
    double lat;
    if (CRS.getAxisOrder(gridBounds.getCoordinateReferenceSystem()) == CRS.AxisOrder.EAST_NORTH) {
      lat = x;
      lon = y;
    } else {
      lat = y;
      lon = x;
    }
    String code = "AUTO:42001," + lat + "," + lon;

    CoordinateReferenceSystem auto = CRS.decode(code);
    ReferencedEnvelope bounds = gridBounds.transform(auto, true);
    bounds.expandBy(squareWidth);
    double w = Math.ceil(bounds.getWidth() / squareWidth);
    double h = Math.ceil(bounds.getHeight() / squareWidth);
    System.out.println("producing a " + w + " by " + h + " grid (" + (w * h) + ")");

    SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
    tb.setName("grid");
    tb.add(GridFeatureBuilder.DEFAULT_GEOMETRY_ATTRIBUTE_NAME, Polygon.class, auto);
    tb.add("id", Integer.class);
    SimpleFeatureType TYPE = tb.buildFeatureType();
    GridFeatureBuilder builder = new DefaultGridFeatureBuilder(TYPE.getTypeName(), auto);

    return Grids.createSquareGrid(bounds, squareWidth, -1, builder);
  }
}

Also, if you plan to move to other countries then using AUTO:42004 may be better otherwise you can run into issues at the poles with Transverse Mercator issues.
EDIT
I think the problem is that your getCreateFeature method is doing too much work by parsing a filter and then comparing it against the features in the data source. You can go with a much simpler implementation as the target geometry doesn't change.
public static class IntersectionBuilder extends GridFeatureBuilder {
final FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2();
final GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();

final SimpleFeature source;
Geometry geom;
int id = 0;

public IntersectionBuilder(SimpleFeatureType type, SimpleFeature source, MathTransform transform) {
  super(type);
  this.source = source;

  try {

    this.geom = JTS.transform((Geometry) source.getDefaultGeometry(), transform);
  } catch (MismatchedDimensionException | TransformException e) {
    e.printStackTrace();
  }
}

@Override
public boolean getCreateFeature(GridElement el) {
  // filter based on grid element geometry

  boolean result = el.toGeometry().intersects(geom);
  return result;
}

@Override
public void setAttributes(GridElement el, Map<String, Object> attributes) {
  attributes.put("id", ++id);

}
}

This gives me a run time of 3.98 seconds in total for India.


text:
Q: How to get rid off this error with TCPDF :"TCPDF ERROR: Some data has already been output to browser, can't send PDF file" I want to print the output(i.e. value of variable $matter) but I'm getting the error message mentioned above. I did lot of google for it and checked for spaces before and after php tags. But couldn't get the solution. Please help me. Here is my code to print output using tcpdf:
<?php
    ob_start();
  require_once("../../includes/application-header.php");

  // Include tcpdf liabrary
  require_once OCN_ROOT."/core/extention/tcpdf/config/lang/eng.php";
  require_once OCN_ROOT."/core/extention/tcpdf/tcpdf.php";

    define ('PDF_MARGIN_TOP', 22);
    define ('PDF_HEADER_TITLE', 'This is Heading');
    define ('PDF_HEADER_STRING', $head_string);
    define ('PDF_CREATOR', PAGE_TITLE);

    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor(PDF_CREATOR);
    $pdf->SetTitle('TCPDF Example');

    // set default header data
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    //set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    //set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    //set some language-dependent strings
    $pdf->setLanguageArray($l);

    // ---------------------------------------------------------

    // set font
    $pdf->SetFont('helvetica', '', 10);

    // add a page
    $pdf->AddPage();

    $matter = <<<EOD

HTML Example

EOD;

    $pdf->writeHTML($matter, true, false, true, false, '');

    // reset pointer to the last page
    $pdf->lastPage();

    // ---------------------------------------------------------
    ob_flush();
    //Close and output PDF document
    $pdf->Output('example_061.pdf', 'I');

    //============================================================+
    // END OF FILE
    //============================================================+
?>

A: Try instead of ob_flush(); with ob_end_clean();


text:
Q: Probability based function in Node.JS I wanted to create a function that when clicking when opening a chest, the person will get a random character, based on their probability of each class:
1 - Common: 90%
2 - Rare: 8%
3 - Super rare: 2%
Is this possible in Node.JS?

A: It's indeed possible, and in any language since that's just generating a random number (see Math.Random()) and doing some maths!
Here's an example with the code commented to explain what's going on:

 // The actual function to draw a character class
function drawCharacterClass() {
  // We generate a random number between 0 and 1
  const r = Math.random();
  // If the number is between 0 and 0.02 (included) - so 2% chance
  if (r <= 0.02)
    return "Super Rare";
  // If the number is between 0.02 (not included) and 0.10 - so 8% chance.
  if (r <= 0.10)
    return "Rare";
  // If the number is anything else, so between 0.10 (not included) and 1 - so 90% chance.
  else
    return "Common";
}

// ===== ===== ===== Testing code below ===== ===== =====

// Now let's make a function that draw a lot of characters and record how many of each we got, this way we can make sure the drawCharacterClass() function is correct
function checkProbabilities(sample) {
  const res = {};
  for (let i = 0; i < sample; ++i) {
    const c = drawCharacterClass();
    res[c] = ++res[c] || 0;
  }
  return res;
}

// Let's poll 10 million characters.
// The higher the number the more precise it will be, but also slower.
const records = checkProbabilities(10000000);
// We count the total. We could also just use 10000000 directly.
const total = records["Common"] + records["Rare"] + records["Super Rare"];

// Now for each class of character, we count the amount we got from this class (records[class]) divided by the total of characters drawn. This will tell us what % of this class of character got drawn among the 10 millions draws.
console.log(`${Math.round(records["Common"] / total * 100)}% of Common.`); // Should say 90%
console.log(`${Math.round(records["Rare"] / total * 100)}% of Rare.`); // Should say 8%
console.log(`${Math.round(records["Super Rare"] / total * 100)}% of Super Rare.`); // Should say 2%

You can execute this code, will simulate the draw of 10 millions characters (might take a few seconds) using the function at the top of the snippet, and then calculate the effective drop rate of each character class, allowing you to make sure they are correct.

Note that this function drawCharacterClass() is very straightforward and only respect what you said in the question. Its goal is just to show you that "yes, it's possible", but it's by far not the best way to do it, especially if you plan to change the percentages, the names of the classes, add another class, etc...
In this case you might better do a more modular/generic approach so that for example you need only to change something like this:
const classes = {
  "Common": 0.90,
  "Rare": 0.08,
  "Super Rare": 0.02
}

Also note that it will only draw a certain class of character, not the character itself.
But now that you know how to pick a randomized item among others (here a class among several classes), picking one character among several characters shouldn't be very hard!


text:
Q: Use ajax request to load sidebar For a project, i've to improve SEO perf and one of this optimization is to load the sidebar with an ajax request.
I've looking for this solution through the documentation, source code, plugins repository without success.
So i need your help and advices. Is it possible to do this ? If yes, what is the best way ?
Thanks.

A: I didn't test anything, but I imagine it would be something like this:
As you must include a sidebar.php, just include an empty sidebar.php, and leave the real one to the sidebar-ajax.php, for example.
To call the sidebar:
<?php get_template_part('sidebar'); ?>

And it should be something like this:

In your functions.php:
add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
function theme_enqueue_scripts() {
    wp_enqueue_script('jquery');
    /* load your js file in footer */
    wp_enqueue_script('theme-script', get_stylesheet_directory_uri() . '/your-js-file.js', false, false, true);
}

add_action('wp_ajax_get_ajax_sidebar', 'check_ajax');
add_action('wp_ajax_nopriv_get_ajax_sidebar', 'check_ajax');
function check_ajax() {
    ?>
    get_template_part('sidebar-ajax');
    <?php
}

And in your-js-file.js:
jQuery.ajax({
    type: 'POST',
    url: location.href,
    data: { get_ajax_sidebar: 1 },
    success: function(data){
        jQuery('#sidebar').html(data);
    }
});


text:
Q: How to combine UIViewRepresentable and instance methods for Mapkit? For an app I need to display a Map from mapkit.
I'm using SwiftUI.
On top of the Map itself there need to be a search function and when you finish the search (enter) the map moves the visible region to the result of the search

import MapKit
import SwiftUI

struct MapViewTwo: View {
    @Environment(\.presentationMode) var presentationMode

    let location: CLLocationCoordinate2D
    let annotationItems: [MyAnnotationItem]
    @State   var searchText = ""
    @State private var region: MKCoordinateRegion = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: MapDefaults.latitude, longitude: MapDefaults.longitude),
        span: MKCoordinateSpan(latitudeDelta: MapDefaults.zoomedOut, longitudeDelta: MapDefaults.zoomedOut))

    private enum MapDefaults {
        static let latitude = 51.507222
        static let longitude = -0.1275
        static let zoomedOut = 2.0
        static let zoomedIn = 0.01
    }

    func searchMap(){
        let searchRequest = MKLocalSearch.Request()
        searchRequest.naturalLanguageQuery =   searchText // This is where you can pass in you search string parameter.
        searchRequest.resultTypes = .address

        let search = MKLocalSearch(request: searchRequest)
        search.start { response, error in
            guard let response = response else {
                print("Error: \(error?.localizedDescription ?? "Unknown error").")
                return
            }
            print("Found \(response.mapItems.count)")
            region = response.boundingRegion
        }
    }

    var body: some View {
        Map(coordinateRegion: $region,
            interactionModes: .all,
            showsUserLocation: true,
            annotationItems: annotationItems) { item in
            MapPin(coordinate: item.coordinate)
        }

        ZStack(alignment:.top){
            VStack(alignment:.leading){

                HStack {
                    Circle()
                        .fill(.white)
                        .frame(width: 44, height: 44)
                        .overlay(   Image(systemName: "arrow.backward"))
                        .onTapGesture(){
                            print("Back button")
                        }

                    HStack {
                        Image(systemName: "magnifyingglass")
                        TextField("search", text: $searchText, onEditingChanged: { isEditing in

                        }, onCommit: {
                            print ("Search for \(searchText)")
                            searchMap()

                        })
                        .foregroundColor(.primary)
                        .textInputAutocapitalization(.never)

                        Button(action: {
                            self.searchText = ""
                            //BACK TO NORMAL

                        }) {
                            Image(systemName: "xmark.circle.fill").opacity(searchText == "" ? 0 : 1)
                        }

                    }
                    .padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
                    .foregroundColor(.secondary)
                    .background(Color(.secondarySystemBackground))
                    .cornerRadius(10.0)
                }

            }.padding(.top,50).padding(.leading,20).padding(.trailing,20)

        }
        //MARK: User location button
        ZStack(alignment: .bottom){
            VStack(alignment:.trailing){
                Spacer()
                HStack{
                    Spacer()
                    Circle()
                        .fill(.white)
                        .frame(width: 50, height: 50)
                        .overlay(   Image( "user-location"))
                        .onTapGesture(){

                            region  = MKCoordinateRegion(
                                center: CLLocationCoordinate2D(latitude: 50.96847915649414, longitude: 5.982074737548828),
                                span: MKCoordinateSpan(latitudeDelta: MapDefaults.zoomedOut, longitudeDelta: MapDefaults.zoomedOut))

                        }
                }.padding(.bottom,100).padding(.trailing,30)

            }
        }
        .ignoresSafeArea()
        .onAppear(perform: setupLocation)
    }

    func setupLocation() {
        region = MKCoordinateRegion(
            center: location,
            span: MKCoordinateSpan(latitudeDelta: MapDefaults.zoomedIn, longitudeDelta: MapDefaults.zoomedIn))
    }
}

I also need to have the functionality that a user can drop a pin on the map (center) and select the pin and move it to a different location. When he does, the GLGeocoder will reverse geocode the location and provide this feedback on some Text elements.
For this I have the following code (playgrounds).

*

*TryView (my view to display the DropApinMapView and search bar

*DropAPinMapView handling the drag and drop and geocoding

#TryView.swift

import SwiftUI
import MapKit
struct TryView: View {
    @State var mapItems: [MKMapItem] = []
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @State var isPinDropped:Bool = false
    @State var showSearchResults:Bool = false
    @State   var searchText = ""
    @State private var showCancelButton: Bool = false
    @State var pinDropDetail  = PinDropDetail(address: "", locality: "", postalCode: "", latitude: 50.96847915649414, longitude: 5.98207473754882, coordinateString: "",isBack: false)

    @Binding var model: PinDropDetail
    var onDismiss: ((_ model: PinDropDetail) -> Void)?

    func searchMap(){
        let searchRequest = MKLocalSearch.Request()
        searchRequest.naturalLanguageQuery =   searchText // This is where you can pass in you search string parameter.
        searchRequest.resultTypes = .address

        let search = MKLocalSearch(request: searchRequest)
        search.start { response, error in
            guard let response = response else {
                print("Error: \(error?.localizedDescription ?? "Unknown error").")
                return
            }
            //NOW I WANT TO MAP TO ANIMATE AND SET THE REGION TO  response.boundingRegion
        }
    }

    var body: some View {
        DropAPinMapView(pinDropDetail:self.$pinDropDetail )
            .ignoresSafeArea()
        //MARK: controls
            //search bar
        ZStack(alignment:.top){
            VStack(alignment:.leading){
                HStack {
                    Circle()
                        .fill(.white)
                        .frame(width: 44, height: 44)
                        .overlay(   Image(systemName: "arrow.backward"))
                        .onTapGesture(){
                            print("Back button")
                        }

                    HStack {
                        Image(systemName: "magnifyingglass")
                        TextField("search", text: $searchText, onEditingChanged: { isEditing in

                        }, onCommit: {
                            print ("Search for \(searchText)")
                            searchMap()
                        })
                        .foregroundColor(.primary)
                        .textInputAutocapitalization(.never)

                        Button(action: {
                            self.searchText = ""
                        }) {
                            Image(systemName: "xmark.circle.fill").opacity(searchText == "" ? 0 : 1)
                        }
                    }
                    .padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
                    .foregroundColor(.secondary)
                    .background(Color(.secondarySystemBackground))
                    .cornerRadius(10.0)
                }

            }.padding(.top,50).padding(.leading,20).padding(.trailing,20)
        }
        .ignoresSafeArea()
        //MARK: User location button
        ZStack(alignment: .bottom){
            VStack(alignment:.trailing){
                Spacer()
                HStack{
                    Spacer()
                    Circle()
                        .fill(.white)
                        .frame(width: 50, height: 50)
                        .overlay(   Image( "user-location"))
                        .onTapGesture(){
                            print("Userlocation")

                        }
                }.padding(.bottom,100).padding(.trailing,30)

            }
        }
        .ignoresSafeArea()
        //MARK: end of controls
        //IN APP THIS IS A DIFFERENT CONTROL DISPLAYING THE RESULT OF THE PINDROP
        Text(pinDropDetail.address).foregroundColor(.red)
    }
}

DropAPinMapView

import SwiftUI
import MapKit
import Foundation

struct PinDropDetail {
    var address: String
    var locality: String
    var postalCode: String
    var latutide: Double
    var longitude:Double
    var coordinateString: String
    var isBack: Bool

    init(address:String,locality:String,postalCode:String,latitude:Double,longitude:Double,coordinateString:String,isBack:Bool){
        self.address = address
        self.locality = locality
        self.postalCode = postalCode
        self.latutide = latitude
        self.longitude = longitude
        self.coordinateString = coordinateString
        self.isBack = isBack
    }

}

struct DropAPinMapView: UIViewRepresentable {

    let coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude:50.96847915649414,longitude: 5.98207473754882)
    @Binding var pinDropDetail:  PinDropDetail

    func makeUIView(context: Context) -> MKMapView {
        let map = MKMapView()
        map.mapType = .standard//.hybrid
        map.delegate = context.coordinator
        let coordinate: CLLocationCoordinate2D = coordinate
        let region = MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.3, longitudeDelta: 0.3))
        map.setRegion(map.regionThatFits(region), animated: true)
        map.showsCompass = true
        map.showsUserLocation = true
        let annotation = MKPointAnnotation()
        annotation.coordinate = self.coordinate
        map.addAnnotation(annotation)
        //geocode initial state as well
        CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)) { places, error in
            let latitudeString = String(format: "%.5f",coordinate.latitude)
            let longitudeString = String(format: "%.5f", coordinate.longitude)
            self.pinDropDetail.coordinateString = latitudeString + " , " + longitudeString
            self.pinDropDetail.address = (places?.first?.name!)! + ", " + (places?.first?.locality!)!
            self.pinDropDetail.postalCode = (places?.first?.postalCode!)!
            self.pinDropDetail.locality = (places?.first?.locality!)!
            self.pinDropDetail.latutide = coordinate.latitude
            self.pinDropDetail.longitude = coordinate.longitude
        }
        return map
    }

    func updateUIView(_ uiView: MKMapView, context: Context) {

    }

    func makeCoordinator() -> DropAPinMapView.Coordinator {
        return DropAPinMapView.Coordinator(parent1: self)

    }

    final class Coordinator: NSObject, MKMapViewDelegate {

        var parent:DropAPinMapView
        init(parent1:DropAPinMapView){
            parent = parent1
        }

        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            let pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")
            pin.isDraggable = true
            pin.pinTintColor = .red
            pin.animatesDrop = true
            return pin
        }

        func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationView.DragState, fromOldState oldState: MKAnnotationView.DragState) {
            //print(view.annotation?.coordinate.latitude)
            CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: (view.annotation?.coordinate.latitude)!, longitude: (view.annotation?.coordinate.longitude)!)) { places, error in
                let lat = (view.annotation?.coordinate.latitude)!
                let lon = (view.annotation?.coordinate.longitude)!
                let latitudeString = String(format: "%.5f",lat)
                let longitudeString = String(format: "%.5f", lon)
                self.parent.pinDropDetail.coordinateString = latitudeString + " , " + longitudeString
                self.parent.pinDropDetail.address = (places?.first?.name!)! + ", " + (places?.first?.locality!)!
                self.parent.pinDropDetail.postalCode = places?.first?.postalCode ?? ""
                self.parent.pinDropDetail.locality = places?.first?.locality ?? ""
                self.parent.pinDropDetail.latutide = (view.annotation?.coordinate.latitude)!
                self.parent.pinDropDetail.longitude = (view.annotation?.coordinate.longitude)!
            }
        }

    }

}

You see two different approaches for the first one (search) simply using a Map and that works. The second problem drop a pin also works but requires to create the UIViewRepresentable
How can I combine the two functionalities in one solution?
It would be great if the DropAPinMapView could be instantiated so a function could be called. I've tried adding a static function which also works but the line
let map = MKMapView()

Makes the map object private
Please provide solutions, tips or ideas

A: Inject MKMapView() instance from parent. It is a reference type, so parent will be an owner and will be able to work with it while the same reference is used inside representable for rendering.
So it would look like
struct TryView: View {
    private let map = MKMapView()   // << owner here !!

    // ...

    var body: some View {
        DropAPinMapView(map: map, pinDropDetail:self.$pinDropDetail ) // << injected

    // ...
    }
}

struct DropAPinMapView: UIViewRepresentable {
    let map: MKMapView   // << constructor contract !!

    // ...

    func makeUIView(context: Context) -> MKMapView {

        map.mapType = .standard//.hybrid   // << just configure/reset here !!
        // ...


text:
Q: Discord Music bot (Does not work but no errors) I was building a discord bot which plays music with 2 diffrent files.
It does not work but there are 0 errors. Help is appreciated.
My main.py file

import discord
from discord.ext import commands
import os
import time
import music
from keep_alive import keep_alive
TOKEN = os.environ['TOKEN']
bot = commands.Bot(command_prefix="$", intents = discord.Intents.all())

cogs = [music]
for i in range(len(cogs)):
  cogs[i].setup(bot)
keep_alive()
bot.run(TOKEN)

Ignore the keep alive that works perfectly
And then there is the music.py file
import discord
from discord.ext import commands
import youtube_dl
print("Test 1")
class music(commands.Cog):
  def __init__(self, client):
    self.client = client
    print("Test2")
  @commands.command()
  async def join(self, ctx):
    print("E")
    if ctx.author.voice is None:
      await ctx.send("Youre not in a voice channel")
    voice_channel = ctx.author.voice.channel
    if ctx.voice_client is None:
      await voice_channel.connect()
    else:
      await ctx.voice_client.move_to(voice_channel)

  @commands.command()
  async def disconnect(self, ctx):
    await ctx.voice_client.disconnect()

  @commands.command()
  async def play(self, ctx, url):
    ctx.voice_client.stop()
    FFMPEG_OPTIONS = {'before_options':'-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    YDL_OPTIONS = {'format':'bestaudio'}
    vc = ctx.voice_client

    with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
      info = ydl.extract_info(url, download = False)
      url2 = info['formats'][0]['url']
      source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
    vc.play(source)

  @commands.command()
  async def pause(self, ctx):
    await ctx.voice_client.pause()
    await ctx.send("Paused ⏸")
  @commands.command()
  async def resume(self, ctx):
    await ctx.voice_client.resume()
    await ctx.send("Resumed ⏯")

def setup(client):
  client.add_cog(music(client))

When i set this up, test 1 and 2 run perfectly but the commands never get executed.
I typed $join multiple times but nothing happened and no error popped up.
Im running blind here so i would heavily appreciate help.

A: try this and reply if working
    async def _join(self, ctx: commands.Context, *, channel: discord.VoiceChannel = None):

        if not channel and not ctx.author.voice:
            return await ctx.send('You are neither connected to a voice channel nor specified a channel to join.')

        destination = channel or ctx.author.voice.channel
        client = ctx.guild.voice_client
        if client:
            await client.move_to(destination)
        else:
            await destination.connect()


text:
Q: Removing Images from CustomAdapter I have a custom ImageAdapter that wraps item for a GridView in my activity.
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ArrayList<Integer>  mThumbIds = new ArrayList<Integer>();

public ImageAdapter(Context c, ArrayList<Integer> mThumbIds) {
mContext = c;
this.mThumbIds = mThumbIds;
}

public Object getItem(int position) {
    return mThumbIds.get(position);
}

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

@Override
public int getCount() {
    return mThumbIds.size();
}
public View getView(int position, View convertView, ViewGroup parent) {
              ImageView imageView;
              if (convertView == null) {
                  imageView = new ImageView(mContext);
                  imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
                  imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                  imageView.setPadding(8, 8, 8, 8);
                  } else {
                  imageView = (ImageView) convertView;
              }

              imageView.setImageResource(mThumbIds.get(position));
              return imageView;
  }

public void modifyData (ArrayList<Integer> newData){
    getmThumbIds().clear();
    for (Integer var : newData){
        getmThumbIds().add(var);
        }

    notifyDataSetChanged();
}

This adapter is created in my main Activity and associated to the GridView.
    imageAdapter = new ImageAdapter(this, getIdIngredients());
    grilleImagesIngredients = (GridView) findViewById(R.id.grilleImagesIngredients);
    grilleImagesIngredients.setAdapter(imageAdapter);

Finally I just want to erase all the images from my grid view, so:
imageAdapter.mThumbIds.clear();
imageAdapter.notifyDataSetChanged();

This method is working fine when I add objects. With some empirical tests I' ve seen that it's not removing the previous images in the grid, just drawing the new one over it.
Once I removed the objects from the adapter, they're no longer selectable in the gridView, but I still see the images.


text:
Q: Python Curses for windows not overwriting strings I'm using the package from: http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses
and I'm making a screen object like so:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import curses
import time

class Screen(object):
    def __enter__(self):
        self.stdscr = curses.initscr()
        curses.cbreak()
        curses.noecho()
        self.stdscr.keypad(1)
        curses.curs_set(0)

        Y, X = self.stdscr.getmaxyx()

        gap = 1
        self.bar = self.stdscr.derwin(3, X, 1, 0)
        self.threads = self.stdscr.derwin(Y-4-gap, X/2, 4, 0)
        self.messages = self.stdscr.derwin(Y-4-gap, X/2 -1, 4, X/2 + 1)

        # self.bar.box()
        # self.threads.box()
        # self.messages.box()
        return self

    def __exit__(self, type, value, traceback):
        curses.nocbreak()
        self.stdscr.keypad(0)
        curses.echo()
        curses.endwin()

    def refresh(self):
        self.bar.refresh()
        self.threads.refresh()
        self.messages.refresh()

if __name__ == '__main__':
    with Screen() as S:
        S.bar.addstr(0, 0, "Hello")
        S.refresh()
        time.sleep(2)
        S.bar.addstr(0, 0, "\rHi")
        time.sleep(2)

But when I actually execute this it just stays as "Hello" rather than overwriting it and printing "hi"
I've tried removing the '\r' but to no avail.
Any ideas?

A: If you want to clean the "Hello", you can add S.bar.erase() before S.bar.addstr(0, 0, "\rHi"). And you also need to add S.refresh() after S.bar.addstr(0, 0, "\rHi") to update the window, or the "Hi" will not be displayed.
The window.erase() is used to clear the window. You can check the documentation for more details: https://docs.python.org/2/library/curses.html


text:
Q: How to process Result of StringReplace? StringReplace["item_10", "item_" ~~ x__ -> x + 1]

returns "1+10"
How can I force it to evaluate to 11?

A: This returns "11":
StringReplace["item_10",  "item_" ~~ x__ :> ToString[ToExpression[x] + 1] ]
StringReplace["item_10",  "item_" ~~ x__ :> ToString[ToExpression[x <> "+1"]] ]

This 11:
StringCases["item_10", "item_" ~~ x__ :> ToExpression[x] + 1]
StringCases["item_10", "item_" ~~ x__ :> ToExpression[x <> "+1"]]

And step by step, first of all, :> not ->, the latter, Rule, is evaluated immediately:
x = 5;
StringReplace["item_10", "item_" ~~ x__ -> x]
StringReplace["item_10", "item_" ~~ x__ :> x]

StringExpression[5]
10

Then, you get a string "10", not a number so you have to perform appriopriate conversion first.


text:
Q: Heroku rake error in terminal Seem to be getting the following error in my terminal. Any reason why this is not working?
 Running `rake` attached to terminal... up, run.7822
 !
 ! Error connecting to process

A: You're probably bumping up against connectivity issues.
Ensure it is, in fact, a network issue by trying to connect to heroku's servers rendezvous.heroku.com:5000 and s1.runtime.heroku.com:5000. If so, you'll need to figure out where along the route you're getting snagged.
You can also try running your rake command in detached mode as a temporary workaround:
heroku run:detached rake some:task


text:
Q: Generalizing XPaths I would like seek your help for a problem I am trying to tackle involving XPaths.
I am trying to generalize multiple Xpaths provided by a user to get an XPath that would best 'fit' all the provided examples. This is for a web scraping system I am building.
Eg: If the user gives the following xpaths (each pointing to a link in the 'Spotlight' section from the Google News page)
Good examples:
/html/body/div[@id='page']/div/div[@id='main-wrapper']/div[@id='main']/div/div/div[3] /div[1]/table[@id='main-am2-pane']/tbody/tr/td[@id='rt-col']/div[3]/div[@id='s_en_us:ir']/div[2]/div[1]/div[2]/a[@id='MAE4AUgAUABgAmoCdXM']/span

/html/body/div[@id='page']/div/div[@id='main-wrapper']/div[@id='main']/div/div/div[3]/div[1]/table[@id='main-am2-pane']/tbody/tr/td[@id='rt-col']/div[3]/div[@id='s_en_us:ir']/div[2]/div[6]/div[2]/a[@id='MAE4AUgFUABgAmoCdXM']/span

/html/body/div[@id='page']/div/div[@id='main-wrapper']/div[@id='main']/div/div/div[3]/div[1]/table[@id='main-am2-pane']/tbody/tr/td[@id='rt-col']/div[3]/div[@id='s_en_us:ir']/div[2]/div[12]/div[2]/a[@id='MAE4AUgLUABgAmoCdXM']/span

Bad Examples: (pointing to a link in another section)
/html/body/div[@id='page']/div/div[@id='main-wrapper']/div[@id='main']/div/div/div[3]/div[1]/table[@id='main-am2-pane']/tbody/tr/td[@id='lt-col']/div[2]/div[@id='replaceable-section-blended']/div[1]/div[4]/div/h2/a[@id='MAA4AEgFUABgAWoCdXM']/span

It should be able to generalize and produce an xpath expression that would select all the links in the 'Spotlight' section. (It should be able to throw out the incorrect xpath given)
Generalized XPath
/html/body/div[@id='page']/div/div[@id='main-wrapper']/div[@id='main']/div/div/div[3]/div[1]/table[@id='main-am2-pane']/tbody/tr/td[@id='rt-col']/div[3]/div[@id='s_en_us:ir']/div[2]/div/div[2]/a[@id='MAE4AUgLUABgAmoCdXM']/span

Could you kindly advice me on how to go about it. I was thinking of using the Longest Common Substring strategy but however that would over-generalize if a bad example is given (like the fourth example given) Are there any libraries or any open source software that has been done in this area?
I saw some similar posts (finding common ancestor from a group of xpath? and Howto find the first common XPath ancestor in Javascript?) However they are talking about longest common ancestor.
I am writing it in Javascript as a form of a firefox extension.
Thanks for your time and any help would be greatly appreciated!

A: The question here is in Automaton minimization problem. So you have (Xpath1|Xpath2|Xpath3) and you would like to get minimal automaton Xpath4 which match same nodes. THere are also question about minimization with information lose or not, like JPEG. For exact minimization you could google "Algorithms for Minimization of Finite-State Automata".
Ok, the simplest way is finding common subsequence, after converting each Xpath operator to character and run character based substring finder from list of string. So we have for example
adcba, acba, adba --common substring--> aba --general reg exp--> a.*b.*a --convert back to xpath--> ...
You can also try to set something less general in place of .*


text:
Q: React scroll page to the top after transition I want my application to go to the top of the page when another page within the site is clicked. I have used the code from: https://v5.reactrouter.com/web/guides/scroll-restoration and put in a separate file.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

What I have tried:
I have placed <ScrollToTop /> before <Switch /> and after <BrowserRouter />as in the docs (these are in separate files).
Unlike the docs, the <App /> in my application is in a separate file, so <ScrollToTop /> is not placed near it.
When I console.log, I see it being hit at the correct instance (when there is a page change), but nothing occurs. I have also looked into many stackoverflow posts concerning the same issue, but I could not incorporate their suggestions.
What are possible issues:
Calling window.scrollTo(0, 0) outside the function does not seem to work. Are there any alternatives to this function?
Is the placement of  <ScrollToTop /> incorrect? Does it have to be called near the <App />?

A: Welcome to Stackoverflow @user19251203
You have already gone half the way. You really don't need to create a component for it. You can create a custom hook and place it in your <App /> and then call it:
function App() {

  // Scroll to top on every transition custom hook
  const useScrollToTop = () => {
    const { pathname } = useLocation();

    useEffect(() => {
      window.scrollTo(0, 0);
    }, [pathname]);
  };

  useScrollToTop();

  return (
    <div className="App">
      .......
    </div>
  )
}

This way whenever you go to a new page, it scrolls to the top of the page.


text:
Q: Print current age given the date of birth I have to make a code outside of a function where I print the current age given the input of the date of birth. So far I've got this:
from datetime import date, datetime
birth1 = input("Input your date of birth (dd/mm/yyyy):")

currentDate = date.today()
birth2 = datetime.strptime(birth1, "%d/%m/%Y").date()
age = currentDate - birth2

But I'm stuck here. How can I make it so the var "age" gets the current age from the person so I can later print it in something like this:
print(age, "years old")

A: See below code -it should work for you

A: age = currentDate.year - birth2.year
if currentDate.month < birth2.month or \
  (currentDate.month == birth2.month and currentDate.day < birth2.day):
  age -= 1
print(age, "years old")


text:
Q: Celery beat scheduling option to immediately launch task upon celery launch I can schedule an hourly task in my Django app using celery beat in settings.py like so:
CELERYBEAT_SCHEDULE={
'tasks.my_task':{
'task':'tasks.my_task',
'schedule':timedelta(seconds=60*60),
'args':(),
},
}

But is there a way to schedule a task such that it immediately queues up and is calculated, thereafter following the configured schedule from there on? E.g., something like executing a selected task instantly at celery launch. What's the configuration for that?

A: Add the following to tasks.py:
obj = locals()['task_function_name']
obj.run()

This ensures the specified task is run when celery is run. Thereafter, it executes according to schedule.


text:
Q: Google Client for Calendar service responding with a 404 Target
I'm trying to integrate Google Calendar API to my company website to automate event creation upon some events.
The events will be added to a company calendar and displayed to the users, so i don't need the users to authenticate, i will not work on their own calendars.
What i've done

*

*made a OAuth 2.0 service account as described in the Google OAuth 2.0 for Server to Server Applications docs

*created, downloaded and added the credentials file to my project, and added its path to the environment variable GOOGLE_APPLICATION_CREDENTIALS;

*followed the docs example to authorize my requests using the service account and the docs to create events.
Here's a short version of my sourcecode:
$client = new Google_Client();
$client->setApplicationName("XXX");
$client->addScope(Google_Service_Calendar::CALENDAR); // "https://www.googleapis.com/auth/calendar"
$client->useApplicationDefaultCredentials();

$service = new Google_Service_Calendar($client);

$event = new Google_Service_Calendar_Event(/* array with event data */);
$calendarId = /* calendar id taken from calendar Settings and Sharing on calendar.google.com*/;

$event      = $service->events->insert($calendarId, $event);

Compared to the example (lines 43:52) I didn't manually check for the credential files but gone straight for useApplicationDefaultCredentials().
The error
The logged errror from my code is
[2020-10-19 14:29:19] local.ERROR: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "Not Found"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}
 {"userId":2,"exception":"[object] (Google_Service_Exception(code: 404): {
 \"error\": {
  \"errors\": [
   {
    \"domain\": \"global\",
    \"reason\": \"notFound\",
    \"message\": \"Not Found\"
   }
  ],
  \"code\": 404,
  \"message\": \"Not Found\"
 }
}
 at /var/www/vendor/google/apiclient/src/Google/Http/REST.php:123)
[stacktrace]

It looks like it is calling the wrong api endpoint since a 404 is a page not found response.
Calendar ID
Just to be clear, here is where i taken the calendar id

A: As far as I know, service accounts do not have their own calendars, so they need to be granted access to a specific organization in order to create/read events.
If this is for an internal application (and you are an administrator for your organization), you can follow the steps under Delegating Authority to grant your service account access to the calendars for your organization:

Then, a super administrator of the G Suite domain must complete the following steps:

*

*From your G Suite domain's Admin console, go to Main menu menu > Security > API Controls.

*In the Domain wide delegation pane, select Manage Domain Wide Delegation.
Click Add new.

*In the Client ID field, enter the service account's Client ID. You can find your service account's client ID in the Service accounts page.

*In the OAuth scopes (comma-delimited) field, enter the list of scopes that your application should be granted access to. For example, if your application needs domain-wide full access to the Google Drive API and the Google Calendar API, enter: https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/calendar.

*Click Authorize.

You'll also need to follow the steps to impersonate a specific user under Preparing to make an authorized API call in order to retrieve a token for a user that has access to the calendar in question.
If this is for an application intended to be installed by multiple organizations, you should consider using a managed OAuth service, like Xkit (where I work). Xkit in particular has a Google Calendar Service Account connector that abstracts away all of these steps (including a step-by-step guide for the IT admin) from you as the developer to deliver you a working access token in one API call.
As a side note, the service account example you cited uses public data from the Books API, so it does not need authorization from a user, it only needs to identify itself as an application.


text:
Q: load csv into leaflet and convert coordinates with proj4 This question involves the use of:

*

*leaflet.js (used to create my map)

*leaflet omnivore plugin (used to load my csv data file)

*and proj4 (used to convert easting/northing to lat/lon)

My code below loads a stamen map with leaflet, and then uses omnivore to load my csv file.
In order to display the csv geo data on my map i need to first convert the easting/northing coordinates to lat/lon. The next sections of code contain the logic to do this, and it works successfully for the single coordinate sample within the console.log at the bottom.
But I have no idea how to use this logic on my full csv file. There is one column for easting, one for northing in the file - ultimately i want to my code to convert all these to lat lon, and plot them as points on my map.
var map = L.map('map').setView([51.44, -1.01], 8);

L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner-background/{z}/{x}/{y}.{ext}',
{
    subdomains: 'abcd',
    minZoom: 8,
    maxZoom: 20,
    ext: 'png'
}).addTo(map);

var dataset = omnivore.csv('assets_cwy_new simple.csv');

var osgb = '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs ';
var wgs84 = '+proj=longlat +datum=WGS84 +no_defs ';

console.log(proj4(osgb,wgs84,[514545.49,215008.4]));

A: As you figured out, you can use Proj4Leaflet plugin with Proj4js to convert your easting/northing coordinates into WGS84 lng/lat. Do not forget to revert the coordinates into lat/lng for Leaflet.
Now to have leaflet-omnivore use the correct columns from your CSV file, you have to use the parser_options (2nd parameter of your call to omnivore.csv), which are actually passed to the underlying library csv2geojson. These options let you specify the latitude and longitude fields of your CSV file. For now you have only easting/northing, but we can convert them later on:
var csv2geojsonOptions = {
  latfield: 'northing',
  lonfield: 'easting',
  delimiter: ','
}

omnivore.csv('./assets_cwy_new_simple.csv', csv2geojsonOptions);

Next, you need to convert your easting/northing coordinates into WGS84 lng/lat coordinates, using proj4leaflet. To have omnivore perform this conversion on each of your lines, you have to use the customLayer (3rd parameter of your call to omnivore.csv). It is actually just a preconfigured Leaflet GeoJSON Layer Group. With this group, you can use its coordsToLatLng option to implement your conversion with proj4leaflet:
var customLayer = L.geoJSON(null, {
  coordsToLatLng: projCoordsToLatLng
});

function projCoordsToLatLng(coords) {
  return lngLatToLatLng(proj4(osgb, wgs84, coords));
}

function lngLatToLatLng(lngLat) {
  return [lngLat[1], lngLat[0]];
}

omnivore.csv('./assets_cwy_new_simple.csv', csv2geojsonOptions, customLayer);

Live example: https://plnkr.co/edit/Dj9Mukig8PAHUYinsapJ?p=preview


text:
Q: How to post label in center of picture box? I have a Picturebox contain image (sketchImage mode) and I want to make a transparent Label (contain number) in the center of picturebox
So to make the Label transparent i use Parent like this ( in form load event ) :
Label7.Parent = PictureBox2
Label7.BackColor = System.Drawing.Color.Transparent

but now i have problem ! when i start the app the label cituate in the bottom of picture box ? how to fix that !!

A: What I would suggest is that you place the Label exactly where you want it to be in the designer, then translate the Location when you change the Parent, i.e.
Dim labelLocation = myLabel.PointToScreen(Point.Empty)

myLabel.Parent = myPictureBox
myLabel.Location = myPictureBox.PointToClient(labelLocation)

When you add the Label in the designer, its Parent will be the form. The first line above gets the screen coordinates of the Label on the form. The second line moves the Label from the form to the PictureBox, which will move the Label to the same point relative to the top-left of the PictureBox as it was to the top-left of the form. The last line will move the Label back where it was, by translating those screen coordinates to client coordinates relative to the PictureBox.
Here's an extension method you can use to do this for any control:
Imports System.Runtime.CompilerServices

Public Module ControlExtensions

    <Extension>
    Public Sub ChangeParentMaintainingAbsoluteLocation(source As Control, newParent As Control)
        Dim absoluteLocation = source.PointToScreen(Point.Empty)

        source.Parent = newParent
        source.Location = newParent.PointToClient(absoluteLocation)
    End Sub

End Module

Once that's added, either directly to your project or via reference and import, you can simply call that method on the control you want to move. In your case, that would be:
Label7.ChangeParentMaintainingAbsoluteLocation(PictureBox2)

EDIT:
That said, if you specifically want a child control in the centre of its parent:
Dim parentSize = parent.ClientSize

child.Location = New Point((parentSize.Width - child.Width) \ 2,
                           (parentSize.Height - child.Height) \ 2)

The ClientSize is used because some controls - most particularly forms - have borders and those borders may also be asymmetrical. A PictureBox is one control that may have a border, making the client size less than the overall size. Forms will generally have a border and the top is thicker than the bottom, so using ClientSize is even more important.


text:
Q: Converting image into bytes and dividing it into chunks I am trying to read a image file into bytes and divide those bytes into smaller chunks as shown in code below. Can someone guide me on whether this is the right & efficient approach to do it? Please help.
public static IEnumerable<IEnumerable<char>> ReadByChunk(int chunkSize)
            {
                IEnumerable<char> result;
                int startByte = 0;
                do
                {
                    result = ReadBytes(startByte, chunkSize);
                    startByte += chunkSize;
                    yield return result;
                }
                while (result.Any());
            }

            public static IEnumerable<char> ReadBytes(int startByte, int byteToRead)
            {
                char[] result;
                byte[] b = File.ReadAllBytes(@"C:\Users\1.jpg");
                for (int i = startbyte; i <= b.length; i++)
                {
                    result = b;
                }
                return result;
            }
            public static void Main()
            {
                const int chunkSize = 2048;
                foreach (IEnumerable<byte> bytes in ReadByChunk(chunkSize))
                {
                  //more code

                }
            }

A: There are numerous problems with your code:

*

*Every single call to ReadBytes reads the entire file into memory.

*The for loop in ReadBytes doesn't actually chunk the result, it simply assigns b to result, meaning that the result form this method is always the entire file.

*For some reason you're trying to use char for binary data. This is not a good idea because text encoding doesn't work correctly for binary data. Encoding an arbitrary series of bytes with, for example, UTF8, and reversing that won't get you the same byte values.

*Because ReadBytes always returns the entire file, while (result.Any()) will loop forever (unless the file is empty).

Here is a more correct way to do it:
public static IEnumerable<IEnumerable<byte>> ReadByChunk(int chunkSize)
{
    using (var reader = File.OpenRead("filename")) // open the file as a stream
    {
        byte[] chunk = new byte[chunkSize]; // create a byte array equal to our chunkSize
        int bytesRead = 0;
        // when `Read` returns `0`, it means we've reached the end of the file
        // so loop while the number of bytes read is > 0
        while ((bytesRead = reader.Read(chunk, 0, chunkSize)) > 0)
        {
            // take the actual number of bytes read and return
            // this chunk as an array
            yield return chunk.Take(bytesRead).ToArray();
        }
    }
}


text:
Q: string splitting based on delimiters My string is
 c("closely-monitored",  "rights-of-way", "THIS_IS_A_CONSTANT")

I like to split this to separate words as
  "closely" "-monitored", "rights", "-of", "-way", "THIS", "_IS", "_A", "_CONSTANT"

Tried
 paste("\\-", strsplit(str3, "_|-"))

but it is not working.

A: Here's an approach with perl-compatible regex:
vec <- c("closely-monitored",  "rights-of-way", "THIS_IS_A_CONSTANT")

unlist(strsplit(vec, "(?<=[^-_])(?=[-_])", perl = TRUE))

# [1] "closely"    "-monitored" "rights"     "-of"        "-way"
# [6] "THIS"       "_IS"        "_A"         "_CONSTANT"


text:
Q: Mocking a class which has a static final field initialised in an unsafe manner Problem:
In order to test a given class I need to be able to mock ClassWithBadStaticFinalField
I am unable to modify ClassWithBadStaticFinalField
Mocking ClassWithBadStaticFinalField with mockito is not possible because it attempts to interact with production servers when initialising its bad static final field
I have attempted to hack the field in the manner described in this answer but that fails with the following stacktrace
java.lang.ExceptionInInitializerError
    at sun.misc.Unsafe.ensureClassInitialized(Native Method)
    at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
    at sun.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:140)
    at java.lang.reflect.Field.acquireFieldAccessor(Field.java:1057)
    at java.lang.reflect.Field.getFieldAccessor(Field.java:1038)
    at java.lang.reflect.Field.set(Field.java:741)
    at com.example.SomeTest.setFinalStatic(SomeTest.java:76)
    at com.example.SomeTest.setUp(SomeTest.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.NullPointerException
    at com.example.ClassWithBadStaticFinalField.<clinit>(ClassWithBadStaticFinalField.java:17)
    ... 34 more

ClassWithBadStaticFinalField.java
public abstract class ClassWithBadStaticFinalField {
    protected static final String SOME_STRING = SomeRidiculousClass.someInsaneStaticMethodWhichDoesBadThings();

    public ClassWithBadStaticFinalField() { // line 17

    }

    ...
}

I have requested that ClassWithBadStaticFinalField have an interface created which details all public methods, and so gets me out of this problem, but wheels turn slowly..
When the production servers are not available  SomeRidiculousClass.someInsaneStaticMethodWhichDoesBadThings() null pointers
I would rather not have to intercept the outbound call made from SomeRidiculousClass.someInsaneStaticMethodWhichDoesBadThings() and force a response back.


text:
Q: Как сделать свой REST API? надо сделать свой сервис API на PHP, у которого будет функционал доступа к данным в стиле REST. Используя базу данных.
Что бы работало вот так:
GET /api/games/ - список игрушек
GET /api/game/12345/ – информация о игрушке
POST /api/games/ + JSON – добавить новую игрушку
PUT /api/games/12345/ + JSON – обновить существующую игрушку
DELETE /api/games/12345/ – удалить игрушку
Данные возвращаются в JSON, с использованием как можно большего количества HTTP-статусов. Можно использовать готовые решения через composer.
Как сделать описанное мною выше, умею только получать JSON с помощью ajax, а вот как сделать свою, понятия не имею от слова совсем. Желательно какой-нибудь простенький пример с объяснениями или ссылочку где это всё простенько объясняется, опять же с примерами. Т.к. в этом деле новичок.

A: Рекомендую Вам попробовать php фреймворк Slim.
И вот как раз обучающее видео по тому как на нем реализовать rest api:
YouTube - Slim Framework Rest API


text:
Q: Getting SonarQube major Vulnerabilities in Jenkins Pipeline In my Springboot application project using Java Script. I have written a code like this,
 document.getElementById("pendingARModID").action = "annualReviewApproval?status="+ status,
 {penArKeys : penArKeysArray};

Getting Sonar qube vulnerabilities in Jenkins pipeline.

Issue type:
Any statement (other than a null statement, which means a statement containing only a semicolon ;) which has no side effect and does not result in a change of control flow will normally indicate a programming error, and therefore should be refactored.


text:
Q: Adding provisioning profile from different team to xcode I have developed an iOS for my client using my developer account where I manage the provisioning profiles and certificates etc. and that account is linked to xcode.
However, my client wants to deploy the app using their provisioning profile.
They do not want to add me to their development account, because I am doing a freelance project and they dont want me to have access to their other apps.
They sent me an adhoc and distribution provisioning profiles (.mobileprovision) they created through their developer account. They instructed me to add the provision profiles to my keychain and then I would be able to use it.
However, when I try to deploy the app I get the following error:
No provisioning profiles with a valid identity (i.e. certificate and private key pair) were found
Is it at all possible to use provisioning profiles that are not associated with my developer account?
Any suggestions would be greatly appreciated!


text:
Q: What purpose does ODBCParameters setting serve in DB2 configuration? When I export my DB2 configuration (that was set up by an administrator) using db2cfexp, I have some CLI entries that have an ODBCParameters setting.
Here's an example:
[CLI_ODBC>SMPLE1]
DataSourceName=SMPLE1
DataSourceType=System
DBALIAS=SMPLE1
ODBCParameters=Yes

[CLI_ODBC>SMPLE2]
DataSourceName=SMPLE2
DataSourceType=System
DBALIAS=SMPLE2
ODBCParameters=No

What is the purpose of the ODBCParameters=Yes and ODBCParameters=No setting? I have searched for an explanation but found nothing.
Thanks.


text:
Q: Fade background-image to another background-image Sorry if this seems like a repeat of similar questions on Stack.
I've found lots of questions about fading background images in-and-out, or changing them with hovers but that doesn't entirely suit my need. I simply want to make it look like a loading.gif (set as background-image) is fading out.
I've tried to use the code and suggestions in this Stack Question here.
I've made a JSFiddle to work on my code but as I'm not a professional developer my jQuery experience and knowledge is ok at best and I can't get it to work.
Any help on this would be appreciated. JS Fidde: https://jsfiddle.net/tsruxyan/1/

A: I don't really understand what you want to do and how but for changing the background or any thing other you can add a class to your element by jQuery $(elemnt).addClass then use animation in it's css codes and at the end remove class in callback function.

A: The Problem is you didn't include jQuery as external Ressource in your JsFiddle. That is why you couldn't call jQuery functions in it.
I'm not exactly sure what you want to achieve, but if you add jQuery, you can simply add another (hidden) backround, use .fadeOut() to fade the first background out and then show the second background image using .toggle() to show the other background as soon as the first animation is done.
This is what that could look like:
$( "#clickme" ).click(function() {

  $( ".library-layout" ).fadeOut( "slow", function() {

    //Fade out ready, time to fade in the other image
    $( "#other-img" ).toggle( "slow", function() {
    // Animation complete.
        });
  });
});

A proof of concept is here.