Programs & Examples On #Url link

Vertical align in bootstrap table

The following appears to work:

table td {
  vertical-align: middle !important;
}

You can apply to a specific table as well like so:

#some_table td {
  vertical-align: middle !important;
}

Git remote branch deleted, but still it appears in 'branch -a'

Don't forget the awesome

git fetch -p

which fetches and prunes all origins.

Setting Curl's Timeout in PHP

See documentation: http://www.php.net/manual/en/function.curl-setopt.php

CURLOPT_CONNECTTIMEOUT - The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
CURLOPT_TIMEOUT - The maximum number of seconds to allow cURL functions to execute.

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds

also don't forget to enlarge time execution of php script self:

set_time_limit(0);// to infinity for example

Update Query with INNER JOIN between tables in 2 different databases on 1 server

You could call it just style, but I prefer aliasing to improve readability.

UPDATE A    
  SET ControllingSalesRep = RA.SalesRepCode   
from DHE.dbo.tblAccounts A
  INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink RA
    ON A.AccountCode = RA.AccountCode

For MySQL

UPDATE DHE.dbo.tblAccounts A 
  INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink RA 
      ON A.AccountCode = RA.AccountCode 
SET A.ControllingSalesRep = RA.SalesRepCode

SQL Server IF EXISTS THEN 1 ELSE 2

Its best practice to have TOP 1 1 always.

What if I use SELECT 1 -> If condition matches more than one record then your query will fetch all the columns records and returns 1.

What if I use SELECT TOP 1 1 -> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.

IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

What is an Android PendingIntent?

Why PendingIntent is required ? I was thinking like

  1. Why the receiving application itself cannot create the Intent or
  2. Why we cannot use a simple Intent for the same purpose.

E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

If I send bluetoothIntent to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent).

The limitation is overcome using PendingIntent. With PendingIntent the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN for enabling Bluetooth. Source.

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.

The difference between firstOrCreate() and firstOrNew():

  • firstOrCreate() will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.
  • firstOrNew() will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save() on the model). Otherwise it will give you the matched item.

Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name or some mandatory field), you should use firstOrNew(). If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate().

Check if a class `active` exist on element with jquery

Pure JavaScript answer:

document.querySelector('.menu').classList.contains('active');

Might help someone someday.

Can't find AVD or SDK manager in Eclipse

Chances are that you may be running your eclipse using Java 1.5.

Latest Plugin requires that the JRE be 1.6 or higher. 

You will have to use Eclipse that runs on JRE 1.6

Edit: I had run into same problems. If it is not JRE problem then you can debug this. Follow below procedure:

  1. Window -> show View -> other -> Plugin Development -> Plugin Registry
  2. In the plugin registry search for com.android.ide.eclipse.adt or any other plugin related to android (depending on your installation there maybe 7-8)
  3. Select , Right Click -> Diagnose. This will show the problem why the plugin was not loaded

Static Initialization Blocks

static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member

Eg:-class Solution{
         // static int x=10;
           static int x;
       static{
        try{
          x=System.out.println();
          }
         catch(Exception e){}
        }
       }

     class Solution1{
      public static void main(String a[]){
      System.out.println(Solution.x);
        }
        }

Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..

}

How to clear the canvas for redrawing

This is 2018 and still there is no native method to completely clear canvas for redrawing. clearRect() does not clear the canvas completely. Non-fill type drawings are not cleared out (eg. rect())

1.To completely clear canvas irrespective of how you draw:

context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.beginPath();

Pros: Preserves strokeStyle, fillStyle etc.; No lag;

Cons: Unnecessary if you are already using beginPath before drawing anything

2.Using the width/height hack:

context.canvas.width = context.canvas.width;

OR

context.canvas.height = context.canvas.height;

Pros: Works with IE Cons: Resets strokeStyle, fillStyle to black; Laggy;

I was wondering why a native solution does not exist. Actually, clearRect() is considered as the single line solution because most users do beginPath() before drawing any new path. Though beginPath is only to be used while drawing lines and not closed path like rect().

This is the reason why the accepted answer did not solve my problem and I ended up wasting hours trying different hacks. Curse you mozilla

What's the maximum value for an int in PHP?

Ah I found it: 232 - 1 (2147483647)

http://au2.php.net/int

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

<?php
$large_number =  2147483647;
var_dump($large_number);
// output: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648)

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

Use offset() function of jQuery. Here it would be:

$container.offset({
        'left': 100,
        'top': mouse.y - ( event_state.mouse_y - event_state.container_top ) 
    });

Load json from local file with http.get() in angular 2

If you are using Angular CLI: 7.3.3 What I did is, On my assets folder I put my fake json data then on my services I just did this.

const API_URL = './assets/data/db.json';

getAllPassengers(): Observable<PassengersInt[]> {
    return this.http.get<PassengersInt[]>(API_URL);
  }

enter image description here

Get int value from enum in C#

public enum QuestionType
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

...is a fine declaration.

You do have to cast the result to int like so:

int Question = (int)QuestionType.Role

Otherwise, the type is still QuestionType.

This level of strictness is the C# way.

One alternative is to use a class declaration instead:

public class QuestionType
{
    public static int Role = 2,
    public static int ProjectFunding = 3,
    public static int TotalEmployee = 4,
    public static int NumberOfServers = 5,
    public static int TopBusinessConcern = 6
}

It's less elegant to declare, but you don't need to cast it in code:

int Question = QuestionType.Role

Alternatively, you may feel more comfortable with Visual Basic, which caters for this type of expectation in many areas.

Disable elastic scrolling in Safari

None of the 'overflow' solutions worked for me. I'm coding a parallax effect with JavaScript using jQuery. In Chrome and Safari on OSX the elastic/rubber-band effect was messing up my scroll numbers, since it actually scrolls past the document's height and updates the window variables with out-of-boundary numbers. What I had to do was check if the scrolled amount was larger than the actual document's height, like so:

$(window).scroll(
    function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height()) return;
        updateScroll(); // my own function to do my parallaxing stuff
    }
);

How to get RegistrationID using GCM in android

Here I have written a few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find a complete tutorial here:

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snippet to get Registration ID (Device Token for Push Notification).

Configure project for GCM


Update AndroidManifest file

To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml and add this code: Add Permissions

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration in your application tag:

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>
     
<application/>

Add GCM Service declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);
    context = getApplicationContext();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = getRegistrationId(context);

        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.d(TAG, "No valid Google Play Services APK found.");
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    checkPlayServices();
}


// # Implement GCM Required methods(Add below methods in LaunchActivity)

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
            finish();
        }
        return false;
    }
    return true;
}

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.d(TAG, "Registration ID not found.");
        return "";
    }
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
        Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Could not get package name: " + e);
    }
}


private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Log.d(TAG, "########################################");
                Log.d(TAG, "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return null;
        }
        protected void onPostExecute(Object result) {
            //to do here
        };
    }.execute(null, null, null);
}

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY only.

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Run a command over SSH with JSch

Usage:

String remoteCommandOutput = exec("ssh://user:pass@host/work/dir/path", "ls -t | head -n1");
String remoteShellOutput = shell("ssh://user:pass@host/work/dir/path", "ls");
shell("ssh://user:pass@host/work/dir/path", "ls", System.out);
shell("ssh://user:pass@host", System.in, System.out);
sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");

Implementation:

import static com.google.common.base.Preconditions.checkState;
import static java.lang.Thread.sleep;
import static org.apache.commons.io.FilenameUtils.getFullPath;
import static org.apache.commons.io.FilenameUtils.getName;
import static org.apache.commons.lang3.StringUtils.trim;

import com.google.common.collect.ImmutableMap;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.util.Map;
import java.util.Properties;

public final class SshUtils {

    private static final Logger LOG = LoggerFactory.getLogger(SshUtils.class);
    private static final String SSH = "ssh";
    private static final String FILE = "file";

    private SshUtils() {
    }

    /**
     * <pre>
     * <code>
     * sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
     * sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
     * </code>
     *
     * <pre>
     *
     * @param fromUri
     *            file
     * @param toUri
     *            directory
     */
    public static void sftp(String fromUri, String toUri) {
        URI from = URI.create(fromUri);
        URI to = URI.create(toUri);

        if (SSH.equals(to.getScheme()) && FILE.equals(from.getScheme()))
            upload(from, to);
        else if (SSH.equals(from.getScheme()) && FILE.equals(to.getScheme()))
            download(from, to);
        else
            throw new IllegalArgumentException();
    }

    private static void upload(URI from, URI to) {
        try (SessionHolder<ChannelSftp> session = new SessionHolder<>("sftp", to);
                FileInputStream fis = new FileInputStream(new File(from))) {

            LOG.info("Uploading {} --> {}", from, session.getMaskedUri());
            ChannelSftp channel = session.getChannel();
            channel.connect();
            channel.cd(to.getPath());
            channel.put(fis, getName(from.getPath()));

        } catch (Exception e) {
            throw new RuntimeException("Cannot upload file", e);
        }
    }

    private static void download(URI from, URI to) {
        File out = new File(new File(to), getName(from.getPath()));
        try (SessionHolder<ChannelSftp> session = new SessionHolder<>("sftp", from);
                OutputStream os = new FileOutputStream(out);
                BufferedOutputStream bos = new BufferedOutputStream(os)) {

            LOG.info("Downloading {} --> {}", session.getMaskedUri(), to);
            ChannelSftp channel = session.getChannel();
            channel.connect();
            channel.cd(getFullPath(from.getPath()));
            channel.get(getName(from.getPath()), bos);

        } catch (Exception e) {
            throw new RuntimeException("Cannot download file", e);
        }
    }

    /**
     * <pre>
     * <code>
     * shell("ssh://user:pass@host", System.in, System.out);
     * </code>
     * </pre>
     */
    public static void shell(String connectUri, InputStream is, OutputStream os) {
        try (SessionHolder<ChannelShell> session = new SessionHolder<>("shell", URI.create(connectUri))) {
            shell(session, is, os);
        }
    }

