text:
Q: The Synaptics touchpad driver cannot prevent the touchpad from "tapping = click"  This is related to this question.
the Synaptics touchpad driver cannot prevent the touchpad from treating a tap as a click.  Is there some window that is not seen that actually can set it or can there be any other method?

A: I have tried using Synaptics for that same purpose. It never worked. If you go to
Dell Support if you're running a dell, the pointing stick driver will enable you to control "tap to click" preferences.


text:
Q: Root profile page for club in .net core For a club page I am wanting to provide a url to them like the following. Am using .net 5 and ef core as well.
I am storing the url for each club in the database which is a striped version the the club Name field.
www.yoursite.com/clubpage
I have a controller obv with the action method and the controller is called ClubController.cs
public async Task<IActionResult> Index(string url) {
  var club = _context.Clubs
  .Where(w => w.isActive == true && w.Url == url && w.isDeleted ==
   false).ToList();
}

Question is what do i need in my config mapping to allow the url style but still allow the other controllers to function
Can I have multiple useend points statement's or am i over complicating by not just having www.yoursite.com/club/clubpage?
My startup configuration.
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
    name: "areas",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});
}

If I should do the latter why is must my parameter always be Id?
    public async Task<IActionResult> Index(string url) {
        return (IActionResult)_context.Clubs.Where(w => w.isActive == true && w.Url == url && w.isDeleted == false).FirstOrDefault();
    }

Edit 2
Ok this got me to where i needed to be but is their way to take it step futher and remove the club just the name?.
endpoints.MapControllerRoute(name: "club",
 pattern: "club/{clubname?}",
 defaults: new { controller = "Club", action = "Index" });

When I have this I would still like club to be able to go to say /Club/Timeline but with the above root also it doesnt allot me it just keeps going to index.
Edit 3
If I do the following it allows me to have both scenarios but i feel i shouldn't need to do both?
endpoints.MapControllerRoute(name: "TimeLine",
  pattern: "Club/TimeLine/{clubname?}",
  defaults: new { controller = "Club", action = "ClubTimeLine" });

endpoints.MapControllerRoute(name: "Club",
  pattern: "Club/{clubname?}",
  defaults: new { controller = "Club", action = "Club" });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the Green's function $G(\mathbf{x},\xi)$, such that $\nabla^2G = \delta(\mathbf{x}-\xi)$ a) Consider a domain
$$D=[(x.y)|x\gt0,y\gt 0]$$
Let $\mathbf{x}=(x,y)$ and $\xi = (\xi_{x},\xi_{y})$.
Find the Green's function $G(\mathbf{x},\xi)$, such that $$\nabla^2G = \delta(\mathbf{x}-\xi), \mathbf{x}\in D$$
subject to
$$\frac{\partial G}{\partial x}(0,y,\xi)=0\space\space\space \text{for} \space\space\space y\gt0$$
and
$$G(x,0,\xi)=0\space\space\space \text{for} \space\space\space x\gt 0$$
b) Using part a), solve
$$\nabla^2{u}=0, \textbf{x} \in D$$
subject to $u$ tends to $0$ as $|\textbf{x}|$ tends to $\infty$
$$\frac{\partial u}{\partial x}(0,y)=h(y)\space\space\space \text{for} \space\space\space y\gt0$$
and
$$u(x,0)=g(x)\space\space\space \text{for} \space\space\space x\gt0$$
So i'm pretty sure we use the method of images for a). Let the source be $\xi=(\xi_{x},\xi_{y})$, then the image sources are $\xi_{1}=(-\xi_{x},\xi_{y})$,$\xi_{2}=(\xi_{x},-\xi_{y})$,$\xi_{3}=(-\xi_{x},-\xi_{y})$.
So we have $\nabla ^2 G=\delta ( \textbf x - \xi )+ \delta ( \textbf x - \xi_1 ) - \delta ( \textbf x - \xi_2 )- \delta ( \textbf x - \xi_3 )$
Therefore $G(\textbf x , \xi)=\frac1{2 \pi} \ln |\textbf x - \xi |-\frac1{2 \pi} \ln |\textbf x - \xi_1 |-\frac1{2 \pi} \ln |\textbf x - \xi_2 |+\frac1{2 \pi} \ln |\textbf x - \xi_3 |$
I am completely lost after this. How would I go about using this for solving b)?


text:
Q: how to select images randomly from oracle database using java i want to display images and their information randomly to the web pages. after every some period of time it should automatically change the images and view in the browser. how can i do that using java and oracle database
i just tried to create a timer and then try to call the below query but it doesn't work
SELECT  *
FROM    (
        SELECT  name
        FROM    employee
        ORDER BY
                dbms_random.value
        )
