text:
Q: No such acos function exists I've a problem. I want to get the nearest points on google map in android app. Different points/coordinates are stored in sqlite database. And I have to get the nearest 5 from them. The Query I'm using is:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 5;

But I'm getting an error i.e. "no such function: acos exists".
What will be its proper solution

A: SQLite doesn't support any trigonometric functions by default, so you can't use them in SQL queries.
You can either fetch the list of coordinates and process it in application code, or you can try and expose Java's trigonometric functions in SQLite with user defined functions (see How can I create a user-defined function in SQLite?).

A: You can create extension in C that implements trigonometric functions, for example:
/* sql_trig.c */
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1;
#include <stdlib.h>

/* this bit is required to get M_PI out of MS headers */
#if defined( _WIN32 )
#define _USE_MATH_DEFINES
#endif /* _WIN32 */

#include <math.h>

#define RADIANS(d) (( d / 180.0 ) * M_PI)

static void sql_trig_sin( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
    double a = RADIANS(sqlite3_value_double( values[0] ));
    sqlite3_result_double( ctx, sin( a ) );
}

static void sql_trig_cos( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
    double a = RADIANS(sqlite3_value_double( values[0] ));
    sqlite3_result_double( ctx, cos( a ) );
}

static void sql_trig_acos( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
    double a = sqlite3_value_double( values[0] );
    sqlite3_result_double( ctx, acos( a ) );
}

static void sql_trig_radians( sqlite3_context *ctx, int num_values, sqlite3_value **values )
{
    sqlite3_result_double( ctx, RADIANS(sqlite3_value_double( values[0] ) ));
}

int sqlite3_extension_init( sqlite3 *db, char **error, const sqlite3_api_routines *api )
{
    SQLITE_EXTENSION_INIT2(api);

    sqlite3_create_function( db, "sin",1,
        SQLITE_UTF8, NULL, &sql_trig_sin, NULL, NULL );
    sqlite3_create_function( db, "cos",1,
        SQLITE_UTF8, NULL, &sql_trig_cos, NULL, NULL );
    sqlite3_create_function( db, "acos",1,
        SQLITE_UTF8, NULL, &sql_trig_acos, NULL, NULL );

    return SQLITE_OK;
}

Now you can compile it as a shared library:
$ gcc -c -fPIC sql_trig.c
$ ld -shared -o sql_trig.so sql_trig.o -lm

and load it with SELECT load_extension('./sql_trig.so')


text:
Q: Firebase Realtime Database UID different from Authentication UID I am trying to call for the UID that firebase provides and register it to the Realtime Database. For some reason the two UIDs are different. I think Authentication UID is changing after I register the original UID to Realtime Database. Perhaps the way I am calling the UID is wrong?
Authentication UID: zD40xuce4SWPiidMGOm62hFWOFP2
Realtime Database UID: rhqgglru9FXV5jhITSQmpqwBdc53
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_user);

    email = findViewById(R.id.email_create);
    password = findViewById(R.id.password_create);
    con_password = findViewById(R.id.password_confirm);

    auth = FirebaseAuth.getInstance();

    registerBtn = findViewById(R.id.Register);

    registerBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String txt_email = email.getText().toString();
            String txt_password = password.getText().toString();
            String txt_con_password = con_password.getText().toString();

            FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
            Toast.makeText(New_User.this, "" + currentFirebaseUser.getUid(), Toast.LENGTH_SHORT).show();
            String txt_UID = currentFirebaseUser.getUid();

            //check empty fields
            if (txt_email.isEmpty() || txt_password.isEmpty()) {
                Toast.makeText(New_User.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
            }

            //check passwords match
            else if (!txt_password.equals(txt_con_password)){
                Toast.makeText(New_User.this, "Passwords are not matching", Toast.LENGTH_SHORT).show();
            }

            else{
                databaseReference.child("User ID").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if (snapshot.hasChild(txt_UID)) {
                            Toast.makeText(New_User.this, "User ID is taken", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            registerUser(txt_email, txt_password, txt_UID);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });

            }

        }
    });
}

private void registerUser(String email, String password, String UID) {

    auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(New_User.this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            //doesnt upload login information into realtime database, but registers account
            if (task.isSuccessful()) {
                databaseReference.child("User ID").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        databaseReference.child("User ID").child(UID).child("email").setValue(email);
                        databaseReference.child("User ID").child(UID).child("password").setValue(password);

                        Toast.makeText(New_User.this, "User registered successfully.", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(New_User.this, PhysicalParameters.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
                FirebaseUser user = auth.getCurrentUser();
                Toast.makeText(New_User.this, "Registering user successful", Toast.LENGTH_SHORT).show();
                //Intent intent = new Intent(New_User.this, Welcome_Page.class);
                //startActivity(intent);
            }else {

                Toast.makeText(New_User.this, "Failed Registration: " + task.getException(), Toast.LENGTH_SHORT).show();
            }
        }
    });

}

}

A: fAuth = FirebaseAuth.getInstance();
fAuth.getUid()

For more reference. This is my project
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Base64;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import org.w3c.dom.Text;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;

public class Register extends AppCompatActivity {
    EditText mFullName, mEmail, mPassword, mPhone;
    Button mRegisterBtn, pickimagebtn;
    TextView mLoginHereBtn,imgsourcetxtview;

    FirebaseAuth fAuth;
    ProgressBar progressBar;
    String encryptionimagestring;
    Bitmap bitmap;
    ImageView ProfileImage;
    SparseArray<Face> faces;
    private static final int PICK_IMAGE = 1;
    int count = 0;
    private byte encryptionkey[] = {9, 115, 51, 86, 105, 4, -31, 23, -68, 88, 17, 20, 3, -105, 119, -53};
    private Cipher cipher, decipher;
    private SecretKeySpec secretKeySpec;
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        imgsourcetxtview =(TextView) findViewById(R.id.imagesoucetxtview);
        imgsourcetxtview.setMovementMethod(new ScrollingMovementMethod());
        imgsourcetxtview.setSingleLine();

        //pick image