    /**
     * <pre>
     * <code>
     * String remoteOutput = shell("ssh://user:pass@host/work/dir/path", "ls")
     * </code>
     * </pre>
     */
    public static String shell(String connectUri, String command) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            shell(connectUri, command, baos);
            return baos.toString();
        } catch (RuntimeException e) {
            LOG.warn(baos.toString());
            throw e;
        }
    }

    /**
     * <pre>
     * <code>
     * shell("ssh://user:pass@host/work/dir/path", "ls", System.out)
     * </code>
     * </pre>
     */
    public static void shell(String connectUri, String script, OutputStream out) {
        try (SessionHolder<ChannelShell> session = new SessionHolder<>("shell", URI.create(connectUri));
                PipedOutputStream pipe = new PipedOutputStream();
                PipedInputStream in = new PipedInputStream(pipe);
                PrintWriter pw = new PrintWriter(pipe)) {

            if (session.getWorkDir() != null)
                pw.println("cd " + session.getWorkDir());
            pw.println(script);
            pw.println("exit");
            pw.flush();

            shell(session, in, out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void shell(SessionHolder<ChannelShell> session, InputStream is, OutputStream os) {
        try {
            ChannelShell channel = session.getChannel();
            channel.setInputStream(is, true);
            channel.setOutputStream(os, true);

            LOG.info("Starting shell for " + session.getMaskedUri());
            session.execute();
            session.assertExitStatus("Check shell output for error details.");
        } catch (InterruptedException | JSchException e) {
            throw new RuntimeException("Cannot execute script", e);
        }
    }

    /**
     * <pre>
     * <code>
     * System.out.println(exec("ssh://user:pass@host/work/dir/path", "ls -t | head -n1"));
     * </code>
     * 
     * <pre>
     * 
     * @param connectUri
     * @param command
     * @return
     */
    public static String exec(String connectUri, String command) {
        try (SessionHolder<ChannelExec> session = new SessionHolder<>("exec", URI.create(connectUri))) {
            String scriptToExecute = session.getWorkDir() == null
                    ? command
                    : "cd " + session.getWorkDir() + "\n" + command;
            return exec(session, scriptToExecute);
        }
    }

    private static String exec(SessionHolder<ChannelExec> session, String command) {
        try (PipedOutputStream errPipe = new PipedOutputStream();
                PipedInputStream errIs = new PipedInputStream(errPipe);
                InputStream is = session.getChannel().getInputStream()) {

            ChannelExec channel = session.getChannel();
            channel.setInputStream(null);
            channel.setErrStream(errPipe);
            channel.setCommand(command);

            LOG.info("Starting exec for " + session.getMaskedUri());
            session.execute();
            String output = IOUtils.toString(is);
            session.assertExitStatus(IOUtils.toString(errIs));

            return trim(output);
        } catch (InterruptedException | JSchException | IOException e) {
            throw new RuntimeException("Cannot execute command", e);
        }
    }

    public static class SessionHolder<C extends Channel> implements Closeable {

        private static final int DEFAULT_CONNECT_TIMEOUT = 5000;
        private static final int DEFAULT_PORT = 22;
        private static final int TERMINAL_HEIGHT = 1000;
        private static final int TERMINAL_WIDTH = 1000;
        private static final int TERMINAL_WIDTH_IN_PIXELS = 1000;
        private static final int TERMINAL_HEIGHT_IN_PIXELS = 1000;
        private static final int DEFAULT_WAIT_TIMEOUT = 100;

        private String channelType;
        private URI uri;
        private Session session;
        private C channel;

        public SessionHolder(String channelType, URI uri) {
            this(channelType, uri, ImmutableMap.of("StrictHostKeyChecking", "no"));
        }

        public SessionHolder(String channelType, URI uri, Map<String, String> props) {
            this.channelType = channelType;
            this.uri = uri;
            this.session = newSession(props);
            this.channel = newChannel(session);
        }

        private Session newSession(Map<String, String> props) {
            try {
                Properties config = new Properties();
                config.putAll(props);

                JSch jsch = new JSch();
                Session newSession = jsch.getSession(getUser(), uri.getHost(), getPort());
                newSession.setPassword(getPass());
                newSession.setUserInfo(new User(getUser(), getPass()));
                newSession.setDaemonThread(true);
                newSession.setConfig(config);
                newSession.connect(DEFAULT_CONNECT_TIMEOUT);
                return newSession;
            } catch (JSchException e) {
                throw new RuntimeException("Cannot create session for " + getMaskedUri(), e);
            }
        }

        @SuppressWarnings("unchecked")
        private C newChannel(Session session) {
            try {
                Channel newChannel = session.openChannel(channelType);
                if (newChannel instanceof ChannelShell) {
                    ChannelShell channelShell = (ChannelShell) newChannel;
                    channelShell.setPtyType("ANSI", TERMINAL_WIDTH, TERMINAL_HEIGHT, TERMINAL_WIDTH_IN_PIXELS, TERMINAL_HEIGHT_IN_PIXELS);
                }
                return (C) newChannel;
            } catch (JSchException e) {
                throw new RuntimeException("Cannot create " + channelType + " channel for " + getMaskedUri(), e);
            }
        }

        public void assertExitStatus(String failMessage) {
            checkState(channel.getExitStatus() == 0, "Exit status %s for %s\n%s", channel.getExitStatus(), getMaskedUri(), failMessage);
        }

        public void execute() throws JSchException, InterruptedException {
            channel.connect();
            channel.start();
            while (!channel.isEOF())
                sleep(DEFAULT_WAIT_TIMEOUT);
        }

        public Session getSession() {
            return session;
        }

        public C getChannel() {
            return channel;
        }

        @Override
        public void close() {
            if (channel != null)
                channel.disconnect();
            if (session != null)
                session.disconnect();
        }

        public String getMaskedUri() {
            return uri.toString().replaceFirst(":[^:]*?@", "@");
        }

        public int getPort() {
            return uri.getPort() < 0 ? DEFAULT_PORT : uri.getPort();
        }

        public String getUser() {
            return uri.getUserInfo().split(":")[0];
        }

        public String getPass() {
            return uri.getUserInfo().split(":")[1];
        }

        public String getWorkDir() {
            return uri.getPath();
        }
    }

    private static class User implements UserInfo, UIKeyboardInteractive {

        private String user;
        private String pass;

        public User(String user, String pass) {
            this.user = user;
            this.pass = pass;
        }

        @Override
        public String getPassword() {
            return pass;
        }

        @Override
        public boolean promptYesNo(String str) {
            return false;
        }

        @Override
        public String getPassphrase() {
            return user;
        }

        @Override
        public boolean promptPassphrase(String message) {
            return true;
        }

        @Override
        public boolean promptPassword(String message) {
            return true;
        }

        @Override
        public void showMessage(String message) {
            // do nothing
        }

        @Override
        public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
            return null;
        }
    }
}

Add custom header in HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
    {
        const string WEBSERVICE_URL = "<<Web service URL>>";
        try
        {
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");

                using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                    {
                        var jsonResponse = sr.ReadToEnd();
                        Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

Finding duplicate integers in an array and display how many times they occurred

Here is an answer that avoids using Dictionaries. Since the OP said he is not familiar with them, this might give him a little insight into what Dictionaries do.

The downside to this answer is you have to enforce a limit on the max number in the array, and you can't have negative numbers. You'd never actually use this version in real code.

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int[] count = new int[13];

foreach(int number in array) {
    // using the index of count same way you'd use a key in a dictionary
    count[number]++;
}

foreach(int c in count) {
    int numberCount = count[c];
    if(numberCount > 0) {
        Console.WriteLine(c + " occurs " + numberCount + " times");
    }
}

Can inner classes access private variables?

var is not a member of inner class.

To access var, a pointer or reference to an outer class instance should be used. e.g. pOuter->var will work if the inner class is a friend of outer, or, var is public, if one follows C++ standard strictly.

Some compilers treat inner classes as the friend of the outer, but some may not. See this document for IBM compiler:

"A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class. Unless you use explicit pointers, references, or object names, declarations in a nested class can only use visible constructs, including type names, static members, and enumerators from the enclosing class and global variables.

Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes. Member functions of the enclosing class have no special access to members of a nested class."

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

Disable scrolling on `<input type=number>`

$(document).on("wheel", "input[type=number]", function (e) {
    $(this).blur();
});

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

i simply change my import from import from { AngularFirestore} from '@angular/fire/firestore'; to import { AngularFirestoreModule } from '@angular/fire/firestore';

and it's working fine

SSRS the definition of the report is invalid

I just received this obscure message when trying to deploy a report from BIDS.

After a little hunting I found a more descriptive error by going into the Preview window.

Create a button programmatically and set a background image

Swift: Ui Button create programmatically

let myButton = UIButton()

myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)

myButton.titleLabel!.text = "Button Label"

myButton.titleLabel!.textColor = UIColor.redColor()

myButton.titleLabel!.textAlignment = .Center

myButton.addTarget(self,action:"Action:",forControlEvents:UIControlEvent.TouchUpInside)

self.view.addSubview(myButton)

Populating Spring @Value during Unit Test

Adding PropertyPlaceholderConfigurer in configuration is working for me.

@Configuration
@ComponentScan
@EnableJpaRepositories
@EnableTransactionManagement
public class TestConfiguration {
    @Bean
    public DataSource dataSource() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        builder.setType(EmbeddedDatabaseType.DERBY);
        return builder.build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPackagesToScan(new String[] { "com.test.model" });
        // Use hibernate
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
        entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
        return entityManagerFactoryBean;
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", "false");
        properties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
        properties.put("hibernate.hbm2ddl.auto", "update");
        return properties;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(
              entityManagerFactory().getObject()
         );

         return transactionManager;
    }

    @Bean
    PropertyPlaceholderConfigurer propConfig() {
        PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
        placeholderConfigurer.setLocation(new ClassPathResource("application_test.properties"));
        return placeholderConfigurer;
    }
}

And in test class

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
public class DataServiceTest {

    @Autowired
    private DataService dataService;

    @Autowired
    private DataRepository dataRepository;

    @Value("${Api.url}")
    private String baseUrl;

    @Test
    public void testUpdateData() {
        List<Data> datas = (List<Data>) dataRepository.findAll();
        assertTrue(datas.isEmpty());
        dataService.updateDatas();
        datas = (List<Data>) dataRepository.findAll();
        assertFalse(datas.isEmpty());
    }
}

IN-clause in HQL or Java Persistence Query Language

Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.

String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);

JavaScript CSS how to add and remove multiple CSS classes to an element

In modern browsers, the classList API is supported.

This allows for a (vanilla) JavaScript function like this:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];

        // Loop through the array of classes to add one class at a time
        for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
            className = classArray[j];

            element.classList.add(className);
        }
    }
};

Modern browsers (not IE) support passing multiple arguments to the classList::add function, which would remove the need for the nested loop, simplifying the function a bit:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var classList, className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];
        classList = element.classList;

        // Pass the array of classes as multiple arguments to classList::add
        classList.add.apply(classList, classArray);
    }
};

Usage

addClasses('.button', ['large', 'primary']);

Functional version

var addClassesToElement, addClassesToSelection;

addClassesToElement = function (element, classArray) {
    'use strict';

    classArray.forEach(function (className) {
       element.classList.add(className);
    });
};

addClassesToSelection = function (selector, classArray) {
    'use strict';

    // Use Array::forEach on NodeList to iterate over results.
    // Okay, since we’re not trying to modify the NodeList.
    Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
        addClassesToElement(element, classArray)
    });
};

// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])

The classList::add function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.

Resources on the classList API:

How does HTTP file upload work?

I have this sample Java Code:

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class TestClass {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8081);
        Socket accept = socket.accept();
        InputStream inputStream = accept.getInputStream();

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        char readChar;
        while ((readChar = (char) inputStreamReader.read()) != -1) {
            System.out.print(readChar);
        }

        inputStream.close();
        accept.close();
        System.exit(1);
    }
}

and I have this test.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>File Upload!</title>
</head>
<body>
<form method="post" action="http://localhost:8081" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input type="submit">
</form>
</body>
</html>