WHERE rownum <= 1000
& then in the timer run method i call this query like this .
  TimerTask task = new TimerTask(){
    public void run()
    {
     //execute the code for every 10 mins

       Timer timer = new Timer();

      timer.scheduleAtFixedRate(task, 0, 10 * 60 * 1000); // period is  10 mins

       try
      {

         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:
         @localhost:1521:orcl","Admin","secret");
         Statement st=con.createStatement();
         System.out.println("connection established successfully...!!");

         ResultSet rs=st.executeQuery("SELECT  *\n" +
  "FROM    (\n" +
   "        SELECT  name\n" +
     "        FROM    employee\n" +
    "        ORDER BY\n" +
   "                dbms_random.value\n" +
    "        )\n" +
   "WHERE rownum <= 1000");

     //   pw.println("
");
             while(rs.next())
             {

            System.out.println("
"+"Id :"+rs.getInt("name"));
             }
//         pw.println("
");
    }
    catch (Exception e){
        e.printStackTrace();
    }
}
    };

A: step 1 : fire SQL query to fetch id's from your image table
select image_id from ImageTable ;

step 2 : store id's values in some java list
ArrayList<Integer> IdList = new ArrayList<Integer>();
while(rs.next())
{
idList.add(rs.getString(1));
}

step 3 : write a function to generate random no from a given list
int randomIdMethod(ArrayList<Integer> idList)
{
// logic
return randomImageId;
}

step 4 : pass the id's list to random id generator method
step 5 : retrieve the random id returned from randomIdmethod
Strnig newQuery = "select image fom ImageTable where imageId=randomImageId" ;

step 6 : fetch the image from your image table passing the is as parameter


text:
Q: Git clone error "(gnome-ssh-askpass:11720): Gtk-WARNING **: cannot open display:" I got this error when I tried to clone a repo in bit bucket.

"(gnome-ssh-askpass:11720): Gtk-WARNING **: cannot open display:"

The command used is:
git clone https://user@bitbucket.org/repo.git scripts/

A: Run below command and then try again:
unset SSH_ASKPASS


text:
Q: Google Cloud Storage JSON API with JWT Token I'm trying to use the JSON API for Google Cloud Storage to retrieve a file from Google Cloud Storage. I am not allowed to use the SDKs. Is it possible to create a JWT from a ServiceAccount.json file and use the JWT to access files from Google Cloud Storage? I have a script in node.js that generates a JWT from the service account, but i'm not sure if the audience is right
const jwt = require('jsonwebtoken');
const serviceAccount = require('./serviceAccount.json');
const issuedAt = Math.floor(Date.now() / 1000);

const TOKEN_DURATION_IN_SECONDS = 3600;

let params = {
    'iss': serviceAccount.client_email,
    'sub': serviceAccount.client_email,
    'aud': serviceAccount.project_id,
    'iat': issuedAt,
    'exp': issuedAt + TOKEN_DURATION_IN_SECONDS,
};

let options = {
    algorithm: 'RS256',
    header: {
        'kid': serviceAccount.private_key_id,
        'typ': 'JWT',
        'alg': 'RS256',
    },
};

let token = jwt.sign(params, serviceAccount.private_key, options);
console.log(token);

I then use that JWT to call the Google Cloud Storage JSON API:
https://www.googleapis.com/storage/v1/b/test
Using the header: Authorization Bearer {token}
That simply resulted in a Invalid Credentials response.
A few questions:

*

*I'm not sure what the 'aud' should be when creating the JWT. I've seen examples where it's a url and also where it's the projectId. Neither work for me.

*One of the JSON API examples said the Authorization token should be an oauth token. Can I use a JWT instead or do I need to make a call using the JWT to get an access token?

*Is my bucket path correct? Is the base folder for the bucket path your projectId? Should my path be /{projectId}/test. I've tried both and neither work.

Recap
This is an IoT project and I need embedded devices to download files from Google Cloud Storage. I need to create a web portal to upload files to (using Firebase Functions) and pass to the device either a bucket path or a private/signed URL that. The bottom line being I need to access a Google Cloud Storage bucket using a service account key. If there is an embedded SDK - great, but I couldn't find one for C. My only thought was to use the JSON API. If there is a way I can sign a URL which can only be accessed using a service account - that works too.
Thanks!

A: Yes, you can create your own Signed JWT from a service account Json (or P12) file and exchange the JWT for an Access Token that you then use as Authorization: Bearer TOKEN
I have written a number of articles on how to use Json and P12 credentials.
Google Cloud – Creating OAuth Access Tokens for REST API Calls
For your questions:

I'm not sure what the 'aud' should be when creating the JWT. I've seen
  examples where it's a url and also where it's the projectId. Neither
  work for me.

Set aud to "https://www.googleapis.com/oauth2/v4/token"

One of the JSON API examples said the Authorization token should be an
  oauth token. Can I use a JWT instead or do I need to make a call using
  the JWT to get an access token?

Some APIs accept signed JWTs, others expect an OAuth Access Token. It is just easier to always obtain the OAuth Access Token. In my example code below, I show you how.

Is my bucket path correct? Is the base folder for the bucket path your
  projectId? Should my path be /{projectId}/test. I've tried both and
  neither work.

Your url shold look like this (Python string building example)
url = "https://www.googleapis.com/storage/v1/b?project=" + project

Below I show you how to call two services (GCE and GCS). Most Google APIs will follow similar styles for building the REST API urls.
From the code in your question, you are missing the last step in the OAuth process. You need to exchange your Signed JWT for an Access Token.
def exchangeJwtForAccessToken(signed_jwt):
        '''
        This function takes a Signed JWT and exchanges it for a Google OAuth Access Token
        '''

        auth_url = "https://www.googleapis.com/oauth2/v4/token"

        params = {
                "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
                "assertion": signed_jwt
        }

        r = requests.post(auth_url, data=params)

        if r.ok:
                return(r.json()['access_token'], '')

        return None, r.text

Here is a complete Python 3.x example that will list GCE instances. Below this code are changes to display GCS Buckets.
'''
This program lists lists the Google Compute Engine Instances in one zone
'''

import time
import json
import jwt
import requests
import httplib2

# Project ID for this request.
project = 'development-123456'

# The name of the zone for this request.
zone = 'us-west1-a'

# Service Account Credentials, Json format
json_filename = 'service-account.json'

# Permissions to request for Access Token
scopes = "https://www.googleapis.com/auth/cloud-platform"

# Set how long this token will be valid in seconds
expires_in = 3600   # Expires in 1 hour

def load_json_credentials(filename):
    ''' Load the Google Service Account Credentials from Json file '''

    with open(filename, 'r') as f:
        data = f.read()

    return json.loads(data)

def load_private_key(json_cred):
    ''' Return the private key from the json credentials '''

    return json_cred['private_key']

def create_signed_jwt(pkey, pkey_id, email, scope):
    '''
    Create a Signed JWT from a service account Json credentials file
    This Signed JWT will later be exchanged for an Access Token
    '''

    # Google Endpoint for creating OAuth 2.0 Access Tokens from Signed-JWT
    auth_url = "https://www.googleapis.com/oauth2/v4/token"

    issued = int(time.time())
    expires = issued + expires_in   # expires_in is in seconds

    # Note: this token expires and cannot be refreshed. The token must be recreated

    # JWT Headers
    additional_headers = {
            'kid': pkey_id,
            "alg": "RS256",
            "typ": "JWT"    # Google uses SHA256withRSA
    }

    # JWT Payload
    payload = {
        "iss": email,       # Issuer claim
        "sub": email,       # Issuer claim
        "aud": auth_url,    # Audience claim
        "iat": issued,      # Issued At claim
        "exp": expires,     # Expire time
        "scope": scope      # Permissions
    }

    # Encode the headers and payload and sign creating a Signed JWT (JWS)
    sig = jwt.encode(payload, pkey, algorithm="RS256", headers=additional_headers)

    return sig

def exchangeJwtForAccessToken(signed_jwt):
    '''
    This function takes a Signed JWT and exchanges it for a Google OAuth Access Token
    '''

    auth_url = "https://www.googleapis.com/oauth2/v4/token"

    params = {
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion": signed_jwt
    }

    r = requests.post(auth_url, data=params)

    if r.ok:
        return(r.json()['access_token'], '')

    return None, r.text

def gce_list_instances(accessToken):
    '''
    This functions lists the Google Compute Engine Instances in one zone
    '''

    # Endpoint that we will call
    url = "https://www.googleapis.com/compute/v1/projects/" + project + "/zones/" + zone + "/instances"

    # One of the headers is "Authorization: Bearer $TOKEN"
    headers = {
        "Host": "www.googleapis.com",
        "Authorization": "Bearer " + accessToken,
        "Content-Type": "application/json"
    }

    h = httplib2.Http()

    resp, content = h.request(uri=url, method="GET", headers=headers)

    status = int(resp.status)

    if status < 200 or status >= 300:
        print('Error: HTTP Request failed')
        return

    j = json.loads(content.decode('utf-8').replace('\n', ''))

    print('Compute instances in zone', zone)
    print('------------------------------------------------------------')
    for item in j['items']:
        print(item['name'])

if __name__ == '__main__':
    cred = load_json_credentials(json_filename)

    private_key = load_private_key(cred)

    s_jwt = create_signed_jwt(
            private_key,
            cred['private_key_id'],
            cred['client_email'],
            scopes)

    token, err = exchangeJwtForAccessToken(s_jwt)

    if token is None:
        print('Error:', err)
        exit(1)

    gce_list_instances(token)

To display GCS Buckets instead, modify the code:
# Create the HTTP url for the Google Storage REST API
url = "https://www.googleapis.com/storage/v1/b?project=" + project

resp, content = h.request(uri=url, method="GET", headers=headers)

s = content.decode('utf-8').replace('\n', '')

j = json.loads(s)

print('')
print('Buckets')
print('----------------------------------------')
for item in j['items']:
    print(item['name'])

A: I found this [Service account authorization without OAuth].(https://developers.google.com/identity/protocols/oauth2/service-account#jwt-auth
You can avoid having to make a network request to Google's authorization server before making an API call.
Available APIs are listed in https://github.com/googleapis/googleapis.
It looks like Google Cloud Storage api is not yet published as per the comments in the repository.
Were you able to use the cloud storage API with JWT?


text:
Q: Cannot find module 'gulp-util' I have some trouble with gulp. I use laravel/elixir which has gulp as its dependency. I did the steps like here Can't get Gulp to run: cannot find module 'gulp-util' but still no success. Actually the gulp-util files are inside the node_modules folder...

Anyway I'm using Xubuntu 17.04 64bit if it counts.

A: I had the same problem, and tried almost everything.
But then I realized that the error does not point to the local gulp in the respective project but to the global one (/usr/lib/nodejs/gulp/...).
What solved the problem for me was to update that respective gulp:
sudo npm install -g gulp

I am not sure if it is in general correct that the global gulp is used or if the one of the project should be used instead. But at least for now I was able to solve the problem with that.
Hope it helps.


text:
Q: tmux: Remapping keys to pane on the left/right/top/down Tmux allows one to move through panes using Ctrl-b + (→, ←, ↑, ↓).
I would like to remap this to:
Ctrl-b + Ctrl-(l, j, i, k).
For reference, the layout of the keys l,j,i,k is similar to that of the arrow keys, but they are easier to type without moving the hand.
I have been editing a few things here and there on the .tmux.conf, but I could not find information on how to rebind the above commands.

A: If you want to stick to vim-like navigation, would be useful to remap the resize-pane also:
# vim-like pane resizing
bind -r C-k resize-pane -U
bind -r C-j resize-pane -D
bind -r C-h resize-pane -L
bind -r C-l resize-pane -R

# vim-like pane switching
bind -r k select-pane -U
bind -r j select-pane -D
bind -r h select-pane -L
bind -r l select-pane -R

# and now unbind keys
unbind Up
unbind Down
unbind Left
unbind Right

unbind C-Up
unbind C-Down
unbind C-Left
unbind C-Right

I'll show you my .tmux.conf as a reference
And by the way, don't forget to remap the 'horizontal-split' in case you have it on the h key as it will interfere with your pane-resize and pane-switch.

A: tmux list-keys (or prefix + ? in dfault settings) will give you current key mappings in the form of commands needed to set them up. See man tmux, the command name is bind-key (and you might want to remove the default bindings with unbind-key).
You might also want to consider more "standard" combination hjkl, known from vi and clones (all keys in the home row), especially if you are a fast typist.


text:
Q: How to implement autocomplete with top K suggestions algorithm? This is a question for an interview: Write a program to implement autocomplete for a given set of N strings and positive weights. That is, given a prefix and an integer k, find the top k strings in the set among those that start with the prefix.
And I found a suggested algorithm here with ternary search tree and max heap: http://www.cs.princeton.edu/courses/archive/fall13/cos226/checklist/autocomplete.html
I kinda get the algorithm but I have no idea how to print out the top K words. One biggest confusion I have is: we can traverse the tree and get all the nodes with max weights, but how do we go back and get the words together?
Any help is appreciated.


text:
Q: Android and databases I'm writing my first Android app and I came to a moment when I need to store users and other data. What is a good practice of doing it? To my surprise I wasn't able to find one good solid manual online. Can you share your experience please?

A: *

*Use MySQL database.

*Use PHP script to store data.

*Use Android Volley or Http request to perform storing the data.

Follow this tutorial .

A: It depends on where you will want to access this data from at a later time.  For example you might want your app to allow User Preferences to be synchronized between multiple devices.  You might want the settings to stay with only that device... you need to make that decision first before choosing from the below options.
Please read this Android documentation first before going further.
Some options (not exhaustive):

*

*Store locally on the device.
a.  Write to a file.  Serializable files are great for storing data structures from memory for easy re-use.
b.  Use a local DB service one option, official Android SQL documentation,
c. Store Key-Value sets

*Store on a server for access from more than 1 device.
a. SQL servers run by your company
b. Google Drive
These options are just the beginning.  You need to refine your question with a bit more background information (purpose of your app, how users will interact with it, etc) before you will get a detailed answer.

A: I highly reccomend using an existing cloud database solution instead of creating your own web server solution.
Check out Firebase Realtime Database. I think you'll find that it will provide a clean and simple solution.
https://firebase.google.com/docs/database/
https://firebase.google.com/features/
(Btw, Firebase is a Google product, so you'll get really good support and documentation.)


text:
Q: Csv Files & Java Searching through google didn't help me out.
I've got a csv file [called dataset.csv] which has many rows of information, using a "," delimeter.
The information is about businesses [name of business, type etc.]. On the very first row there are the categories:

[city,review_count,rating,name,full_address,type,categories/0,categories/1,
  working_days,working hours,max_reservations] = 11 of them.

But not a single row has all 11 of these information.
Example of 2 rows :

Fountain Hills, AZ 85268",business,Bars,American (New),2,9:00-17:00,15
Gilbert,8,2,Salon Lola,"3479 E Baseline Rd

Some information is missing, not the same though in each row. There are a few that has all of these 11 infos given.
I would like to understand somehow the way to read this csv file, and see, if its possible , where the info is empty , to put a null or something.
Thanks in advance and sorry for possible vocabulary and grammar mistakes !

A: The two rows look to be actually two pieces of a single row, if you take the following
Fountain Hills, AZ 85268",business,Bars,American (New),2,9:00-17:00,15

Gilbert,8,2,Salon Lola,"3479 E Baseline Rd

and add the bottom row to the top row you get the following
Gilbert,8,2,Salon Lola,"3479 E Baseline Rd Fountain Hills, AZ 85268",business,Bars,American (New),2,9:00-17:00,15

[city, review_count, rating, name, full_address, type, categories/0, categories/1, working_days, working hours, max_reservations]

Which lines up with the column descriptors at the beginning of the file, 11 for 11. It's weird to have the second row be the start of the first row but this would be my best guess as to why it looks like rows are missing column values.
I would bet that if you find the first occurrence of your incomplete rows the first one is the start and the second on is the other half. Instead of the example you gave us which might in fact be a second half of a previous row and the first half of the next row.


text:
Q: How to transform problem to convex optimization problem? I have the following problem
$$min \{ x^TAx + 2b^Tx + c : \|x\|_2 <=1
\}$$
where $$A \in R^{n x n}, b \in R^n, c\in R$$
I need to show that this problem can be transformed to convex optimization problem.
What I did:
By Spectral decomposition theorem $$A = UDU^T$$ thus replacing it $$min \{x^TUDU^Tx + 2b^TUU^Tx + c : \|U^Tx\|_2 <=1 \}$$ where $$\|U^Tx\| = \|x\|$$.
By changing variable $$y=U^Tx$$ we will get $$y^TDy + 2b^TUy + c : \|y\|_2 <=1$$
how to proceed ? I want to have problem in form of the sum of matrix elements.


text:
Q: Is it possible to change the Class type of an object that has a different Class? For example I have these classes:

*

*MyGradientButton.h/.m

*RedGradientButton.h/.m (Inherits the MyGradientButton class with background color red)

Now, I have an instantiated object "buttonA" that has the characteristics of MyGradientButton class. However, is it possible later on to change "buttonA" class to RedGradientButton and acquire this new class characteristics which will turn the button into red?
If possible, let me know how. Thank you

A: No, you cannot change the type of a class after it's created.[1]
Best approach is typically to create a method which clones. The class variable in this case is typically the object you message.
A common example of this form is: [NSString stringWithString:s] against [NSMutableString stringWithString:s];.
Because you're dealing with a view, it is often easier to just define an internal type and use object composition. So you would not have a RedGradientButton type, but instead one MyGradientButton which has (for example) a characteristics member. Then you may create multiple characteristics types (if subclassing is really a good design).

[1] You could, but don't …if somebody tells you how it can be achieved. The reason: It's unsafe, and one approach is going away. Although you can set the class, which would update the methods, doing this would not modify other aspects of the object. The obvious case is that your object would not be resized or updated to reflect any difference in member layout, which means that when you message the object and it accesses members present in the subclass but not the superclass, your method's implementation would read or write to invalid memory (that's undefined behavior). Even if it appears to work or you have dynamically proven or done everything you can to ensure it is safe, modern runtimes use a non-fragile object ABI - the memory required by your base classes is free to change from one release to another. Such a design is open to other errors when resizing (leaks, memory which cannot be referenced, or memory 'initialized-at-type-conversion' to the data of another class). So even if you overcame the problem of allocation size, you would still need to devise a way to perform partial deallocation and partial initialization of your instance, in a way which leaves the object in a usable state -- quite complicated.

A: The acacemic answer is: "Yes you can".
The smarter answer is: "No you should not do that unless you understand very well what you are doing and can therefore justify yourself whether it is a good idea doing so".
If I were you then I would crate a new factory method for RedGradientButtion like +(instancetype) redGradientButtonWithMyGradientButton:(MyGradientButton*)myGradientButton;
This method could then instanciate a new RedGradientButton object and copy all relevant charachteristics of myGradientButton. Then, if you think that is a good idea, it could fetch myGradientButtons' superview, remove it from its superview and add the new RedGradientButton object instead of it.
Of course this would make all references to myGradientButton to refer to an unused (but with ARC still valid) Button object. You would have to update them.
You say that RedGradientButton inherits from MyGradientButton. That means that all classes which use MyGradientButton should continue working well - once the references have been updated of course.


text:
Q: Python Selenium - How to avoid the "switch_to_window()" function to steal focus? I have this. It's a Python programm to automate the download of documents from our intern company website. I used Webdriver Chrome.
For that, the Python Programm opens a first windows (0), gives the document number and then a second windows will open (1) to click on "print". To be sure that the system will interact with the right windows, I use the  switch_to_window().
Issue is that every time the function switch_to_window() is called, it steals the focus and If I'm (for example) typing an email in Outlook, it will steals the focus and my typing will come in the document number and then, the whole Selenium will definitely stops because the Document number can not be found since it's false.
Question: Is there a way to change the windows without stealing the Focus ?
def csv_print():
    global browser
    global h
    numm=0
    numm_1=0
    while numm<h:
        kalknum= browser.find_element_by_id("uc_1")
        searchkalk=browser.find_element_by_id("uc_2")
        kalknum.send_keys(user_entries[numm].get())
        searchkalk.click()
        fenetre.after(2000)

        window_before = browser.window_handles[0]

        open_kalk=browser.find_element_by_id("uc_12")
        open_kalk.click()
        fenetre.after(5000)

        window_after = browser.window_handles[1]
        browser.switch_to_window(window_after)

        element_to_hover_over=browser.find_element_by_id('uc_14')
        hover = ActionChains(browser).move_to_element(element_to_hover_over)
        hover.perform()

        element_to_hover_over2=browser.find_element_by_id('uc_15')
        hover2 = ActionChains(browser).move_to_element(element_to_hover_over2)
        hover2.perform()

        csv_dwd=browser.find_element_by_id("uc_16")
        csv_dwd.click()
        fenetre.after(5000)

        element_to_hover_over3=browser.find_element_by_id('uc_17')
        hover3 = ActionChains(browser).move_to_element(element_to_hover_over3)
        hover3.perform()

        kalk_close=browser.find_element_by_id("uc_18")
        kalk_close.click()
        fenetre.after(5000)

        browser.close()

        browser.switch_to_window(window_before)

        kalknum2= browser.find_element_by_id("uc_1")
        kalknum2.clear()
        fenetre.after(1)

        numm+=1
        numm_1+=1

Thank you !


text:
Q: Context_info value is null in trigger I want to get some value in trigger when its start executing. However getting the value using parameter option is not available in trigger. So I decided to store that particular value in one variable and pass it to Context_info in my stored procedure.
And I am getting that value in my trigger. But still I am getting null value only. But I tried manually by passing parameter to stored procedure, it is executed correctly and Context_info value is also showing correctly in that stored procedure.
But when I am getting this value in trigger it is showing NULL. And also in sys.dm_exec_sessions table context_info value is not getting updated but last_request_start_time and last_request_end_time is getting updated.
Can anyone please guide me to find my mistake where I am going wrong?
Here are my stored procedure and trigger:
ALTER PROCEDURE [dbo].[dm_ApptResRecurrReasonRelViewSel]
   (@IDLocation int,
    @IDApptResource int,
    @StartDate datetime,
    @IDApptResRecurr int,
    @ClientID varchar(50) )
AS
    SET NOCOUNT ON;

    DECLARE @context_info varbinary(100);
    SET @context_info = CAST(@ClientID as varbinary(100));

    SET CONTEXT_INFO @context_info;

     etc....

Trigger
ALTER TRIGGER [dbo].[xC2C_ADT_Upd]
ON [dbo].[dmAppt]
FOR INSERT, UPDATE
AS
BEGIN
    If Not Exists (Select top 1* from inserted)
       Return

    declare @ADT_ID UniqueIdentifier
    declare @personuid int
    declare @ApptID int

    select @personuid = PID, @ApptID = IDAppt
    from inserted

    set @ADT_ID = NewID()

    declare @MSG_Type varchar(1)
    declare @AddDate datetime
    declare @LastUpdateDate datetime
    declare @ServerID [varchar](50)
    declare @ClientDB [varchar](max)
    declare @ClientID [varchar](50)

    set @ServerID = Convert(varchar(50),CONNECTIONPROPERTY('local_net_address'))
    set @ClientDB = db_name()

    set @ClientID = CAST(CONTEXT_INFO() as varchar(50))


text:
Q: Javascript Table won't move I'd just like to say I am having a problem with moving a table across the page like I would with an image. However it is being problematic. I already know how to move a image in a circle using coordinates or using an equation. I tried applying the co-ordinates way on this, however, even though the table displays and hides properly, the table won't move at all.
<!DOCTYPE html>

    <title></title>

            Hello World,

                Please hit the close button to close this table.

All help is appreciated!
UPDATED CODE
Updated code due to ideas from answers.
Still have the same problem, still won't move.
UPDATED CODE and EDIT #2
Okay, so it sorta moves, however not in the way I would like it to. I want it to be continuous and only activate on one mouse-over (if that makes sense). Right now, I have to do multiple mouse-overs to make it move.

A: <!DOCTYPE html>

    <title>...</title>

I rip off some of the code to focus on the staffs that form my answer ;)

A: If you want to move the table linearly, you can use CSS3 tansform properties and not necessarily javascript to accomplish that.
e-g:
 #tblFormat:hover{transform:translateX(250px);}

Will move your element with id tblFormat in X axis to a distance of 250px on hover.

A: One thing I noticed is that you have the if (playing == false) statement. So after the first time you hovered on the start button, the value of playing is changed to true. Then the code inside if (playing == false) will never get a chance to run.

A: Your table with class auto-style1 needs to have position: relative, absolute or fixed to respect the left property. This is the root cause; other issues may be present that prevent the table from moving exactly how you want.


text:
Q: Error page registrar and Global exception handling I am creating a Spring Boot web application, but i am confused why people use Global Exception handlers(@ControllerAdvice) when there is Error Page Registrar which is neater and more explicit. Please can someone explain more and is it possible to call an Error page registrar from a global Exception Handler Class( class annoted with @ControllerAdvice, with an @Exceptionhandler method).

A: As Brian answer, I think you can do this. I got a sample to prove this one in here if you still need to refer:  https://github.com/kennytai/SampleSpringbootExceptionHandler
At this sample, I use the @ControllerAdvice in class GlobalExceptionHandler to manage all exceptions from TestController.
Hope this help.

A: It's actually the opposite the error pages mechanism in Spring Boot is the global one; it's catching all exceptions unhandled by the application. Note that in a Servlet environment, it's even dispatching the request back into the container on the /error path.
You're right though, this mechanism is really powerful and you can achieve a lot with it.
The other exception handling mechanisms you're mentioning are provided by Spring MVC itself. They're executed during the handling of the request and don't require an additional dispatch to the container. In some cases, they can be more limited because they offer less features than the full ErrorController (which is an MVC Controller).
But unlike error pages, you can configure those to focus on only specific errors:

*

*You can declare an @ExceptionHandler within a Controller and specify the type of Exception you'd like to handle

*You can configure the @ControllerAdvice annotation to only apply to specific packages, Controllers extending a specific interface or annotated with a specific annotation

I'd say the latter are quite useful when you want to deal with business exceptions at the controller level. You can do that with error pages, but you might end up with a single error controller dealing with too many things.


text:
Q: Checking for a phrase within a string - Java String serverNamePercentage = "http://&askldjsakldjskadjlsajdklsajdlsjakldsjakldjsakl";

How do i check in that string that it starts with a "http://&"?
EDIT:
nevermind, i actually phrased my question wrongly. I wanted a method to check if the string contains "http://&" , not starts with it . i  just used
if ( myString.indexOf( "http://&" ) > -1 ) {
  //yes
 }

A: if(serverNamePercentage.startsWith("http://&")) {
   ...
}

Javadocs for String are your friends. Here's the documentation for String#startsWith(String).
EDIT
The reason you got downvoted on your question is because you didn't look up the Javadocs for String first. Your first step as a Java programmer should always be to look up the Javadocs. A quick google search would have also given you your answer.

A: Try
if (serverNamePercentage.startsWith("http://&")) {
    // yes, it does.
}


text:
Q: Second HDD with Ubuntu causes Windows to "searching preconfigured driver folders" indefinitely I normally use Windows 7 and recently got a new HDD to install Ubuntu with. I was able to boot windows by default and switch to Ubuntu by manually choosing the booting hard disk. This was all fine until the Ubuntu disk failed*, and it has not even been one month since I purchased it.
*It stopped showing up on the boot devices dialog one day and attempts to change sata cables, sata ports, use an enclosure, using 2 other different pcs all failed to pick up the disk.
I now have a replacement hard disk up and running the same way, but I am paranoid that I am doing something that is causing the hardware to fail somehow.
I have just booted into windows the first time after this replacement hdd was loaded with Ubuntu, and I am seeing this box:

It's been doing this for a while now. Can this be in any way damaging to the hard disk?


text:
Q: Regularization of Logistic Regression coefficients in MATLAB I'm trying to implement a Logistic Regression with regularization (either L1 or L2). The mnrfit() function does not implement regularization. Is there any built-in function that can do the regularization or do I have to roll my own regularization code?
If so, are there any tutorials that I can look at? The papers I have been looking at are rather mathematically dense.

A: Liblinear was the standard we used.
http://www.csie.ntu.edu.tw/~cjlin/liblinear/

A: L1 as well as L2 regularization are very easy to implement.
L1 regularization works by subtracting a fixed amount of the absolute value of your weights after each training step. So with an L1 regularization coefficient of e.g. 0.01,  your weights (1.0, -2.0, 3.0) would become (0.99, -1.99, 2.99).
L2 regularization works by subtracting a percentage of your weights. With a coefficient of 0.01, this means multiplying your weight vector by 1. - 0.01 = 0.99. The weights (1.0, -2.0, 3.0) would become (0.99, -1.98, 2.97). This is also known as weight decay.
As you can see, L1 regularization pulls small weights towards 0. L2 regularization on the other side has almost no effect on small weights but drastically reduces large weights.


text:
Q: BorderLayout orientation I'm trying to create the top buttons of a window. I have a JFrame and a JPanel with the differents buttons when I try to add the panel with the buttons to a JPanel on the frame, it doesn't show... digging and trying to find the solution, I realize that the issue is when I set the orientation to the panel with the buttons on the BorderLayout panel. I think that it might be something dumb that I haven't realize but I haven't found any issue like this.
The issue is here when I set the orientation:
contentPanel.add(buttons,BorderLayout.PAGE_START);

if I remove the:
BorderLayout.PAGE_START

it works
This is my Frame:
package view;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.Color;
import java.awt.CardLayout;
import java.awt.BorderLayout;

public class MainFrame extends JFrame{
 private JPanel contentPanel, layOutPanel;
 private CardLayout mainCardLayout;
 private BorderLayout borderLayout;
 private static MainFrame instance = null;
 private FrameButtonsPanel buttons;

private MainFrame(){
 setSize(1000,700);
 //setUndecorated(true);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 contentPanel = new JPanel();
 borderLayout = new BorderLayout();
 contentPanel.setLayout(borderLayout);
 add(contentPanel);

 buttons = new FrameButtonsPanel();
 buttons.setBackground(Color.red);
 contentPanel.add(buttons,BorderLayout.PAGE_START);

 /*layOutPanel = new JPanel();
 mainCardLayout = new CardLayout();
 layOutPanel.setLayout(mainCardLayout);
 layOutPanel.setBackground(Color.red);
 contentPanel.add(layOutPanel,BorderLayout.SOUTH);*/
}

 public static MainFrame getInstance(){
  if (instance == null){
   instance = new MainFrame();
  }
  return instance;
 }

  public static void main(String[] args) {
   MainFrame.getInstance().setVisible(true);
  }
 }

and this is my panel with the buttons:
package view;

import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.Spring;
import javax.swing.JButton;
import javax.swing.JFrame;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

 public class FrameButtonsPanel extends JPanel{
 private Spring spring;
 private JButton iconify, maximize, close;

  public FrameButtonsPanel(){
   SpringLayout mySpring = new SpringLayout();
   setLayout(mySpring);

  iconify = new JButton("-");
  add(iconify);
  maximize = new JButton("O");
  add(maximize);
  close = new JButton("X");
  add(close);

  spring = Spring.constant(850,850,2000);

mySpring.putConstraint(SpringLayout.WEST,iconify,spring,SpringLayout.WEST,this);
mySpring.putConstraint(SpringLayout.WEST,maximize,3,SpringLayout.EAST,iconify);
mySpring.putConstraint(SpringLayout.WEST,close,3,SpringLayout.EAST,maximize);
mySpring.putConstraint(SpringLayout.EAST,this,3,SpringLayout.EAST,close);

iconifyWindow();
maximizeWindow();
closeWindow();
}

 private void iconifyWindow(){
  iconify.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent arg0) {
        MainFrame.getInstance().setExtendedState(JFrame.ICONIFIED);
     }
   });
 }

 private void maximizeWindow(){
  maximize.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
    if(MainFrame.getInstance().getExtendedState() == JFrame.MAXIMIZED_BOTH){
        MainFrame.getInstance().setExtendedState(JFrame.NORMAL);
    }else{
        MainFrame.getInstance().setExtendedState(JFrame.MAXIMIZED_BOTH);
    }
        }
     });
  }