        pickimagebtn = findViewById(R.id.pickimagebtn);
        pickimagebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CropImage.activity(null)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setAspectRatio(1, 1)
                        .start(Register.this);
            }
        });

        try {
            cipher = Cipher.getInstance("AES");
            decipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        secretKeySpec = new SecretKeySpec(encryptionkey, "AES");

        mFullName = findViewById(R.id.Register_FullName);
        mEmail = findViewById(R.id.Email);
        mPassword = findViewById(R.id.Password);
        mPhone = findViewById(R.id.Register_Phone);
        mRegisterBtn = findViewById(R.id.Register_button);
        mLoginHereBtn = findViewById(R.id.LoginHere);
        mFullName = findViewById(R.id.Register_FullName);

        fAuth = FirebaseAuth.getInstance();
        progressBar = findViewById(R.id.progressBar);

        if (fAuth.getCurrentUser() != null) {
            startActivity(new Intent(getApplicationContext(), MainActivity.class).putExtra("fuid", String.valueOf(fAuth.getUid())));
            finish();
        }

        mRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String email = mEmail.getText().toString().trim();
                String password = mPassword.getText().toString().trim();

                if (TextUtils.isEmpty(mFullName.getText().toString().trim())) {
                    mFullName.setError("Name is required.");
                    return;
                }
                if (TextUtils.isEmpty(email)) {
                    mEmail.setError("Email is required.");
                    return;
                }

                if (TextUtils.isEmpty(mPhone.getText().toString().trim())) {
                    mPhone.setError("Phone is required.");
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    mPassword.setError("Password is required.");
                    return;
                }

                if (password.length() < 6) {
                    mPassword.setError("Password must be >= 6 characters.");
                    return;
                }
                if (TextUtils.isEmpty(imgsourcetxtview.getText().toString().trim())) {
                   imgsourcetxtview.setError("Image is required.");
                    return;
                }
                else{
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inMutable = true;
                    detectFace(options);
                    if (faces.size() < 1) {
                        imgsourcetxtview.setError("Can't detect face.");
                        return;
                    }
                    if (faces.size() > 1) {
                        imgsourcetxtview.setError("More than one face is detected.");
                        return;
                    }
                }

                progressBar.setVisibility(View.VISIBLE);

                fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            //add information to firebase

                            myRef.child("Account").child(fAuth.getUid()).child("name").setValue(AESEncryptionmethod(mFullName.getText().toString()));
                            myRef.child("Account").child(fAuth.getUid()).child("phone").setValue(AESEncryptionmethod(mPhone.getText().toString()));
                            myRef.child("Account").child(fAuth.getUid()).child("email").setValue(AESEncryptionmethod(mEmail.getText().toString()));
                            myRef.child("Account").child(fAuth.getUid()).child("photo").setValue(encryptionimagestring);
                            myRef.child("Account").child(fAuth.getUid()).child("coin").setValue("0");
                            Toast.makeText(Register.this, "User created.", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(), MainActivity.class).putExtra("fuid", String.valueOf(fAuth.getUid())));

                        } else {
                            Toast.makeText(Register.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

        mLoginHereBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), Login.class));
            }
        });
    }

    private String AESEncryptionmethod(String string) {
        byte[] stringByte = string.getBytes();
        byte[] encryptedByte = new byte[stringByte.length];
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            encryptedByte = cipher.doFinal(stringByte);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        String returnString = null;
        try {
            returnString = new String(encryptedByte, "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return returnString;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // handle result of CropImageActivity
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result.getUri());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imgsourcetxtview.setText(String.valueOf(result.getUri()));

                Toast.makeText(
                        this, "Cropping successful, Sample: " + result.getUri(), Toast.LENGTH_LONG)
                        .show();
                encryptionimage(bitmap);
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
            }
        }
    }
    public void encryptionimage(Bitmap bitmap){
        ByteArrayOutputStream baos=new  ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
        byte [] b=baos.toByteArray();
        String string=Base64.encodeToString(b, Base64.DEFAULT);
        byte[] stringByte = string.getBytes();
        byte[] encryptedByte = new byte[stringByte.length];
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            encryptedByte = cipher.doFinal(stringByte);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        String returnString = null;
        try {
            returnString = new String(encryptedByte, "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        encryptionimagestring = returnString;

    }
    private void  detectFace(BitmapFactory.Options options) {
        /*Bitmap bitmap = BitmapFactory.decodeResource(
                this.getResources(), R.drawable.test1,
                options
        );*/
        Paint paint = new Paint();
        paint.setStrokeWidth(6);
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);

        Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(tempBitmap);
        canvas.drawBitmap(bitmap,0,0,null);

        FaceDetector faceDetector = new FaceDetector.Builder(Register.this).setTrackingEnabled(false)
                .build();
        if(!faceDetector.isOperational()){
            new AlertDialog.Builder(this).setMessage("Could not set up Face Detector!").show();
            return;
        }

        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
         faces = faceDetector.detect(frame);
        /*for(int i=0; i<faces.size(); i++) {
            Face thisFace = faces.valueAt(i);
            float x1 = thisFace.getPosition().x;
            float y1 = thisFace.getPosition().y;
            float x2 = x1 + thisFace.getWidth();
            float y2 = y1 + thisFace.getHeight();
            canvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, paint);
        }*/
       // imageView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing the value of a nested dictionary changes other nested dictionary values I started making a Python Discord bot in the library of Pycord. I wanted to make a bot that will work on multiple servers and each server will have different values. So, to do this I made a dictionary that will store all these values within a nested dictionary. However, when I tried to change the value of one nested dictionary, it changes the values in the other nested dictionaries.
Code:
server_ids = {}
default_server_vals = {'beetle_game_started': False, 'beetle_message_id': None,
'beetle_message_channel': None, 'beetle_player_1': None, 'beetle_player_2': None, 'beetle_game_on': False, 'player1_list' : [], "player2_list":[]}

@bot.event
async def on_ready():
    print('logged in')
    for i in bot.guilds:
        global server_ids
        global default_server_vals
        server_ids[str(i.id)] = default_server_vals
    print(server_ids)  # Generate server IDS
@bot.event
async def on_guild_join(guild):
    server_ids[str(guild.id)] = default_server_vals

@bot.slash_command(guild_ids=testing_servers, name="beetle", description="2 Player game")
async def beetle(ctx):
    print(server_ids[str(ctx.guild.id)].get('beetle_game_on'), server_ids[str(ctx.guild.id)].get('beetle_game_started'))

    if server_ids[str(ctx.guild.id)].get('beetle_game_on') == False and server_ids[str(ctx.guild.id)].get('beetle_game_started') == False:
        await ctx.respond("Game starting! React to join.")
        game_start_embed = discord.Embed(title="React to join beetle game! (2 Players Only)",
                                         colour=discord.Colour.green())
        game_start_embed.add_field(name="GAME RULES", value="""There are two players. There is one dice! The first player to finish the beetle drawing wins.
    Rolling a 1 – Body

    Rolling a 2 – Head

    Rolling a 3 – A leg

    Rolling a 4 – An eye

    Rolling a 5 – An antenna

    Rolling a 6 – The tail
    The first player to roll all 6 wins. However, the head and body must be drawn first to draw the other beetle parts.""")
        message = await ctx.send(embed=game_start_embed)
        await message.add_reaction("")
        print(ctx.guild.id)
        server_ids[str(ctx.guild.id)]['beetle_game_started'] = True
        print(server_ids)
        server_ids[str(ctx.guild.id)]['beetle_message_id'] = message.id
        server_ids[str(ctx.guild.id)]['beetle_message_channel'] = message.channel
    elif server_ids[str(ctx.guild.id)].get('beetle_game_started'):
        await ctx.respond("Someone already started a game! Try and join them.")
    else:
        await ctx.respond("There is already a beetle game playing!")

on_ready takes the server IDS that the bot is already in, and put it in a global server_ids variable. Then the nested dictionary is given as the server ID value for the dictionary. But, when I try to edit a value of a nested dictionary (inside the beetle slash command) it changes all of the other nested values.
For example, when I try to change the nested dictionary value of beetle_game_started it prints this:
{'912361242985918464': {'beetle_game_started': True, 'beetle_message_id': None, 'beetle_message_channel': None, 'beetle_player_1': None, 'beetle_player_2': None, 'beetle_game_on': False, 'player1_list': [], 'player2_list': []}, '938245167880753202': {'beetle_game_started': True, 'beetle_message_id': None, 'beetle_message_channel': None, 'beetle_player_1': None, 'beetle_player_2': None, 'beetle_game_on': False, 'player1_list': [], 'player2_list': []}}

It somehow changes the value of both nested dictionaries of the server IDS (the value of 'beetle_game_started')
How would I change the value of one nested dictionary without changing the value of others?

A: The reason you see this behavior is because in Python dictionaries are mutable objects.
Pulling the relevant sections from the code provided
default_server_vals = {'beetle_game_started': False, 'beetle_message_id': None,
'beetle_message_channel': None, 'beetle_player_1': None, 'beetle_player_2': None, 'beetle_game_on': False, 'player1_list' : [], "player2_list":[]}

and
server_ids[str(i.id)] = default_server_vals

The server_ids[str(i.id)] assignment is just creating new references to a single dictionary.  This is why when you change the value for one id, you observe the change for all other ids.
One way to get around this is to make a copy.  I suggest taking a look at Python's copy library.
Since default_server_vals contains lists as values, you'll want to consider deepcopy.


text:
Q: Curve intersecting points in JavaScript I wish to modify an image by moving columns of pixels up or down such that each column offset follows a curve.
I wish for the curve to intersect 6 or so points in some smooth way. I Imagine looping over image x co-ordinates and calling a curve function that returns the y co-ordinate for the curve at that offset, thus telling me how much to move each column of pixels.
I have investigated various types of curves but frankly I am a bit lost, I was hoping there would be a ready made solution that would allow me to plug in my point co-ords and spit out the data that I need. I'm not too fussed what kind of curve is used, as long as it looks "smooth".
Can anyone help me with this?
I am using HTML5 and canvas. The answer given here looks like the sort of thing I am after, but it refers to an R library (I guess) which is Greek to me!

A: Sigmoid curve
A very simple solution if you only want the curve in the y direction is to use a sigmoid curve to interpolate the y pos between control points
// where 0 <= x <= 1 and p > 1
// return value between 0 and 1 inclusive.
// p is power and determines the amount of curve
function sigmoidCurve(x, p){
    x = x < 0 ? 0 : x > 1 ? 1 : x;
    var xx = Math.pow(x, p);
    return xx / (xx + Math.pow(1 - x, p))
}

If you want the y pos at x coordinate px that is between two control points x1,y1 and x2, y2
First find the normalized position of px between x1,x2
var nx = (px - x1) / (x2 - x1); // normalised dist between points

Plug the value into sigmoidCurve
var c = sigmoidCurve(nx, 2); // curve power 2

The use that value to calculate y
var py = (y2 - y1) * c + y1;

And you have a point on the curve between the points.
As a single expression
var py = (y2 - y1) *sigmoidCurve((px - x1) / (x2 - x1), 2) + y1;

If you set the power for the sigmoid curve to 1.5 then it is almost a perfect match for a cubic bezier curve
Example
This example shows the curve animated. The function getPointOnCurve will get the y pos of any point on the curve at position x

const ctx = canvas.getContext("2d");
const curve = [[10, 0], [120, 100], [200, 50], [290, 150]];
const pos = {};
function  cubicInterpolation(x, p0, p1, p2, p3){
    x = x < 0 ? 0 : x > 1 ? 1 : x;
    return p1 + 0.5*x*(p2 - p0 + x*(2*p0 - 5*p1 + 4*p2 - p3 + x*(3*(p1 - p2) + p3 - p0)));
}
function sigmoidCurve(x, p){
    x = x < 0 ? 0 : x > 1 ? 1 : x;
 var xx = Math.pow(x, p);
 return xx / (xx + Math.pow(1 - x, p))
}
// functional for loop
const doFor = (count, cb) => { var i = 0; while (i < count && cb(i++) !== true); };
// functional iterator
const eachOf = (array, cb) => { var i = 0; const len = array.length; while (i < len && cb(array[i], i++, len) !== true ); };

// find index for x in curve
// returns pos{ index, y }
// if x is at a control point then return the y value and index set to -1
// if not at control point the index is of the point befor x
function getPosOnCurve(x,curve, pos = {}){
  var len = curve.length;
  var i;
  pos.index = -1;
  pos.y = null;
  if(x <= curve[0][0]) { return (pos.y = curve[0][1], pos) }
  if(x >= curve[len - 1][0]) { return  (pos.y = curve[len - 1][1], pos) }
  i = 0;
  var found = false;
  while(!found){  // some JS optimisers will mark "Do not optimise"
                  // code that do not have an exit clause.
    if(curve[i++][0] <x && curve[i][0] >= x) { break }
  }
  i -= 1;
  if(x === curve[i][0]) { return (pos.y = curve[i][1], pos) }
  pos.index =i
  return pos;
}
// Using Cubic interpolation to create the curve
function getPointOnCubicCurve(x, curve, power){
  getPosOnCurve(x, curve, pos);
  if(pos.index === -1) { return pos.y };
  var i = pos.index;
  // get interpolation values for points around x
  var p0,p1,p2,p3;
  p1 = curve[i][1];
  p2 = curve[i+1][1];
  p0 = i === 0 ? p1 : curve[i-1][1];
  p3 = i === curve.length - 2 ? p2 : curve[i+2][1];
  // get unit distance of x between curve i, i+1
  var ux = (x - curve[i][0]) / (curve[i + 1][0] - curve[i][0]);
  return cubicInterpolation(ux, p0, p1, p2, p3);
}

// Using Sigmoid function to get curve.
// power changes curve power = 1 is line power > 1 tangents become longer
// With the power set to 1.5 this is almost a perfect match for
// cubic bezier solution.
function getPointOnCurve(x, curve, power){
  getPosOnCurve(x, curve, pos);
  if(pos.index === -1) { return pos.y };
  var i = pos.index;
  var p = sigmoidCurve((x - curve[i][0]) / (curve[i + 1][0] - curve[i][0]) ,power);
  return curve[i][1] + (curve[i + 1][1] - curve[i][1]) * p;
}

const step = 2;
var w = canvas.width;
var h = canvas.height;
var cw = w / 2;  // center width and height
var ch = h / 2;
function update(timer){
    ctx.setTransform(1,0,0,1,0,0); // reset transform
    ctx.globalAlpha = 1;           // reset alpha
  ctx.clearRect(0,0,w,h);
    eachOf(curve, (point) => {
      point[1] = Math.sin(timer / (((point[0] + 10) % 71) * 100) ) * ch * 0.8 + ch;
    });

    ctx.strokeStyle = "black";
    ctx.beginPath();
    doFor(w / step, x => { ctx.lineTo(x * step, getPointOnCurve(x * step, curve, 1.5) - 10)});
    ctx.stroke();
    ctx.strokeStyle = "blue";
    ctx.beginPath();
    doFor(w / step, x => { ctx.lineTo(x * step, getPointOnCubicCurve(x * step, curve, 1.5) + 10)});
    ctx.stroke();

    ctx.strokeStyle = "black";
    eachOf(curve,point => ctx.strokeRect(point[0] - 2,point[1] - 2 - 10, 4, 4) );
    eachOf(curve,point => ctx.strokeRect(point[0] - 2,point[1] - 2 + 10, 4, 4) );
    requestAnimationFrame(update);
}
requestAnimationFrame(update);
canvas { border : 2px solid black; }
<canvas id="canvas"></canvas>

Update
I have added a second curve type to the above demo as the blue curve offset from the original sigmoid curve in black.
Cubic polynomial
The above function can be adapted to a variety of interpolation methods. I have added the function
function  cubicInterpolation(x, p0, p1, p2, p3){
    x = x < 0 ? 0 : x > 1 ? 1 : x;
    return p1 + 0.5*x*(p2 - p0 + x*(2*p0 - 5*p1 + 4*p2 - p3 + x*(3*(p1 - p2) + p3 - p0)));
}

Which produces a curve based on the slope of the line at two points either side of x. This method is intended for evenly spaced points but still works if you have uneven spacing (such as this example). If the spacing gets too uneven you can notice a bit of a kink in the curve at that point.
Also the curve over and under shoot may be an issue.
For more on the Maths of cubic interpolation.


text:
Q: How to handle verbs that use different preposition when used in pairs For example the sentence

I will widen my perspective and approach to complex interdisciplinary
  research

should it be?

perspective of and approach to

If this is the correct way, is there a better construction that flows better? At least to me, reading "perspective of and" doesn't sound very good.

A: Note, first, that we generally speak of a perspective on a subject, not of it.
There is no graceful way to deploy one noun phrase as object of two different prepositions heading complements of two different nouns, adjectives or verbs. There is a notoriously graceless way, which is the construction you suggest:

I will widen my perspective on and approach to complex interdisciplinary research.

This ugly construction infuriates writers and troubles linguists, because it conjoins non-constituent collocations. Nonetheless, it is universally accepted in academic and bureaucratic/legal dialects, so you need not hesitate to employ it.
The alternative is to rewrite. If you cannot find an alternative to one of your nouns which takes the same complement as the other, you may conjoin at a higher level:

I will widen my perspective on complex interdisciplinary research and my approach to it.

A POSSIBLY IMPERTINENT OBSERVATION:
If I might take a step back from the immediate question: My own experience is that awkward constructions like this usually betray some defect in my underlying metaphors. You should think about, for instance, what exactly you mean by widening your perspective and widening your approach. Is it possible that widen is just an approximation to what you really mean? —which might be something as remote from your first-order expression as this:

I will take a wider view of complex interdisciplinary research in order to find more productive approaches to the problem at hand.

A: Either is acceptable. I would go with the first example as it is likely to be the usual format. The second format is more pedantic and you are probablly more likely to see it in academic writing in the humanities.


text:
Q: Why does running this not issue a segmentation fault?
Possible Duplicate:
Invalid read/write sometimes creates segmentation fault and sometimes does not

I have the following code:
#include <stdlib.h>
#include <stdio.h>

int main() {
    int *ptr = NULL;
    ptr = malloc(sizeof(char));
    if (ptr) {
        *ptr = 10;
        printf("sizeof(int): %zu\nsizeof(char): %zu\n", sizeof(int), sizeof(char));
        printf("deref of ptr: %d\n", *ptr);
        free(ptr);
        return EXIT_SUCCESS;
    }
    else
        return EXIT_FAILURE;
}

When I compile and run it, I get following output:
$ gcc test.c
$ ./a.out
sizeof(int): 4
sizeof(char): 1
deref of ptr: 10

The value sizeof(char) is less than sizeof(int). My malloc call only sets aside enough space for a char. Yet, my program is able to assign an integer value to ptr without crashing. Why does this work?

A: Just because you are writing into unallocated memory does not mean the program will crash. There is no runtime bounds checking like that.
The segfault will occur when you are accessing memory out of the address range allocated through the operating system as detected by the hardware. You may get away with a lot of memory access before then in your heap.

A: Writing to a too-small buffer is undefined behavior. There is no guarentee that it will crash. It might not crash. It might appear to work. It might also corrupt some data silently. It might cause your program to do something unintended - many security holes come from this, when an attacker manipulates the effect of undefined behavior into something undesired. By a strict reading of a standard, this might even have the effect of summoning demons from your nose.
At an architectural level, usually allocations are rounded up to some power of two (but this is not guaranteed by any means!), hence why you didn't see anything obviously untoward here. But do not rely on this, as it can and does vary.

A: malloc implementations can, and often will, allocate a bit more memory than you asked for. Most implementations will round up to the nearest multiple of 8 or 16 bytes, at a minimum.

A: Hardware memory managers control complete memory pages, often 4K.  Unless your write overflows a page boundary, the memory management hardware will not generate a SEGFAULT/Access Violation interrupt.
Your example 'works' because one element of the large set of 'undefined behavior' is 'appearing to work correctly, at least for now'.  If you add complexity to your app, other members of the set will appear...

A: This works accidentally.  Your malloc likely allocates a chunk significantly larger than a single character (usually because tracking nanoscopic pieces isn't worth the overhead).  So you are likely tromping outside the space you are supposed to have, but it doesn't matter in your implementation.
Your program is still erroneous, I think, according to the standard.  And if it were much bigger, and you made that mistake in places where it didn't work accidentally, you'd get all kinds of bad behavior, sometimes an illegal memory access, but sometimes just completely crazy behavior because you can damage your or system data structures.
Our CheckPointer test tool should be able to spot this error; technically, you're storing outside the area you requested, and that's detectable with enough effort.


text:
Q: Как спрятать ссылку ajax Подскажите пожалуйста, нужно спрятать ссылку в коде что бы она была не видна.
Пробовал так, но выполняе

$(function(){
    $('#link42').click(function(){
        window.open("http://site.ru/");
    });
});
.link {
   cursor: pointer;
   color: #00f;
   text-decoration: underline;
}

Вообще, это не самый лучший вариант, но если хочется, то кликни по псевдо-ссылке.

Вообще, это не самый лучший вариант, но если хочется, то кликни по псевдо-ссылке.

A:


text:
Q: Nested for-loop element-wise list comparison As a novel approach to solving my challenge described here, I have put together the following:
from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

diffs =[
"""- It contains a Title II provision that changes the age at which workers
compensation/public disability offset ends for disability beneficiaries from age 65 to full retirement age (FRA).""",
"""+ It contains a Title II provision that changes the age at which workers
compensation/public disability offset ends for disability beneficiaries from age 68 to full retirement age (FRA).""",
"""+ Here's a new paragraph I added for testing."""]

for s in diffs:
    others = [i for i in diffs if i != s]
    for j in others:
        if similar(s, j) > 0.7:
            print '"{}" and "{}" refer to the same sentence'.format(s, j)
            print
            diffs.remove(j)
        else:
            print '"{}" is a new sentence'.format(s)

The idea is to loop over the strings, and compare each with the others. If a given string is deemed to be similar to another, remove the other, otherwise the given string is deemed to be a unique string in the list.
Here's the output:
"- It contains a Title II provision that changes the age at which workers
compensation/public disability offset ends for disability beneficiaries from age 65 to full retirement age (FRA)." and "+ It contains a Title II provision that changes the age at which workers
compensation/public disability offset ends for disability beneficiaries from age 68 to full retirement age (FRA)." refer to the same sentence

"- It contains a Title II provision that changes the age at which workers
compensation/public disability offset ends for disability beneficiaries from age 65 to full retirement age (FRA)." is a new sentence
"+ Here's a new paragraph I added for testing." is a new sentence

So it's correctly detecting that the first two sentences are similar, and that the last is unique. The problem is it's then going back and deeming the first sentence to be unique (which it isn't, and it should not be returning to this sentence anyway).
Where's the flaw in my looping logic? Can this be achieved without nested fors and removal of elements?

A: from difflib import SequenceMatcher
from collections import defaultdict

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

diffs =[
"""- It contains a Title II provision that changes the age at which workers
compensation/public disability offset ends for disability beneficiaries from age 65 to full retirement age (FRA).""",
"""+ It contains a Title II provision that changes the age at which workers
compensation/public disability offset ends for disability beneficiaries from age 68 to full retirement age (FRA).""",
"""+ Here's a new paragraph I added for testing."""]

sims = set()
simdict = defaultdict(list)
for i in range(len(diffs)):
    if i in sims:
        continue
    s = diffs[i]

    for j in range(i+1, len(diffs)):
        r = diffs[j]
        if similar(s, r) > 0.7:
            sims.add(j)
            simdict[i].append(j)

for k, v in simdict.iteritems():
    print diffs[k] + " is similar to:"
    print '\n'.join(diffs[e] for e in v)

A: You can see exactly when it determines the first sentence is unique by changing
print '"{}" is a new sentence'.format(s)

to
print '"{}" and "{}" are different sentences'.format(s,j)

This should help you to see where exactly your loop fails.

A: Since modified strings will always appear back-to-back (one with preceded with '-', the other '+', and '-', the following can be done (and I believe it will work in all cases).
When the list has an odd number of elements, the last must necessarily be a new sentence.
def extract_modified_and_new(diffs):
    for z1, z2 in zip(diffs[::2], diffs[1::2]):
        if similar(z1, z2) > 0.7:
            print z1, 'is similar to', z2
            print
        else:
            print z1, ' and ', z2, 'are new'
            print
    if len(diffs) % 2 != 0:
            print diffs[-1], ' is new'


text:
Q: Link a binary to execute from it's orignal directory I have a program written in C. It's directory structure is like this:
root/
    program.sh
    textures/
        texture1.png

program.sh imports textures in a way like: load_textures("./textures/texture1.png") (relative paths). Hence, the program only works whenever I execute program.sh from the root directory.
I want to create a link to program.sh such that, whenever I execute the link, I am able to execute the program.sh from the root directory. In other words, I want to execute program.sh from outside the root directory.
Now, I would prefer a solution to do this without changing the source code (if there is a way), otherwise, how would you recommend that I open files/textures in C, given the current scenario?
Had a similar question here, but it's unanswered.

A: As it became clear from comments, the goal was to execute the program from a different directory, but with the program's current working directory pointing to its own directory.
While this can be done in C (in a POSIX system, as assumed due to the .sh extension, via a combination of the chdir and execvp syscalls), it's much more easily achieved in a wrapper shell script, like so:
#!/bin/sh

pushd /path/to/executable
./program.sh $@
popd


text:
Q: Writing a parametrization of the cissoid by using $\theta$ The cissoid of Diocles is the curve whose equation in terms of polar coordinates $(r,\theta)$ is
$$r = \sin\theta \tan\theta, −\frac{\pi}{2}<\theta <\frac{\pi}{2}$$
Write down a parametrization of the cissoid using $\theta$ as a parameter and show that
$$\gamma(t)=\left(t^2, \frac{t^3}{\sqrt{1-t^2}}\right)$$ for $-1\lt t\lt 1$
is a parametrization of it.

I researched what is the cissoid of Diocles. And I reached the following graph result;

I found the question a differential geometry textbook while I am studying by myself .
Please help me solving the question. Thank you:)

A: You almost have the answer already. Recall the definition of polar coordinates:
$$x=r\cos\theta,\qquad y=r\sin\theta.$$
Now you have an expression for $r$ in terms of $\theta$. Replacing it in these formulas we get
\begin{align}
&x=\sin\theta\tan\theta\cdot\cos\theta=\sin^2\theta,\\
&y=\sin\theta\tan\theta\cdot\sin\theta=\frac{\sin^3\theta}{\cos\theta}.
\end{align}
This is a parameterization of $x$ and $y$ by $\theta$. Now if instead of $\theta$ we use $t=\sin\theta$ as a new parameter, these formulas will transform into
$$x=t^2,\qquad y=\frac{t^3}{\sqrt{1-t^2}}.$$


text:
Q: Within Looping Make Summary Table by filling data based on conditional Lets say I have looping and in each looping there is a table result like this:
  #Looping Result Data
  value <- c("A1", "A2", "A3", "A4")
  value.dat <- rep("Yes", 4)
  n <- c(4, 1, 2, 4 )
  resloop <- data.frame(value, value.dat, n)

Within the loop I want to have (in the end) summary table for every loop and the table looks like this:
Country <- rep(c("Germany", "France"), each=12)
Sectoral <- rep(c("A-A", "B-A", "B-B", "A-C", "C-B", "C-C"), times=4)
Connection <- rep(c("Yes", "No"), each=6)
Freq.Ind <- NA
t.sum<- data.frame(Country, Sectoral, Connection, Freq.Ind)

Freq.Ind should be filled by the value from resloop which has the most n (so can be more than one value if there are same big n)
So if now in the loop:
 i<-"Germany"
 j<-"A-A"

I want in the Freq.Ind first row fill with:  A1, A4
I have tried something like this, but something still wrong :( (newbie)
 t.sum[t.sum$Country == i && t.sum$Sectoral == j && t.sum$Connection ==  "Yes", "Freq.Ind"]<- as.character(resloop$value[resloop$n==max(resloop$n)])
t.sum$Freq.Ind <- ifelse( t.sum$Country == i & t.sum$Sectoral == j & t.sum$Connection == "Yes",  as.character(resloop$value[resloop$n==max(resloop$n)]), next )

 t.sum %>%
     mutate(Freq.Ind=replace(Freq.Ind, Country == i & Sectoral == j &  Connection == "Yes" ,as.character(resloop$value[resloop$n==max(resloop$n)])))

Thank you

A: I have got this from trial (so far)
as.character(resloop$value[resloop$n==max(resloop$n)])-> themax
themax <- cbind(themax)
library(stringr)
str_c(themax, collapse = ",") ->themax

t.sum %>%
mutate(Freq.Ind=replace(Freq.Ind, Country == i & Sectoral == j & Connection == "Yes" ,themax))

Im sure there are more simple way, feel free to share.


text:
Q: How to allow CORS in JavaEE Servlets using Tomcat? I've already installed the Access Control plugin and It didn't help, and I'm using servlets with gson, my http methods work if I use an API platform (hoppscotch), my method GET is working with axios but when I try to send a POST from my vue.js project using axios I get the following CORS error:
Access to XMLHttpRequest at 'http://localhost:8080/demo5_war_exploded/client'
from origin 'http://localhost:8081' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

A also this one:
xhr.js:233
POST http://localhost:8080/demo5_war_exploded/client net::ERR_FAILED

Here is my Java code and I'm using the headers, with my doGet is working but not with my doPost.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
    response.setHeader("Access-Control-Max-Age", "86400");
    response.setHeader("Content-Type", "application/json");

    JsonReader jsonReader = Json.createReader(request.getReader());
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();

    // extract the fields from the JSON object
    String name = jsonObject.getString("name");
    String email = jsonObject.getString("email");

    // create the Client object
    Client client = new Client(name, email);

    // insert the client into the database
    try {
        clientDao.insert(client);
        response.setStatus(HttpServletResponse.SC_CREATED);
    } catch (SQLException e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

This in my doGet, which is working.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
    response.setHeader("Access-Control-Max-Age", "86400");
    response.setHeader("Content-Type", "application/json");

    String idString = request.getParameter("id");
    if (idString != null) {
        // get the client with the specified id
        int id = Integer.parseInt(idString);
        try {
            Client client = clientDao.buscarPorId(id);
            if (client != null) {
                JsonObjectBuilder builder = Json.createObjectBuilder();
                builder.add("name", client.getName());
                builder.add("email", client.getEmail());
                JsonObject jsonObject = builder.build();
                response.setContentType("application/json");
                PrintWriter out = response.getWriter();
                out.print(jsonObject);
                out.flush();
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        // get all the client
        try {
            // a different way to get the json and simpler TBH
            List<Client> client = clientDao.list();

            Gson gson = new Gson();
            String clientJSON = gson.toJson(client);

            PrintWriter printWriter = response.getWriter();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            printWriter.write(clientJSON);
            printWriter.close();

        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

A: This is related to the application server, in this case Tomcat 10, but it looks like that is the same for a lot of versions of Tomcat.
First, you need to create where ever you want inside your Source root your CorsFilter class implementing Filter, in my case the path is projectName/src/main/java/servlet/CorsFilter.java, code of the file (you can copy it, just be careful to change the package name and to import the servlet with java instead of jakarta if you aren't using it) is:
package servlet;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // No initialization required
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        // No cleanup required
    }
}

The second step is to go inside your web.xml file which is inside tomcat, in my case the path is ~/Documents/apache-tomcat-10.1.5/conf/web.xml, you open the file and add the following code in web.xml next to where <filter> is commented inside the file, just edit the path of your CorsFilter.java in my case is servlet.CorsFilter, because you need to add the path from the Source root:
<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>servlet.CorsFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And the last step is to stop running your project and re-run it.
In addition I'll leave this image as a visual reference:


text:
Q: ExecuteReader() Object reference not set to an instance of an object error I am trying to figure out why I am getting an error of 'Object reference not set to an instance of an object.' when my winforms code runs. I have set a breakpoint on the sql statement and stepped into the code and it shows as the line: Using dr = oledbCmd.ExecuteReader()
I am still learning vb.Net so would appreciate some help as to how to overcome this error. Many thanks
    DBConnection.connect()

    sql = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"

    Dim cmd As New OleDb.OleDbCommand

    cmd.Parameters.AddWithValue("@p1", cmbCustomer.Text)

    cmd.CommandText = sql
    cmd.Connection = oledbCnn
    dr = cmd.ExecuteReader

    Using dr = oledbCmd.ExecuteReader()

        While dr.Read()

            Dim LV As New ListViewItem

            With LV

                .UseItemStyleForSubItems = False
                .Text = dr(1).ToString()
                .SubItems.Add(dr(2).ToString())

            End With
            lvSelectRequestItems.Items.Add(LV)
        End While

    End Using

    cmd.Dispose()
    dr.Close()
    oledbCnn.Close()

DBConnect module
Imports System.Data.OleDb

    Module DBConnection

        Public connetionString As String = My.Settings.storageConnectionString
        Public oledbCnn As New OleDbConnection
        Public oledbCmd As OleDbCommand
        Public dr As OleDbDataReader
        Public sql As String

        Sub connect()

            'connetionString = My.Settings.storageConnectionString
            oledbCnn.ConnectionString = connetionString
            oledbCnn.Open()

        End Sub

    End Module

A: I saw several mistakes. Look to the comments for reasons for the changes
Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
'.Net uses connection pooling, such that you're better using a new connection object for each query
'Also, a Using block will ensure the connection is closed, **even if an exception is thrown**
' The original code would leak connections when exceptions occured, eventually locking you out of the db
Using cn As New OleDb.OleDbConnection("Connection string here"), _
      cmd As New OleDb.OleDbCommand(sql, cn) 'set CommandText BEFORE adding parameters

    'Use explicit parameter types
    cmd.Parameters.Add("?", SqlDbType.NVarChar, 50).Value = cmbCustomer.Text

    cn.Open()
    Using dr As OleDb.OleDbDataReader = cmd.ExecuteReader()
        While dr.Read()

            Dim LV As New ListViewItem
            With LV
                .UseItemStyleForSubItems = False
                .Text = dr(1).ToString()
               .SubItems.Add(dr(2).ToString())
            End With
            lvSelectRequestItems.Items.Add(LV)

        End While
        dr.Close()

    End Using
End Using

A: You have failed to properly bind the SqlConnection to the SqlCommand object.
Using connection As New SqlConnection(connectionString)
    connection.Open()

    Dim command As New SqlCommand(queryString, connection)
    Dim reader As SqlDataReader = command.ExecuteReader()
    While reader.Read()
        Console.WriteLine("{0}", reader(0))
    End While
End Using

See: MSDN
Edit: Requested adjustment to aid in clarity:
    Using connection As New Data.SqlClient.SqlConnection
        Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
        connection.Open()
        Using command As New Data.SqlClient.SqlCommand(Sql, connection)
            command.Parameters.AddWithValue("@p1", cmbCustomer.Text)
            dr = command.ExecuteReader()

            While dr.Read()
                Dim LV As New ListViewItem
                With LV
                    .UseItemStyleForSubItems = False
                    MediaTypeNames.Text = dr(1).ToString()
                    .SubItems.Add(dr(2).ToString())

                End With
                lvSelectRequestItems.Items.Add(LV)
            End While
        End Using
    End Using

Your code should look something like that.

A: you have a fair amount of potential issues going on here.
1-you are using your dr variable twice. once before the using, which is probably causing your error. then again in for using, which does not look right because it is not the cmd variable used to execute the reader. so change this part of your code:
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader

Using dr = oledbCmd.ExecuteReader()

to this:
cmd.CommandText = sql
cmd.Connection = oledbCnn

Using dr = cmd.ExecuteReader()

2-you are not showing if oledbCnn has been opened yet. I'm assuming your DBConnection.connect() function is doing this and olebCnn is a variable that function sets and opens
3-I'm not sure if the question mark in your query string will work. Even if it does you should replace it with the parameter name. so your query string should be:
sql = "SELECT * from Boxes WHERE Customer = @p1 AND Status = 'I'"

lastly you should probably show all the code for the sub(or function) this is for so we can get a full picture. example dr must be declared before the using else you would get a build error.


text:
Q: Mat-Table dinamica incluso el encabezado de cada columna Hola estoy tratando de armar una dataTable (mat-table) de angular material con un objeto formado de varias tablas de la BD que me mandan desde el backend. El objeto que me llega es el siguiente:

Esto es lo que me trae el response.dato:

Y el encabezado de cada columna también lo podría sacar del objeto (response.title):

Mi idea es insertar esos datos en la mat table donde el .ts es:
import { Component, OnInit } from '@angular/core';
import { MatTableDataSourcePageEvent } from '@angular/material/table';
import { MatTableDataSource } from '@angular/material/table';
import { MatTableModule } from '@angular/material/table';
import { CdkTableModule }  from '@angular/cdk/table';
import { PayrollServices } from 'src/app/services/payroll.services';
import { global } from 'src/app/services/global';

@Component({
  selector: 'app-payroll',
  templateUrl: './payroll.component.html',
  styleUrls: ['./payroll.component.css'],
  providers: [PayrollServices]
})
export class PayrollComponent {
  public url;
  public data :any;
  public array: any;
  public columnas: string[]=[];

  constructor(
    private _payrollServices: PayrollServices
  ) {
    this.url = global.url;
   }

   ngOnInit(): void {
     this.getPosts();
  }

  getPosts(){
    this._payrollServices.getPosts().subscribe(
      response =>{
        this.data= response;
        this.columnas = response.title;

        console.log(this.columnas);
        console.log(this.data);
      },
      error =>{
        console.log(error)
      }
    )
  }

}

Y el HTML es el siguiente:

            <ng-container matColumnDef="columna" *ngFor="let columna of columnas">
                {{columnas}}
                {{element[columnas]}
            </ng-container>

Pero me da los siguientes errores:

He buscado información sobre lo que estoy queriendo hacer y no encuentro. Lo que encuentro siempre dejan al menos el encabezado de cada columna fijo, y necesito que todo sea dinámico. Si alguien tiene solución para esto le voy a estar muy agradecido.
PD: Perdón si estoy cometiendo algún error fulero, hace poco empecé a programar y menos tiempo que estoy con angular material. :)

A: Creo que te está fallando el tipo de dato, estás enviando una colección de objetos y está esperando un string.
Prueba convirtiendo la variable de tu array antes de pasarla al material con:
 getPosts(){
this._payrollServices.getPosts().subscribe(
  response =>{
    this.data= response;
    this.columnas = response.title;
    this.columnas = JSON.stringify(this.columnas)

    console.log(this.columnas);
    console.log(this.data);
  },
  error =>{
    console.log(error)
  }
)

}
Espero que te sirva.


text:
Q: Why has my JSP application slowed down considerably since upgrading to Tomcat 8? Having upgraded a legacy JSP application from Tomcat 7/Java 7 to Tomcat 8/Java 8 the page response time has deteriorated noticeably; some pages take 4 or 5 times as long to load.
I've found this in the JavaServer Pages 2.3 section of the Tomcat 8 migration notes:
"Unified Expression Language 3.0 added support for referencing static fields and methods. Supporting this feature in JSPs required changing the javax.servlet.jsp.el.ScopedAttributeELResolver implementation so that it also checked identifiers to see if they were names of imported classes or fields. In some circumstances, this change triggers significant slow down. This affects identifiers that may refer to a page, request, session or application scoped variable or may be undefined. When undefined, it takes significantly longer to resolve the identifier since it is now also checked to see if it is an imported class or field."
This goes some way to explaining the slow-down because the application includes many (100's) of .jsp and .tag files that include references to unscoped variables.  Sure enough, running strace on the Tomcat process I can see the class loader attempting to resolve these references e.g.

    Line 7063: 27709 13:42:46.248512 stat("/opt/tomcat/webapps/App/WEB-INF/classes/java/lang/width.class", 0x7f69cc9eb4f0) = -1 ENOENT (No such file or directory)
    Line 7075: 27709 13:42:46.250092 stat("/opt/tomcat/webapps/App/WEB-INF/classes/javax/servlet/width.class", 0x7f69cc9eb4f0) = -1 ENOENT (No such file or directory)
    Line 7085: 27709 13:42:46.251337 stat("/opt/tomcat/webapps/App/WEB-INF/classes/javax/servlet/http/width.class", 0x7f69cc9eb4f0) = -1 ENOENT (No such file or directory)
    Line 7095: 27709 13:42:46.252548 stat("/opt/tomcat/webapps/App/WEB-INF/classes/javax/servlet/jsp/width.class", 0x7f69cc9eb4f0) = -1 ENOENT (No such file or directory)

I see this behaviour every time a page is accessed.  I have two questions:
1.) Is there are way to configure Tomcat 8 to behave like Tomcat 7 in the way it treats unscoped variables so I don't have to trawl through 100's of .jsp and .tag files inserting the appropriate scope?
2.) Why does this happen every time a page is accessed?  I understand why it happens the first time, but once the page is compiled surely the JSP engine (Jasper) has worked out the correct scope.


text:
Q: Salesforce -Fire apex trigger only after complete data load So here is the issue We are loading data into a CustomObject__c using DataLoader. Usually the no of records that are passed are 3. Also, if there is any issue with the data passed, they run the dataloader again and pass the corrected data. Now, the older data has to be deleted. So, I am handling it in before insert code and calling a batch in after insert code.
Here is the code for my trigger:
trigger TriggerCustom on CustomObject__c (before insert, after insert) {
  List<CustomObject__c> customobjectlist = [Select Id from CustomObject__c WHERE CreatedDate = TODAY ];
    if (Trigger.isBefore) {
        delete exchlisttoday;

    }
    if(Trigger.isAfter)
    {
         BatchApex b = BatchApex();
            Database.executebatch(b);
    }
}

This was designed keeping in mind they pass only 3 records at a time. However, now they want to pass more than 200 records using data loader. How can I modify my trigger so that it fires only after one single dataload is completed (for e.g. if they pass 1000 records at once, the trigger has to fire only after the 1000 records are completely inserted

A:
How can I modify my trigger so that it fires only after one single dataload is completed (for e.g. if they pass 1000 records at once, the trigger has to fire only after the 1000 records are completely inserted

You can't. Triggers don't work like that, because triggers are part of the insertion process (the save order). Your trigger will fire for each batch of 200 records inserted during a single transaction. Note that it may or may not be possible to insert 1000 records in one transaction at all,  depending on how well-optimized your automation is; you may hit various governor limits.
Your trigger appears to be aiming to delete existing records when new ones are inserted. This is a risky pattern because it assumes that a data load fits within a single transaction, and moreso within a single trigger invocation. That latter point is no longer the case, so you'll have to change how you manage this process.
I would suggest you reframe your process to use a script or off-platform middleware solution to orchestrate the multi-stage operation, where you delete existing data, load new data, and then apparently process the new data with a batch job. You could also consider preprocessing the data off-platform to avoid the need for a batch job.


text:
Q: Using Shrine uploader with Google Drive I'm looking for an image and PDF upload solution for a Rails 4.2 app. Can shrine be used with Google Drive? I see documentation for use with Google Cloud Storage, but nothing about Google Drive. Thanks

A: Shrine can be used with any storage, someone just needs to write an integration gem for a given service. The website holds the list of all existing integration gems, and Google Drive isn't on the list yet.
If you want to create the Google Drive integration, I wrote a guide on creating new storages.


text:
Q: visual studio issue Q:
I have the following problem :
i don't know what the problem i made, but the visual studio sound strange,, arrows in the the side  of the .cs page and when type tab, dots appeared on the page ..many keys type other letters.
i reset my visual studio through import and export , reset keyboard shortcuts in the visual studio and restart my visual studio b ut still the same problem.

A: Try going to:
Edit > Advanced > View White Space
If it's turned on it'll show tabs as arrows and spaces as dots.

A: It sounds like you have View WhiteSpace switched on:
Edit -> Advanced -> Decheck View Whitepace

Ctrl + E, S works too


text:
Q: Angular Changing filter based on select value and text input I am new to Angular so I think this is a basic concept that I'm just missing some step on. I want to have a search that does basic angular filtering, but I want to have a separate select that chooses what the text input searches on. Currently it looks like this:
Search inputs:
<input type="text" class="form-control" id="search-users" ng-model="userQuery">

        <select ng-model="searchOn" ng-change="setSearchOn(searchOn)">
            <option value="CustomerId" selected>CustomerId</option>
            <option value="Username">Username</option>
        </select>

Function:
$scope.setSearchOn = function(searchOnIn){
            console.log("setting searchOn to "+searchOnIn);
            $scope.searchOn = searchOnIn;
        }

Repeater:

I feel like i shouldn't even need the function, shouldn't i be able to data-bind the value of the select to the filter on the repeater? I couldn't get that to work either. Help would be appreciated. Angular is awesome, but the beginning learning the way it works is a little rough :)

A: As I understand it, we want to pick the property which we search on with the dropdown, and then search that property for value on the userQuery input.
One way to accomplish that is to (re)build an object to filter with when either userQuery or searchOn alters.
var app = angular.module('myapp', []).controller('ctrl', function($scope){
    /* some test data */
    $scope.users = [{CustomerId : 1, Username : 'Pete'},
                   {CustomerId : 2, Username : 'John'},
                   {CustomerId : 3, Username : 'Claus'}]

    $scope.setSearchFilter = function()
    {
        $scope.searchFilter = {};
        $scope.searchFilter[$scope.searchOn] = $scope.userQuery;
    }
})

In the html, I've set an ng-change on both the userQuery and searchOn to update the search filter.

    <input type="text" class="form-control" id="search-users" ng-model="userQuery" ng-change="setSearchFilter()" />

        <select ng-model="searchOn" ng-change="setSearchFilter()">
            <option value="CustomerId" selected>CustomerId</option>
            <option value="Username">Username</option>
        </select>

          {{user.CustomerId}} -- {{user.Username}}

http://jsfiddle.net/nwdx7/1/


text:
Q: How to write a O(n^2) method that finds the largest distance between two points I have an array int [] nums = {5, 1, 6, 10, 4, 7, 3, 9, 2}
I want to find the distance between the smallest and largest number in that array in O(n^2) time.  It needs to be O(n^2) time as per the requirements of the assignment.  To do this, I am writing a method called quadratic.  So far I have come up with the code below.
public static int quadratic(int[] nums) {

    int max = nums[0];
    int min = nums[0];

    for (int i = 0; i < nums.length; i++) {
        for (int j = 0; j < nums.length; j++) {

            if (nums[i] > nums[j])
                max = nums[i];
            else if (nums[i] < nums[j])
                min = nums[i];
            }
        }

    int maxDifference = max - min;
    return maxDifference;
}

The problem is, when I run that method with array mentioned above, I get a max difference of 0.  I expect 9, since the largest number is 10, and the smallest is 1.  10 - 1 = 9.
My question is, can someone show me how I can change my code so that it properly computes the max distance between the smallest and largest numbers?

A: You're overwriting the max and mins.
if (nums[i] > nums[j])
    max = nums[i];
else if (nums[i] < nums[j])
    min = nums[i];
}

You need to compare the current number with the max/min that is set already. Instead you're comparing the current number with another number, and then overwriting max/min if the condition is true. In this example, at one point 10 was the max, but then you later checked if(9>2), which is true, so you changed max = 10 to max = 9.
Here it is in O(n^2) time, with the outer loop being completely useless.
public static int quadratic(int[] nums) {

    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;

    for (int i = 0; i < nums.length; i++) {
        for (int j = 0; j < nums.length; j++) {

            if (nums[j] > max)
                max = nums[j];
            if (nums[j] < min)
                min = nums[j];
            }
        }
    System.out.println(max + " " + min);
    int maxDifference = max - min;
    return maxDifference;
}

A: For numbers (as opposed to points on a plane) You can do that in linear time. Find maximum, find minimum, then subtract. So, no nested loops required.


text:
Q: UBUNTU 14.04/16.04 Server Boot: Dev Mount failed, falls to initramfs When booting a virtual server with Ubuntu 14.04/16.04 (I had the issues with both), it cant find the boot partition for root and the system falls to the initramfs shell with the following error:
(initframs) exit
Gave up waiting for root device. Common problems:
- Boot args (cat proc/cmdline)
- Check rootdelay= (did the system wait long enough?)
- Check root= (did the system wait for the right device?)
- Missing modules (cat /proc/modules; ls /dev)
ALERT! /dev/mapper/CAC_VG-CAC_LV does not exist. Dropping to a shell!

if I type
ls /dev/mapper/

I still can see the partition mentioned in the error (and in the GRUB)
root=/dev/mapper/CAC_VG-CAC_LV

cat output as suggested in the error message
(initframs) cat /proc/cmdline
BOOT_IMAGE=/vmlinuz-4.4.0-66-generic root=/dev/mapper/CAC_VG-CAC_LV ro

Notice: it seems to mount the device in Read-Only (ro). Maybe I should change this after I manage to start the system...
If I type exit I get the same error as above.
Then I try to mount:
mount -t ext4 /dev/mapper/CAC_VG-CAC_LV
mount: can't find /dev/mapper/CAC_VG-CAC_LV in /etc/fstab`

A: I had the same problem after a fresh install of Ubuntu 14.04
And this actually worked!!
mount -o remount, rw /
lvm vgscan
lvm vgchange -a y
mount -t ext4 /dev/mapper/CAC_VG-CAC_LV /root
exit


text:
Q: How to check quality gate status for a project using the API? I need to trigger HipChat notification for a project as soon as quality gate fails for a project in SonarQube. Is there a REST API for checking the quality gate status of a project. I couldn't find it under api/quailty_gate or api/projects.
I am open to other approaches of triggering a hipChat notifications as well.

A: You can get the quality gate status by using this REST endpoint:
/api/resources/index?includealerts=true&metrics=alert_status

which will give you an output similar to this one:
{
    "key": "alert_status",
    "data": "ERROR",
    "alert": "ERROR",
    "alert_text": "Major issues > 10, Files > 3"
}

A: The web service api/qualitygates/project_status has been introduced in v.5.3 to be able to get the gate status of a specified analysis (see parameter analysisId, which value is output during analysis). The initial goal is to be able to "break the build".
Version 5.4 added the parameters projectId and projectKey which are convenient when analysis is not known.
Note that version 5.5 will allow a SonarQube plugin to directly send a notification, for example to HipChat, when an analysis is finished. See JIRA ticket SONAR-7488.


text:
Q: Fibonacci series optimisation How can i optimise this ? Am getting timeout error when i executes this
I am trying to execute this on my wampserver on a windows 10.
This code is actually that i wrote for a test but the test fails if i get the values of $a and $b as huge.
Any help will be welcome. Thank you.
     * @param $n
     * @param false $offset
     * @param false $injectResult
     * @return int|mixed
     */

Seems that this part is the worm
function fibonacci($n, $offset = false, $injectResult = false)
{
    if ($offset == $n && $injectResult) {
        return $injectResult;
    }
    if ($n == 0) {
        return 0;
    }
    if ($n == 1) {
        return 1;
    }
    if ($n > 1) {
        return fibonacci($n - 1) + fibonacci($n - 2);
    }
}

    /**
     * Function to sum the fibonacci series result
     * @param $a
     * @param $b
     * @return float|int
     */

This part seems ok
function sumFibonacci($a, $b)
{
   $diff = $b - $a;
   $result = [];
   for ($i = 0; $i <= $diff; $i++) {
       if ($i == 0) {
           $result[$i] = fibonacci($a);
       } else {
           $result[$i] = fibonacci($a + $i, $a - ($i - 1), $result[$i - 1]);
       }
   }
       return array_sum($result);
}
// Example of how to use it
echo sumFibonacci(38,58);

/**
* How can i optimise this if  $a = 38 $b= 58 e.g sumFibonacci(38,58);
*/ ```

A: I solved it by modified the function to be non recursive
{
    $numnar1 = 0;
    $numnar2 = 1;
    $count = 0;
    $result='';
    while ($count < $numnar) {
        $result =  $numnar1;
        $numnar3 = $numnar2 + $numnar1;
        $numnar1 = $numnar2;
        $numnar2 = $numnar3;
        $count++;
    }
    return $result;
}


text:
Q: How to kill previous HttpRequest for a user session in a HttpServlet Is there any way to locate a previous HttpRequest, for a given session?
Web client sends request to a long running web service.  While this service is running the client sends another request. I want to locate the first request and send it a stop signal.
Background:
I have a web service that requires 2-4 seconds to process.  The servlet is hosted in a Tomcat container and is using OSGi to access the main processor in another plugin.
The requests come from another web site that allows users to make 10 or so requests at a time.  While the user is waiting they may make another page change that will start another 10 web requests.   I need a way to locate the previous requests.  Then I'll find a way to send a stop signal to the long running process which will allow the original HttpRequest to finish with some suitable error code.
Perhaps another way to look at this problem is to say:  if a client makes a series of requests that overlap then we only want to service the last request and cancel the previous requests as soon as possible.

A: I don't think HttpSession gives you what you are looking for, but I would recommend making some kind of object that your requests can periodically check to see if they are the "newest" request.  If they are no longer the newest request then they can stop themselves and return immediately.

A: You can keep the previous request job task in the session. And on next parallel request, you can get the earlier request job and take the action you want.


text:
Q: jQuery - Save / Update Credit Cards using Stripe Element and Local Storage In a test environment, I am trying to hook the Stripe Elements Credit Card validator into code that is set up to save the validated form information as well as update stored information. The code is to simulate a checkout UX where users can enter new credit card information (using the Stripe Elements form) and save their validated information using local storage.
In addition to being able to save their new cards, they can update cards that were already saved / appear on load.
The problem I have is that I am unsure how to define the var valid = (); that would loop the Stripe Elements form with the update / save code as well as run two instances of the Stripe validator (one for new cards, and another for updating saved cards).
Here is the codepen: https://codepen.io/moofawsaw/pen/jOOwbwG

$(document).ready(function() {
  var stripe = Stripe("pk_test_6pRNASCoBOKtIshFeQd4XMUh");
  var elements = stripe.elements();

  var style = {
    base: {
      iconColor: "#666EE8",
      color: "#31325F",
      lineHeight: "40px",
      fontWeight: 600,
      fontSize: "16px",

      "::placeholder": {
        color: "#CFD7E0",
        fontWeight: 400
      }
    }
  };

  var cardNumberElement = elements.create("cardNumber", {
    style: style
  });
  cardNumberElement.mount("#cc-number");

  var cardExpiryElement = elements.create("cardExpiry", {
    style: style
  });
  cardExpiryElement.mount("#cc-exp");

  var cardCvcElement = elements.create("cardCvc", {
    style: style
  });
  cardCvcElement.mount("#cc-cvc");

  function setOutcome(result) {
    var successElement = document.querySelector(".success");
    var errorElement = document.querySelector(".error");
    successElement.classList.remove("visible");
    errorElement.classList.remove("visible");

    if (result.token) {
      // In this example, we're simply displaying the token
      successElement.querySelector(".token").textContent = result.token.id;
      successElement.classList.add("visible");

      // In a real integration, you'd submit the form with the token to your backend server
      //var form = document.querySelector('form');
      //form.querySelector('input[name="token"]').setAttribute('value', result.token.id);
      //form.submit();
    } else if (result.error) {
      errorElement.textContent = result.error.message;
      errorElement.classList.add("visible");
    }
  }

  var cardBrandToPfClass = {
    visa: "pf-visa",
    mastercard: "pf-mastercard",
    amex: "pf-american-express",
    discover: "pf-discover",
    diners: "pf-diners",
    jcb: "pf-jcb",
    unknown: "pf-credit-card"
  };

  function setBrandIcon(brand) {
    var brandIconElement = document.getElementById("brand-icon");
    var pfClass = "pf-credit-card";
    if (brand in cardBrandToPfClass) {
      pfClass = cardBrandToPfClass[brand];
    }
    for (var i = brandIconElement.classList.length - 1; i >= 0; i--) {
      brandIconElement.classList.remove(brandIconElement.classList[i]);
    }
    brandIconElement.classList.add("pf");
    brandIconElement.classList.add(pfClass);
  }

  cardNumberElement.on("change", function(event) {
    // Switch brand logo
    if (event.brand) {
      setBrandIcon(event.brand);
    }

    setOutcome(event);
  });

  document.querySelector(".payment").addEventListener("submit", function(e) {
    e.preventDefault();
    var options = {};
    stripe.createToken(cardNumberElement, options).then(setOutcome);
  });

  $(function() {
    var $selectedItem;

    window.localStorage.clear();
    if (!localStorage.getItem("_storage")) {
      localStorage.setItem("_storage", "");
    }
    //create localStorage item
    if (localStorage.getItem("_storage")) {
      $("#content").html(localStorage.getItem("_storage"));
    }
    //set data to localStorage function
    function saveData() {
      localStorage.setItem("_storage", $("#content").html());
    }

    $(".payment").on("click", ".btn--save", function() {

      if (valid) {
        var id = $("#cc-cvc").val();
        var createnumb = $("#cc-number").val();
        var exp = $("#cc-exp").val();
        var item = "";
        if (id[0]) {
          for (var i = 0; i < id.length; i++) {
            item += "
" + id[i] + "
";
          }
        } else {
          item = "
Click update to add a card
";
        }
        $("#content").append(
          '
' +
          '
' +
          createnumb +
          "
" +
          "
" +
          id +
          "
" +
          "
" +
          exp +
          "
" +
          '<button class="card__remove">Delete</button>' +
          '<button class="card__update">Update</button>' +
          "
"
        );
        $("#cc-number").val("");
        $("#cc-exp").val("");
        $("#cc-cvc").val("");
        /*  $(".payment").toggle();*/
        saveData();
      }
    });
    //Close out of creating a new item
    /*  $(".close").click(function() {
    $("#cc-number").val("");
    $("#cc-cvc").val("");
    $(".create").toggle();
  });*/
    //Get inputs and open edit window to update the items:
    $("#content").on("click", ".card__update", function() {
      $selectedItem = $(this).closest(".checkout__card");
      $(".updatenumb").val(
        $(this)
        .closest(".checkout__card")
        .find(".card__numb")
        .text()
      );
      $(".updateexp").val(
        $(this)
        .closest(".checkout__card")
        .find(".card__exp")
        .text()
      );
      $(".updatecvc").val(
        $(this)
        .closest(".checkout__card")
        .find(".card__cvc")
        .text()
      );
      $(".card__modal").toggle();
    });
    //Save changes and update the items (error:changes all items when clicked):
    $(".card__modal").on("click", ".card__save", function() {

      if (valid) {
        var id = $(".updatecvc").val();
        var numb = $(".updatenumb").val();
        var exp = $(".updateexp").val();
        var item = "";
        if (id[0]) {
          for (var i = 0; i < id.length; i++) {
            item += "
" + id[i] + "
";
          }
        } else {
          item = "
Click edit to add a card
";
        }

        $selectedItem.html(
          '
' +
          numb +
          "
" +
          "
" +
          id +
          "
" +
          "
" +
          exp +
          "
" +
          '<button class="card__remove">Deleted(saved)</button>' +
          '<button class="card__update">Updated(saved)</button>'
        );
        $(".updatenumb").val("");
        $(".updateexp").val("");
        $(".updatecvc").val("");
        $(".card__modal").toggle();
        saveData();
      } else {}
    });
    //Discard any of these changes:
    $(".card__discard").click(function() {
      $(".updatenumb").val("");
      $(".updateexp").val("");
      $(".updatecvc").val("");
      $(".card__modal").toggle();
    });
    //Delete an item:
    $("#content").on("click", ".card__remove", function() {
      $(this)
        .closest(".checkout__card")
        .remove();
      saveData();
    });
  });
});
#content {
  display: flex;
  background-color: #f5f5f5;
  border: 1px solid #c2c2c2;
}

.checkout__card {
  display: flex;
  align-items: center;
}

.card__numb,
.card__cvc,
.card__exp {
  padding: 3px;
  margin: 3px;
  border: 1px solid;
}

payment__card,
.card__modal {
  display: none;
  position: absolute;
  z-index: 10;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  height: 200px;
  overflow: hidden;
  border: 2px solid;
}

input {
  border: 2px solid;
}

.field {
  background: transparent;
  font-weight: 400;
  border: 0;
  color: #31325f;
  outline: none;
  flex: 1;
  padding-right: 10px;
  padding-left: 10px;
  cursor: text;
}

.field::-webkit-input-placeholder {
  color: #cfd7e0;
}

.field::-moz-placeholder {
  color: #cfd7e0;
}

.outcome {
  float: left;
  width: 100%;
  padding-top: 8px;
  min-height: 24px;
  text-align: center;
}

.success,
.error {
  display: none;
  font-size: 13px;
}

.success.visible,
.error.visible {
  display: inline;
}

.error {
  color: #e4584c;
}

.success {
  color: #666ee8;
}

.success .token {
  font-weight: 500;
  font-size: 13px;
}

<form class="payment" action="//httpbin.org/post" method="POST">
  <input type="hidden" name="token" />

        Card number

        Expiry date

        CVC

  <button type="submit" class="btn--payment">Confirm</button>
  <button type="button" class="btn--save">Save</button>

      Success! Your Stripe token is

</form>

4353 2455 2346 8236

101

01/24

      <button class="card__remove">Delete</button>
      <button class="card__update">Update</button>

    <form class="payment" action="//httpbin.org/post" method="POST">
      <input type="hidden" name="token" />

        Card number

        Expiry date

        CVC

      <button type="submit" class="btn--payment">Confirm</button>
      <button type="button" class="btn--save">Save</button>

          Success! Your Stripe token is

    </form>
    <button class="card__save">Save</button>
    <button class="card__discard">Discard</button>

A:  var valid = $(".card__board").paymentForm("valid");

You can't get the card valid state from the above code since there is no method called paymentForm in div element.
Instead, you can call the stripe.createToken(cardNumberElement) method on click of .btn--save button and get the card validity then proceed the save or update operation.
 $(".payment").on("click", ".btn--save", function() {
    stripe.createToken(cardNumberElement).then(function(result){
        if(result.token){
         // do your stuff
        }else{
       // show the error
       }
    });
 });

or else, on specific to your code you can have a global variable to maintain the card validity state, update the variable value on .payment form submit and check that variable on save or update button click.
$(document).ready(function() {
  var stripe = Stripe("pk_test_6pRNASCoBOKtIshFeQd4XMUh");
  var elements = stripe.elements();
  var isValidCard =false;
 var style = {
    base: {
      iconColor: "#666EE8",
      color: "#31325F",
      lineHeight: "40px",
      fontWeight: 600,
      fontSize: "16px",

      "::placeholder": {
        color: "#CFD7E0",
        fontWeight: 400
      }
    }
  };

  var cardNumberElement = elements.create("cardNumber", {
    style: style
  });
  cardNumberElement.mount("#cc-number");

  var cardExpiryElement = elements.create("cardExpiry", {
    style: style
  });
  cardExpiryElement.mount("#cc-exp");

  var cardCvcElement = elements.create("cardCvc", {
    style: style
  });
  cardCvcElement.mount("#cc-cvc");

  function setOutcome(result) {
    var successElement = document.querySelector(".success");
    var errorElement = document.querySelector(".error");
    successElement.classList.remove("visible");
    errorElement.classList.remove("visible");

    if (result.token) {
      // In this example, we're simply displaying the token
      successElement.querySelector(".token").textContent = result.token.id;
      successElement.classList.add("visible");
      isValidCard = true;
      // In a real integration, you'd submit the form with the token to your backend server
      //var form = document.querySelector('form');
      //form.querySelector('input[name="token"]').setAttribute('value', result.token.id);
      //form.submit();
    } else if (result.error) {
      errorElement.textContent = result.error.message;
      errorElement.classList.add("visible");
      isValidCard=false;
    }
  }
   document.querySelector(".payment").addEventListener("submit", function(e) {
    e.preventDefault();
    var options = {};
    stripe.createToken(cardNumberElement, options).then(setOutcome);
  });

    $(".payment").on("click", ".btn--save", function() {
     // var valid = $(".card__board").paymentForm("valid");
      if(isValidCard){
      }
    });

});


text:
Q: Program is timing out while waiting to exit I'm not sure what is making this code time out and not exit, I suspect its something to do with my while loop near the end of the code
// Copies a BMP file and resizes it

#include <stdio.h>
#include <stdlib.h>
#include "bmp.h"

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 4)
    {
        fprintf(stderr, "Usage: ./resize factor infile outfile\n");
        return 1;
    }
    // Check argument 1 to see if integer within aceptable range
    int factor = atoi(argv[1]);
    if (factor <= 0 || factor > 100)
    {
        fprintf(stderr, "Must be a positive integer greater than 0 and eqaul or less than 100\n");
        return 1;
    }

    // remember filenames
    char *infile = argv[2];
    char *outfile = argv[3];

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }

    // open output file
    FILE *outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 3;
    }

    // read infile's BITMAPFILEHEADER
    BITMAPFILEHEADER bf;
    BITMAPFILEHEADER bf_New;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);
    bf_New = bf;

    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi;
    BITMAPINFOHEADER bi_New;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);
    bi_New = bi;

    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }

    // set new height and width of BMP
    bi_New.biHeight = bi.biHeight * factor;
    bi_New.biWidth = bi.biWidth * factor;

    // calculate padding for old file and new file
    int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
    int padding_New = (4 - (bi_New.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

    // set the file size for the new file
    bf_New.bfSize = 54 + (bi_New.biWidth * sizeof(RGBTRIPLE) + padding_New) * abs(bi_New.biHeight);
    bi_New.biSizeImage = bf_New.bfSize - 54;

    // write outfile's BITMAPFILEHEADER
    fwrite(&bf_New, sizeof(BITMAPFILEHEADER), 1, outptr);

    // write outfile's BITMAPINFOHEADER
    fwrite(&bi_New, sizeof(BITMAPINFOHEADER), 1, outptr);

    // iterate over infile's scanlines
    for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
    {
        // iterate over pixels in scanline
        for (int j = 0; j < bi.biWidth; j++)
        {
            // intialise counter to print rows by amount of the factor
            int counter = 0;

            // while loop to keep continuing until factor is less than or equal to counter
            while (counter < factor)
            {
                // iterate over pixels in scanline
                for(int k = 0; k < bi.biWidth; k++)
                {
                    // temporary storage
                    RGBTRIPLE triple;

                    // declare pixel counter
                    int pixel_counter = 0;

                    // read RGB triple from infile
                    fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

                    // write RGB triple to outfile and use a while loop to iterate the same pixel by factor times
                    while (pixel_counter < factor)
                    {
                        fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
                        pixel_counter++;
                    }
                }
                // add new padding
                for (int l = 0; l < padding_New; l++)
                {
                    fputc(0x00, outptr);
                }

                // seek back to the beginning of row in input file, but not after iteration of printing
                if (counter < (factor - 1))
                {
                    fseek(inptr, -(bi.biWidth * sizeof(RGBTRIPLE)), SEEK_CUR);
                    counter++;
                }
            }
        }

        // skip over padding, if any
        fseek(inptr, padding, SEEK_CUR);
    }

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    // success
    return 0;
}

**These are the error messages im getting from my course code checker cs50
:) resize.c and bmp.h exist.
:) resize.c compiles.
:( doesn't resize small.bmp when n is 1
    timed out while waiting for program to exit
:( resizes small.bmp correctly when n is 2
    timed out while waiting for program to exit
:( resizes small.bmp correctly when n is 3
    timed out while waiting for program to exit
and so on...**

A: The while (counter < factor) loop will never exit, because you only increment counter when the condition counter < (factor - 1) is true.
You probably want to increment counter outside the if (counter < factor - 1) condition.


text:
Q: SQLDev limiting results TIA for any help/advice/further reading.
I'm trying to make SQLDev do a count of how many packages customers have had and then only show the top 10 of those results.
So I have this....
    select  pickup_customer , count (pickup_customer)
from
( select pickup_customer, count (pickup_customer)
    from manifest
   order by count (pickup_customer) desc )
 where ROWNUM <= 10
 group by pickup_customer
 order by count (pickup_customer) desc

With that I'm getting 'Not a single group function' and I can't figure out where it's gone wrong. Probably very simple fix, I just can't see it right now!
EDIT: I have tried this code but am getting a 'missing right parenthesis ' error now!
select  pickup_customer , count (pickup_customer)
from
(select pickup_customer, count (pickup_customer) --sub-query which pre-orders the results for rownum to then limit.
    from manifest
   order by count (pickup_customer) desc
   group by pickup_customer)
 where ROWNUM <= 10    -- limits the results to be only the top 10

A: The following query should work.
SELECT pickup_customer, COUNT (pickup_customer)
FROM enrollment
WHERE ROWNUM <= 10
GROUP BY pickup_customer
ORDER BY COUNT (pickup_customer) DESC


text:
Q: Can we add custom validation to Editor Part Property? I have Appearance Editor Part in my application. I have an requirement like i have to include a custom validation like required field validation to the Title Property of Appearance Editor Part. How to include this?
I found many answers to change to custom web part rather than Appearance Editor Part. But in my project , i cannot do this. I want to include custom validator to the title property of Appearance Editor part alone.


text:
Q: What options can I pass to Amplify.configure()? There seem to be two different ways to configure Amplify. Some examples use a key-value properties format:
import aws_exports from "./aws-exports";
Amplify.configure(aws_exports);

Where the aws-exports is something like this:
    const awsmobile = {
        "aws_project_region": "ap-southeast-2",
        "aws_appsync_graphqlEndpoint": "<my graphQL endpoint URL>",
        "aws_appsync_region": "ap-southeast-2",
        "aws_appsync_authenticationType": "API_KEY",
        "aws_appsync_apiKey": "<my API key>",
        "aws_cognito_region": "ap-southeast-2",
        "aws_user_pools_id": "<my user pool id>",
        "aws_user_pools_web_client_id": "<my user pool web client id>",
        "aws_cognito_identity_pool_id": "<my cognito id pool id>",
    };
    export default awsmobile;

And other examples configure Amplify (and its modules) passing the properties in a json format:
Amplify.configure({
  Auth: {
    mandatorySignIn: true,
    region: "ap-southeast-2",
    userPoolId: "<my user pool id>",
    identityPoolId: "<my cognito id pool id>",
    userPoolWebClientId: "<my user pool web client id>"
  },
});

The properties are similar but different. I currently use the key-value properties but want to reconfigure Appsync to use authenticationType AMAZON_COGNITO_USER_POOLS using the json format.
What is the difference in the two formats and how do the key-values translate to the Json structure?

A: I haven't come across any explicit explanation for the two formats. But if you look at the documentation page for setting up the Amplify API, the two formats are used in different scenarios. The automated setup uses the key-value file generated by the Amplify CLI (by importing "./aws-exports"). The manual setup, on the other hand, uses the nested json format.
The documentation makes similar differentiation for setting up Authentication, Analytics, etc. I believe the implication is that "./aws-exports" is a file generated by the Amplify CLI, so it shouldn't be modified manually and thus its key-value format is intended more for internal use. Examples for manual configuration tend to use the nested json format.
Having said that, the documentation is not 100% consistent. The documentation for Amplify GraphQL illustrates configuration using the key-value format when you're using AWS AppSync as your GraphQL server. To configure for other kinds of GraphQL servers, it uses the nested json format.
My best guess is that the Amplify library was originally designed to be self-contained and its key-value configuration file was only for internal use. Over time they opened it up for customization, and then created the nested json format to make configuration more readable (and possibly add type checking). However, things haven't fully switched over so we are seeing both formats in use.


text:
Q: Install AWS SSL Certificate to home server I have a domain name bought from AWS, and can get SSl certificate from AWS ACM.
I could install the certificates to Load Balancer for EC2.
Now I am hosting a server at home, either a NodeJS app or Python Flask app.
How can I get the website to use https protocol?

A:
How can I get the website to use https protocol?

Yes, you can, but not from AWS ACM. The SSL certificates from ACM can only be used on:

*

*Elastic Load Balancing

*Amazon CloudFront

*Amazon API Gateway

For home server, you have to get a SSL certificate from a third party. A popular choice is https://letsencrypt.org/ which offers free public SSL certificates. But to register an SSL cert, you will need a DNS domain for your home server.


text:
Q: Symbol for twice differentiable functions Is there a symbol for the set of twice differentiable functions (2nd derivative not necessarily continuous)? I believe the symbol for twice continuously differentiable functions is $C^2(\mathbb F)$? Thanks

A: Given your tag of functional analysis, the following might be of interest for you:
The Sobolev space $W^{k,p}(\Omega)$ is the set of all functions $f \in L^p(\Omega)$ such that for every  multi-index $\alpha$ $|α| \leq k$, the weak partial derivative $D^\alpha f$ belongs to $L^p(\Omega)$.
More details in Wikipedia.


text:
Q: Difference between if-else and conditional-operator I have come across the following code snippet and need help in understanding what's going on under the hood.
    Object o1,o2;

    o1 = true?new Integer(2):new Double(3);
    if(true){
        o2 = new Integer(2);
    }else{
        o2 = new Double(3);
    }

    System.out.println(o1 + "\t" + o1.getClass().getName());
    System.out.println(o2 + "\t" + o2.getClass().getName());

The above code would seem to be easy enough to guess the accurate result, but when I run it, I get the following output.
2.0     java.lang.Double
2       java.lang.Integer

It looks like the JVM is somehow typecasting the output (Integer) to a Double in the first case and not in the second.
I would like to know the reason behind this, as I have always believed that the conditional-operator and the if-else statements are equivalent.