and finally the file I will be using for testing purposes, named a.dat has the following content:

0x39 0x69 0x65

if you interpret the bytes above as ASCII or UTF-8 characters, they will actually will be representing:

9ie

So let 's run our Java Code, open up test.html in our favorite browser, upload a.dat and submit the form and see what our server receives:

POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 196
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary06f6g54NVbSieT6y
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,tr;q=0.6
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF

------WebKitFormBoundary06f6g54NVbSieT6y
Content-Disposition: form-data; name="file"; filename="a.dat"
Content-Type: application/octet-stream

9ie
------WebKitFormBoundary06f6g54NVbSieT6y--

Well I am not surprised to see the characters 9ie because we told Java to print them treating them as UTF-8 characters. You may as well choose to read them as raw bytes..

Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF 

is actually the last HTTP Header here. After that comes the HTTP Body, where meta and contents of the file we uploaded actually can be seen.

Get the current language in device

public void GetDefaultLanguage( ) {
    try {
        String langue = Locale.getDefault().toString(); //        ---> en_US
        /*
        Log.i("TAG", Locale.getDefault().getLanguage() ); //       ---> en
        Log.i("TAG", Locale.getDefault().getISO3Language()  ); //  ---> eng
        Log.i("TAG", Locale.getDefault().getCountry()  ); //       ---> US
        Log.i("TAG", Locale.getDefault().getISO3Country()  ); //   ---> USA
        Log.i("TAG", Locale.getDefault().getDisplayCountry() ); // ---> United States
        Log.i("TAG", Locale.getDefault().getDisplayName() ); //    ---> English (United States)
        Log.i("TAG", Locale.getDefault().toString()   ); //        ---> en_US
        Log.i("TAG", Locale.getDefault().getDisplayLanguage() ); //---> English 
        */

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            langue = Locale.getDefault().toLanguageTag(); //     ---> en-US
            url_Api = getUrlMicrosoftLearn(langue);
            Log.i("TAG", url_Api );
            Log.i("TAG", langue );
        }else{
            langue = langue.replace("_","-"); //     ---> en-US
            url_Api = getUrlMicrosoftLearn(langue);
            Log.i("TAG", url_Api );
            Log.i("TAG", langue );
        }
    }catch (Exception ex) {
        Log.i("TAG", "Exception:GetDefaultLanguage()", ex);
    }
}

public String getUrlMicrosoftLearn(String langue) {
    return "https://docs.microsoft.com/"+langue+"/learn";
}

Set background colour of cell to RGB value of data in cell

To color each cell based on its current integer value, the following should work, if you have a recent version of Excel. (Older versions don't handle rgb as well)

Sub Colourise()
'
' Colourise Macro
'
' Colours all selected cells, based on their current integer rgb value
' For e.g. (it's a bit backward from what you might expect)
' 255 = #ff0000 = red
' 256*255 = #00ff00 = green
' 256*256*255 #0000ff = blue
' 255 + 256*256*255 #ff00ff = magenta
' and so on...
'
' Keyboard Shortcut: Ctrl+Shift+C (or whatever you want to set it to)
'
  For Each cell In Selection
    If WorksheetFunction.IsNumber(cell) Then
      cell.Interior.Color = cell.Value
    End If
  Next cell
End Sub

If instead of a number you have a string then you can split the string into three numbers and combine them using rgb().

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

Get Time from Getdate()

select convert(varchar(10), GETDATE(), 108)

returned 17:36:56 when I ran it a few moments ago.

How to upload image in CodeIgniter?

//this is the code you have to use in you controller 

        $config['upload_path'] = './uploads/';  

// directory (http://localhost/codeigniter/index.php/your directory)

        $config['allowed_types'] = 'gif|jpg|png|jpeg';  
//Image type  

        $config['max_size'] = 0;    

 // I have chosen max size no limit 
        $new_name = time() . '-' . $_FILES["txt_file"]['name']; 

//Added time function in image name for no duplicate image 

        $config['file_name'] = $new_name;

//Stored the new name into $config['file_name']

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload() && !empty($_FILES['txt_file']['name'])) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('production/create_images', $error);
        } else {
            $upload_data = $this->upload->data();   
        }

Stop Visual Studio from launching a new browser window when starting debug?

This is what solved it for me:

Go to Project Properties > Debug > Uncheck "Launch Browser".

enter image description here

OR operator in switch-case?

What are the backgrounds for a switch-case to not accept this operator?

Because case requires constant expression as its value. And since an || expression is not a compile time constant, it is not allowed.

From JLS Section 14.11:

Switch label should have following syntax:

SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :


Under the hood:

The reason behind allowing just constant expression with cases can be understood from the JVM Spec Section 3.10 - Compiling Switches:

Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.

So, for the cases label to be used by tableswitch as a index into the table of target offsets, the value of the case should be known at compile time. That is only possible if the case value is a constant expression. And || expression will be evaluated at runtime, and the value will only be available at that time.

From the same JVM section, the following switch-case:

switch (i) {
    case 0:  return  0;
    case 1:  return  1;
    case 2:  return  2;
    default: return -1;
}

is compiled to:

0   iload_1             // Push local variable 1 (argument i)
1   tableswitch 0 to 2: // Valid indices are 0 through 2  (NOTICE This instruction?)
      0: 28             // If i is 0, continue at 28
      1: 30             // If i is 1, continue at 30
      2: 32             // If i is 2, continue at 32
      default:34        // Otherwise, continue at 34
28  iconst_0            // i was 0; push int constant 0...
29  ireturn             // ...and return it
30  iconst_1            // i was 1; push int constant 1...
31  ireturn             // ...and return it
32  iconst_2            // i was 2; push int constant 2...
33  ireturn             // ...and return it
34  iconst_m1           // otherwise push int constant -1...
35  ireturn             // ...and return it

So, if the case value is not a constant expressions, compiler won't be able to index it into the table of instruction pointers, using tableswitch instruction.

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

how to find my angular version in my project?

try this command :

ng --version

It prints out Angular, Angular CLI, Node, Typescript versions etc.

Using bootstrap with bower

You have install nodeJs on your system in order to execute npm commands. Once npm is properly working you can visit bower.io. There you will find complete documentation on this topic. You will find a command $ npm install bower. this will install bower on your machine. After installing bower you can install Bootstrap easily.

Here is a video tutorial on that

SQL statement to get column type

If you're using MySQL you could try

SHOW COLUMNS FROM `tbl_name`;

SHOW COLUMNS on dev.mysql.com

Otherwise you should be able to do

DESCRIBE `tbl_name`;

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

For what it's worth; I had this error on a app that was running services in the background. On one of them a timeout dialog had to be shown to the user. That dialog was the issue causing this error if the app was no longer running in the foreground.

In our case showing the dialog wasn't useful when app was in background so we just kept track of that (boolean flagged onPause en onResume) and then only show the dialog when the app is actually visible to the user.

sudo echo "something" >> /etc/privilegedFile doesn't work

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"

How to force two figures to stay on the same page in LaTeX?

You can put two figures inside one figure environment. For example:

\begin{figure}[p]
\centering
\includegraphics{fig1}
\caption{Caption 1}
\includegraphics{fig2}
\caption{Caption 2}
\end{figure}

Each caption will generate a separate figure number.

How to add new DataRow into DataTable?

I found dotnetperls examples on DataRow very helpful. Code snippet for new DataTable from there:

static DataTable GetTable()
{
    // Here we create a DataTable with four columns.
    DataTable table = new DataTable();
    table.Columns.Add("Weight", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Breed", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
    table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
    table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
    table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
    table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);

    return table;
}

Append column to pandas dataframe

It seems in general you're just looking for a join:

> dat1 = pd.DataFrame({'dat1': [9,5]})
> dat2 = pd.DataFrame({'dat2': [7,6]})
> dat1.join(dat2)
   dat1  dat2
0     9     7
1     5     6

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

How to add "active" class to wp_nav_menu() current menu item (simple way)

In header.php insert this code to show menu:

<?php
    wp_nav_menu(
        array(
            'theme_location' => 'menu-one',
            'walker' => new Custom_Walker_Nav_Menu_Top
        )
    );
?>

In functions.php use this:

class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $is_current_item = '';
        if(array_search('current-menu-item', $item->classes) != 0)
        {
            $is_current_item = ' class="active"';
        }
        echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
    }

    function end_el( &$output, $item, $depth = 0, $args = array() ) {
        echo '</a></li>';
    }
}

python requests file upload

Client Upload

If you want to upload a single file with Python requests library, then requests lib supports streaming uploads, which allow you to send large files or streams without reading into memory.

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

Server Side

Then store the file on the server.py side such that save the stream into file without loading into the memory. Following is an example with using Flask file uploads.

@app.route("/upload", methods=['POST'])
def upload_file():
    from werkzeug.datastructures import FileStorage
    FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'OK', 200

Or use werkzeug Form Data Parsing as mentioned in a fix for the issue of "large file uploads eating up memory" in order to avoid using memory inefficiently on large files upload (s.t. 22 GiB file in ~60 seconds. Memory usage is constant at about 13 MiB.).

@app.route("/upload", methods=['POST'])
def upload_file():
    def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
        import tempfile
        tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
        app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
        return tmpfile

    import werkzeug, flask
    stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
    for fil in files.values():
        app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
        # Do whatever with stored file at `fil.stream.name`
    return 'OK', 200

Server is already running in Rails

I just had this issue and tried setting it to a different port, but the only thing I needed to do was to delete my [app_directory]/tmp/pids/server.pid and everything was good to go.

How can I drop all the tables in a PostgreSQL database?

Following Pablo and LenW, here's a one-liner that does it all both preparing and then executing:

psql -U $PGUSER $PGDB -t -c "select 'drop table \"' || tablename || '\" cascade;' from pg_tables where schemaname = 'public'" | psql -U $PGUSER $PGDB

NB: either set or replace $PGUSER and $PGDB with the values you want

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

In Excel 2010 it is easy, just takes a few more steps for each list items.

The following steps must be completed for each item within the validation list. (Have the worksheet open to where the drop down was created)

1) Click on cell with drop down list.
2) Select which answer to apply format to.
3) Click on "Home" tab, then click the "Styles" tool button on the ribbon.
4) Click "Conditional Formatting", in drop down list click the "*New Rule" option.
5) Select a Rule Type: "Format only cells that contain"
6) Edit the Rule Description: "Cell Value", "equal to", click the cell formula icon in the formula bar (far right), select which worksheet the validation list was created in, select the cell within the list to which you wish to apply the formatting.

Formula should look something like: ='Workbook Data'!$A$2

7) Click the formula icon again to return to format menu.
8) Click on Format button beside preview pane.
9) Select all format options desired.
10) Press "OK" twice.

You are finished with only one item within list. Repeat steps 1 thru 10 until all drop down list items are finished.

Request Monitoring in Chrome

You can also just right click on the page in the browser and select "Inspect Element" to bring up the developer tools.

https://developer.chrome.com/devtools

"call to undefined function" error when calling class method

Mates,