private void closeWindow(){
  close.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);
        }
    });
 }
}

A: I have no  idea why you are trying to use a SpringLayout to display buttons.
Just use a JPanel with a right aligned FlowLayout.
Read the FlowLayout API for more information on how to right align the components added to the panel.


text:
Q: Would it be possible to write a parser generator for the Zend/PHP engine? Out of curiosity, having been studying a few parser generator libraries (Flex, Bison, ANTLR, some LLVM related stuff), would it be possible to write a new parser generator for a pre-existing scripting language's engine such as PHP? I realize Facebook has basically done it except they wrote a whole new virtual machine to address issues they had with the Zend engine (?).
I've been able to create a few toy compiler examples for compiled VMs such as the JVM by generating the opcodes for a basic syntax and learning a lot of the JVM's class file structures and opcodes.
What intrigues me though is whether it's possible to replace Zend's PHP parser with your own without having to edit the core of the engine.
I ask this simply out of curiosity since I think it'd be an enjoyable little product to try work on some Zend/PHP engine languages that aren't source-to-source.


text:
Q: Printing individual letters in a list I am writing a program that takes a statement or phrase from a user and converts it to an acronym.
It should look like:
Enter statement here:
> Thank god it's Friday
Acronym : TGIF

The best way I have found to accomplish this is through a list and using .split() to separate each word into its own string and am able to isolate the first letter of the first item, however when I try to modify the program for the following items by changing to print statement to:
print("Acronym :", x[0:][0])
it just ends up printing the entirety of the letters in the first item.
Here's what I have gotten so far, however it only prints the first letter of the first item...
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()