I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this

      try{
             foo();
         }
       catch (exception $e)
           {
            echo "$e->getMessage()";
           }

       function foo(){
                       echo "blah blah blah";
                     }

so php was throwing me error "call to undefined function ".

This kinda seem classic programming error but may help someone in need of clue.

What does enctype='multipart/form-data' mean?

When you make a POST request, you have to encode the data that forms the body of the request in some way.

HTML forms provide three methods of encoding.

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data
  • text/plain

Work was being done on adding application/json, but that has been abandoned.

(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)

The specifics of the formats don't matter to most developers. The important points are:

  • Never use text/plain.

When you are writing client-side code:

  • use multipart/form-data when your form includes any <input type="file"> elements
  • otherwise you can use multipart/form-data or application/x-www-form-urlencoded but application/x-www-form-urlencoded will be more efficient

When you are writing server-side code:

  • Use a prewritten form handling library

Most (such as Perl's CGI->param or the one exposed by PHP's $_POST superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.

Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is body-parser which cannot handle multipart requests (but has documentation which recommends some alternatives which can).


If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.

application/x-www-form-urlencoded is more or less the same as a query string on the end of the URL.

multipart/form-data is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the HTML 4 specification.

text/plain is introduced by HTML 5 and is useful only for debugging — from the spec: They are not reliably interpretable by computer — and I'd argue that the others combined with tools (like the Network Panel in the developer tools of most browsers) are better for that).

Simple parse JSON from URL on Android and display in listview

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class GetJsonFromUrl {
    String url = null;

    public GetJsonFromUrl(String url) {
        this.url = url;
    }

    public String GetJsonData() {
        try {
            URL Url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            line = sb.toString();
            connection.disconnect();
            is.close();
            sb.delete(0, sb.length());
            return line;
        } catch (Exception e) {
            return null;
        }
    }
} 

and this class use for post data

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by user on 11/2/16.
 */
public class sendDataToServer {
   public String postdata(String requestURL,HashMap<String,String> postDataParams){
        try {
            String response = "";
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
            Log.d("test", response);
            return response;
        }catch (Exception e){
            return e.toString();
        }
    }

    public String postjson(String url,String json){
        try {

            URL obj = new URL(url);
            HttpURLConnection con= (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept", "application/json");
            String urlParameters = ""+json;

            // Send post request
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json");
            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
            wr.write(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());
            return response.toString();
        }catch(Exception e){

            return e.toString();
        }
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }

   /* public String postdata(String url) {
    }*/
}

How to extract a single value from JSON response?

Extract single value from JSON response Python

Try this

import json
import sys

#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

#print the resp
print (resp)

#extract an element in the response
print (resp['test1'])

Check for column name in a SqlDataReader object

This code corrects the issues that Levitikon had with their code: (adapted from: [1]: http://msdn.microsoft.com/en-us/library/system.data.datatablereader.getschematable.aspx)

public List<string> GetColumnNames(SqlDataReader r)
{
    List<string> ColumnNames = new List<string>();
    DataTable schemaTable = r.GetSchemaTable();
    DataRow row = schemaTable.Rows[0];
    foreach (DataColumn col in schemaTable.Columns)
    {
        if (col.ColumnName == "ColumnName") 
        { 
            ColumnNames.Add(row[col.Ordinal].ToString()); 
            break; 
        }
    }
    return ColumnNames;
}

The reason for getting all of those useless column names and not the name of the column from your table... Is because your are getting the name of schema column (i.e. the column names for the Schema table)

NOTE: this seems to only return the name of the first column...

EDIT: corrected code that returns the name of all columns, but you cannot use a SqlDataReader to do it

public List<string> ExecuteColumnNamesReader(string command, List<SqlParameter> Params)
{
    List<string> ColumnNames = new List<string>();
    SqlDataAdapter da = new SqlDataAdapter();
    string connection = ""; // your sql connection string
    SqlCommand sqlComm = new SqlCommand(command, connection);
    foreach (SqlParameter p in Params) { sqlComm.Parameters.Add(p); }
    da.SelectCommand = sqlComm;
    DataTable dt = new DataTable();
    da.Fill(dt);
    DataRow row = dt.Rows[0];
    for (int ordinal = 0; ordinal < dt.Columns.Count; ordinal++)
    {
        string column_name = dt.Columns[ordinal].ColumnName;
        ColumnNames.Add(column_name);
    }
    return ColumnNames; // you can then call .Contains("name") on the returned collection
}

HTTP response header content disposition for attachments

Problems

The code has the following issues:

  • An Ajax call (<a4j:commandButton .../>) does not work with attachments.
  • Creating the output content must happen first.
  • Displaying the error messages also cannot use Ajax-based a4j tags.

Solution

  1. Change <a4j:commandButton .../> to <h:commandButton .../>.
  2. Update the source code:
    1. Change bw.write( getDomainDocument() ); to bw.write( document );.
    2. Add String document = getDomainDocument(); to the first line of the try/catch.
  3. Change the <a4j:outputPanel.../> (not shown) to <h:messages showDetail="false"/>.

Essentially, remove all the Ajax facilities related to the commandButton. It is still possible to display error messages and leverage the RichFaces UI style.

References

Difference between "process.stdout.write" and "console.log" in node.js?

One big difference that hasn't been mentioned is that process.stdout only takes strings as arguments (can also be piped streams), while console.log takes any Javascript data type.

e.g:

// ok
console.log(null)
console.log(undefined)
console.log('hi')
console.log(1)
console.log([1])
console.log({one:1})
console.log(true)
console.log(Symbol('mysymbol'))

// any other data type passed as param will throw a TypeError
process.stdout.write('1')

// can also pipe a readable stream (assuming `file.txt` exists)
const fs = require('fs')
fs.createReadStream('file.txt').pipe(process.stdout)

Post form data using HttpWebRequest

Try this:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Bootstrap: How do I identify the Bootstrap version?

Method 1 - Very Simple

In Package.json - you'll see bootstrap package installed with version mentioned.

"dependencies": {
    // ...
   "bootstrap": "x.x.x"
    // ...
}

Method 2

  1. Open node_modules folder and under that
  2. Search and open bootstrap folder
  3. Now you'll be able to see version number in the following files
    • package.json
    • scss/bootstrap.scss or css/bootstrap.css
    • README.md

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

Open local folder from link

Only IE6-8 - there's an ActiveX workaround this local-files issue in JavaScript:

        function OpenImage(filePath)
        {
            var myshell = new ActiveXObject("WScript.shell");
            myshell.run(filePath, 1, true); 
        }

What's the best way to build a string of delimited items in Java?

Your approach is not too bad, but you should use a StringBuffer instead of using the + sign. The + has the big disadvantage that a new String instance is being created for each single operation. The longer your string gets, the bigger the overhead. So using a StringBuffer should be the fastest way:

public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {
        if ( original == null ) {
                StringBuffer buffer = new StringBuffer();
                buffer.append(addition);
                return buffer;
        } else {
                buffer.append(delimiter);
                buffer.append(addition);
                return original;
        }
}

After you have finished creating your string simply call toString() on the returned StringBuffer.

How can I convert a long to int in Java?

Shortest, most safe and easiest solution is:

long myValue=...;
int asInt = Long.valueOf(myValue).intValue();

Do note, the behavior of Long.valueOf is as such:

Using this code:

System.out.println("Long max: " + Long.MAX_VALUE);
System.out.println("Int max: " + Integer.MAX_VALUE);        
long maxIntValue = Integer.MAX_VALUE;
System.out.println("Long maxIntValue to int: " + Long.valueOf(maxIntValue).intValue());
long maxIntValuePlusOne = Integer.MAX_VALUE + 1;
System.out.println("Long maxIntValuePlusOne to int: " + Long.valueOf(maxIntValuePlusOne).intValue());
System.out.println("Long max to int: " + Long.valueOf(Long.MAX_VALUE).intValue());

Results into:

Long max: 9223372036854775807
Int max: 2147483647
Long max to int: -1
Long maxIntValue to int: 2147483647
Long maxIntValuePlusOne to int: -2147483648

Alter user defined type in SQL Server

This is what I normally use, albeit a bit manual:

/* Add a 'temporary' UDDT with the new definition */ 
exec sp_addtype t_myudt_tmp, 'numeric(18,5)', NULL 


/* Build a command to alter all the existing columns - cut and 
** paste the output, then run it */ 
select 'alter table dbo.' + TABLE_NAME + 
       ' alter column ' + COLUMN_NAME + ' t_myudt_tmp' 
from INFORMATION_SCHEMA.COLUMNS 
where DOMAIN_NAME = 't_myudt' 

/* Remove the old UDDT */ 
exec sp_droptype t_mydut


/* Rename the 'temporary' UDDT to the correct name */ 
exec sp_rename 't_myudt_tmp', 't_myudt', 'USERDATATYPE' 

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

Create directories using make file

All solutions including the accepted one have some issues as stated in their respective comments. The accepted answer by @jonathan-leffler is already quite good but does not take into effect that prerequisites are not necessarily to be built in order (during make -j for example). However simply moving the directories prerequisite from all to program provokes rebuilds on every run AFAICT. The following solution does not have that problem and AFAICS works as intended.

MKDIR_P := mkdir -p
OUT_DIR := build

.PHONY: directories all clean

all: $(OUT_DIR)/program

directories: $(OUT_DIR)

$(OUT_DIR):
    ${MKDIR_P} $(OUT_DIR)

$(OUT_DIR)/program: | directories
    touch $(OUT_DIR)/program

clean:
    rm -rf $(OUT_DIR)

What is the difference between sscanf or atoi to convert a string to an integer?

*scanf() family of functions return the number of values converted. So you should check to make sure sscanf() returns 1 in your case. EOF is returned for "input failure", which means that ssacnf() will never return EOF.

For sscanf(), the function has to parse the format string, and then decode an integer. atoi() doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.

You should use strtol() or strtoul() functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.

If you want an int, you can always use strtol(), and then check the returned value to see if it lies between INT_MIN and INT_MAX.

Reverting to a specific commit based on commit id with Git?

git reset c14809fafb08b9e96ff2879999ba8c807d10fb07 is what you're after...

Correct file permissions for WordPress

It actually depends on the plugins you plan to use as some plugins change the root document of the wordpress. but generally I recommend something like this for the wordpress directory.

This will assign the "root" (or whatever the user you are using) as the user in every single file/folder, R means recursive, so it just doesn't stop at the "html" folder. if you didn't use R, then it only applicable to the "html" directory.

sudo chown -R root:www-data /var/www/html  

This will set the owner/group of "wp-content" to "www-data" and thus allowing the web server to install the plugins through the admin panel.

chown -R www-data:www-data /var/www/html/wp-content

This will set the permission of every single file in "html" folder (Including files in subdirectories) to 644, so outside people can't execute any file, modify any file, group can't execute any file, modify any file and only the user is allowed to modify/read files, but still even the user can't execute any file. This is important because it prevents any kind of execution in "html" folder, also since the owner of the html folder and all other folders except the wp-content folder are "root" (or your user), the www-data can't modify any file outside of the wp-content folder, so even if there is any vulnerability in the web server, and if someone accessed to the site unauthorizedly, they can't delete the main site except the plugins.

sudo find /var/www/html -type f -exec chmod 644 {} +

This will restrict the permission of accessing to "wp-config.php" to user/group with rw-r----- these permissions.

chmod 640 /var/www/html/wp-config.php

And if a plugin or update complained it can't update, then access to the SSH and use this command, and grant the temporary permission to "www-data" (web server) to update/install through the admin panel, and then revert back to the "root" or your user once it's completed.

chown -R www-data /var/www/html

And in Nginx (same procedure for the apache)to protect the wp-admin folder from unauthorized accessing, and probing. apache2-utils is required for encrypting the password even if you have nginx installed, omit c if you plan to add more users to the same file.

sudo apt-get install apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd userName

Now visit this location

/etc/nginx/sites-available/

Use this codes to protect "wp-admin" folder with a password, now it will ask the password/username if you tried to access to the "wp-admin". notice, here you use the ".htpasswd" file which contains the encrypted password.

location ^~ /wp-admin {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
    index  index.php index.html index.htm;
}

Now restart the nginx.

sudo /etc/init.d/nginx restart

How to run a method every X seconds

Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution

     Thread t = new Thread() {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(10000);  //1000ms = 1 sec
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
                            Gson gson = new Gson();
                            String json = mPrefs.getString("chat_list", "");
                            GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
                            String sam = "";

                            ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
                            listview.setAdapter(adapter);
                           // listview.setStackFromBottom(true);
                          //  Util.showMessage(Chat.this,"Merhabalar");
                        }
                    });

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

    t.start();

In case it needed it can be stoped by

@Override
protected void onDestroy() {
    super.onDestroy();
    Thread.interrupted();
    //t.interrupted();
}

How to color the Git console?

Another way is to edit the .gitconfig (create one if not exist), for instance:

vim ~/.gitconfig

and then add:

[color]
  diff = auto
  status = auto
  branch = auto

Angularjs $q.all

In javascript there are no block-level scopes only function-level scopes:

Read this article about javaScript Scoping and Hoisting.

See how I debugged your code:

var deferred = $q.defer();
deferred.count = i;

console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects

// some code

.success(function(data){
   console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
   deferred.resolve(data);
})
  • When you write var deferred= $q.defer(); inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop.
  • With each loop, the last deferred is overriding the previous one, there is no block-level scope to save a reference to that object.
  • When asynchronous callbacks (success / error) are invoked, they reference only the last deferred object and only it gets resolved, so $q.all is never resolved because it still waits for other deferred objects.
  • What you need is to create an anonymous function for each item you iterate.
  • Since functions do have scopes, the reference to the deferred objects are preserved in a closure scope even after functions are executed.
  • As #dfsq commented: There is no need to manually construct a new deferred object since $http itself returns a promise.

Solution with angular.forEach:

Here is a demo plunker: http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview

UploadService.uploadQuestion = function(questions){

    var promises = [];

    angular.forEach(questions , function(question) {

        var promise = $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

        promises.push(promise);

    });

    return $q.all(promises);
}

My favorite way is to use Array#map:

Here is a demo plunker: http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview

UploadService.uploadQuestion = function(questions){

    var promises = questions.map(function(question) {

        return $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

    });

    return $q.all(promises);
}

Using ORDER BY and GROUP BY together

You can try this

 SELECT tbl.* FROM (SELECT * FROM table ORDER BY timestamp DESC) as tbl
 GROUP BY tbl.m_id  

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

I had this similar error when using wget ..., and after much unfruitful searching in the Internet, I discovered that it was happening when hostnames were being resolved to IPv6 addresses. I discovered this by comparing the outputs of wget ... in two machines, one was resolving to IPv4 and it worked there, the other was resolving to IPv6 and it failed there.

So the solution in my case was to run networksetup -setv6off Wi-Fi on macOS High Sierra 10.13.6. (I discovered this command in this page).

Hope this helps you.

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}

TypeScript: Creating an empty typed container array

I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.

I had

return [];

where [] was Criminal[] type.

Neither return: Criminal[] []; nor return []: Criminal[]; worked for me.

At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.

For thoroughness I'll report this solution in my answer too:

let temp: Criminal[] = [];
return temp;

Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:

return <Criminal[]>[];

Hope this will help future readers!

Maven: repository element was not specified in the POM inside distributionManagement?

You can also override the deployment repository on the command line: -Darguments=-DaltDeploymentRepository=myreposid::default::http://my/url/releases

Error on renaming database in SQL Server 2008 R2

Try to close all connections to your database first:

use master
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]

ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER

Taken from here

How can I scale an image in a CSS sprite

Old post, but here's what I did using background-size:cover; (hat tip to @Ceylan Pamir)...

EXAMPLE USAGE
Horizontal circle flipper (hover on front side image, flips to back with different image).

EXAMPLE SPRITE
480px x 240px

EXAMPLE FINAL SIZE
Single image @ 120px x 120px

GENERIC CODE
.front {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:0px 0px;}

.back {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:-120px 0px;}

ABBREVIATED CASE FIDDLE
http://jsfiddle.net/zuhloobie/133esq63/2/

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Rollback... will prompt you to select a folder to rollback, ie, it will work on specific folders, and you can rollback to labels or changlists or dates. Back out works on the files in specific changelists.

What does ON [PRIMARY] mean?

ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.

Get values from other sheet using VBA

Try

 ThisWorkbook.Sheets("name of sheet 2").Range("A1")

to access a range in sheet 2 independently of where your code is or which sheet is currently active. To make sheet 2 the active sheet, try

 ThisWorkbook.Sheets("name of sheet 2").Activate

If you just need the sum of a row in a different sheet, there is no need for using VBA at all. Enter a formula like this in sheet 1:

=SUM([Name-Of-Sheet2]!A1:D1)

Android dependency has different version for the compile and runtime

I solved it by upgrading my gradle dependency in the android/build.gradle file: classpath 'com.android.tools.build:gradle:3.3.1' (I was previously on version 3.2.

How to get exception message in Python properly

from traceback import format_exc


try:
    fault = 10/0
except ZeroDivision:
    print(format_exc())

Another possibility is to use the format_exc() method from the traceback module.

JavaScript - Getting HTML form values

This is a developed example of https://stackoverflow.com/a/41262933/2464828

Consider

<form method="POST" enctype="multipart/form-data" onsubmit="return check(event)">
    <input name="formula">
</form>

Let us assume we want to retrieve the input of name formula. This can be done by passing the event in the onsubmit field. We can then use FormData to retrieve the values of this exact form by referencing the SubmitEvent object.

const check = (e) => {
    const form = new FormData(e.target);
    const formula = form.get("formula");
    console.log(formula);
    return false
};

The JavaScript code above will then print the value of the input to the console.

If you want to iterate the values, i.e., get all the values, then see https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods

Count number of matches of a regex in Javascript

As mentioned in my earlier answer, you can use RegExp.exec() to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using String.match().

var re = /\s/g,
count = 0;

while (re.exec(text) !== null) {
    ++count;
}

return count;

Get Application Directory

For current Android application package:

public String getDataDir(Context context) throws Exception {
    return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
}

For any package:

public String getAnyDataDir(Context context, String packageName) throws Exception {
    return context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.dataDir;
}

Fragment onResume() & onPause() is not called on backstack

You can try this,

Step1: Override the Tabselected method in your activity

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    try {
    if(MyEventsFragment!=null && tab.getPosition()==3)
    {
        MyEvents.fragmentChanged();
    }
    }
    catch (Exception e)
    {

    }
    mViewPager.setCurrentItem(tab.getPosition());
}

Step 2: Using static method do what you want in your fragment,

public static void fragmentChanged()
{
    Toast.makeText(actvity, "Fragment Changed", Toast.LENGTH_SHORT).show();
}

Separators for Navigation

I believe the best solution for this, is what I use, and that is a natural css border:

border-right:1px solid;

You might need to take care of padding like:

padding-left: 5px;
padding-right: 5px;

Finally, if you don't want the last li to have that seperating border, give it's last-child "none" in "border-right" like this:

li:last-child{
  border-right:none;
}

Good luck :)

Difference between jQuery .hide() and .css("display", "none")

no difference

With no parameters, the .hide() method is the simplest way to hide an element:

$('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

Same about show

Checking if a file is a directory or just a file

You can call the stat() function and use the S_ISREG() macro on the st_mode field of the stat structure in order to determine if your path points to a regular file:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int is_regular_file(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}

Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.

How to do SVN Update on my project using the command line

I think I got it. It's:

"SVN Client Path"  /command:update / path:"My folder path"

How can I access and process nested objects, arrays or JSON?

In case you're trying to access an item from the example structure by id or name, without knowing it's position in the array, the easiest way to do it would be to use underscore.js library:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

_.find(data.items, function(item) {
  return item.id === 2;
});
// Object {id: 2, name: "bar"}

From my experience, using higher order functions instead of for or for..in loops results in code that is easier to reason about, and hence more maintainable.

Just my 2 cents.

How to install JDK 11 under Ubuntu?

First check the default-jdk package, good chance it already provide you an OpenJDK >= 11.
ref: https://packages.ubuntu.com/search?keywords=default-jdk&searchon=names&suite=all&section=all

Ubuntu 18.04 LTS +

So starting from Ubuntu 18.04 LTS it should be ok.

sudo apt update -qq
sudo apt install -yq default-jdk

note: don't forget to set JAVA_HOME

export JAVA_HOME=/usr/lib/jvm/default-java
mvn -version

Ubuntu 16.04 LTS

For Ubuntu 16.04 LTS, only openjdk-8-jdk is provided in the official repos so you need to find it in a ppa:

sudo add-apt-repository -y ppa:openjdk-r/ppa
sudo apt update -qq
sudo apt install -yq openjdk-11-jdk

note: don't forget to set JAVA_HOME

export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
mvn -version

How to validate numeric values which may contain dots or commas?

\d means a digit in most languages. You can also use [0-9] in all languages. For the "period or comma" use [\.,]. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.

* means "zero-or-more", so \d* and [0-9]* mean "zero or more numbers". ? means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n} to mean "between m and n" (ie: {1,2} means "between 1 and 2")

Since the dot or comma and additional numbers are optional, you can put them in a group and use the ? quantifier to mean "zero-or-one" of that group.

Putting that all together you can use:

\d{1,2}([\.,][\d{1,2}])?

Meaning, one or two digits \d{1,2}, followed by zero-or-one of a group (...)? consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}

Can you put two conditions in an xslt test attribute?

Not quite, the AND has to be lower-case.

<xsl:when test="4 &lt; 5 and 1 &lt; 2">
<!-- do something -->
</xsl:when>

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

How do I concatenate a string with a variable?

Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.

To identify the first case or determine the cause of the second case, add these as the first lines inside the function:

alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));

That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.

The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:

<head>
<title>My Web Page</title>
<script>
    function AddBorder(id) {
        ...
    }
    AddBorder(42);    // Won't work; the page hasn't completely loaded yet!
</script>
</head>