x = acroPhrase.split(" ")
    print("Acronym :", x[0][0])

A: Using re.sub with a callback we can try:
inp = "Peas porridge hot"
output = re.sub(r'(\S)\S*', lambda m: m.group(1).upper(), inp)
print(output)  # PPH

A: The code needs to iterate through the .split result. For example, using a list comprehension:
inp = "Thank god its friday"
inp = inp.split()
first_lets = [word[0] for word in inp]

A: acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()

x = acroPhrase.split(" ")
result = ''
for i in x:
    word = list(i)
    result+=word[0]

print(result)


text:
Q: Determining whether a function is injective or surjective in a certain range I ran into this question while preparing for an exam:

Let f : [1, 3] → [0, 2] be the function defined by
f(x) = ln x
for all x ∈ [1, 3]. Determine whether or not this function is injective
and whether or not it is surjective

I understand what injective (one-to-one) and surjective (onto) are but I don't know where to start to show surjectivity and the specified range is confusing me also as I know functions alone can't be injective, bijective, or surjective as it is dependant on the range
This is my attempt so far to show injectivity but I am not sure it is correct:
y=logx is injective.
x1=x2⟹logx1=lnx2
logx1=logx2⟹x1=x2
This is the graph I obtained from desmos:

Any help would be appreciated thank you!

A: We assume that the properties of the function $\ln:\mathbb R^{+*}\to \mathbb R$ are known.
Then your proof for injectivity is correct.
For surjectivity, thanks to the remarks that have been made to you, rather than a simple graphical reading or the use of the calculator, as you are interested in proofs, I suggest this one:
$2\in [0,2]$. Let us prove that there is no element $x\in [1,3]$ such that $\ln(x)=2$. As the funtion is an increasing function, it suffices to show that $2>\ln(3)$.
$e>2$. So, $e^2>4>3.$ So, $\ln(e^2)>\ln(3)$, i.e. $2>\ln(3)$. Q.E.D.


text:
Q: Change the size of a GroupBox I am new in Qt and C ++, I have a code and I want to change it, when I open the file .ui  i find a GroupBox , I tried to change its size in the interface but it does not work, I tried to change it in the code but I can't find it, is that normal that it is in the interface and not in the code? and how to change it if it does, I expect your help and thank you.

A: i use that code and it work:
ui->groupBox->setMinimumSize(QSize(0,0));
ui->groupBox->setMaximumSize(QSize(10000,10000));
ui->groupBox->setGeometry(9,707,810,450);


text:
Q: How to click on doughnut Chart using selenium? I'm a trainee and trying to write a test using selenium in C# which clicks on a clickable chart and then this leads to another page. But the action doesn't work. I have also tried using JS.Executor to call a function in JavaScript, but that doesn't work either.
I have tried all possible ways i have found.
It would be nice if someone could help me.
Thank you very much in advance
Here is my chart:

var obj = driver.FindElement(By.Id("someID"));
switch (chart)
{
    case string year when year.Contains("2020"):

        new Actions(driver).MoveToElement(obj).MoveByOffset(68, 120).Click().Build().Perform();
        //IJavaScriptExecutor exe = (IJavaScriptExecutor)driver;
        //exe.ExecuteScript("arguments[0].click()",obj);
        //exe.ExecuteScript("window.document.elementFromPoint(68, 120).click()");
        //exe.ExecuteScript("javascript:window.document.elementFromPoint(68, 120).click()");
        //new Actions(driver).MoveToElement(obj).MoveByOffset(68, 120).Click();
        //((IJavaScriptExecutor)driver).ExecuteScript("javascript:clickAtChart();");
        //((IJavaScriptExecutor)driver).ExecuteScript("clickAtChart();");
        //((IJavaScriptExecutor)driver).ExecuteScript("clickAtChart(arguments[0],arguments[1]);","#circural_1","2020");
        break;

    case string year when year.Contains("älter"):
        new Actions(driver).MoveToElement(obj).MoveByOffset(68, 120).Click().Build().Perform();
        break;

    case string year when year.Contains("2019"):
        new Actions(driver).MoveToElement(obj).MoveByOffset(68, 120).Click().Build().Perform();
        break;

    case string year when year.Contains("2021"):
        new Actions(driver).MoveToElement(obj).MoveByOffset(68, 120).Click().Build().Perform();
        break;
}

here is my code and everything i have tried. none of them work properly
and this is the function i've tried to call.
function clickAtChart(lable, locationID) {
    //var lable = "2020 (58.99 % | 164 )";
    //var locationID = "#circular_1";

    var interval = "";
    if (locationID === '#circular_1') {

        interval = 'YEAR_ONLY';
        var sqlOperator = '%3D';// %3D is a escaped for '='
        var Now = moment();
        var currentYear = new Date().getFullYear();
        var diff = 0;
        lable = lable.substring(0, 4);

        if (lable === "Älte" || lable === "Olde") {
            interval = 'YEAR';
            sqlOperator = "<";
            diff = -2;
        }
        else if (lable === (currentYear - 2).toString()) {
            diff = -2;
        }
        else if (lable === (currentYear - 1).toString()) {
            diff = -1;
        }
        else if (lable === (currentYear).toString()) {
            diff = 0;
        }
        else {

            var yearString = lable.substring(11, 15);
            var year = moment([yearString]);
            diff = year.diff(Now, 'days');
            interval = 'DAY';
            sqlOperator = '%3C'; //%3C is a escaped for '>'
        }

        window.location.href = DashboardUrlSettings.IndexForChart + '/?number=' + diff + '&interval=' + interval + '&sqlOperator=' + sqlOperator;

    }
    else if (locationID === '#circular_2' || locationID === '#circular_3') {
        var day = lable.substring(0, 4);

        var number = 0;
        var numberTo = 0;
        interval = 'DAY';
        var betweenSearch = false;
        var dateColumn = 'schadendatum_sch';

        if (day === "> 60") {
            number = -60;
            sqlOperator = '%3C'; //%3C is a escaped for '<'
        }
        else if (day === "30 -") {
            number = -30;
            numberTo = -60;
            betweenSearch = true;
        }
        else if (day === "< 30") {
            number = -30;
            sqlOperator = '%3E'; //%3C is a escaped for '>'
        }

        if (locationID === '#circular_3') {
            dateColumn = 'oasis_kommdokumente.sortdatum_d';
        }

        window.location.href = DashboardUrlSettings.IndexForChart + '/?number=' + number + '&numberTo=' + numberTo + '&interval=' + interval + '&betweenSearch=' + betweenSearch + '&sqlOperator=' + sqlOperator + '&dateColumn=' + dateColumn;
    }
}