To fix this, put all the code that uses AddBorder inside an onload event handler:

// Can only have one of these per page
window.onload = function() {
    ...
    AddBorder(42);
    ...
} 

// Or can have any number of these on a page
function doWhatever() {
   ...
   AddBorder(42);
   ...
}

if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);

jQuery click events firing multiple times

If you're calling that function on each "click", then it's adding another pair of handlers on each call.

Adding handlers with jQuery just isn't like setting the value of the "onclick" attribute. One can add as many handlers as one desires.

Querying data by joining two tables in two database on different servers

From a practical enterprise perspective, the best practice is to make a mirrored copy of the database table in your database, and then just have a task/proc update it with delta's every hour.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

You need to run these two commands

php artisan cache:clear
php artisan config:cache

How do I view an older version of an SVN file?

You can update to an older revision:

svn update -r 666 file

Or you can just view the file directly:

svn cat -r 666 file | less

"could not find stored procedure"

make sure that your schema name is in the connection string?

Best way to center a <div> on a page vertically and horizontally?

One more method (bulletproof) taken from here utilizing 'display:table' rule:

Markup

<div class="container">
  <div class="outer">
    <div class="inner">
      <div class="centered">
        ...
      </div>
    </div>
  </div>
</div>

CSS:

.outer {
  display: table;
  width: 100%;
  height: 100%;
}
.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.centered {
  position: relative;
  display: inline-block;

  width: 50%;
  padding: 1em;
  background: orange;
  color: white;
}

Int to Char in C#

int i = 65;
char c = Convert.ToChar(i);

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

<configuration>
 <location path="Path/To/Public/Folder">
  <system.web>
     <authorization>
        <allow users="?"/>
     </authorization>
  </system.web>
 </location>
</configuration>

How do you create a read-only user in PostgreSQL?

I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!!

user@server:~$ sudo su - postgres

create psql user:

postgres@server:~$ createuser --interactive 
Enter name of role to add: readonly
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n

start psql cli and set a password for the created user:

postgres@server:~$ psql
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
Type "help" for help.

postgres=# alter user readonly with password 'readonly';
ALTER ROLE

connect to the target database:

postgres=# \c target_database 
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
You are now connected to database "target_database" as user "postgres".

grant all the needed privileges:

target_database=# GRANT CONNECT ON DATABASE target_database TO readonly;
GRANT

target_database=# GRANT USAGE ON SCHEMA public TO readonly ;
GRANT

target_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ;
GRANT

alter default privileges for targets db public shema:

target_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
ALTER DEFAULT PRIVILEGES

How to get name of calling function/method in PHP?

You can also use the info provided by a php exception, it's an elegant solution:


function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];
    print_r($last_call);
}

function firstCall($a, $b){
    theCall($a, $b);
}

function theCall($a, $b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

And you get this... (voilà!)

Array
(
    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
        (
            [0] => lucia
            [1] => php
        )

)

Where will log4net create this log file?

I think your sample is saving to your project folders and unless the default iis, or .NET , user has create permission then it won't be able to create the logs folder.

I'd create the logs folder first and allow the iis user full permission and see if the log file is being created.

Programmatically find the number of cores on a machine

On Linux, you can read the /proc/cpuinfo file and count the cores.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

In my case, I had to do this

 // Initialization in the dom
 // Consider the muted attribute
 <audio id="notification" src="path/to/sound.mp3" muted></audio>


 // in the js code unmute the audio once the event happened
 document.getElementById('notification').muted = false;
 document.getElementById('notification').play();

Global javascript variable inside document.ready

like this: put intro outside your document ready, Good discussion here: http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery @thecodeparadox is awesomely fast :P anyways!

 var intro;

$(document).ready(function() {



    if ($('.intro_check').is(':checked')) {
        intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };

    $('.intro_check').change(function(){
        if(this.checked) {
            intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

Get IP address of visitors using Flask for Python

The user's IP address can be retrieved using the following snippet:

from flask import request
print(request.remote_addr)

How to create a timeline with LaTeX?

There is a new chronology.sty by Levi Wiseman. The documentation (pdf) says:

Most timeline packages and solutions for LATEX are used to convey a lot of information and are therefore designed vertically. If you are just attempting to assign labels to dates, a more traditional timeline might be more appropriate. That's what chronology is for.

Here is some example code:

\documentclass{article}
\usepackage{chronology}
\begin{document}

\begin{chronology}[5]{1983}{2010}{3ex}[\textwidth]
\event{1984}{one}
\event[1985]{1986}{two}
\event{\decimaldate{25}{12}{2001}}{three}
\end{chronology}

\end{document}

Which produces this output:

example output from chronology.sty

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

The accepted answer doesn't work if some package vendors it's own copy of urllib3, in which case this will still work:

import warnings

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

function setDate(){
    var now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    var timeToSet = now.toISOString().slice(0,16);

    /*
        If you have an element called "eventDate" like the following:

        <input type="datetime-local" name="eventdate" id="eventdate" />

        and you would like to  set the current and minimum time then use the following:
    */

    var elem = document.getElementById("eventDate");
    elem.value = timeToSet;
    elem.min = timeToSet;
}

How to read AppSettings values from a .json file in ASP.NET Core

First off: The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use: e.g.

"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"

as a dependency in project.json. Use beta5 or 6 if you don't have 7 installed. Then you can do something like this in Startup.cs.

public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
     var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddEnvironmentVariables();
     Configuration = configurationBuilder.Build();
}

If you then want to retrieve a variable from the config.json you can get it right away using:

public void Configure(IApplicationBuilder app)
{
    // Add .Value to get the token string
    var token = Configuration.GetSection("AppSettings:token");
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
    });
}

or you can create a class called AppSettings like this:

public class AppSettings
{
    public string token { get; set; }
}

and configure the services like this:

public void ConfigureServices(IServiceCollection services)
{       
    services.AddMvc();

    services.Configure<MvcOptions>(options =>
    {
        //mvc options
    });

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}

and then access it through e.g. a controller like this:

public class HomeController : Controller
{
    private string _token;

    public HomeController(IOptions<AppSettings> settings)
    {
        _token = settings.Options.token;
    }
}

git rebase fatal: Needed a single revision

I ran into this and realized I didn't fetch the upstream before trying to rebase. All I needed was to git fetch upstream

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.

The full shortcut target is:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

So I put the following at the start of my script and it seemed to function as expected:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Notes:

  • Has to be run in 64bit PS
  • This was tested on a server with just the Management Tools installed. It automatically connected to our existing Exchange infrastructure.
  • No extensive testing has been done, so I do not know if this method is viable. I will edit this post if I run into any issues.

Match groups in Python

You could create a helper function:

def re_match_group(pattern, str, out_groups):
    del out_groups[:]
    result = re.match(pattern, str)
    if result:
        out_groups[:len(result.groups())] = result.groups()
    return result

And then use it like this:

groups = []
if re_match_group("I love (\w+)", statement, groups):
    print "He loves", groups[0]
elif re_match_group("Ich liebe (\w+)", statement, groups):
    print "Er liebt", groups[0]
elif re_match_group("Je t'aime (\w+)", statement, groups):
    print "Il aime", groups[0]

It's a little clunky, but it gets the job done.

C++ where to initialize static const

In a translation unit within the same namespace, usually at the top:

// foo.h
struct foo
{
    static const std::string s;
};

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
{
    struct bar
    {
        static const float f;
    };
}

// bar.cpp
namespace baz
{
    const float bar::f = 3.1415926535;
}

IN vs ANY operator in PostgreSQL

(Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of ANY. Details:

IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

ANY is more versatile

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:

Related:

Inversion / opposite / exclusion

"Find rows where id is in the given array":

SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);

Inversion: "Find rows where id is not in the array":

SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));

All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;

What is WebKit and how is it related to CSS?

A good documentation about WebEngines especially webKit and its developers you can read at: WebKit

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

Composer: how can I install another dependency without updating old ones?

To install a new package and only that, you have two options:

  1. Using the require command, just run:

    composer require new/package
    

    Composer will guess the best version constraint to use, install the package, and add it to composer.lock.

    You can also specify an explicit version constraint by running:

    composer require new/package ~2.5
    

–OR–

  1. Using the update command, add the new package manually to composer.json, then run:

    composer update new/package
    

If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).

Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m doesn't list mcrypt then it's missing.

Important: Don't forget to specify new/package when using composer update! Omitting that argument will cause all dependencies, as well as composer.lock, to be updated.

How to bind DataTable to Datagrid

using (SqlCeConnection con = new SqlCeConnection())
   {
   con.ConnectionString = connectionString;
   con.Open();
   SqlCeCommand com = new SqlCeCommand("SELECT S_no,Name,Father_Name")
   SqlCeDataAdapter sda = new SqlCeDataAdapter(com);
   System.Data.DataTable dt = new System.Data.DataTable();
   sda.Fill(dt);
   dataGrid1.ItemsSource = dt.DefaultView;
   dataGrid1.AutoGenerateColumns = true;
   dataGrid1.CanUserAddRows = false;
   }

XSLT counting elements with a given value

Your xpath is just a little off:

count(//Property/long[text()=$parPropId])

Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId] than the text() xpath, though you could make a case for the latter on readability grounds.

What can I say, I'm a bit tired today :)

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Reading images in python

For the better answer, you can use these lines of code. Here is the example maybe help you :

image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()

In imread() you can pass the directory .so you can also use str() and + to combine dynamic directories and fixed directory like this:

path = '/home/pictures/'
for i in range(2) :
    image = cv2.imread(str(path)+'1.jpg')
    plt.imshow(image)
    plt.show()

Both are the same.

Copy all values in a column to a new column in a pandas dataframe

Following up on these solutions, here is some helpful code illustrating :

#
# Copying columns in pandas without slice warning
#
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))

#
# copies column B into new column D
df.loc[:,'D'] = df['B']
print df

#
# creates new column 'E' with values -99
# 
# But copy command replaces those where 'B'>0 while others become NaN (not copied)
df['E'] = -99
print df
df['E'] = df[df['B']>0]['B'].copy()
print df

#
# creates new column 'F' with values -99
# 
# Copy command only overwrites values which meet criteria 'B'>0
df['F']=-99
df.loc[df['B']>0,'F'] = df[df['B']>0]['B'].copy()
print df

Docker-compose: node_modules not present in a volume after npm install succeeds

If you want the node_modules folder available to the host during development, you could install the dependencies when you start the container instead of during build-time. I do this to get syntax highlighting working in my editor.

Dockerfile

# We're using a multi-stage build so that we can install dependencies during build-time only for production.

# dev-stage
FROM node:14-alpine AS dev-stage
WORKDIR /usr/src/app
COPY package.json ./
COPY . .
# `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
CMD ["sh", "-c", "yarn install && yarn run start"]

# production-stage
FROM node:14-alpine AS production-stage
WORKDIR /usr/src/app
COPY package.json ./
RUN yarn install
COPY . .

.dockerignore

Add node_modules to .dockerignore to prevent it from being copied when the Dockerfile runs COPY . .. We use volumes to bring in node_modules.

**/node_modules

docker-compose.yml

node_app:
    container_name: node_app
    build:
        context: ./node_app
        target: dev-stage # `production-stage` for production
    volumes:
        # For development:
        #   If node_modules already exists on the host, they will be copied
        #   into the container here. Since `yarn install` runs after the
        #   container starts, this volume won't override the node_modules.
        - ./node_app:/usr/src/app
        # For production:
        #   
        - ./node_app:/usr/src/app
        - /usr/src/app/node_modules

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

github: server certificate verification failed

Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:

$ date

If the date and/or time is incorrect, try to update using:

$ sudo ntpdate -u time.nist.gov

Why isn't textarea an input[type="textarea"]?

It was a limitation of the technology at the time it was created. My answer copied over from Programmers.SE:

From one of the original HTML drafts:

NOTE: In the initial design for forms, multi-line text fields were supported by the Input element with TYPE=TEXT. Unfortunately, this causes problems for fields with long text values. SGML's default (Reference Quantity Set) limits the length of attribute literals to only 240 characters. The HTML 2.0 SGML declaration increases the limit to 1024 characters.

What does Visual Studio mean by normalize inconsistent line endings?

Line endings also called newline, end of line (EOL) or line break is a control character or sequence of control characters in a character encoding specification (e.g. ASCII or EBCDIC) that is used to signify the end of a line of text and the start of a new one. Some text editors set/implement this special character when you press the Enter key.

The Carriage Return, Line Feed characters are ASCII representations for the end of a line (EOL). They will end the current line of a string, and start a new one.

However, at the operating system level, they are treated differently:

  • The Carriage Return ("CR") character (ASCII 13\0x0D, \r): Moves the cursor to the beginning of the line without advancing to the next line. This character is used as the new line character in Commodore and Early Macintosh operating systems (Mac OS 9 and earlier).

  • The Line Feed ("LF") character (ASCII 10\0x0A, \n): Moves the cursor down to the next line without returning to the beginning of the line. This character is used as the new line character in Unix based systems (Linux, macOS X, Android, etc).

  • The Carriage Return Line Feed ("CRLF") character (0x0D0A, \r\n): This is actually two ASCII characters and is a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as the new line character in most other non-Unix operating systems, including Microsoft Windows and Symbian OS.

Normalizing inconsistent line endings in Visual Studio means selecting one character type to be used for all your files. It could be:

  • The Carriage Return Line Feed ("CRLF") character
  • The Line Feed ("LF") character
  • The Carriage Return ("CR") character

However, you can set this in a better way using .gitattributes file in your root directory to avoid conflicts when you move your files from one Operating system to the other.

Simply create a new file called .gitattributes in the root directory of your application:

touch .gitattributes

And add the following in it:

# Enforce Unix newlines
* text=auto eol=lf

This enforces the Unix line feed line ending character.

Note: If this is an already existing project, simply run this command to update the files for the application using the newly defined line ending as specified in the .gitattributes.

git rm --cached -r .
git reset --hard

That's all.

I hope this helps

Giving graphs a subtitle in matplotlib

As mentioned here, uou can use matplotlib.pyplot.text objects in order to achieve the same result:

plt.text(x=0.5, y=0.94, s="My title 1", fontsize=18, ha="center", transform=fig.transFigure)
plt.text(x=0.5, y=0.88, s= "My title 2 in different size", fontsize=12, ha="center", transform=fig.transFigure)
plt.subplots_adjust(top=0.8, wspace=0.3)

Why do multiple-table joins produce duplicate rows?

If one of the tables M, S, D, or H has more than one row for a given Id (if just the Id column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).

References:

Related Question on MSDN Forum

Need table of key codes for android and presenter

Additionally, if you have the NDK installed, you can also find the listing in ${ndk_path}platforms\android-${api}\${architecture}\usr\include\android\keycodes.h.

I'm only mentioning it because I've found it simpler to navigate and read than the KeyEvent class or docs.

How do you change the formatting options in Visual Studio Code?

To change specifically C# (OmniSharp) formatting settings you can use a json file:
User: ~/.omnisharp/omnisharp.json or %USERPROFILE%\.omnisharp\omnisharp.json
Workspace: omnisharp.json file in the working directory which OmniSharp has been pointed at.

Example:

{
  "FormattingOptions": {
    "NewLinesForBracesInMethods": false,
    "NewLinesForBracesInProperties": false,
    "NewLinesForBracesInAccessors": false,
    "NewLinesForBracesInAnonymousMethods": false,
    "NewLinesForBracesInControlBlocks": false,
    "NewLinesForBracesInObjectCollectionArrayInitializers": false,
    "NewLinesForBracesInLambdaExpressionBody": false
  }
}

Details on this post | omnisharp.json schema (it's already in vscode, you can just CTRL+SPACE it)

Other language extensions may have similar files for setting it.

Unable instantiate android.gms.maps.MapFragment

Do not forget to actually build the google-play-services_lib!! That's why it shows the "Could not find google-play....apk". For me, on Eclipse, no other hacks were needed, but to reference the project from the Android submenu, not from Java build path, or Project references or whatever else. No manually placed jars, no nothing were actually needed for me.

On Duplicate Key Update same as insert

There is a MySQL specific extension to SQL that may be what you want - REPLACE INTO

However it does not work quite the same as 'ON DUPLICATE UPDATE'

  1. It deletes the old row that clashes with the new row and then inserts the new row. So long as you don't have a primary key on the table that would be fine, but if you do, then if any other table references that primary key

  2. You can't reference the values in the old rows so you can't do an equivalent of

    INSERT INTO mytable (id, a, b, c) values ( 1, 2, 3, 4) 
    ON DUPLICATE KEY UPDATE
    id=1, a=2, b=3, c=c + 1;
    

I'd like to use the work around to get the ID to!

That should work — last_insert_id() should have the correct value so long as your primary key is auto-incrementing.

However as I said, if you actually use that primary key in other tables, REPLACE INTO probably won't be acceptable to you, as it deletes the old row that clashed via the unique key.

Someone else suggested before you can reduce some typing by doing:

INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);

Merge two objects with ES6

You can use Object.assign() to merge them into a new object:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

You can also use object spread, which is a Stage 4 proposal for ECMAScript:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

overlay opaque div over youtube iframe

Information from the Official Adobe site about this issue

The issue is when you embed a youtube link:

https://www.youtube.com/embed/kRvL6K8SEgY

in an iFrame, the default wmode is windowed which essentially gives it a z-index greater then everything else and it will overlay over anything.

Try appending this GET parameter to your URL:

wmode=opaque

like so:

https://www.youtube.com/embed/kRvL6K8SEgY?wmode=opaque

Make sure its the first parameter in the URL. Other parameters must go after

In the iframe tag:

Example:

<iframe class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/NWHfY_lvKIQ?wmode=opaque" frameborder="0"></iframe>

Hide/Show Column in an HTML Table

The following is building on Eran's code, with a few minor changes. Tested it and it seems to work fine on Firefox 3, IE7.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
        var index = $(this).attr('name').substr(3);
        index--;
        $('table tr').each(function() { 
            $('td:eq(' + index + ')',this).toggle();
        });
        $('th.' + $(this).attr('name')).toggle();
    });
});
</script>
<body>
<table>
<thead>
    <tr>
        <th class="col1">Header 1</th>
        <th class="col2">Header 2</th>
        <th class="col3">Header 3</th>
    </tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

<form>
    <input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
    <input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
    <input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
</body>
</html>

CodeIgniter htaccess and URL rewrite issues

There are 3 steps to remove index.php.

  1. Make below changes in application/config.php file

    $config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/Your Ci folder_name';
    $config['index_page'] = '';
    $config['uri_protocol'] = 'AUTO';
    
  2. Make .htaccess file in your root directory using below code

    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]
    
  3. Enable the rewrite engine (if not already enabled)

    i. First, initiate it with the following command:

    a2enmod rewrite
    

    ii. Edit the file /etc/apache2/sites-enabled/000-default

    Change all AllowOverride None to AllowOverride All.

    Note: In latest version you need to change in /etc/apache2/apache2.conf file

    iii. Restart your server with the following command:

    sudo /etc/init.d/apache2 restart
    

How to copy a file to a remote server in Python using SCP or SSH?

You can use the vassal package, which is exactly designed for this.

All you need is to install vassal and do

from vassal.terminal import Terminal
shell = Terminal(["scp username@host:/home/foo.txt foo_local.txt"])
shell.run()

Also, it will save you authenticate credential and don't need to type them again and again.

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

How do I copy a folder from remote to local using scp?

Go to Files on your unity toolbar

enter image description here

Press Ctrl + l and write [email protected]

The 192.168.1.103 is the host that you want to connect.

The here one example

enter image description here

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

Your target SDK might be higher than SDK of the device, change that. For example, your device is running API 23 but your target SDK is 25. Change 25 to 23.

Checking if object is empty, works with ng-show but not from controller?

Check Empty object

$scope.isValid = function(value) {
    return !value
}

How To change the column order of An Existing Table in SQL Server 2008

I got the answer for the same , Go on SQL Server ? Tools ? Options ? Designers ? Table and Database Designers and unselect Prevent saving changes that require table re-creation

enter image description here

2- Open table design view and that scroll your column up and down and save your changes.

enter image description here

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

make *** no targets specified and no makefile found. stop

make takes a makefile as input. Makefile usually is named makefile or Makefile. The configure command should generate a makefile, so that make could be in turn executed. Check if a makefile has been generated under your working directory.

At runtime, find all classes in a Java application that extend a base class

Thanks all who answered this question.

It seems this is indeed a tough nut to crack. I ended up giving up and creating a static array and getter in my baseclass.

public abstract class Animal{
    private static Animal[] animals= null;
    public static Animal[] getAnimals(){
        if (animals==null){
            animals = new Animal[]{
                new Dog(),
                new Cat(),
                new Lion()
            };
        }
        return animals;
    }
}

It seems that Java just isn't set up for self-discoverability the way C# is. I suppose the problem is that since a Java app is just a collection of .class files out in a directory / jar file somewhere, the runtime doesn't know about a class until it's referenced. At that time the loader loads it -- what I'm trying to do is discover it before I reference it which is not possible without going out to the file system and looking.

I always like code that can discover itself instead of me having to tell it about itself, but alas this works too.

Thanks again!

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

A little late for the party, here's how I do it

  1. Undeploy application from manager
  2. Shutdown tomcat using ./shutdown.sh
  3. Delete browser cache
  4. Delete the application from webapps, and from /work/Catalina/...
  5. Startup tomcat using ./startup.sh
  6. Copy the new version of the application into /webapps and start it.

How to automatically generate getters and setters in Android Studio

Use Ctrl+Enter on Mac to get list of options to generate setter, getter, constructor etc

enter image description here

How to duplicate a whole line in Vim?

For someone who doesn't know vi, some answers from above might mislead him with phrases like "paste ... after/before current line".
It's actually "paste ... after/before cursor".

yy or Y to copy the line
or
dd to delete the line

then

p to paste the copied or deleted text after the cursor
or
P to paste the copied or deleted text before the cursor