text:
Q: The button of a Android project simply does not work I am developing a small project of test, and I wrote the following code. I already created in the xml file, a button with id called "registerBtn".
I erased the imports of this source code to shorten space of this source code.
In the java file, I created a variable called mRegisterBtn, in the type of Button. Inside the method called onCreate(Bundle savedInstanceState) the mRegisterBtn receives the method called findViewById(R.id.registerBtn);
However, in the mRegisterBtn.setOnClickListener, the part of new View.OnClickListener appears in gray color, and it is not working when trying to test this code.
This image shows what I really mean. Please, perceive that the the part of new View.OnClickListener appears in gray color. It means a error. But trying to compile, this code runs, but the button simply does not work.
There is no error message in the Logcat.
The Java Lambda expression also does not work.
The button simply does not work.
Can anyone know how to fix this error, please?

```
public class Register2 extends AppCompatActivity {

    Button mRegisterBtn;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register2);

        mRegisterBtn = findViewById(R.id.registerBtn);

        mRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Testing", Toast.LENGTH_LONG).show();
            }
        });
    }
}```

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#007FFF"
        tools:context=".Register">

        <Button
            android:id="@+id/registerBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/white"
            android:text="Register"
            android:textColor="@color/black"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.499" />
    </androidx.constraintlayout.widget.ConstraintLayout>```


text:
Q: About Previewing an Image in Angular <img [src]="imageInput" alt="" width="100%">
<input type="file" (change)="onChange($event)" accept="image/*">

onChange(event: any) {
    this.imageInput = event.target.files[0];
    let reader = new FileReader();

    reader.onload = (e: any) => {
        this.imageInput = e.target.result;
    }

    reader.readAsDataURL(event.target.files[0]);
}

So here is my code in angular. My problem is that every time I will upload and preview an image. There's this "GET http://localhost:4200/[object%20File] 404 (Not Found)" that keeps on showing in my console log.

A: Initially imageInput is null, so you can get rid of the message with an ngIf like this:
<img *ngIf="imageInput" [src]="imageInput" alt="" width="100%">

Check it here.

A: you just need to delete this line
this.imageInput = event.target.files[0];


text:
Q: Unable to insert data into database (PHP MVC) I want to allow people to submit their contacts by entering it into a field and it would eventually send it to the database but been trying it for quite some time and cant find out whats wrong with it, if possible do let me know how to return a echo saying "SENT" when its in database. Redirecting to the same page, if possible , dont even need a refresh to get that SENT shown to people.
This is my Controller
  $this->config->db_config_fetch();
$this->load->model('skills_model');

//Get Form Data
$this->input->post('submitsms')  ;
//GEt phone number from field
$type = $this->input->post('phonenumber');
//Call model
$this->skills_model->addsms($type);
}

This is my View @ home page
    <form method="post" action="<?php echo site_url(''); ?>" name="form"  enctype="multipart/form-data">
  <label>SMS Subscription</label>
  <input type="text" name="phonenumber" placeholder="Phone Number here">
  <button class="btn btn-info" name="submitsms"  type="submit">Subscribe</button>
  </form>

This is my Model
function addsms($type){
     $this->db->set('number', $type);
     $this->db->insert('subscribers');
 }

I also tried the following
function addsms($type){
    $sql = "INSERT INTO 'subscribers' ('number') VALUES ($type)";
    $this->db->query($sql);
    echo $this->db->affected_rows();
 }

You advice would be of a great help! thank you!

A: A small example ...........
View file
<form action="<?php echo ROOT_FOLDER ?>/add_price" method="post">

<input type="text" class="text" name="amount" value="<?php echo set_value('amount'); ?>" />

<input type="submit" class="submit" value="Approve" />
</form>

Controller...........
public function post_add_price()
{
  $data = array(
'amount'=>$this->input->post('amount'),
 );
$this->model->add_amount($data);  //sending amount to model to insert in dataabse
echo "Amount added to database";
}

Model................
public function add_amount($data)
{
    $this->insert_helper('order_amount_table',$data);
}

public function insert_helper($table_name, $data_array){
    $this->db->insert($table_name,$data_array);
    return $this->db->insert_id();

}

I hope this example will help you .........if you have any doubts ask


text:
Q: Return double from vector multiplication with Armadillo C++ Do you know why I cannot store in a double the result from a vector multiplication ?
double A = rowvec({1,3,4})*vec({5,6,7});

It gives "no suitable conversion function from "const arma::Glue"... to "const double" exists.
Still that matrix vector multiplication gives a double.
How can I get around ?
Thank you!

A: The result of the product is an expression template called arma::Glue which can be converted to a 1x1 matrix.  To do this inline and assign it to a double evaluate it explicitly using .eval() and take the only element which is (0,0).
#include <armadillo>

int main() {
  using arma::rowvec;
  using arma::vec;
  double A = (rowvec({1,3,4})*vec({5,6,7})).eval()(0,0);
};

N.B.: Did you mean dot(a,b)?
#include <armadillo>

int main() {
  using arma::rowvec;
  using arma::vec;
  using arma::dot;
  double A = dot(rowvec({1,3,4}), vec({5,6,7}));
};


text:
Q: Add custom labels to http_server_requests_seconds_bucket metric in Spring boot I'm currently working on a Spring boot (Spring webflux) project where we have exposed metrics of our application on /actuator/prometheus endpoint. We have added spring boot actuator dependency which by default gave us the http_server_requests_seconds_bucket metric. By default it has {exception="None",method="POST",outcome="SUCCESS",status="200",uri="/test",le="0.268435456",} labels. I want to add another label say "challenge" which depends on the request payload. For example, my request payload looks like this,
{
 "type" : "basic",
 "method" : "someMethod"
}

I want to add a label within that metric as, http_server_requests_seconds_bucket{exception="None",method="POST",outcome="SUCCESS",status="200",uri="/pos/authenticate",le="0.268435456",     challenge="basic"} which is based on the request payload "type" parameter. Can someone please help with this
Note: We only allow limited number of values for "type"


text:
Q: Reactjs with Aurelia I'm looking for some help with using ReactJS with Aurelia.  I went to http://ilikekillnerds.com/2015/03/how-to-use-react-js-in-aurelia/ page, which seems to be the only page on google that talks about it but his method did not work for me.  I am trying to full understand how to integrate the two.  If anyone has done this already or has a working example that I can try to figure out that would be amazing.  Any help at this point is greatly appreciated.

A: Please see some example code here on Github. You can also view a live demo here (using the code in the linked repository). More strategies for using React with Aurelia will be added over time. For now, things are basic, but the code explains more than the aforementioned blog post (which will also be updated).


text:
Q: A word or short phrase meaning "the pleasure taken in being different and misunderstood" Is there a word or short phrase for this? I have a cell in the back of my head insisting that it's "[something] pain".
The person who feels this way tries to wear their outcast status as a badge of honor, without letting other people realize that they are trying to do so. They are quietly trying to get themselves compared with those great geniuses of history who just wanted to fit in but, because of their genius, could not.

A: You want to highlight this poseur's objectionable affectation?  We've got a lot of words for inauthenticity.
How contemptuous do you want to be?
To say he's an aspiring outcast suggests, to me, that the harm is relatively minor.
To say he's a professional outcast underscores the artifice of his behavior with a little more irony.

A: I think that in the context you are describing
masochist , with the following connotation, may fit:

*

*(In general use) the enjoyment of what appears to be painful or tiresome:
  isn't there some masochism involved in taking on this kind of project?

(ODO)

A: Perhaps martyrish or or martyrly?  Also, masochistic, because of your use of the word "pleasure."
If pleasure isn't a necessary component, then perhaps contrarian, egoistic, egotistical, self-conceited, vainglorious, or self-important.

A: If you're looking for a word to describe someone that is pretentious and countercultural, I think Bohemian would fit well.  It tends to be used more for artists, though.
Maverick is similar and can be used more generally.

A: Try pariah.  It actually means "outcast", but when used sarcastically means someone who has affected this status.


text:
Q: bbPress redirecting with php code Hello I want to redirect to my page to user page right now i write code inside wordpress page
this code for redirecting me to example.com/*userid*
<meta http-equiv="refresh" content="0;URL=http://www.example.com/members/<?php
$id = bbp_get_user_id();

?>/?user='.$id/">

Where am I actually making mistake

A: By default, you can't type PHP into a WordPress post/page contents for security reasons. Additionally, <meta> tags belong in the header, not in a post body.


text:
Q: Visual Studio Code NuGet Package Manager GUI Work Directory is Empty Error Installed Python 3.10.4, made sure to select the add to Path option, installed VS Code 1.66.2, added extension NuGet Package Manager GUI but when I go to Command Palette and select NuGet Package Manager GUI I get error: nugetpackagemanagergui.view not found. Workdirectoy is empty.
I have tried reinstalling both Python on VS Code. I have tried to use the NuGet Package Manager extension also but I get the "path" argument must be of type string or an instance of Buffer or URL. Received undefined.
NuGet Package Manager GUI Error


text:
Q: Does "yield" cast lambdas to procs? I'm learning Ruby, and while testing the behaviour of procs and lambdas, I wrote this code:
def test_f(&a_block)
  puts "in test_f"
  yield 7
  puts "still in test_f"
end

def test_f_2(&a_block)
  puts "in test_f_2"
  a_block.call(7)
  puts "still in test_f_2"
end

lam = lambda do |i|
  puts "lambda #{i}"
  return "lambda #{i}"
end

test_f_2(&lam)
test_f(&lam)

The result of running this is:
in test_f_2
lambda 7
still in test_f_2
in test_f
lambda 7
test.rb:17: in 'block in <main>': unexpected return <LocalJumpError>
        from test.rb:3:in 'test_f'
        from poop.rb:21:in '<main>'

I have two questions from this:

*

*Does this mean that using yield 'casts' the lambda into a proc, since it is only when using yield that attempting to return causes an error?

*Under what circumstances is it not permitted to return from a proc?

I've read that "it's not possible to call a proc containing a return when the creating context no longer exists" but the context here is global so it doesn't make sense to me to say that the creating context for lam no longer exists. However, enclosing the entire creating of lam and calls of the test functions within another function prevents any error message from appearing, which leads me to conclude that the criterion at play is that any call to a proc containing a return must be from within a context from which you can return.
Am I right?


text:
Q: Microsoft translator API Qt I have a problem geting application token for Microsoft translator with QNetworkAccessManager. This is my code:
QUrl serverUrl("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13");
QNetworkRequest request(serverUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrl postData;
postData.addQueryItem("grant_type", "client_credentials");
postData.addQueryItem("client_id", ClientID);
postData.addQueryItem("client_secret", ClientSecret);
postData.addQueryItem("scope", "http://api.microsofttranslator.com");
networkAccessManager->post(request, postData.encodedQuery());

and when a finished(QNetworkReply*) signal is emitted I found that server reply contains no data at all, it is just empty! Does anyone know the solution of this problem?
UPD I checked a reply for errors and got the following: "Error creating ssl context". So I added SSL libs to my project, but got next error - "Unknown error". Any ideas?

A: I have used this class subclassed from QNetworkAccessManager to ignore SSL errors:
sslqnetworkaccessmanager.h
#ifndef SSLQNETWORKACCESSMANAGER_H
#define SSLQNETWORKACCESSMANAGER_H
#include <QtNetwork>
#include <QtCore>

class SslQNetworkAccessManager : public QNetworkAccessManager
{
    Q_OBJECT
public:
    explicit SslQNetworkAccessManager(QObject *parent = 0);

protected:
    QNetworkReply* createRequest(Operation op, const QNetworkRequest & request, QIODevice * outgoingData = 0);
};

#endif // SSLQNETWORKACCESSMANAGER_H

sslqnetworkaccessmanager.cpp
#include "sslqnetworkaccessmanager.h"

SslQNetworkAccessManager::SslQNetworkAccessManager(QObject *parent)
    : QNetworkAccessManager(parent)
{
}

QNetworkReply* SslQNetworkAccessManager::createRequest(Operation op, const QNetworkRequest& request, QIODevice* outgoingData)
{
    QNetworkRequest req(request);
    QNetworkReply* reply = QNetworkAccessManager::createRequest(op, req, outgoingData);
    reply->ignoreSslErrors();

    return reply;
}

This class overrides the createRequest method and ignores any SSL errors that may occur with the QNetworkReply returned.


text:
Q: Cassandra LWT ReadTimeoutException or WriteTimeoutException I am trying to have two process insert in the same table. So first I try to enter the partition and clustering key values with a LWT if this succeeds it means the process can continue with that work for that time bucket otherwise another process already completed that bucket.
The LWT is set with a consistency level of One and a serial consistency level of LOCAL_SERIAL.
If the first insert success the work is done and another insert is done with also a consistency level of one. The first statement has a TTL statement for the case where the process doing the work terminates in the middle the row will be empty after a TTL of 90.
Even if I run a single process the LWT fails with either a read or write timeout exception.
Here is the prepared statement and the exceptions I am getting. Any help is appreciated.
com.datastax.driver.core.exceptions.ReadTimeoutException:
Cassandra timeout during read query at consistency LOCAL_QUORUM
(2 responses were required but only 1 replica responded)

com.datastax.driver.core.exceptions.WriteTimeoutException:
Cassandra timeout during write query at consistency LOCAL_SERIAL
(2 replica were required but only 1 acknowledged the write)

statement = {DefaultPreparedStatement@10844}
 preparedId = {PreparedId@10886}
 query = "INSERT INTO event_store(evt_type, rcncl_date, rcncl_ts) values( ?, ?, ?) IF NOT EXISTS USING TTL 90;"
 queryKeyspace = "test"
 routingKey = null
 consistency = {ConsistencyLevel@10882} "ONE"
 serialConsistency = {ConsistencyLevel@10883} "LOCAL_SERIAL"
 traceQuery = false
 retryPolicy = null

A: It seems that your cluster is having some sort of problem with the responses. Either timeouts on the nodes (Due to overloading or other sort of problems) or some nodes are actually down. Another cause might be your replication factor, so confirm that you have at least has many nodes up, as your RF.
Do a nodetool status to check the status of your nodes. Also use nodetool info to check if they have exceptions (If so, check the logs after, you can grep for exception to help narrow down).
In case of overload, it should be visible with nodetool tpstats, look for a lot of PENDING or BLOCKED/ALL TIME BLOCKED.


text:
Q: how does this do while loop work? so I was pretty confused about loopings during class, but we have to use it in one of our homeworks. after fiddling around and tweaking a program that I compiled from the textbook, I managed to execute a do while loop the way I want it but I don't really get how this works. can someone explain this to me so that I can do it by myself from scratch? thanks
    do
{
    cout << "enter number of items : ";
    cin >> itemsnum;

    if (itemsnum < 1 || itemsnum > 5)
        {
        cout << "\nyou must order at least one item and not more than five items\nplease reenter the amount of items ordered : ";
        cout << endl;
        }

    else
        break;
}
while (1);

so in this part of the code, users have to enter at least one number of item and not more than 5. if the data entered doesn't obey the conditions, the program will loop and prompt users to enter the amount again. I understand the "doing" part but I don't understand the "while (1)" down there. One more thing, below the "else" is a break. What does this part mean? Thank you

A: It's a rather lazy way of building a loop control structure.
do {   } while(1);

is ostensibly an infinite loop. To exit the otherwise endless cycle, break is used to exit the loop.
Personally I dislike even the appearance of an infinite loop in a program. They do have a habit of becoming infinite over time due to errant refactoring. I'd prefer something like
   do {
       // use continue to go round again, or break to exit immediately
   } while (0); // if control reaches here, the loop finishes.

A: These three things are just different ways of writing an infinite loop:
do { } while (1)
while (1) { }
for (;;) { }

The loop is terminated by the break (or return, abort(), exit(), std::terminate(), throw, etc.) statement.
Most people would not use do/while for an infinite loop.  The other ways are less typing, and call out the fact that it's an infinite loop right at the top.
You can also use true instead of 1 in C++.  In a boolean (true/false) context, they are equivalent.

A: in C and C++ 0 is considered false and any other numeric value is true, especially 1. This relates to the underlying mechanism of how comparisons are performed by the cpu.
so while(1) is the same as while(true). so your do{X}while(1) means do X until 1 is false or in other words do X forever.
break means exit this loop.


text:
Q: How do you check if IDENTITY_INSERT is set to ON or OFF in SQL Server? I've searched for this, but threads in which it appeared tended to have answers from people who didn't understand the question.
Take the following syntax:
SET IDENTITY_INSERT Table1 ON

How do you do something more like this:
GET IDENTITY_INSERT Table1

I don't want to do anything whatsoever to the data in the database or to the settings to get this information though.  Thanks!

A: You can discover whether or not identity_insert is on, and if so for what table using the code below.
declare @tableWithIdentity varchar(max) = '';
SET IDENTITY_INSERT ExampleTable ON

begin try
  create table #identityCheck (id int identity(1,1))
  SET IDENTITY_INSERT #identityCheck ON
  drop table #identityCheck
end try
begin catch
  declare @msg varchar(max) = error_message()
  set @tableWithIdentity= @msg;
  set @tableWithIdentity =
  SUBSTRING(@tableWithIdentity,charindex('''',@tableWithIdentity,1)+1, 10000)

  set @tableWithIdentity = SUBSTRING(@tableWithIdentity,1, charindex('''',@tableWithIdentity,1)-1)

  print @msg;
  drop table #identityCheck
end catch

if @tableWithIdentity<>''
begin
  print ('Name of table with Identity_Insert set to ON: ' + @tableWithIdentity)
end
else
begin
  print 'No table currently has Identity Insert Set to ON'
end

A: If you're attempting to turn off IDENTITY_INSERT for some other table to avoid getting an error when you want to set IDENTITY_INSERT on, the following may also work for you. As other have said on this thread IDENTITY_INSERT is a session setting with no direct visibility. However I made the interesting discovery that SET IDENTITY_INSERT  OFF doesn't error out for any table that has an identity whether or not IDENTITY_INSERT is ON for that table. So it occurred to me that I could just call SET IDENTITY_INSERT ... OFF for every table with an identity in the database. It feels a bit like a brute force solution, but
I found that the following dynamic SQL block did the trick very nicely.
---- make sure IDENTITY_INSERT is OFF ----
DECLARE @cmd NVARCHAR(MAX)
SET @cmd = CAST((SELECT 'SET IDENTITY_INSERT ' +
             QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + '.' +
             QUOTENAME(t.name) + ' OFF' + CHAR(10)
             FROM sys.columns c
             JOIN sys.tables t ON t.object_id = c.object_id
             WHERE c.is_identity = 1
             ORDER BY 1 FOR XML PATH('')) AS NVARCHAR(MAX))
EXEC sp_executesql @cmd

A: Since SET IDENTITY_INSERT is a session sensitive, it is managed in buffer level without storing somewhere. This means we do not need to check the IDENTITY_INSERT status as we never use this key word in current session.
Sorry, no help for this.
Great question though :)
Source: Here
Update
There are ways maybe to do this, also seen in the site I linked, IMO, it is too much effort to be useful.
if

(select max(id) from MyTable) < (select max(id) from inserted)

--Then you may be inserting a record normally

BEGIN
    set @I = 1 --SQL wants something to happen in the "IF" side of an IF/ELSE
END

ELSE --You definitely have IDENTITY_INSERT on.  Done as ELSE instead of the other way around so that if there is no inserted table, it will run anyway

BEGIN
.... Code that shouldn't run with IDENTITY_INSERT on
END

A: In summary:

*

*Nathan's solution is the fastest:
SELECT OBJECTPROPERTY(OBJECT_ID('MyTable'), 'TableHasIdentity');

*

*when using an API wrapper, one can reduce the entire check to just checking for rows. For instance when using C#'s SqlDataReaders  property HasRows and a query construct like:
SELECT CASE OBJECTPROPERTY(OBJECT_ID('MyTable'), 'TableHasIdentity')
       WHEN 1 THEN '1' ELSE NULL END

*Ricardo's solution allows more flexibility but requires the Column's identity name
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('MyTable', 'U')
                        AND name = 'MyTableIdentityColumnName';

*Bogdan Bodanov solution, using try/catch would work as well, but additional checking should confine exception handling to cases of  IDENTITY_INSERT is already ON for table 'MyTable'. Cannot perform SET operation for table 'MyTable';

A: Very good question. I Have same issue. May be you can try to reset IDENTITY_INSERT using TRY/CATCH? For example, you make the job but not sure if the job is finished and IDENTITY_INSERT is set to OFF.
Why you don't try:
BEGIN TRY
...
END TRY
BEGIN CATCH
SET IDENTITY_INSERT table OFF;
END CATCH;

Also I am not sure that this is working correctly but I see that adding only SET IDENTITY_INSERT ... OFF did not return error. So you can set just in case in the end SET IDENTITY_INSERT ... OFF.

A: If you want to know about the session variable... Good question, but I cant see where this information would be usefull. In normal execution to check a normal table response to an insert, this should work!
-- If you only want to know if there is identity insert on a given table:
select is_identity
from sys.columns
where object_id = OBJECT_ID('MyTable', 'U') and name = 'column_Name'

-- Or... Use this if you want to execute something depending on the result:
if exists (select *
from sys.columns
where object_id = OBJECT_ID('MyTable', 'U') and is_identity = 1)
... your code considering identity insert
else
... code that should not run with identity insert

Have fun!

A: Here is my solution. It is very similar to @jmoreno's answer.
You would call it like this
DECLARE @IdentityInsert VARCHAR(20)
EXEC dbo.GetIdentityInsert 'YourDb', 'YourSchema', 'YourTable', @IdentityInsert OUT
SELECT @IdentityInsert

This returns a 1-row recordset with column name IDENTITY_INSERT, that can be either ON, OFF, or NO_IDENTITY (if the given table doesn't have an identity column). It also sets the output parameter @IdentityInsert. So you can adjust the code to whichever method you prefer.
It would be nice to get this into a user-defined function, but unfortunately I couldn't find a way to avoid the TRY..CATCH block, which you cannot use in user-defined functions.
-- ================================================================================
-- Check whether the table specified has its IDENTITY_INSERT set to ON or OFF.
-- If the table does not have an identity column, NO_IDENTITY is returned.
-- Tested on SQL 2008.
-- ================================================================================
CREATE PROCEDURE dbo.GetIdentityInsert

      @dbname sysname
    , @schemaname sysname
    , @table sysname
    , @IdentityInsert VARCHAR(20) OUTPUT

AS

BEGIN

    SET NOCOUNT ON

    DECLARE @OtherTable nvarchar(max)
    DECLARE @DbSchemaTable nvarchar(max)

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    DECLARE @ErrorNumber INT;
    DECLARE @object_id INT;

    SET @DbSchemaTable = @dbname + '.' + @schemaname + '.' + @table

    SET @object_id = OBJECT_ID(@DbSchemaTable)
    IF @object_id IS NULL
    BEGIN
        RAISERROR('table %s doesn''t exist', 16, 1, @DbSchemaTable)
        RETURN
    END

    BEGIN TRY

        SET @object_id = OBJECT_ID(@DbSchemaTable)

        IF OBJECTPROPERTY(@object_id,'TableHasIdentity') = 0
        BEGIN
            SET @IdentityInsert = 'NO_IDENTITY'
        END
        ELSE
        BEGIN
            -- Attempt to set IDENTITY_INSERT on a temp table. This will fail if any other table
            -- has IDENTITY_INSERT set to ON, and we'll process that in the CATCH
            CREATE TABLE #GetIdentityInsert(ID INT IDENTITY)
            SET IDENTITY_INSERT #GetIdentityInsert ON
            SET IDENTITY_INSERT #GetIdentityInsert OFF
            DROP TABLE #GetIdentityInsert

            -- It didn't fail, so IDENTITY_INSERT on @table must set to OFF
            SET @IdentityInsert = 'OFF'
        END
    END TRY

    BEGIN CATCH

        SELECT
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE(),
            @ErrorNumber = ERROR_NUMBER();

        IF @ErrorNumber = 8107  --IDENTITY_INSERT is already set on a table
        BEGIN
            SET @OtherTable = SUBSTRING(@ErrorMessage, CHARINDEX(char(39), @ErrorMessage)+1, 2000)
            SET @OtherTable = SUBSTRING(@OtherTable, 1, CHARINDEX(char(39), @OtherTable)-1)

            IF @OtherTable = @DbSchemaTable
            BEGIN
                -- If the table name is the same, then IDENTITY_INSERT on @table must be ON
                SET @IdentityInsert = 'ON'
            END
            ELSE
            BEGIN
                -- If the table name is different, then IDENTITY_INSERT on @table must be OFF
                SET @IdentityInsert =  'OFF'
            END
        END
        ELSE
        BEGIN
            RAISERROR (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState);
            --THROW     Use this if SQL 2012 or higher
        END

    END CATCH

    SELECT [IDENTITY_INSERT] = @IdentityInsert
END
GO

A: you can also use the ObjectProperty method to determine if a table has an identity:
DECLARE @MyTableName nvarchar(200)
SET @MyTableName = 'TestTable'
SELECT CASE OBJECTPROPERTY(OBJECT_ID(@MyTableName), 'TableHasIdentity')
WHEN 1 THEN 'has identity'
ELSE 'no identity columns'
END as HasIdentity


text:
Q: Paperclip with Devise I have a app with a frontend app in AngularJS, sending JSON requests to my Rails backend app. I'm using Paperclip and Devise, and the spec for the User model changed in order to permit the uploading of an image.
Since I already have a image attribute, to store the url returned by Omniauth logins, I created a new attribute to my User model, with the command:
rails g paperclip user stored_image
And run the consequent migration.
My user.rb
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, #:confirmable,
     :recoverable, :rememberable, :trackable, :validatable,
     :omniauthable, :omniauth_providers => [:facebook]

  has_attached_file :stored_image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/noimg.png"
  validates_attachment_content_type :stored_image, content_type: /\Aimage\/.*\Z/
end

And my registration controller, that I'm using to override some Devise limitations is the following
class RegistrationsController < Devise::RegistrationsController
  protected

  def update_resource(resource, params)
    # debugger
    resource.update_without_password(params)
  end
end

My application_controller.rb
class ApplicationController < ActionController::Base
  respond_to :html, :json
  before_filter :configure_permitted_parameters, if: :devise_controller?
  after_filter :set_csrf_cookie_for_ng
  protect_from_forgery  #with: :null_session
  before_action :set_locale

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

  def handle_unverified_request
    forgery_protection_strategy.new(self).handle_unverified_request
  end

  def set_csrf_cookie_for_ng
    cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
  end

  protected

  def verified_request?
    super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
  end

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:current_password ,:first_name, :last_name, :email, :password, :password_confirmation, :sex, :phone_number, :location, :birthday, :stored_image)}
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :email, :sex, :phone_number, :location, :birthday, :stored_image ) }
    end
  end

It's important to clarify, that the user only uploads his image in an update action. So I when I debug in the update_resource action and inspect the params I see that the stored_image is not present, and therefore unable to store the image. Is my application_controller.rb correct to enable devise to accept image uploads?

A: Take a look at THIS article on how to add custom fields to Devise.

This is because the way Rails 4 deals with "mass assignment." Due to security reasons we have to explicitly permit parameters inside each controller.

In your app/controllers/application_controller.rb explicitly permit your parameter - in you case stored_image:
class ApplicationController < ActionController::Base
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception

    before_filter :configure_permitted_parameters, if: :devise_controller?

    protected

        def configure_permitted_parameters
            devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :email, :password) }
            devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :password, :stored_image) }
        end
end

A: My problem here was not no related with strong params. For some reason, I had to first parse the request as JSON, and then update the attributes, in this case, the stored_image attribute


text:
Q: Can I instantiate or produce an enum value from the enum name and the value's rawValue at runtime in Swift? We are using Swift 5.0. I need to turn a list of strings into a set of enum cases regularly. I wrote a Kotlin function easily that takes an enum class at runtime and a list of strings, and converts it to a Java EnumSet (well, 2 functions that work together):
fun <EnumT : Enum<EnumT>> ConvertStrToEnum(enumClass: Class<EnumT>, str: String?): EnumT? {
    if (str == null)
        return null
    for (enumval in enumClass.enumConstants) {
        if (enumval.toString() == str)
            return enumval
    }
    throw IllegalArgumentException("Gave an invalid enum value for class ${enumClass.canonicalName}: [$str]")
}

fun <EnumT : Enum<EnumT> > ConvertStrArrayToEnumSet(enumClass: Class<EnumT>, array: List<String>?) : EnumSet<EnumT> {
    val set = EnumSet.noneOf(enumClass)
    array?.forEach { value -> ignoreExceptions { set.add(ConvertStrToEnum(enumClass, value)) } }
    return set
}

And, to be clear, an actual usage is:
var intent: EnumSet<Intent>
intent = ConvertStrArrayToEnumSet(Intent::class.java, filters.array(MatchFilter.Intent.jsonName))

Can I write a function in Swift 5 that achieves the same result? I wrote this for one conversion, here's the example. If I can't write this function I will have this boilerplate code repeated throughout the app.
  public var intents: Set<Intent>
  if let jsonIntents = filters?["intent"] as? Array<String> {
     for jsonIntent in jsonIntents {
        if let intent = Intent(rawValue: jsonIntent) {
           intents.insert(intent)
        }
     }
  }

A: Assuming your enums are RawRepresentable with RawValue == String...
Enums in Swift don't have a special "base class" like Enum. But in this situation, we really just need to make use of their common property - both RawRepresentable and Hashable. Sure, lots of non-enums have this property, too. So our method will work on not just enums, but any type that conforms to these two protocols. That's rather nice isn't it?
func convertStringArrayToEnumSet<T>(type: T.Type, _ strings: [String]) -> Set<T>
    where T : RawRepresentable & Hashable, T.RawValue == String {
    Set(strings.compactMap(T.init(rawValue:)))
}

Note the use of compactMap, which discards any invalid raw values.
In fact, you can generalise this to not just string arrays, but any array:
func convertRawValueArrayToEnumSet<T>(type: T.Type, _ rawValues: [T.RawValue]) -> Set<T>
    where T : RawRepresentable & Hashable {
    Set(rawValues.compactMap(T.init(rawValue:)))
}

A: Sweeper's answer is good, but I see you put some effort into error handling. Swift isn't good about helping you with that, so you have to make your own extensions.
(Dictionary and RawRepresentable are from Swift 1, which didn't have errors. They never got modernized, and just return optionals.)
/// Acts as a dictionary that `throw`s instead of returning optionals.
public protocol valueForKeyThrowingAccessor {
  associatedtype Key

  /// Should just be a throwing subscript, but those don't exist yet.
  func value<Value>(for: Key) throws -> Value
}

/// Acts as a dictionary.
public protocol valueForKeySubscript: valueForKeyThrowingAccessor {
  associatedtype Value

  subscript(key: Key) -> Value? { get }
}

public extension valueForKeySubscript {
  /// - Throws: `KeyValuePairs<Key, Value>.AccessError.noValue`
  func value(for key: Key) throws -> Value {
    guard let value = self[key]
    else { throw KeyValuePairs<Key, Value>.AccessError.noValue(key: key) }

    return value
  }

  /// - Throws: `KeyValuePairs<Key, Value>.AccessError.typeCastFailure`
  func value<Value>(for key: Key) throws -> Value {
    guard let value = try value(for: key) as? Value
    else { throw KeyValuePairs<Key, Value>.AccessError.typeCastFailure(key: key) }

    return value
  }
}

extension Dictionary: valueForKeySubscript { }

public extension KeyValuePairs {
  /// An error throw from trying to access a value for a key.
  enum AccessError: Error {
    case noValue(key: Key)
    case typeCastFailure(key: Key)
  }
}

public extension RawRepresentable {
  /// Like `init(rawValue:)`, if it was throwing instead of failable.
  /// - Throws: `RawRepresentableExtensions<Self>.Error.invalidRawValue`
  /// if there is no value of the type that corresponds with the specified raw value.
  init(_ rawValue: RawValue) throws {
    guard let instance = Self(rawValue: rawValue)
    else { throw RawRepresentableExtensions<Self>.Error.invalidRawValue(rawValue) }

    self = instance
  }
}

/// A namespace for nested types within `RawRepresentable`.
public enum RawRepresentableExtensions<RawRepresentable: Swift.RawRepresentable> {
  public enum Error: Swift.Error {
    case invalidRawValue(RawRepresentable.RawValue)
  }
}

public extension InitializableWithElementSequence where Element: RawRepresentable {
  /// - Throws: `RawRepresentableExtensions<Element>.Error.invalidRawValue`
  init<RawValues: Sequence>(rawValues: RawValues) throws
  where RawValues.Element == Element.RawValue {
    self.init(
      try rawValues.map(Element.init)
    )
  }
}

/// A type that can be initialized with a `Sequence` of its `Element`s.
public protocol InitializableWithElementSequence: Sequence {
  init<Sequence: Swift.Sequence>(_: Sequence)
  where Sequence.Element == Element
}

extension Array: InitializableWithElementSequence { }
extension Set: InitializableWithElementSequence { }

extension InitializableWithElementSequence where Element == Intent {
  init(filters: [String: Any]) throws {
    try self.init(
      rawValues: try filters.value(for: "intent") as [String]
    )
  }
}

try filters.map(Set.init)


text:
Q: How do I reduce the size of inference rule? I am using package mathpartir, with environment mathpar. In the environment I am using command \inferrule to write down some inference rules. The problem is that this rules are just too big, and I have way too many in my document so I'm struggling to fit them. I tried some ideas to try to lower the font size but it didn't work. I am also not sure if just trying to scale the graph is a good idea because I want the rules themselves to be smaller, so that they fit better in the figure.
Minimal example of what my code looks like:
\documentclass[11pt]{article}
\usepackage{mathpartir}
\begin{document}
\begin{figure}[h]
  \begin{mathpar}
    \inferrule*[left=Rule-X] { x = 1 }
      { x = 10 }
    \inferrule*[left=Rule-Y] { y = 1 }
      { y = 10 }
  \end{mathpar}
\end{figure}
\end{document}

Thank you!

A: @andrew-swann, in the comments, pointed out that it is possible to just scale down the font by specifying the font size in envinroment mathpar, like this:
\documentclass[11pt]{article}
\usepackage{mathpartir}
\begin{document}
\begin{figure}[h]
  \begin{mathpar}\tiny
    \inferrule*[leftstyle={\tiny \sc},left=Rule-X] { x = 1 }
      { x = 10 }
    \inferrule*[leftstyle={\tiny \sc},left=Rule-Y] { y = 1 }
      { y = 10 }
  \end{mathpar}
\end{figure}
\end{document}

Notice that in the labels I'm also choosing the font size and the \sc font style. And it is important to define the style before defining the label as it will not work in the opposite order.

A: You can set globally a style for the labels:
\documentclass[11pt]{article}
\usepackage{mathpartir}

\makeatletter
\define@key {mprset}{style}[1]{\def\TirNameStyle{#1}}
\makeatother

\mprset{style={\scriptsize\scshape}}

\begin{document}

\begin{mathpar}
  \inferrule*[left=Rule-X] { x = 1 }
    { x = 10 }
  \inferrule*[left=Rule-Y] { y = 1 }
    { y = 10 }
\end{mathpar}

\end{document}

You can use leftstyle or rightstyle for setting just the left labels or the right labels, respectively.
The code between \makeatletter and \makeatother is necessary because of a funny bug in the package. No change is needed for the leftstyle and rightstyle keys. In the original code we find
\define@key {mprset}{style}[1]{\def\TirNameStyle{#1}def}

which would typeset def when the key is set.
If your aim is to print the whole thing in reduced size:
\documentclass[11pt]{article}
\usepackage{mathpartir}

\makeatletter
\define@key {mprset}{style}[1]{\def\TirNameStyle{#1}}
\makeatother

\AtBeginEnvironment{mathpar}{\scriptsize}
\mprset{style={\scriptsize\scshape}}

\begin{document}

\begin{mathpar}
  \inferrule*[left=Rule-X] { x = 1 }
    { x = 10 }
  \inferrule*[left=Rule-Y] { y = 1 }
    { y = 10 }
\end{mathpar}

\end{document}

You can also selectively apply a size to the environment, but this requires using a different name.
\documentclass[11pt]{article}
\usepackage{mathpartir}

\makeatletter
\define@key {mprset}{style}[1]{\def\TirNameStyle{#1}}
\makeatother

\newenvironment{mymathpar}[1][]
 {%
  \AtBeginEnvironment{mathpar}{\scriptsize}%
  \mprset{style={#1\scshape}}%
  \mathpar
 }
 {\endmathpar}

\begin{document}

\begin{mymathpar}
  \inferrule*[left=Rule-X] { x = 1 }
    { x = 10 }
  \inferrule*[left=Rule-Y] { y = 1 }
    { y = 10 }
\end{mymathpar}

\begin{mymathpar}[\scriptsize]
  \inferrule*[left=Rule-X] { x = 1 }
    { x = 10 }
  \inferrule*[left=Rule-Y] { y = 1 }
    { y = 10 }
\end{mymathpar}

\end{document}


text:
Q: Sqoop error on data fetch from Oracle Database using Oracle wallet sqoop import -D mapred.map.child.java.opts='-Doracle.net.tns_admin=. -Doracle.net.wallet_location=.' -files $HOME/wallet/cwallet.sso,$HOME/wallet/ewallet.p12,$HOME/wallet/sqlnet.ora,$HOME/wallet/tnsnames.ora --connect jdbc:oracle:thin:@TEST2 --table SQOOP_TEST

Am using this sqoop command to fetch data from Oracle DB but ending with below error

ERROR manager.SqlManager: Error executing statement: java.sql.SQLRecoverableException: IO Error: Unknown host specified

My Wallet:
tnsnames.ora
TEST2=   (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = <IP>)(PORT = 1521))
    )
    (CONNECT_DATA = (server=dedicated)
      (SERVICE_NAME = HDPTEST )
    )   )

Wallet works fine,

$sqlplus /@TEST2
SQL*Plus: Release 11.2.0.4.0 Production on Thu Jun 8 14:48:42 2017
Copyright (c) 1982, 2013, Oracle.  All rights reserved.
Connected to: Oracle Database 11g Enterprise Edition Release
  11.2.0.4.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL>

JDBC without uding wallet works fine,

jdbc:oracle:thin:@:1521/HDPTEST

Detailed Log
Warning: /usr/local/hbase does not exist! HBase imports will fail.
Please set $HBASE_HOME to the root of your HBase installation.
Warning: /usr/local/sqoop/../hcatalog does not exist! HCatalog jobs will fail.
Please set $HCAT_HOME to the root of your HCatalog installation.
Warning: /usr/local/sqoop/../accumulo does not exist! Accumulo imports will fail.

Please set $ACCUMULO_HOME to the root of your Accumulo installation.
17/06/08 15:06:15 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6
17/06/08 15:06:15 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/06/08 15:06:16 DEBUG tool.BaseSqoopTool: Enabled debug logging.
17/06/08 15:06:16 DEBUG sqoop.ConnFactory: Loaded manager factory: org.apache.sqoop.manager.oracle.OraOopManagerFactory
17/06/08 15:06:16 DEBUG sqoop.ConnFactory: Loaded manager factory: com.cloudera.sqoop.manager.DefaultManagerFactory
17/06/08 15:06:16 DEBUG sqoop.ConnFactory: Trying ManagerFactory: org.apache.sqoop.manager.oracle.OraOopManagerFactory
17/06/08 15:06:16 DEBUG oracle.OraOopManagerFactory: Data Connector for Oracle and Hadoop can be called by Sqoop!
17/06/08 15:06:16 INFO oracle.OraOopManagerFactory: Data Connector for Oracle and Hadoop is disabled.
17/06/08 15:06:16 DEBUG sqoop.ConnFactory: Trying ManagerFactory: com.cloudera.sqoop.manager.DefaultManagerFactory
17/06/08 15:06:16 DEBUG manager.DefaultManagerFactory: Trying with scheme: jdbc:oracle:thin
17/06/08 15:06:16 DEBUG manager.OracleManager$ConnCache: Instantiated new connection cache.
17/06/08 15:06:16 INFO manager.SqlManager: Using default fetchSize of 1000
17/06/08 15:06:16 DEBUG sqoop.ConnFactory: Instantiated ConnManager org.apache.sqoop.manager.OracleManager@1d2adfbe
17/06/08 15:06:16 INFO tool.CodeGenTool: Beginning code generation
17/06/08 15:06:16 DEBUG manager.OracleManager: Using column names query: SELECT t.* FROM SQOOP_TEST t WHERE 1=0
17/06/08 15:06:16 DEBUG manager.SqlManager: Execute getColumnInfoRawQuery : SELECT t.* FROM SQOOP_TEST t WHERE 1=0
17/06/08 15:06:16 DEBUG manager.OracleManager: Creating a new connection for jdbc:oracle:thin:@TEST2, using username: null
17/06/08 15:06:16 DEBUG manager.OracleManager: No connection paramenters specified. Using regular API for making connection.
17/06/08 15:06:16 ERROR manager.SqlManager: Error executing statement: java.sql.SQLRecoverableException: IO Error: Unknown host specified
java.sql.SQLRecoverableException: IO Error: Unknown host specified
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:662)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:560)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:270)
    at org.apache.sqoop.manager.OracleManager.makeConnection(OracleManager.java:325)
    at org.apache.sqoop.manager.GenericJdbcManager.getConnection(GenericJdbcManager.java:52)
    at org.apache.sqoop.manager.SqlManager.execute(SqlManager.java:744)
    at org.apache.sqoop.manager.SqlManager.execute(SqlManager.java:767)
    at org.apache.sqoop.manager.SqlManager.getColumnInfoForRawQuery(SqlManager.java:270)
    at org.apache.sqoop.manager.SqlManager.getColumnTypesForRawQuery(SqlManager.java:241)
    at org.apache.sqoop.manager.SqlManager.getColumnTypes(SqlManager.java:227)
    at org.apache.sqoop.manager.ConnManager.getColumnTypes(ConnManager.java:295)
    at org.apache.sqoop.orm.ClassWriter.getColumnTypes(ClassWriter.java:1833)
    at org.apache.sqoop.orm.ClassWriter.generate(ClassWriter.java:1645)
    at org.apache.sqoop.tool.CodeGenTool.generateORM(CodeGenTool.java:107)
    at org.apache.sqoop.tool.ImportTool.importTable(ImportTool.java:478)
    at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:605)
    at org.apache.sqoop.Sqoop.run(Sqoop.java:143)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:179)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:218)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:227)
    at org.apache.sqoop.Sqoop.main(Sqoop.java:236)
Caused by: oracle.net.ns.NetException: Unknown host specified
    at oracle.net.resolver.HostnameNamingAdapter.resolve(HostnameNamingAdapter.java:207)
    at oracle.net.resolver.NameResolver.resolveName(NameResolver.java:131)
    at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:476)
    at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:595)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:230)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1452)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:496)
    ... 24 more
17/06/08 15:06:16 ERROR tool.ImportTool: Encountered IOException running import job: java.io.IOException: No columns to generate for ClassWriter
    at org.apache.sqoop.orm.ClassWriter.generate(ClassWriter.java:1651)
    at org.apache.sqoop.tool.CodeGenTool.generateORM(CodeGenTool.java:107)
    at org.apache.sqoop.tool.ImportTool.importTable(ImportTool.java:478)
    at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:605)
    at org.apache.sqoop.Sqoop.run(Sqoop.java:143)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:179)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:218)
    at org.apache.sqoop.Sqoop.runTool(Sqoop.java:227)
    at org.apache.sqoop.Sqoop.main(Sqoop.java:236)

Please help me out to find where am wrong.

A: Do you have oraclepki.jar, osdt_core.jar, and osdt_cert.jar in the classpath and also please check out the "SSL with JDBC"  whitepaper for more details(page 9). Also, the Wallet location can be specified as part of the tnsnames.ora as shown here.
LISTENER = (ADDRESS_LIST=
 (ADDRESS=(PROTOCOL=tcps)(HOST=servername)(PORT=2484))
)  WALLET_LOCATION=(SOURCE=(METHOD=FILE)(METHOD_DATA=(
DIRECTORY=/server/wallet/path))

)