For more key bindings, you can visit this site: vi Complete Key Binding List

Add vertical scroll bar to panel

Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)

mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;

App.Config Transformation for projects which are not Web Projects in Visual Studio?

This works now with the Visual Studio AddIn treated in this article: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file.

You can right-click on your web.config and click "Add Config Transforms." When you do this, you'll get a web.debug.config and a web.release.config. You can make a web.whatever.config if you like, as long as the name lines up with a configuration profile. These files are just the changes you want made, not a complete copy of your web.config.

You might think you'd want to use XSLT to transform a web.config, but while they feels intuitively right it's actually very verbose.

Here's two transforms, one using XSLT and the same one using the XML Document Transform syntax/namespace. As with all things there's multiple ways in XSLT to do this, but you get the general idea. XSLT is a generalized tree transformation language, while this deployment one is optimized for a specific subset of common scenarios. But, the cool part is that each XDT transform is a .NET plugin, so you can make your own.

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()">
  <xsl:copy>           
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/configuration/appSettings">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
    <xsl:element name="add">
      <xsl:attribute name="key">NewSetting</xsl:attribute>
      <xsl:attribute name="value">New Setting Value</xsl:attribute>
    </xsl:element>
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Or the same thing via the deployment transform:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
   <appSettings>
      <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/>
   </appSettings>
</configuration>

Valid characters in a Java class name

Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:

  • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.

  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

From the official Java Tutorial.

Removing pip's cache?

On Mac OS (Mavericks), I had to delete /tmp/pip-build/

How to clear a textbox once a button is clicked in WPF?

I use this. I think this is the simpliest way to do it:

 textBoxName.Clear();

Check if program is running with bash shell script?

You can achieve almost everything in PROCESS_NUM with this one-liner:

[ `pgrep $1` ] && return 1 || return 0

if you're looking for a partial match, i.e. program is named foobar and you want your $1 to be just foo you can add the -f switch to pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0

Putting it all together your script could be reworked like this:

#!/bin/bash

check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`

  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

Running it would look like this:

# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox

# SHELL #2
$ dropbox stop
Dropbox daemon stopped.

# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

Hope this helps!

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

Model Binding to a List MVC 4

This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.

ViewModel looks like this:

public class MyViewModel
{
   public List<Person> Persons{get;set;}
}

View(with BeginForm of course):

@model MyViewModel


@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    @Html.HiddenFor(m => m.Persons[i].PersonId)
    @Html.EditorFor(m => m.Persons[i].FirstName) 
    @Html.EditorFor(m => m.Persons[i].LastName)         
}

Action:

[HttpPost]public ViewResult(MyViewModel vm)
{
...

Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.

Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:

@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    if(i != 4)//conditionally hide 5th item, 
    { //but BUG occurs on postback, all items after 5th will not be bound to the the list
      @Html.HiddenFor(m => m.Persons[i].PersonId)
      @Html.EditorFor(m => m.Persons[i].FirstName) 
      @Html.EditorFor(m => m.Persons[i].LastName)           
    }
}

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Why do we use Base64?

Most computers store data in 8-bit binary format, but this is not a requirement. Some machines and transmission media can only handle 7 bits (or maybe even lesser) at a time. Such a medium would interpret the stream in multiples of 7 bits, so if you were to send 8-bit data, you won't receive what you expect on the other side. Base-64 is just one way to solve this problem: you encode the input into a 6-bit format, send it over your medium and decode it back to 8-bit format at the receiving end.

How do I get this javascript to run every second?

Use setInterval() to run a piece of code every x milliseconds.

You can wrap the code you want to run every second in a function called runFunction.

So it would be:

var t=setInterval(runFunction,1000);

And to stop it, you can run:

clearInterval(t);

Do I commit the package-lock.json file created by npm 5?

Yes, you can commit this file. From the npm's official docs:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

This file is intended to be committed into source repositories[.]

Reading CSV files using C#

Another one to this list, Cinchoo ETL - an open source library to read and write CSV files

For a sample CSV file below

Id, Name
1, Tom
2, Mark

Quickly you can load them using library as below

using (var reader = new ChoCSVReader("test.csv").WithFirstLineHeader())
{
   foreach (dynamic item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

If you have POCO class matching the CSV file

public class Employee
{
   public int Id { get; set; }
   public string Name { get; set; }
}

You can use it to load the CSV file as below

using (var reader = new ChoCSVReader<Employee>("test.csv").WithFirstLineHeader())
{
   foreach (var item in reader)
   {
      Console.WriteLine(item.Id);
      Console.WriteLine(item.Name);
   }
}

Please check out articles at CodeProject on how to use it.

Disclaimer: I'm the author of this library

Why do I need an IoC container as opposed to straightforward DI code?

Honestly I don't find there to be many cases where IoC containers are needed, and most of the time, they just add unneeded complexity.

If you are using it just for making construction of an object simpler, I'd have to ask, are you instantiating this object in more than one location? Would a singleton not suit your needs? Are you changing the configuration at runtime? (Switching data source types, etc).

If yes, then you might need an IoC container. If not, then you're just moving the initialization away from where the developer can easily see it.

Who said that an interface is better than inheritance anyway? Say you're testing a Service. Why not use constructor DI, and create mocks of the dependencies using inheritance? Most services I use only have a few dependencies. Doing unit testing this way prevents maintaining a ton of useless interfaces and means you don't have to use Resharper to quickly find the declaration of a method.

I believe that for most implementations, saying that IoC Containers remove unneeded code is a myth.

First, there's setting up the container in the first place. Then you still have to define each object that needs to be initialized. So you don't save code in initialization, you move it (unless your object is used more than once. Is it better as a Singleton?). Then, for each object you've initialized in this way, you have to create and maintain an interface.

Anyone have any thoughts on this?

Difference between Pig and Hive? Why have both?

Check out this post from Alan Gates, Pig architect at Yahoo!, that compares when would use a SQL like Hive rather than Pig. He makes a very convincing case as to the usefulness of a procedural language like Pig (vs. declarative SQL) and its utility to dataflow designers.

Force IE10 to run in IE10 Compatibility View?

If you want to set the compatibility mode in the browser itself and not in the html do the following

  1. Open IE 10
  2. Press the ALT Key to bring up the IE Menubar
  3. Click on the Tools menu
  4. Click on compatibility view setting.
  5. Clicks check the box; display all the websites in compatibility view or
  6. Add only the desired websites to the compatibility view

As shown in the image below. The website should then open up with IE 10 Compatibility view.

enter image description here

Selected value for JSP drop down using JSTL

In HTML, the selected option is represented by the presence of the selected attribute on the <option> element like so:

<option ... selected>...</option>

Or if you're HTML/XHTML strict:

<option ... selected="selected">...</option>

Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:

request.setAttribute("selectedDept", selectedDept);

then this should do:

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
    </c:forEach>
</select>

See also:

Right to Left support for Twitter Bootstrap 3

  1. I highly recommend bootstrap-rtl. It is built over Bootstrap core, and rtl support is added as it is a bootstrap theme. This would make your code more maintainable as you can always update your core bootstrap files. CDN

  2. Another option to use this stand-alone library, It also comes with few awesome Arabic fonts.

Oracle Sql get only month and year in date datatype

"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.

You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.

If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...

Example..

Month varchar2(3) --Month code in Alpha..
Year  NUMBER      -- Year in number

or

Month number(2)    --Month Number in Year.
Year  NUMBER      -- Year in number

.htaccess: where is located when not in www base dir

The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.

Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.

List to array conversion to use ravel() function

If all you want is calling ravel on your (nested, I s'pose?) list, you can do that directly, numpy will do the casting for you:

L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)

Also worth mentioning that you needn't go through numpy at all.

MySQL Server has gone away when importing large sql file

If you are running with default values then you have a lot of room to optimize your mysql configuration.

The first step I recommend is to increase the max_allowed_packet to 128M.

Then download the MySQL Tuning Primer script and run it. It will provide recommendations to several facets of your config for better performance.

Also look into adjusting your timeout values both in MySQL and PHP.

How big (file size) is the file you are importing and are you able to import the file using the mysql command line client instead of PHPMyAdmin?

How to initialize an array in one step using Ruby?

Along with the above answers , you can do this too

    =>  [*'1'.."5"]   #remember *
    => ["1", "2", "3", "4", "5"]

Accessing last x characters of a string in Bash

Another workaround is to use grep -o with a little regex magic to get three chars followed by the end of line:

$ foo=1234567890
$ echo $foo | grep -o ...$
890

To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep with this regex:

$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd

You can also use different ranges, such as 5,10 to get the last five to ten chars.

How to pass an object into a state using UI-router?

No, the URL will always be updated when params are passed to transitionTo.

This happens on state.js:698 in ui-router.

What is the parameter "next" used for in Express?

Next is used to pass control to the next middleware function. If not the request will be left hanging or open.

remove borders around html input

your code is look like this jsfiddle.net/NTkGZ/

try

border:none;

Floating point exception

It's caused by n % x, when x is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.

General notes:

  1. Try to format your code better. Focus on using a consistent style. E.g. you have one else that starts immediately after a if brace (not even a space), and another with a newline in between.
  2. Don't use globals unless necessary. There is no reason for q to be global.
  3. Don't return without a value in a non-void (int) function.

http post - how to send Authorization header?

I had the same issue. This is my solution using angular documentation and firebase Token:

getService()  {

const accessToken=this.afAuth.auth.currentUser.getToken().then(res=>{
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': res
    })
  };
  return this.http.get('Url',httpOptions)
    .subscribe(res => console.log(res));
}); }}

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

"Could not find Developer Disk Image"

Xcode 7.0.1 and iOS 9.1 are incompatible. You will need to update your version of Xcode via the Mac app store.

If your iOS version is lower then the Xcode version on the other hand, you can change the deployment target for a lower version of iOS by going to the General Settings and under Deployment set your Deployment Target:

enter image description here

Note:

Xcode 7.1 does not include iOS 9.2 beta SDK. Upgraded to Xcode to 7.2 beta by downloading it from the Xcode website.

How to print / echo environment variables?

The syntax

variable=value command

is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:

a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'

The result will be 5 for the first echo and 3 for the second.

Using 'sudo apt-get install build-essentials'

I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:

sudo vi /etc/apt/sources.list

and added the following lines:

deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main

If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:

sudo apt-get update
sudo apt-get install build-essential

Hopefully this will help someone who had the same problem that I did.

Bootstrap 4, how to make a col have a height of 100%?

Use the Bootstrap 4 h-100 class for height:100%;

<div class="container-fluid h-100">
  <div class="row justify-content-center h-100">
    <div class="col-4 hidden-md-down" id="yellow">
      XXXX
    </div>
    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
      Form Goes Here
    </div>
  </div>
</div>

https://www.codeply.com/go/zxd6oN1yWp

You'll also need ensure any parent(s) are also 100% height (or have a defined height)...

html,body {
  height: 100%;
}

Note: 100% height is not the same as "remaining" height.


Related: Bootstrap 4: How to make the row stretch remaining height?