Programs & Examples On #Syck

Matplotlib scatterplot; colour as a function of a third variable

Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

  • Plot points corresponding to Physical variable 'A' in RED.
  • Plot points corresponding to Physical variable 'B' in BLUE.
  • Plot points corresponding to Physical variable 'C' in GREEN.

In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

Coloring scatter plot as a function of x variable

Bootstrap: Position of dropdown menu relative to navbar item

Even if it s late i hope i can help someone. if dropdown menu or submenu is on the right side of screen it's open on the left side, if menu or submenu is on the left it's open on the right side.

$(".dropdown-toggle").on("click", function(event){//"show.bs.dropdown"
    var liparent=$(this.parentElement);
    var ulChild=liparent.find('ul');
    var xOffset=liparent.offset().left;
    var alignRight=($(document).width()-xOffset)<xOffset;


    if (liparent.hasClass("dropdown-submenu"))
    {
        ulChild.css("left",alignRight?"-101%":"");
    }
    else
    {                
        ulChild.toggleClass("dropdown-menu-right",alignRight);
    }

});

To detect vertical position you can also add

$( document ).ready(function() {
        var liparent=$(".dropdown");
    var yOffset=liparent.offset().top;
        var toTop=($(document).height()-yOffset)<yOffset;
    liparent.toggleClass("dropup",toTop);
});

https://jsfiddle.net/jd1100/rf9zvdhg/28/

How to modify a specified commit?

If you haven't already pushed the commits then you can go back to a previous commit using git reset HEAD^[1,2,3,4...]

For example

git commit <file1> -m "Updated files 1 and 2"
git commit <file3> -m "Updated file 3"

Oops, forgot to add file2 to the first commit...

git reset HEAD^1 // because I only need to go back 1 commit

git add <file2>

This will add file2 to the first commit.

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

Arrays.asList(arr).iterator();

Or write your own, implementing ListIterator interface..

How do I set the icon for my application in visual studio 2008?

This is how you do it in Visual Studio 2010.

Because it is finicky, this can be quite painful, actually, because you are trying to do something so incredibly simple, but it isn't straight forward and there are many gotchas that Visual Studio doesn't tell you about. If at any point you feel angry or like you want to sink your teeth into a 2 by 4 and scream, by all means, please do so.

Gotchas:

  • You need to use an .ico file. You cannot use a PNG image file for your executable's icon, it will not work. You must use .ico. There are web utilities that convert images to .ico files.
  • The ico used for your exe will be the ico with the LOWEST RESOURCE ID. In order to change the .ico

1) Open VIEW > RESOURCE VIEW (in the middle of the VIEW menu), or press Ctrl+Shift+E to get it to appear.

2) In Resource view, right click the project name and say ADD > RESOURCE...

3) Assuming you have already generated an .ico file yourself, choose Icon from the list of crap that appears, then click IMPORT.

4) At this dialog *.ico files aren't listed, and you can't use a regular PNG or JPG image as an icon, so change the file filter to *.ico using the dropdown. Misleading UI, I know, I know.

5) If you compile your project now, it will automatically stick the .ico with the lowest ID (as listed in resource.h) as the icon of your .exe file.

6) If you load a bunch of ICO files into the project for whatever reason, be sure the .ico you want Visual Studio to use has the lowest id in resource.h. You can edit this file manually with no problems

Eg.

//resource.h
#define IDI_ICON1                       102
#define IDI_ICON2                       103

IDI_ICON1 is used

//resource.h
#define IDI_ICON1                       106
#define IDI_ICON2                       103

Now IDI_ICON2 is used.

Android change SDK version in Eclipse? Unable to resolve target android-x

If you're using eclipse you can open default.properties file in your workspace and change the project target to the new sdk (target=android-8 for 2.2). I accidentally selected the 1.5 sdk for my version and didn't catch it until much later, but updating that and restarting eclipse seemed to have done the trick.

SQL JOIN, GROUP BY on three tables to get totals

First of all, shouldn't there be a CustomerId in the Invoices table? As it is, You can't perform this query for Invoices that have no payments on them as yet. If there are no payments on an invoice, that invoice will not even show up in the ouput of the query, even though it's an outer join...

Also, When a customer makes a payment, how do you know what Invoice to attach it to ? If the only way is by the InvoiceId on the stub that arrives with the payment, then you are (perhaps inappropriately) associating Invoices with the customer that paid them, rather than with the customer that ordered them... . (Sometimes an invoice can be paid by someone other than the customer who ordered the services)

Regex - how to match everything except a particular pattern

If you want to match a word A in a string and not to match a word B. For example: If you have a text:

1. I have a two pets - dog and a cat
2. I have a pet - dog

If you want to search for lines of text that HAVE a dog for a pet and DOESN'T have cat you can use this regular expression:

^(?=.*?\bdog\b)((?!cat).)*$

It will find only second line:

2. I have a pet - dog

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

In the case of permission denied error, you just need to go with this command.

sudo pip install virtualenv

sudo before the command will throw away the current user permissions error.

Note: For security risks, You should read piotr comment.

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

What regular expression will match valid international phone numbers?

This works for me, without 00, 001, 0011 etc prefix though:

/^\+*(\d{3})*[0-9,\-]{8,}/

Android Center text on canvas

Center with Paint.getTextBounds():

enter image description here

private Rect r = new Rect();

private void drawCenter(Canvas canvas, Paint paint, String text) {
    canvas.getClipBounds(r);
    int cHeight = r.height();
    int cWidth = r.width();
    paint.setTextAlign(Paint.Align.LEFT);
    paint.getTextBounds(text, 0, text.length(), r);
    float x = cWidth / 2f - r.width() / 2f - r.left;
    float y = cHeight / 2f + r.height() / 2f - r.bottom;
    canvas.drawText(text, x, y, paint);
}
  • Paint.Align.CENTER doesn't mean that the reference point of the text is vertically centered. The reference point is always on the baseline. So, why not use Paint.Align.LEFT? You have to calculate the reference point anyway.

  • Paint.descent() has the disadvantage, that it doesn't consider the real text. Paint.descent() retrieves the same value, regardless of whether the text contains letters with descents or not. That's why I use r.bottom instead.

  • I have had some problems with Canvas.getHeight() if API < 16. That's why I use Canvas.getClipBounds(Rect) instead. (Do not use Canvas.getClipBounds().getHeight() as it allocates memory for a Rect.)

  • For reasons of performance, you should allocate objects before they are used in onDraw(). As drawCenter() will be called within onDraw() the object Rect r is preallocated as a field here.


I tried to put the code of the two top answers into my own code (August 2015) and made a screenshot to compare the results:

text centered three versions

The text should be centered within the red filled rectangle. My code produces the white text, the other two codes produces altogether the gray text (they are actually the same, overlapping). The gray text is a little bit too low and two much on the right.

This is how I made the test:

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

class MyView extends View {

    private static String LABEL = "long";
    private static float TEXT_HEIGHT_RATIO = 0.82f;

    private FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(0, 0);
    private Rect r = new Rect();
    private Paint paint = new Paint();
    private Paint rectPaint = new Paint();

    public MyView(Context context) {
        super(context);
    }

    private void drawTextBounds(Canvas canvas, Rect rect, int x, int y) {
        rectPaint.setColor(Color.rgb(0, 0, 0));
        rectPaint.setStyle(Paint.Style.STROKE);
        rectPaint.setStrokeWidth(3f);
        rect.offset(x, y);
        canvas.drawRect(rect, rectPaint);
    }

    // andreas1724 (white color):
    private void draw1(Canvas canvas, Paint paint, String text) {
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setColor(Color.rgb(255, 255, 255));
        canvas.getClipBounds(r);
        int cHeight = r.height();
        int cWidth = r.width();
        paint.getTextBounds(text, 0, text.length(), r);
        float x = cWidth / 2f - r.width() / 2f - r.left;
        float y = cHeight / 2f + r.height() / 2f - r.bottom;
        canvas.drawText(text, x, y, paint);
        drawTextBounds(canvas, r, (int) x, (int) y);
    }

    // Arun George (light green color):
    private void draw2(Canvas canvas, Paint textPaint, String text) {
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(Color.argb(100, 0, 255, 0));
        int xPos = (canvas.getWidth() / 2);
        int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2));
        canvas.drawText(text, xPos, yPos, textPaint);
    }

    // VinceStyling (light blue color):
    private void draw3(Canvas yourCanvas, Paint mPaint, String pageTitle) {
        mPaint.setTextAlign(Paint.Align.LEFT);
        mPaint.setColor(Color.argb(100, 0, 0, 255));
        r = yourCanvas.getClipBounds();
        RectF bounds = new RectF(r);
        bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
        bounds.bottom = mPaint.descent() - mPaint.ascent();
        bounds.left += (r.width() - bounds.right) / 2.0f;
        bounds.top += (r.height() - bounds.bottom) / 2.0f;
        yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int margin = 10;
        int width = w - 2 * margin;
        int height = h - 2 * margin;
        params.width = width;
        params.height = height;
        params.leftMargin = margin;
        params.topMargin = margin;
        setLayoutParams(params);
        paint.setTextSize(height * TEXT_HEIGHT_RATIO);
        paint.setAntiAlias(true);
        paint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD_ITALIC));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.rgb(255, 0, 0));
        draw1(canvas, paint, LABEL);
        draw2(canvas, paint, LABEL);
        draw3(canvas, paint, LABEL);
    }
}

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        FrameLayout container = new FrameLayout(this);
        container.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        container.addView(new MyView(this));
        setContentView(container);
    }
}

Found a swap file by the name

I've also had this error when trying to pull the changes into a branch which is not created from the upstream branch from which I'm trying to pull.

Eg - This creates a new branch matching night-version of upstream

git checkout upstream/night-version -b testnightversion

This creates a branch testmaster in local which matches the master branch of upstream.

git checkout upstream/master -b testmaster 

Now if I try to pull the changes of night-version into testmaster branch leads to this error.

git pull upstream night-version //while I'm in `master` cloned branch

I managed to solve this by navigating to proper branch and pull the changes.

git checkout testnightversion
git pull upstream night-version // works fine.

Make: how to continue after a command fails?

To get make to actually ignore errors on a single line, you can simply suffix it with ; true, setting the return value to 0. For example:

rm .lambda .lambda_t .activity .activity_t_lambda 2>/dev/null; true

This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.

How to merge specific files from Git branches

If you only care about the conflict resolution and not about keeping the commit history, the following method should work. Say you want to merge a.py b.py from BRANCHA into BRANCHB. First, make sure any changes in BRANCHB are either committed or stashed away, and that there are no untracked files. Then:

git checkout BRANCHB
git merge BRANCHA
# 'Accept' all changes
git add .
# Clear staging area
git reset HEAD -- .
# Stash only the files you want to keep
git stash push a.py b.py
# Remove all other changes
git add .
git reset --hard
# Now, pull the changes
git stash pop

git won't recognize that there are conflicts in a.py b.py, but the merge conflict markers are there if there were in fact conflicts. Using a third-party merge tool, such as VSCode, one will be able to resolve conflicts more comfortably.

change figure size and figure format in matplotlib

The first part (setting the output size explictly) isn't too hard:

import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()

But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff plots. There is some mention of the GDK backend being able to do it.

One option would be to convert the output with a tool like imagemagick's convert.

(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)

Time complexity of accessing a Python dict

See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).

The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o).

After a quick check, I have not yet managed to find two tuples that hash to the same value, which would indicate that the lookup is O(1)

l = []
for x in range(0, 50):
    for y in range(0, 50):
        if hash((x,y)) in l:
            print "Fail: ", (x,y)
        l.append(hash((x,y)))
print "Test Finished"

CodePad (Available for 24 hours)

Simple Java Client/Server Program

My try to do client socket program

server reads file and print it to console and copies it to output file

Server Program:

package SocketProgramming.copy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRecieveFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-enerated method stub
        int filesize = 1022386;
        int bytesRead;
        int currentTot;
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        ServerSocket serverSocket = new ServerSocket(15123);
        while (true) {
            Socket socket = serverSocket.accept();
            byte[] bytearray = new byte[filesize];
            InputStream is = socket.getInputStream();
            File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
            FileOutputStream fos = new FileOutputStream(copyFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(bytearray, 0, bytearray.length);
            currentTot = bytesRead;
            do {
                bytesRead = is.read(bytearray, currentTot,
                        (bytearray.length - currentTot));
                if (bytesRead >= 0)
                    currentTot += bytesRead;
            } while (bytesRead > -1);
            bos.write(bytearray, 0, currentTot);
            bos.flush();
            bos.close();
            socket.close();
        }
    }
}

Client program:

package SocketProgramming.copy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSendFile {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
        final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
        System.out.println("Accepted connection : " + socket);
        File transferFile = new File(FILE_NAME);
        byte[] bytearray = new byte[(int) transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");

        os.write(bytearray, 0, bytearray.length);

        BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
        String as = "", line = null;
        while ((line = r.readLine()) != null) {
            as += line + "\n";
            // as += line;

        }
        System.out.print("Input File contains following data: " + as);
        os.flush();
        fin.close();
        bin.close();
        os.close();
        socket.close();

        System.out.println("File transfer complete");
    }
}

Moment.js with Vuejs

TESTED

import Vue from 'vue'
    
Vue.filter('formatYear', (value) => {
  if (!value) return ''
  return moment(value).format('YYYY')
})

How to install SQL Server 2005 Express in Windows 8

I found that on Windows 8.1 with an instance of SQL 2014 already installed, if I ran the SQLEXPR.EXE and then dismissed the Windows 'warning this may be incompatible' dialogs, that the installer completed successfully.

I suspect having 2014 bits already in place probably helped.

Main differences between SOAP and RESTful web services in Java

SOAP Web services:

  1. If your application needs a guaranteed level of reliability and security then SOAP offers additional standards to ensure this type of operation.
  2. If both sides (service provider and service consumer) have to agree on the exchange format then SOAP gives the rigid specifications for this type of interaction.

RestWeb services:

  1. Totally stateless operations: for stateless CRUD (Create, Read, Update, and Delete) operations.
  2. Caching situations: If the information needs to be cached.

SQL WHERE.. IN clause multiple columns

WARNING ABOUT SOLUTIONS:

MANY EXISTING SOLUTIONS WILL GIVE THE WRONG OUTPUT IF ROWS ARE NOT UNIQUE

If you are the only person creating tables, this may not be relevant, but several solutions will give a different number of output rows from the code in question, when one of the tables may not contain unique rows.

WARNING ABOUT PROBLEM STATEMENT:

IN WITH MULTIPLE COLUMNS DOES NOT EXIST, THINK CAREFULLY WHAT YOU WANT

When I see an in with two columns, I can imagine it to mean two things:

  1. The value of column a and column b appear in the other table independently
  2. The values of column a and column b appear in the other table together on the same row

Scenario 1 is fairly trivial, simply use two IN statements.

In line with most existing answers, I hereby provide an overview of mentioned and additional approaches for Scenario 2 (and a brief judgement):

EXISTS (Safe, recommended for SQL Server)

As provided by @mrdenny, EXISTS sounds exactly as what you are looking for, here is his example:

SELECT * FROM T1
WHERE EXISTS
(SELECT * FROM T2 
 WHERE T1.a=T2.a and T1.b=T2.b)

LEFT SEMI JOIN (Safe, recommended for dialects that support it)

This is a very concise way to join, but unfortunately most SQL dialects, including SQL server do not currently suppport it.

SELECT * FROM T1
LEFT SEMI JOIN T2 ON T1.a=T2.a and T1.b=T2.b

Multiple IN statements (Safe, but beware of code duplication)

As mentioned by @cataclysm using two IN statements can do the trick as well, perhaps it will even outperform the other solutions. However, what you should be very carefull with is code duplication. If you ever want to select from a different table, or change the where statement, it is an increased risk that you create inconsistencies in your logic.

Basic solution

SELECT * from T1
WHERE a IN (SELECT a FROM T2 WHERE something)
AND b IN (SELECT b FROM T2 WHERE something)

Solution without code duplication (I believe this does not work in regular SQL Server queries)

WITH mytmp AS (SELECT a, b FROM T2 WHERE something);
SELECT * from T1 
WHERE a IN (SELECT a FROM mytmp)
AND b IN (SELECT b FROM mytmp)

INNER JOIN (technically it can be made safe, but often this is not done)

The reason why I don't recommend using an inner join as a filter, is because in practice people often let duplicates in the right table cause duplicates in the left table. And then to make matters worse, they sometimes make the end result distinct whilst the left table may actually not need to be unique (or not unique in the columns you select). Futhermore it gives you the chance to actually select a column that does not exists in the left table.

SELECT T1.* FROM T1
INNER JOIN 
(SELECT DISTINCT a, b FROM T2) AS T2sub
ON T1.a=T2sub.a AND T1.b=T2sub.b

Most common mistakes:

  1. Joining directly on T2, without a safe subquery. Resulting in the risk of duplication)
  2. SELECT * (Guaranateed to get columns from T2)
  3. SELECT c (Does not guarantee that your column comes and always will come from T1)
  4. No DISTINCT or DISTINCT in the wrong place

CONCATENATION OF COLUMNS WITH SEPARATOR (Not very safe, horrible performance)

The functional problem is that if you use a separator which might occur in a column, it gets tricky to ensure that the outcome is 100% accurate. The technical problem is that this method often incurs type conversions and completely ignores indexes, resulting in possibly horrible performance. Despite these problems, I have to admit that I sometimes still use it for ad-hoc queries on small datasets.

SELECT * FROM T1
WHERE CONCAT(a,"_",b) IN 
(SELECT CONCAT(a,"_",b) FROM T2)

Note that if your columns are numeric, some SQL dialects will require you to cast them to strings first. I believe SQL server will do this automatically.


To wrap things up: As usual there are many ways to do this in SQL, using safe choices will avoid suprises and save you time and headaces in the long run.

Error while trying to run project: Unable to start program. Cannot find the file specified

Deleting and restoring the entire solution from the repository resolved the issue for me. I didn't find this solution listed in any of the other answers, so thought it might help someone.

Generic htaccess redirect www to non-www

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Same as Michael's except this one works :P

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

How to check if std::map contains a key without doing insert?

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

Location for session files in Apache/PHP

The default session.save_path is set to "" which will evaluate to your system's temp directory. See this comment at https://bugs.php.net/bug.php?id=26757 stating:

The new default for save_path in upcoming releaess (sic) will be the empty string, which causes the temporary directory to be probed.

You can use sys_get_temp_dir to return the directory path used for temporary files

To find the current session save path, you can use

Refer to this answer to find out what the temp path is when this function returns an empty string.

Bluetooth pairing without user confirmation

BT version 2.0 or less - You should be able to pair/bond using a standard PIN code, entered programmatically e.g. 1234 or 0000. This is not very secure but many BT devices do this.

BT version 2.1 or greater - Mode 4 Secure Simple Pairing "just works" model can be used. It uses elliptical encryption (whatever that is) and is very secure but is open to Man In The Middle attacks. Compared to the old '0000' pin code approach it is light years ahead. This doesn't require any user input.

This is according to the Bluetooth specs but what you can use depends on what verson of the Bluetooth standard your stack supports and what API you have.

String Concatenation in EL

Mc Dowell's answer is right. I just want to add an improvement if in case you may need to return the variable's value as:

${ empty variable ? '<variable is empty>' : variable }

How do you do relative time in Rails?

Just to clarify Andrew Marshall's solution for using time_ago_in_words
(For Rails 3.0 and Rails 4.0)

If you are in a view

<%= time_ago_in_words(Date.today - 1) %>

If you are in a controller

include ActionView::Helpers::DateHelper
def index
  @sexy_date = time_ago_in_words(Date.today - 1)
end

Controllers do not have the module ActionView::Helpers::DateHelper imported by default.

N.B. It is not "the rails way" to import helpers into your controllers. Helpers are for helping views. The time_ago_in_words method was decided to be a view entity in the MVC triad. (I don't agree but when in rome...)

How to integrate sourcetree for gitlab

If you have the generated SSH key for your project from GitLab you can add it to your keychain in OS X via terminal.

ssh-add -K <ssh_generated_key_file.txt>

Once executed you will be asked for the passphrase that you entered when creating the SSH key.

Once the SSH key is in the keychain you can paste the URL from GitLab into Sourcetree like you normally would to clone the project.

Center a column using Twitter Bootstrap 3

To center more than one column in a Bootstrap row - and the number of cols are odd, simply add this css class to all the columns in that row:

.many-cols-centered {  // To horizontally center bootstrap odd cols, eg col-lg-9, col-md-3, works well in lg
  display:inline-block;
  float:none;
}

So in your HTML you have something like:

<div class="row text-center"> <!-- text-center centers all text in that row -->
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image1.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image2.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image3.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
</div>

Vue.js redirection to another page

To stay in line with your original request:

window.location.href = 'some_url'

You can do something like this:

<div @click="this.window.location='some_url'">
</div>

Note that this does not take advantage of using Vue's router, but if you want to "make a redirection in Vue.js similar to the vanilla javascript", this would work.

CSS: How can I set image size relative to parent height?

Use max-width property of CSS, like this :

img{
  max-width:100%;
}

Generating a SHA-256 hash from the Linux command line

For the sha256 hash in base64, use:

echo -n foo | openssl dgst -binary -sha1 | openssl base64

Example

echo -n foo | openssl dgst -binary -sha1 | openssl base64
C+7Hteo/D9vJXQ3UfzxbwnXaijM=

How to get the current location latitude and longitude in android

**The activity should implements LocationListener

In onCreate(), write the following code **

  Boolean network = haveNetworkConnection();
    Log.e("network", "---------->" + network);
    if (!network) {
        Toast.makeText(getApplicationContext(), "Network is not available",
                3000).show();

    }

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.googleMap);
    googleMap = supportMapFragment.getMap();
    googleMap.setMyLocationEnabled(true);


    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);




        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            && !locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {



         TextView title = new TextView(context);
         title.setText("Location Services Not Active");
            title.setBackgroundColor(Color.BLACK);
            title.setPadding(10, 15, 15, 10);
            title.setGravity(Gravity.CENTER);
            title.setTextColor(Color.WHITE);
            title.setTextSize(22);


            AlertDialog.Builder builder = new AlertDialog.Builder(this);




        builder.setCustomTitle(title);


        // builder.setTitle("Location Services Not Active");
        builder.setMessage("Please enable Location Services and GPS");

        builder.setPositiveButton("Turn on",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface,
                            int i) {
                        // Show location settings when the user acknowledges
                        // the alert dialog
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                        startActivity(intent);
                        finish();
                    }
                });

        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel();
                    }
                });

        builder.show();

    }

    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    if (location == null) {
        Toast.makeText(getApplicationContext(), "GPS signal not found",
                3000).show();
    }
    if (location != null) {
        Log.e("locatin", "location--" + location);

        Log.e("latitude at beginning",
                "@@@@@@@@@@@@@@@" + location.getLatitude());
        onLocationChanged(location);
    }

Write a method haveNetworkConnection

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}



@Override
public void onLocationChanged(Location location) {


    LatLng latLng = new LatLng(latitude, longitude);
    googleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title("Current LOC")
            .icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));


}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

How to get city name from latitude and longitude coordinates in Google Maps?

Try this

  List<Address> list = geoCoder.getFromLocation(location
            .getLatitude(), location.getLongitude(), 1);
    if (list != null & list.size() > 0) {
        Address address = list.get(0);
        result = address.getLocality();
        return result;

TCP vs UDP on video stream

Besides all the other reasons, UDP can use multicast. Supporting 1000s of TCP users all transmitting the same data wastes bandwidth. However, there is another important reason for using TCP.

TCP can much more easily pass through firewalls and NATs. Depending on your NAT and operator, you may not even be able to receive a UDP stream due to problems with UDP hole punching.

jQuery UI Dialog individual CSS styling

The standard way to do this is with jQuery UI's CSS Scopes:

<div class="myCssScope">
   <!-- dialog goes here -->
</div>

Unfortunately, the jQuery UI dialog moves the dialog DOM elements to the end of the document, to fix potential z-index issues. This means the scoping won't work (it will no longer have a ".myCssScope" ancestor).

Christoph Herold designed a workaround which I've implemented as a jQuery plugin, maybe that will help.

JFrame: How to disable window resizing?

You can use a simple call in the constructor under "frame initialization":

setResizable(false);

After this call, the window will not be resizable.

Using grep to search for hex strings in a file

grep has a -P switch allowing to use perl regexp syntax the perl regex allows to look at bytes, using \x.. syntax.

so you can look for a given hex string in a file with: grep -aP "\xdf"

but the outpt won't be very useful; indeed better do a regexp on the hexdump output;

The grep -P can be useful however to just find files matrching a given binary pattern. Or to do a binary query of a pattern that actually happens in text (see for example How to regexp CJK ideographs (in utf-8) )

How to fix a header on scroll

You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.

HTML

<div class="sticky"></div>

CSS

.fixed {
    position: fixed;
    top:0; left:0;
    width: 100%; }

jQuery

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

Example fiddle: http://jsfiddle.net/gxRC9/501/


EDIT: Extended example

If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top can be used.

var stickyOffset = $('.sticky').offset().top;

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= stickyOffset) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

Extended example fiddle: http://jsfiddle.net/gxRC9/502/

Table-level backup

A free app named SqlTableZip will get the job done. Basically, you write any query (which, of course can also be [select * from table]) and the app creates a compressed file with all the data, which can be restored later.

Link: http://www.doccolabs.com/products_sqltablezip.html

413 Request Entity Too Large - File Upload Issue

Use:

php -i

command or add:

phpinfo();

to get the location of configuration file.

Update these variables according to your need and server

max_input_time = 24000
max_execution_time = 24000
upload_max_filesize = 12000M
post_max_size = 24000M
memory_limit = 12000M

On Linux you will need to restart nginx / apache and phpfpm service so the new ini settings are loaded. On xampp, ammps you can restart these from control panel that comes with such applications.

Best design for a changelog / auditing database table?

We also log old and new values and the column they are from as well as the primary key of the table being audited in an audit detail table. Think what you need the audit table for? Not only do you want to know who made a change and when, but when a bad change happens, you want a fast way to put the data back.

While you are designing, you should write the code to recover data. When you need to recover, it is usually in a hurry, best to already be prepared.

Store images in a MongoDB database

You can use the bin data type if you are using any scripting language to store files/images in MongoDB. Bin data is developed to store small size of files.

Refer to your scripting language driver. For PHP, click here.

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

How to get device make and model on iOS?

A category for going getting away from the NSString description

In general, it is desirable to avoid arbitrary string comparisons throughout your code. It is better to update the strings in one place and hide the magic string from your app. I provide a category on UIDevice for that purpose.

For my specific needs I need to know which device I am using without the need to know specifics about networking capability that can be easily retrieved in other ways. So you will find a coarser grained enum than the ever growing list of devices.

Updating is a matter of adding the device to the enum and the lookup table.

UIDevice+NTNUExtensions.h

typedef NS_ENUM(NSUInteger, NTNUDeviceType) {
    DeviceAppleUnknown,
    DeviceAppleSimulator,
    DeviceAppleiPhone,
    DeviceAppleiPhone3G,
    DeviceAppleiPhone3GS,
    DeviceAppleiPhone4,
    DeviceAppleiPhone4S,
    DeviceAppleiPhone5,
    DeviceAppleiPhone5C,
    DeviceAppleiPhone5S,
    DeviceAppleiPhone6,
    DeviceAppleiPhone6_Plus,
    DeviceAppleiPhone6S,
    DeviceAppleiPhone6S_Plus,
    DeviceAppleiPhoneSE,
    DeviceAppleiPhone7,
    DeviceAppleiPhone7_Plus,
    DeviceAppleiPodTouch,
    DeviceAppleiPodTouch2G,
    DeviceAppleiPodTouch3G,
    DeviceAppleiPodTouch4G,
    DeviceAppleiPad,
    DeviceAppleiPad2,
    DeviceAppleiPad3G,
    DeviceAppleiPad4G,
    DeviceAppleiPad5G_Air,
    DeviceAppleiPadMini,
    DeviceAppleiPadMini2G,
    DeviceAppleiPadPro12,
    DeviceAppleiPadPro9
};



@interface UIDevice (NTNUExtensions)

- (NSString *)ntnu_deviceDescription;
- (NTNUDeviceType)ntnu_deviceType;

@end

UIDevice+NTNUExtensions.m

#import <sys/utsname.h>
#import "UIDevice+NTNUExtensions.h"

@implementation UIDevice (NTNUExtensions)

- (NSString *)ntnu_deviceDescription
{
    struct utsname systemInfo;
    uname(&systemInfo);

    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}

- (NTNUDeviceType)ntnu_deviceType
{
    NSNumber *deviceType = [[self ntnu_deviceTypeLookupTable] objectForKey:[self ntnu_deviceDescription]];
    return [deviceType unsignedIntegerValue];
}

- (NSDictionary *)ntnu_deviceTypeLookupTable
{
    return @{
             @"i386": @(DeviceAppleSimulator),
             @"x86_64": @(DeviceAppleSimulator),
             @"iPod1,1": @(DeviceAppleiPodTouch),
             @"iPod2,1": @(DeviceAppleiPodTouch2G),
             @"iPod3,1": @(DeviceAppleiPodTouch3G),
             @"iPod4,1": @(DeviceAppleiPodTouch4G),
             @"iPhone1,1": @(DeviceAppleiPhone),
             @"iPhone1,2": @(DeviceAppleiPhone3G),
             @"iPhone2,1": @(DeviceAppleiPhone3GS),
             @"iPhone3,1": @(DeviceAppleiPhone4),
             @"iPhone3,3": @(DeviceAppleiPhone4),
             @"iPhone4,1": @(DeviceAppleiPhone4S),
             @"iPhone5,1": @(DeviceAppleiPhone5),
             @"iPhone5,2": @(DeviceAppleiPhone5),
             @"iPhone5,3": @(DeviceAppleiPhone5C),
             @"iPhone5,4": @(DeviceAppleiPhone5C),
             @"iPhone6,1": @(DeviceAppleiPhone5S),
             @"iPhone6,2": @(DeviceAppleiPhone5S),
             @"iPhone7,1": @(DeviceAppleiPhone6_Plus),
             @"iPhone7,2": @(DeviceAppleiPhone6),
             @"iPhone8,1" :@(DeviceAppleiPhone6S),
             @"iPhone8,2" :@(DeviceAppleiPhone6S_Plus),
             @"iPhone8,4" :@(DeviceAppleiPhoneSE),
             @"iPhone9,1" :@(DeviceAppleiPhone7),
             @"iPhone9,3" :@(DeviceAppleiPhone7),
             @"iPhone9,2" :@(DeviceAppleiPhone7_Plus),
             @"iPhone9,4" :@(DeviceAppleiPhone7_Plus),
             @"iPad1,1": @(DeviceAppleiPad),
             @"iPad2,1": @(DeviceAppleiPad2),
             @"iPad3,1": @(DeviceAppleiPad3G),
             @"iPad3,4": @(DeviceAppleiPad4G),
             @"iPad2,5": @(DeviceAppleiPadMini),
             @"iPad4,1": @(DeviceAppleiPad5G_Air),
             @"iPad4,2": @(DeviceAppleiPad5G_Air),
             @"iPad4,4": @(DeviceAppleiPadMini2G),
             @"iPad4,5": @(DeviceAppleiPadMini2G),
             @"iPad4,7":@(DeviceAppleiPadMini),
             @"iPad6,7":@(DeviceAppleiPadPro12),
             @"iPad6,8":@(DeviceAppleiPadPro12),
             @"iPad6,3":@(DeviceAppleiPadPro9),
             @"iPad6,4":@(DeviceAppleiPadPro9)
             };
}

@end

Adding attribute in jQuery

use this code <script> $('#someid').attr('disabled,'true'); </script>

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

GCC -fPIC option

Adding further...

Every process has same virtual address space (If randomization of virtual address is stopped by using a flag in linux OS) (For more details Disable and re-enable address space layout randomization only for myself)

So if its one exe with no shared linking (Hypothetical scenario), then we can always give same virtual address to same asm instruction without any harm.

But when we want to link shared object to the exe, then we are not sure of the start address assigned to shared object as it will depend upon the order the shared objects were linked.That being said, asm instruction inside .so will always have different virtual address depending upon the process its linking to.

So one process can give start address to .so as 0x45678910 in its own virtual space and other process at the same time can give start address of 0x12131415 and if they do not use relative addressing, .so will not work at all.

So they always have to use the relative addressing mode and hence fpic option.

How to square all the values in a vector in R?

This will also work

newData <- data*data

updating nodejs on ubuntu 16.04

Using Node Version Manager (NVM):

Install it:

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Test your installation:

close your current terminal, open a new terminal, and run:

command -v nvm

Use it to install as many versions as u like:

nvm install 8              # Install nodejs 8
nvm install --lts          # Install latest LTS (Long Term Support) version

List installed versions:

nvm ls

Use a specific version:

nvm use 8                  # Use this version on this shell

Set defaults:

nvm alias default 8        # Default to nodejs 8 on this shell
nvm alias default node     # always use latest available as default nodejs for all shells

Resizing image in Java

            int newHeight = 150;
            int newWidth = 150; 
            holder.iv_arrow.requestLayout();
            holder.iv_arrow.getLayoutParams().height = newHeight;
            holder.iv_arrow.getLayoutParams().width = newWidth;
            holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
            holder.iv_arrow.setImageResource(R.drawable.video_menu);

Git push failed, "Non-fast forward updates were rejected"

(One) Solution for Netbeans 7.1: Try a pull. This will probably also fail. Now have a look into the logs (they are usually shown now in the IDE). There's one/more line saying:

"Pull failed due to this file:"

Search that file, delete it (make a backup before). Usually it's a .gitignore file, so you will not delete code. Redo the push. Everything should work fine now.

AngularJS $http-post - convert binary to excel file and download

Worked for me -

$scope.downloadFile = function () {
        Resource.downloadFile().then(function (response) {
            var blob = new Blob([response.data], { type: "application/pdf" });
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        },
        function (error) {
            debugger;
        });
    };

Which calls the following from my resource factory-

  downloadFile: function () {
           var downloadRequst = {
                method: 'GET',
                url: 'http://localhost/api/downloadFile?fileId=dfckn4niudsifdh.pdf',
                headers: {
                    'Content-Type': "application/pdf",
                    'Accept': "application/pdf"
                },
                responseType: 'arraybuffer'
            }

            return $http(downloadRequst);
        }

Make sure your API sets the header content type too -

        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

How to get a list of properties with a given attribute?

In addition to previous answers: it's better to use method Any() instead of check length of the collection:

propertiesWithMyAttribute = type.GetProperties()
  .Where(x => x.GetCustomAttributes(typeof(MyAttribute), true).Any());

The example at dotnetfiddle: https://dotnetfiddle.net/96mKep

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

Instead of using the ScrimInsetsFrameLayout... Isn't it easier to just add a view with a fixed height of 24dp and a background of primaryColor?

I understand that this involves adding a dummy view in the hierarchy, but it seems cleaner to me.

I already tried it and it's working well.

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_base_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- THIS IS THE VIEW I'M TALKING ABOUT... -->
        <View
            android:layout_width="match_parent"
            android:layout_height="24dp"
            android:background="?attr/colorPrimary" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/activity_base_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="2dp"
            android:theme="@style/ThemeOverlay.AppCompat.Dark" />

        <FrameLayout
            android:id="@+id/activity_base_content_frame_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <fragment
        android:id="@+id/activity_base_drawer_fragment"
        android:name="com.myapp.drawer.ui.DrawerFragment"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:elevation="4dp"
        tools:layout="@layout/fragment_drawer" />

</android.support.v4.widget.DrawerLayout>

How to debug an apache virtual host configuration?

I found my own mistake, I did not add log file name: ErrorLog /var/log/apache2
And this path: Directory "/usr/share/doc/" Did not contain website sources.

After I changed these two, all worked. Interestingly, apache did not issue any errors, just did not open my website silently on my Mac OS Sierra.

Background color of text in SVG

No, you can not add background color to SVG elements. You can do it programmatically with d3.

var text = d3.select("text");
var bbox = text.node().getBBox();
var padding = 2;
var rect = self.svg.insert("rect", "text")
    .attr("x", bbox.x - padding)
    .attr("y", bbox.y - padding)
    .attr("width", bbox.width + (padding*2))
    .attr("height", bbox.height + (padding*2))
    .style("fill", "red");

Settings to Windows Firewall to allow Docker for Windows to share drive

What did it for me (after several hours of trial-n-error) was changing the Subnet Mask from 255.255.255.240 to 255.255.255.0 (which should not change anything).

As part of the trial-n-error, I had done everything else listed on article, but without any success .. but this last step did it .. and reverting back to 255.255.255.240 does not break the good cycle.

I admit, it makes no sense .. but it might be related to an internal state only being triggered by the network change.

Anyway, if i have helped just one, then it was worth the effort.

Docker Desktop edge, 2.0.4.1 (34207)

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

in case your Latitude and Longitude lists are large and lazily loaded:

from itertools import izip
for lat, lon in izip(latitudes, longitudes):
    process(lat, lon)

or if you want to avoid the for-loop

from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))

How do I set the path to a DLL file in Visual Studio?

  1. Go to project properties (Alt+F7)
  2. Under Debugging, look to the right
  3. There's an Environment field.
  4. Add your relative path there (relative to vcproj folder) i.e. ..\some-framework\lib by appending PATH=%PATH%;$(ProjectDir)\some-framework\lib or prepending to the path PATH=C:\some-framework\lib;%PATH%
  5. Hit F5 (debug) again and it should work.

Postfix is installed but how do I test it?

(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)

You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.

Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:

telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)

You should get a response like:

250 2.0.0 Ok: queued as 6E414C4643A

The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:

sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected]             [email protected]
[email protected]             [email protected]
@localdomain.local                [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the 
generic file)

Happy Trails

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Assuming that you already downloaded chromeDriver, this error is also occurs when already multiple chrome tabs are open.

If you close all tabs and run again, the error should clear up.

Return None if Dictionary key is not available

Use dict.get

Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

scroll image with continuous scrolling using marquee tag

I think you set the marquee width related to 5 images total width. It works fine

ex: <marquee style="width:700px"></marquee>

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

In the app function you have incorrectly spelled the word setpersonSate, missing the letter t, thus it should be setpersonState.

Error:

const app = props => { 
    const [personState, setPersonSate] = useState({....

Solution:

const app = props => { 
        const [personState, setPersonState] = useState({....

Proper Linq where clauses

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

Python 3 print without parenthesis

Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's only a single extra character.

If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.

Python 2:

>>> p = print
  File "<stdin>", line 1
    p = print
            ^
SyntaxError: invalid syntax

Python 3:

>>> p = print
>>> p('hello')
hello

It'll make your code less readable, but you'll save those few characters every time you print something.

How to place the ~/.composer/vendor/bin directory in your PATH?

For Linux Mint 18: edit ~/.bashrc and add this line to it at the bottom:

export PATH="$PATH:$HOME/.config/composer/vendor/bin"

then resource .bashrc (type in console):

source ~/.bashrc (or close and reopen the terminal)

test it by typing in the console:

echo $PATH

or type in console:

laravel

Ruby String to Date Conversion

What is wrong with Date.parse method?

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

It seems to work.

The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time object, suppose we have string:

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

I couldn't find simpler method to convert Time to Date.

Where should I put the log4j.properties file?

You don't need to specify PropertyConfigurator.configure("log4j.properties"); in your Log4J class, If you have already defined the log4j.properties in your project structure.

In case of Web Dynamic Project: -

You need to save your log4j.properties under WebContent -> WEB-INF -> log4j.properties

I hope this may help you.

The type is defined in an assembly that is not referenced, how to find the cause?

In my case, I was referencing a library that was being built to the wrong Platform/Configuration (I had just created the referenced library).

Furthermore, I was unable to fix the problem in Visual Studio Configuration Manager -- unable to switch and create new Platforms and Configurations for this library. I fixed it by correcting the entries in the ProjectConfigurationPlatforms section of the .sln file for that project. All its permutations were set to Debug|Any CPU (I'm not sure how I did that). I overwrote the entries for the broken project with the ones for a working project and changed the GUID for each entry.

Entries for functioning project

{9E93345C-7A51-4E9A-ACB0-DAAB8F1A1267}.Release|x64.ActiveCfg = Release|x64 {9E93345C-7A51-4E9A-ACB0-DAAB8F1A1267}.Release|x64.Build.0 = Release|x64

Entries for corrupted project

{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.ActiveCfg = Debug|Any CPU {94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.Build.0 = Debug|Any CPU

Corrupted entries now fixed

{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.ActiveCfg = Release|x64 {94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.Build.0 = Release|x64

I hope this helps someone.

How to prevent user from typing in text field without disabling the field?

One option is to bind a handler to the input event.

The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).

Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.

This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.

_x000D_
_x000D_
const inputEl = document.querySelector('input');_x000D_
_x000D_
inputEl.addEventListener('input', (event) => {_x000D_
  event.target.value = '';_x000D_
});
_x000D_
<input type="text" />
_x000D_
_x000D_
_x000D_

Tested in Safari 10, Firefox 49, Chrome 54, IE 11.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

Try with the fully qualified name for the resource:

private static final String FILENAME = "resources/skyscrapper";

How do I remove the file suffix and path portion from a path string in Bash?

The basename and dirname functions are what you're after:

mystring=/foo/fizzbuzz.bar
echo basename: $(basename "${mystring}")
echo basename + remove .bar: $(basename "${mystring}" .bar)
echo dirname: $(dirname "${mystring}")

Has output:

basename: fizzbuzz.bar
basename + remove .bar: fizzbuzz
dirname: /foo

How can I check if my Element ID has focus?

Use document.activeElement

Should work.

P.S getElementById("myID") not getElementById("#myID")

Simple UDP example to send and receive data from same socket

(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).

In your server this line:

var data = udpServer.Receive(ref groupEP);

re-assigns groupEP from what you had to a the address you receive something on.

This line:

udpServer.Send(new byte[] { 1 }, 1); 

Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:

UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);

while (true)
{
    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
    var data = udpServer.Receive(ref remoteEP);
    udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data          
}

Also if you have server and client on the same machine you should have them on different ports.

Adding Counter in shell script

Try this:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter limit reached, exit script."
       exit 1
  else
       let counter++
       echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Explanation

  • break - if files are present, it will break and allow the script to process the files.
  • [[ "$counter" -gt 20 ]] - if the counter variable is greater than 20, the script will exit.
  • let counter++ - increments the counter by 1 at each pass.

How to load CSS Asynchronously

The trick to triggering an asynchronous stylesheet download is to use a <link> element and set an invalid value for the media attribute (I'm using media="none", but any value will do). When a media query evaluates to false, the browser will still download the stylesheet, but it won't wait for the content to be available before rendering the page.

<link rel="stylesheet" href="css.css" media="none">

Once the stylesheet has finished downloading the media attribute must be set to a valid value so the style rules will be applied to the document. The onload event is used to switch the media property to all:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'">

This method of loading CSS will deliver useable content to visitors much quicker than the standard approach. Critical CSS can still be served with the usual blocking approach (or you can inline it for ultimate performance) and non-critical styles can be progressively downloaded and applied later in the parsing / rendering process.

This technique uses JavaScript, but you can cater for non-JavaScript browsers by wrapping the equivalent blocking <link> elements in a <noscript> element:

<link rel="stylesheet" href="css.css" media="none" onload="if(media!='all')media='all'"><noscript><link rel="stylesheet" href="css.css"></noscript>

You can see the operation in www.itcha.edu.sv

enter image description here

Source in http://keithclark.co.uk/

C# how to wait for a webpage to finish loading before continuing

I think the DocumentCompleted event of the WebBrowser control should get you where you need to go.

ASP.Net 2012 Unobtrusive Validation with jQuery

Add a reference to Microsoft.JScript in your application in your web.config as below :

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="Microsoft.JScript, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
  </appSettings>
</configuration>

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I have made a simulation of the problem. looks like the issue is how we should Access Object Properties Dynamically Using Bracket Notation in Typescript

interface IUserProps {
  name: string;
  age: number;
}

export default class User {
  constructor(private data: IUserProps) {}

  get(propName: string): string | number {
    return this.data[propName as keyof IUserProps];
  }
}

I found a blog that might be helpful to understand this better.

here is a link https://www.nadershamma.dev/blog/2019/how-to-access-object-properties-dynamically-using-bracket-notation-in-typescript/

Get current application physical path within Application_Start

You can use this code:

AppDomain.CurrentDomain.BaseDirectory

How to cast an Object to an int

For Example Object variable; hastaId

Object hastaId = session.getAttribute("hastaID");

For Example Cast an Object to an int,hastaID

int hastaID=Integer.parseInt(String.valueOf(hastaId));

Replace and overwrite instead of appending

Using python3 pathlib library:

import re
from pathlib import Path
import shutil

shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))

Similar method using different approach to backups:

from pathlib import Path

filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))

How do I create documentation with Pydoc?

As RocketDonkey suggested, your module itself needs to have some docstrings.

For example, in myModule/__init__.py:

"""
The mod module
"""

You'd also want to generate documentation for each file in myModule/*.py using

pydoc myModule.thefilename

to make sure the generated files match the ones that are referenced from the main module documentation file.

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

I do not want to inherit the child opacity from the parent in CSS

Opacity is not actually inherited in CSS. It's a post-rendering group transform. In other words, if a <div> has opacity set you render the div and all its kids into a temporary buffer, and then composite that whole buffer into the page with the given opacity setting.

What exactly you want to do here depends on the exact rendering you're looking for, which is not clear from the question.

How to connect to local instance of SQL Server 2008 Express

One of the first things that you should check is that the SQL Server (MSSQLSERVER) is started. You can go to the Services Console (services.msc) and look for SQL Server (MSSQLSERVER) to see that it is started. If not, then start the service.

You could also do this through an elevated command prompt by typing net start mssqlserver.

Get all child views inside LinearLayout at once

Get all views from any type of layout

public List<View> getAllViews(ViewGroup layout){
        List<View> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            views.add(layout.getChildAt(i));
        }
        return views;
}

Get all TextView from any type of layout

public List<TextView> getAllTextViews(ViewGroup layout){
        List<TextView> views = new ArrayList<>();
        for(int i =0; i< layout.getChildCount(); i++){
            View v =layout.getChildAt(i);
            if(v instanceof TextView){
                views.add((TextView)v);
            }
        }
        return views;
}

Java 8 Lambda filter by Lists

Something like:

clients.stream.filter(c->{
   users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());

This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.

Access properties file programmatically with Spring?

You can get your properties through Environment class. As documentation stands:

Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them.

Having Environment as a env variable, simply call:

env.resolvePlaceholders("${your-property:default-value}")

You can get your 'raw' properties through:

env.getProperty("your-property")

It will search through all properties source that spring has registered.

You can either obtain Environment through:

  • inject ApplicationContext by implementing ApplicationContextAware and then call getEnvironment() on context
  • implement EnvironmentAware.

It's obtain through implementation of a class because properties are resolved on early stage of application startup, as they may be required for bean construction.

Read more on documentation: spring Environment documentation

Cannot open include file 'afxres.h' in VC2010 Express

You can also try replace afxres.h with WinResrc.h

how to use a like with a join in sql?

If this is something you'll need to do often...then you may want to denormalize the relationship between tables A and B.

For example, on insert to table B, you could write zero or more entries to a juncion table mapping B to A based on partial mapping. Similarly, changes to either table could update this association.

This all depends on how frequently tables A and B are modified. If they are fairly static, then taking a hit on INSERT is less painful then repeated hits on SELECT.

CSS to hide INPUT BUTTON value text

The difference some of you are seeing in solutions that work or not in the different IEs may be due to having compatibility mode on or off. In IE8, text-indent works just fine unless compatibility mode is turned on. If compatibility mode is on, then font-size and line-height do the trick but can mess up Firefox's display.

So we can use a css hack to let firefox ignore our ie rule.. like so...

text-indent:-9999px;
*font-size: 0px; line-height: 0;

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

Removing all line breaks and adding them after certain text

You can also try this in Notepad++

  • Highlight the lines you want to join (ctrl + a to select all)
  • Choose Edit -> Line Operations -> Join Lines

Content Type application/soap+xml; charset=utf-8 was not supported by service

I had the same problem and solved it by using EnumMemberAttribute for enum member's attribute. If you are using enum type as data contract and its members attributed with DataMemberAttribute, same error occurs. You must use EnumMemberAttribute for members of enum

How to create a trie in Python

Using defaultdict and reduce function.

Create Trie

from functools import reduce
from collections import defaultdict
T = lambda : defaultdict(T)
trie = T()
reduce(dict.__getitem__,'how',trie)['isEnd'] = True

Trie :

defaultdict(<function __main__.<lambda>()>,
            {'h': defaultdict(<function __main__.<lambda>()>,
                         {'o': defaultdict(<function __main__.<lambda>()>,
                                      {'w': defaultdict(<function __main__.<lambda>()>,
                                                   {'isEnd': True})})})})

Search In Trie :

curr = trie
for w in 'how':
    if w in curr:
        curr = curr[w]
    else:
        print("Not Found")
        break
if curr['isEnd']:
    print('Found')

Open two instances of a file in a single Visual Studio session

Luke's answer didn't work for me. The 'New Window' command was already listed in the customize settings, but not showing up in the .js tabs context menu, despite deleting the registry setting.

So I used:

Tools

Customize...

Keyboard...

Scroll down to select Window.NewWindow

And I pressed and assigned the shortcut keys, Ctrl + Shift + W.

That worked for me.

==== EDIT ====

Well, 'worked' was too strong. My keyboard shortcut does indeed open another tab on the same JavaScript file, but rather unhelpfully it does not render the contents; it is just an empty white window! You may have better luck.

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

In c# is there a method to find the max of 3 numbers?

As generic

public static T Min<T>(params T[] values) {
    return values.Min();
}

public static T Max<T>(params T[] values) {
    return values.Max();
}

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

Address already in use: JVM_Bind

The logged error does say that port 3820 is the problem, but I would suggest investigating all the ports that your app is trying to listen on. I ran into this problem and the issue was a port that I'd forgotten about - not the "main" one that I was looking for.

Import txt file and having each line as a list

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))

How to SSH to a VirtualBox guest externally through a host?

Simply setting the Network Setting to bridged did the trick for me.

Your IP will change when you do this. However, in my case it didn't change immediately. ifconfig returned the same ip. I rebooted the vm and boom, the ip set itself to one start with 192.* and I was immediately allowed ssh access.

How to dynamically create CSS class in JavaScript and apply?

Although I'm not sure why you want to create CSS classes with JavaScript, here is an option:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';

Change width of select tag in Twitter Bootstrap

You can use something like this

<div class="row">
     <div class="col-xs-2">
       <select id="info_type" class="form-control">
             <option>College</option>
             <option>Exam</option>
       </select>
     </div>
</div>

http://getbootstrap.com/css/#column-sizing

Android - Launcher Icon Size

You can create icons directly in the android studio itself.The Steps you need to follow are:

1.Right click on Res->New->Image asset

2.CHange asset type to image.

3.Load the image from the local disk

4.You have options to trim,change padding and add background also.Change the values if you need.

5.click Next->Finish.

The image wil be automatically added to mipmap-mdpi,mipmap-hdpi,mipmap-xhdpi,mipmap-xxhdpi,mipmap-xxxhdpi if you select launcher icon or drawable-mdpi,drawable-hdpi,drawable-xhdpi,drawable-xxhdpi,drawable-xxxhdpi ifyou select other icon optins.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Go to File->Other Settings->Default Settings->Build, Execution, Deployment->Build Tools->Gradle->Uncheck Offline work option.

is of a type that is invalid for use as a key column in an index

There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table. The condition is:

([dbo].[CheckKey]([key])=(1))

and [dbo].[CheckKey] is a scalar function defined as:

CREATE FUNCTION [dbo].[CheckKey]
(
    @key nvarchar(max)
)
RETURNS bit
AS
BEGIN
    declare @res bit
    if exists(select * from key_value where [key] = @key)
        set @res = 0
    else
        set @res = 1

    return @res
END

But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

Random character generator with a range of (A..Z, 0..9) and punctuation

Using some simple command line (bash scripting):

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 30 | xargs
t315,qeqaszwz6kxv?761rf.cj/7gc

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 1 | xargs
f
  • cat /dev/urandom: get a random stream of char from the kernel
  • tr: keep only char char we want
  • head: take only the first n chars
  • xargs: just for adding a '\n' char

Show and hide divs at a specific time interval using jQuery

Loop through divs every 10 seconds.

$(function () {

    var counter = 0,
        divs = $('#div1, #div2, #div3');

    function showDiv () {
        divs.hide() // hide all divs
            .filter(function (index) { return index == counter % 3; }) // figure out correct div to show
            .show('fast'); // and show it

        counter++;
    }; // function to loop through divs and show correct div

    showDiv(); // show first div    

    setInterval(function () {
        showDiv(); // show next div
    }, 10 * 1000); // do this every 10 seconds    

});

concatenate char array in C

asprintf is not 100% standard, but it's available via the GNU and BSD standard C libraries, so you probably have it. It allocates the output, so you don't have to sit there and count characters.

char *hi="Hello";
char *ext = ".txt";
char *cat;

asprintf(&cat, "%s%s", hi, ext);

Setting href attribute at runtime

<style>
a:hover {
    cursor:pointer;
}
</style>

<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(".link").click(function(){
        var href = $(this).attr("href").split("#");
        $(".results").text(href[1]);
    })
})
</script>



<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>


<br /><br />
<div class="results"></div>

Boolean checking in the 'if' condition

The former. The latter merely adds verbosity.

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

Can't find bundle for base name

BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:

$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties 
org/jfree/chart/LocalizationBundle.properties
org/jfree/chart/editor/LocalizationBundle.properties
org/jfree/chart/plot/LocalizationBundle.properties

transparent navigation bar ios

I was able to accomplish this in swift this way:

let navBarAppearance = UINavigationBar.appearance()
let colorImage = UIImage.imageFromColor(UIColor.morselPink(), frame: CGRectMake(0, 0, 340, 64))
navBarAppearance.setBackgroundImage(colorImage, forBarMetrics: .Default)

where i created the following utility method in a UIColor category:

imageFromColor(color: UIColor, frame: CGRect) -> UIImage {
  UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
  color.setFill()
  UIRectFill(frame)
  let image = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()
  return image
}

How are ssl certificates verified?

The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.

You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.

The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).

Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

Forward X11 failed: Network error: Connection refused

I had the same problem, but it's solved now. Finally, Putty does work with Cigwin-X, and Xming is not an obligatory app for MS-Windows X-server.

Nowadays it's xlaunch, who controls the run of X-window. Certainly, xlaunch.exe must be installed in Cigwin. When run in interactive mode it asks for "extra settings". You should add "-listen tcp" to additional param field, since Cigwin-X does not listen TCP by default.

In order to not repeat these steps, you may save settings to the file. And run xlaunch.exe via its shortcut with modified CLI inside. Something like

C:\cygwin64\bin\xlaunch.exe -run C:\cygwin64\config.xlaunch

Generate an integer sequence in MySQL

Warning: if you insert numbers one row at a time, you'll end up executing N commands where N is the number of rows you need to insert.

You can get this down to O(log N) by using a temporary table (see below for inserting numbers from 10000 to 10699):

mysql> CREATE TABLE `tmp_keys` (`k` INTEGER UNSIGNED, PRIMARY KEY (`k`));
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO `tmp_keys` VALUES (0),(1),(2),(3),(4),(5),(6),(7);
Query OK, 8 rows affected (0.03 sec)
Records: 8  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+8 from `tmp_keys`;
Query OK, 8 rows affected (0.02 sec)
Records: 8  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+16 from `tmp_keys`;
Query OK, 16 rows affected (0.03 sec)
Records: 16  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+32 from `tmp_keys`;
Query OK, 32 rows affected (0.03 sec)
Records: 32  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+64 from `tmp_keys`;
Query OK, 64 rows affected (0.03 sec)
Records: 64  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+128 from `tmp_keys`;
Query OK, 128 rows affected (0.05 sec)
Records: 128  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+256 from `tmp_keys`;
Query OK, 256 rows affected (0.03 sec)
Records: 256  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `tmp_keys` SELECT k+512 from `tmp_keys`;
Query OK, 512 rows affected (0.11 sec)
Records: 512  Duplicates: 0  Warnings: 0

mysql> INSERT INTO inttable SELECT k+10000 FROM `tmp_keys` WHERE k<700;
Query OK, 700 rows affected (0.16 sec)
Records: 700  Duplicates: 0  Warnings: 0

edit: fyi, unfortunately this won't work with a true temporary table with MySQL 5.0 as it can't insert into itself (you could bounce back and forth between two temporary tables).

edit: You could use a MEMORY storage engine to prevent this from actually being a drain on the "real" database. I wonder if someone has developed a "NUMBERS" virtual storage engine to instantiate virtual storage to create sequences such as this. (alas, nonportable outside MySQL)

Safely override C++ virtual functions

In MSVC, you can use the CLR override keyword even if you're not compiling for CLR.

In g++, there's no direct way of enforcing that in all cases; other people have given good answers on how to catch signature differences using -Woverloaded-virtual. In a future version, someone might add syntax like __attribute__ ((override)) or the equivalent using the C++0x syntax.

How to convert a JSON string to a dictionary?

Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.

Swift 3

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

let str = "{\"name\":\"James\"}"

let dict = convertToDictionary(text: str)

Swift 2

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}

let str = "{\"name\":\"James\"}"

let result = convertStringToDictionary(str)

Original Swift 1 answer:

func convertStringToDictionary(text: String) -> [String:String]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        var error: NSError?
        let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
        if error != nil {
            println(error)
        }
        return json
    }
    return nil
}

let str = "{\"name\":\"James\"}"

let result = convertStringToDictionary(str) // ["name": "James"]

if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
    println(name) // "James"
}

In your version, you didn't pass the proper parameters to NSJSONSerialization and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]

and of course you would also need to change the return type of the function:

func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

What is the meaning of prepended double colon "::"?

This ensures that resolution occurs from the global namespace, instead of starting at the namespace you're currently in. For instance, if you had two different classes called Configuration as such:

class Configuration; // class 1, in global namespace
namespace MyApp
{
    class Configuration; // class 2, different from class 1
    function blah()
    {
        // resolves to MyApp::Configuration, class 2
        Configuration::doStuff(...) 
        // resolves to top-level Configuration, class 1
        ::Configuration::doStuff(...)
    }
}

Basically, it allows you to traverse up to the global namespace since your name might get clobbered by a new definition inside another namespace, in this case MyApp.

How do I remove link underlining in my HTML email?

To completely "hide" underline for <a> in both mail application and web browser, can do the following tricky way.

<a href="..."><div style="background-color:red;">
    <span style="color:red; text-decoration:underline;"><span style="color:white;">BUTTON</span></span>
</div></a>
  1. Color in 1st <span> is the one you don't need, MUST set as same as your background color. (red in here)

  2. Color in 2nd <span> is the one for your button text. (white in here)

Convert image from PIL to openCV format

This is the shortest version I could find,saving/hiding an extra conversion:

pil_image = PIL.Image.open('image.jpg')
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)

If reading a file from a URL:

import cStringIO
import urllib
file = cStringIO.StringIO(urllib.urlopen(r'http://stackoverflow.com/a_nice_image.jpg').read())
pil_image = PIL.Image.open(file)
opencvImage = cv2.cvtColor(numpy.array(pil_image), cv2.COLOR_RGB2BGR)

How do I load a file from resource folder?

I get it to work without any reference to "class" or "ClassLoader".

Let's say we have three scenarios with the location of the file 'example.file' and your working directory (where your app executes) is home/mydocuments/program/projects/myapp:

a)A sub folder descendant to the working directory: myapp/res/files/example.file

b)A sub folder not descendant to the working directory: projects/files/example.file

b2)Another sub folder not descendant to the working directory: program/files/example.file

c)A root folder: home/mydocuments/files/example.file (Linux; in Windows replace home/ with C:)

1) Get the right path: a)String path = "res/files/example.file"; b)String path = "../projects/files/example.file" b2)String path = "../../program/files/example.file" c)String path = "/home/mydocuments/files/example.file"

Basically, if it is a root folder, start the path name with a leading slash. If it is a sub folder, no slash must be before the path name. If the sub folder is not descendant to the working directory you have to cd to it using "../". This tells the system to go up one folder.

2) Create a File object by passing the right path:

File file = new File(path);

3) You are now good to go:

BufferedReader br = new BufferedReader(new FileReader(file));

How to declare a global variable in JavaScript

If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu under jQuery, and I place everything there.

The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.

Also, for convenience, I usually sub-space the plugin namespace with an i namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.

This is how it works:

// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();

Now I can just do $.miniMenu.i.globalVar = 3 or $.miniMenu.i.parseSomeStuff = function(...) {...} whenever I need to save something globally, and I still keep it out of the global namespace.

Get cookie by name

I like to use a closure for getting cookie values by name. The closure below will allow you to get a cookie value by name but will only parse the cookie string if it has been updated.

You can retrieve the value of a cookie with the following:

var foo = cookies.get( "bar" );

Code:

var cookies = ( function() {
    var cookieString = null;
    var cookieArray = [];

    function getValOf( name ) {
        if ( newCookies() ) {
            parseCookieString()
        }
        return cookieArray[ name ];
    }

    // Check if new cookies have been added
    function newCookies() {
        return cookieString === document.cookie;
    }

    function parseCookieString() {
        cookieString = document.cookie;

        // Separate cookies
        var cookies = cookieString.split( ";" );

        // Empty previous cookies
        cookieArray = [];

        // Update cookieArray with new name-value pairs
        for ( var i in cookies ) {

            // Separate name and value
            var nameVal = cookies[ i ].split( "=" );
            var name = nameVal[ 0 ].trim();
            var value = nameVal[ 1 ].trim();

            // Add cookie name value pair to dictionary
            cookieArray[ name ] = value;
        }
    }

    return {

        /**
         * Returns value or undefined
         */
        get: function( name ) {
            return getValOf( name );
        }  
    };
})();

Using a PagedList with a ViewModel ASP.Net MVC

I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.

Here's a snippet of the code that worked for me:

        int pageSize = 4;
        int pageNumber = (page ?? 1);
        //Used the following two formulas so that it doesn't round down on the returned integer
        decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));     
        ViewBag.TotalPages = Math.Ceiling(totalPages);  
        //These next two functions could maybe be reduced to one function....would require some testing and building
        viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
        ViewBag.OnePageofTeachers = viewModel.Teachers;
        ViewBag.PageNumber = pageNumber;

        return View(viewModel);

I added

using.PagedList;

to my controller as the tutorial states.

Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.

@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.

Page @ViewBag.PageNumber of @ViewBag.TotalPages

@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))

Hope that works for you. Let me know if it works!!

PHP check if date between two dates

Simple solution:

function betweenDates($cmpDate,$startDate,$endDate){ 
   return (date($cmpDate) > date($startDate)) && (date($cmpDate) < date($endDate));
}

Repeat command automatically in Linux

while true; do
    sleep 5
    ls -l
done

Convert List<String> to List<Integer> directly

Using Java8:

stringList.stream().map(Integer::parseInt).collect(Collectors.toList());

Move / Copy File Operations in Java

Try to use org.apache.commons.io.FileUtils (General file manipulation utilities). Facilities are provided in the following methods:

(1) FileUtils.moveDirectory(File srcDir, File destDir) => Moves a directory.

(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.

(3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.

(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.

(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.

It's simple, easy and fast.

File tree view in Notepad++

As of Notepad++ 6.9, the new Folder as Workspace feature can be used.

Folder as Workspace opens your folder(s) in a panel so you can browse folder(s) and open any file in Notepad++. Every changement in the folder(s) from outside will be synchronized in the panel. Usage: Simply drop 1 (or more) folder(s) in Notepad++.

Folder as Workspace

This feature has the advantage of not showing your entire file system when just the working directory is needed. It also means you don't need plugins for it to work.

CSS: image link, change on hover

You could do the following, without needing CSS...

<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>

Example: https://jsfiddle.net/jord8on/k1zsfqyk/

This solution was PERFECT for my needs! I found this solution here.

Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

We're using symfony with doctrine and we are in the process of automating deployment. I got this error when I simply hadn't provided the correct db creds in parameters.yml (I was running doctrine:migrations:migrate)

This thread has sent me on a bit of a wild goose chase, so I'm leaving this here so others might not have to.

Check for special characters (/*-+_@&$#%) in a string?

A great way using C# and Linq here:

public static bool HasSpecialCharacter(this string s)
{
    foreach (var c in s)
    {
        if(!char.IsLetterOrDigit(c))
        {
            return true;
        }
    }
    return false;
 }

And access it like this:

myString.HasSpecialCharacter();

Remove all child elements of a DOM node in JavaScript

Why aren't we following the simplest method here "remove" looped inside while.

const foo = document.querySelector(".foo");
while (foo.firstChild) {
  foo.firstChild.remove();     
}
  • Selecting the parent div
  • Using "remove" Method inside a While loop for eliminating First child element , until there is none left.

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

How to parse this string in Java?

public class Test {
    public static void main(String args[]) {
    String s = "pre/fix/dir1/dir2/dir3/dir4/..";
    String prefix = "pre/fix";
    String[] tokens = s.substring(prefix.length()).split("/");
    for (int i=0; i<tokens.length; i++) {
        System.out.println(tokens[i]);
    }
    }

}

How to set up Automapper in ASP.NET Core

I solved it this way (similar to above but I feel like it's a cleaner solution) Works with .NET Core 3.x

Create MappingProfile.cs class and populate constructor with Maps (I plan on using a single class to hold all my mappings)

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Source, Dest>().ReverseMap();
        }
    }

In Startup.cs, add below to add to DI (the assembly arg is for the class that holds your mapping configs, in my case, it's the MappingProfile class).

//add automapper DI
services.AddAutoMapper(typeof(MappingProfile));

In Controller, use it like you would any other DI object

    [Route("api/[controller]")]
    [ApiController]
    public class AnyController : ControllerBase
    {
        private readonly IMapper _mapper;

        public AnyController(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        public IActionResult Get(int id)
        {
            var entity = repository.Get(id);
            var dto = _mapper.Map<Dest>(entity);
            
            return Ok(dto);
        }
    }


Pandas: ValueError: cannot convert float NaN to integer

For identifying NaN values use boolean indexing:

print(df[df['x'].isnull()])

Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

df['x'] = pd.to_numeric(df['x'], errors='coerce')

And for remove all rows with NaNs in column x use dropna:

df = df.dropna(subset=['x'])

Last convert values to ints:

df['x'] = df['x'].astype(int)

Android Studio: /dev/kvm device permission denied

There's absolutely no need to install qemu-kvm (and all its dependencies) if you only want to run the Android Studio Emulator.

The only thing you have to do is to give your user (i.e. the one you are logged in with) the right to access the /dev/kvm-device.

This is done in three simple steps.

First:

Create the kvm-group

groupadd -r kvm

The option -r creates a system group, i.e. with a GID <= 999 (see /etc/login.defs => SYS_GID_MAX)

Second:

Change permissions on /dev/kvm. This could be done as part of the qemu-kvm-installation, because one of the dependencies is installing qemu-system-common (on current Ubuntu systems, package name may vary), which in turn installs the file /lib/udev/rules.d/60-qemu-system-common.rules containing the following:

KERNEL=="kvm", GROUP="kvm", MODE="0660"

So if you are just create a file /etc/udev/rules.d/60-qemu-permissions.rules containing the above line, you are done with the first step.

Third:

Add your username to the group by executing

usermod -a -G kvm <your_username> - the -a is important for adding your user to the kvm-group. Without that you will overwrite the group-settings for your user to only belonging to "kvm"...

That's it.

For the new udev rule and group setting to take effect it's easiest to reboot and login again.

You can also execute

udevadm control --reload-rules && udevadm trigger

for reloading the rules but you still have to logout and login again with regard to the new group.

What is a CSRF token? What is its importance and how does it work?

Yes, the post data is safe. But the origin of that data is not. This way somebody can trick user with JS into logging in to your site, while browsing attacker's web page.

In order to prevent that, django will send a random key both in cookie, and form data. Then, when users POSTs, it will check if two keys are identical. In case where user is tricked, 3rd party website cannot get your site's cookies, thus causing auth error.

How do I select elements of an array given condition?

I like to use np.vectorize for such tasks. Consider the following:

>>> # Arrays
>>> x = np.array([5, 2, 3, 1, 4, 5])
>>> y = np.array(['f','o','o','b','a','r'])

>>> # Function containing the constraints
>>> func = np.vectorize(lambda t: t>1 and t<5)

>>> # Call function on x
>>> y[func(x)]
>>> array(['o', 'o', 'a'], dtype='<U1')

The advantage is you can add many more types of constraints in the vectorized function.

Hope it helps.

convert big endian to little endian in C [without using provided func]

This code snippet can convert 32bit little Endian number to Big Endian number.

#include <stdio.h>
main(){    
    unsigned int i = 0xfafbfcfd;
    unsigned int j;    
    j= ((i&0xff000000)>>24)| ((i&0xff0000)>>8) | ((i&0xff00)<<8) | ((i&0xff)<<24);    
    printf("unsigned int j = %x\n ", j);    
}

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.

What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:

header('Content-Type: application/json; charset=utf-8');

The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.

jQuery get values of checked checkboxes into array

You need to add .toArray() to the end of your .map() function

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

Demo: http://jsfiddle.net/sZQtL/

How to redirect user's browser URL to a different page in Nodejs?

You can use res.render() or res.redirect() method to redirect to another page using node.js express

Eg:

var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render("index");
});

//This reponds a post request for the login page
app.post('/login', function (req, res) {
    console.log("Got a POST request for the login");
    var data = {
        "email": req.body.email,
        "password": req.body.password
    };

    console.log(data);

    //Data insertion code
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("college");
        var query = { email: data.email };
        dbo.collection("user").find(query).toArray(function(err, result) {
            if (err) throw err;
            console.log(result);
            if(result[0].password == data.password)


 res.redirect('dashboard.html');
            else


 res.redirect('login-error.html');
            db.close();
        });
    });

});


// This responds a POST request for the add user
app.post('/insert', function (req, res) {
    console.log("Got a POST request for the add user");

    var data = {
        "first_name" : req.body.firstName,
        "second_name" : req.body.secondName,
        "organization" : req.body.organization,
        "email": req.body.email,
        "mobile" : req.body.mobile,
    };

    console.log(data);

    **res.render('success.html',{email:data.email,password:data.password});**

});


//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
    navigator.serviceWorker.register('service-worker.js', {scope: '/'})
        .then(function (registration) {
            console.log(registration);
        })
        .catch(function (e) {
            console.error(e);
        })
} else {
    console.log('Service Worker is not supported in this browser.');
}


// TODO add service worker code here
if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('service-worker.js')
        .then(function() { console.log('Service Worker Registered'); });
}

var server = app.listen(63342, function () {

    var host = server.address().host;
    var port = server.address().port;

    console.log("Example app listening at http://localhost:%s", port)
});

Here in the login section, If the email and password matches in the database then the site is directed to dashbaord.html otherwise we will show page-error.html using res.redirect() method. Also you can use res.render() to render a page in node.js

How to clear variables in ipython?

EDITED after @ErdemKAYA comment.

To erase a variable, use the magic command:

%reset_selective <regular_expression>

The variables that are erased from the namespace are the one matching the given <regular_expression>.

Therefore

%reset_selective -f a 

will erase all the variables containing an a.

Instead, to erase only a and not aa:

In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a  # raise NameError
In: aa  # returns 2

see as well %reset_selective? for more examples and https://regexone.com/ for a regex tutorial.

To erase all the variables in the namespace see:

%reset?

serialize/deserialize java 8 java.time with Jackson JSON mapper

For those who use Spring Boot 2.x

There is no need to do any of the above - Java 8 LocalDateTime is serialised/de-serialised out of the box. I had to do all of the above in 1.x, but with Boot 2.x, it works seamlessly.

See this reference too JSON Java 8 LocalDateTime format in Spring Boot

Usage of sys.stdout.flush() method

Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO

C# Iterating through an enum? (Indexing a System.Array)

Here is a simple way to iterate through your custom Enum object

For Each enumValue As Integer In [Enum].GetValues(GetType(MyEnum))

     Print([Enum].GetName(GetType(MyEnum), enumValue).ToString)

Next

LINQ Where with AND OR condition

Linq With Or Condition by using Lambda expression you can do as below

DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));

dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);


var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
            == 1 || emp.Field<int>("EmpID") == 2);

foreach (DataRow row in res2)
{
    Label2.Text += "Emplyee ID: " + row[0] + "   &   Emplyee Name: " + row[1] + ",  ";
}

jQuery .load() call doesn't execute JavaScript in loaded HTML file

A other version of John Pick's solution just before, this works fine for me :

jQuery.ajax({
   ....
   success: function(data, textStatus, jqXHR) {
       jQuery(selecteur).html(jqXHR.responseText);
       var reponse = jQuery(jqXHR.responseText);
       var reponseScript = reponse.filter("script");
       jQuery.each(reponseScript, function(idx, val) { eval(val.text); } );
   }
   ...
});

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Run the following query in the mysql console:

SHOW CREATE TABLE momento_distribution

Check for the line that looks something like

CONSTRAINT `momento_distribution_FK_1` FOREIGN KEY (`momento_id`) REFERENCES `momento` (`id`)

It may be different, I just put a guess as to what it could be. If you have a foreign key on both 'momento_id' & 'momento_idmember', you will get two foreign key names. The next step is to delete the foreign keys. Run the following queries:

ALTER TABLE momento_distribution DROP FOREIGN KEY momento_distribution_FK_1
ALTER TABLE momento_distribution DROP FOREIGN KEY momento_distribution_FK_2

Be sure to change the foreign key name to what you got from the CREATE TABLE query. Now you don't have any foreign keys so you can easily remove the primary key. Try the following:

ALTER TABLE  `momento_distribution` DROP PRIMARY KEY

Add the required column as follows:

ALTER TABLE  `momento_distribution` ADD  `id` INT( 11 ) NOT NULL  PRIMARY KEY AUTO_INCREMENT FIRST

This query also adds numbers so you won't need to depend on @rowid. Now you need to add the foreign key back to the earlier columns. For that, first make these indexes:

ALTER TABLE  `momento_distribution` ADD INDEX (  `momento_id` )
ALTER TABLE  `momento_distribution` ADD INDEX (  `momento_idmember` )

Now add the foreign keys. Change the Reference Table/column as you need:

ALTER TABLE  `momento_distribution` ADD FOREIGN KEY ( `momento_id`) REFERENCES  `momento` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT 
ALTER TABLE  `momento_distribution` ADD FOREIGN KEY ( `momento_idmember`) REFERENCES  `member` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT 

Hope that helps. If you get any errors, please edit the question with the structure of the reference tables & the error code(s) that you are getting.

Domain Account keeping locking out with correct password every few minutes

May be the virus by name CONFLICKER try d.exe tool from symantec on the machine hope your problem will be resolved. Check the security logs in domain controller and scan those machines because of this virus it creates bad passwords and lock the users.

Android: Proper Way to use onBackPressed() with Toast

You may also need to reset counter in onPause to prevent cases when user presses home or navigates away by some other means after first back press. Otherwise, I don't see an issue.

Zoom to fit all markers in Mapbox or Leaflet

You also can locate all features inside a FeatureGroup or all the featureGroups, see how it works!

_x000D_
_x000D_
//Group1_x000D_
m1=L.marker([7.11, -70.11]);_x000D_
m2=L.marker([7.33, -70.33]);_x000D_
m3=L.marker([7.55, -70.55]);_x000D_
fg1=L.featureGroup([m1,m2,m3]);_x000D_
_x000D_
//Group2_x000D_
m4=L.marker([3.11, -75.11]);_x000D_
m5=L.marker([3.33, -75.33]);_x000D_
m6=L.marker([3.55, -75.55]);_x000D_
fg2=L.featureGroup([m4,m5,m6]);_x000D_
_x000D_
//BaseMap_x000D_
baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');_x000D_
var map = L.map('map', {_x000D_
  center: [3, -70],_x000D_
  zoom: 4,_x000D_
  layers: [baseLayer, fg1, fg2]_x000D_
});_x000D_
_x000D_
//locate group 1_x000D_
function LocateOne() {_x000D_
    LocateAllFeatures(map, fg1);_x000D_
}_x000D_
_x000D_
function LocateAll() {_x000D_
    LocateAllFeatures(map, [fg1,fg2]);_x000D_
}_x000D_
_x000D_
//Locate the features_x000D_
function LocateAllFeatures(iobMap, iobFeatureGroup) {_x000D_
  if(Array.isArray(iobFeatureGroup)){   _x000D_
   var obBounds = L.latLngBounds();_x000D_
   for (var i = 0; i < iobFeatureGroup.length; i++) {_x000D_
    obBounds.extend(iobFeatureGroup[i].getBounds());_x000D_
   }_x000D_
   iobMap.fitBounds(obBounds);   _x000D_
  } else {_x000D_
   iobMap.fitBounds(iobFeatureGroup.getBounds());_x000D_
  }_x000D_
}
_x000D_
.mymap{_x000D_
  height: 300px;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>_x000D_
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>_x000D_
_x000D_
<div id="map" class="mymap"></div>_x000D_
<button onclick="LocateOne()">locate group 1</button>_x000D_
<button onclick="LocateAll()">locate All</button>
_x000D_
_x000D_
_x000D_

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Is there a way to check if a file is in use?

Perhaps you could use a FileSystemWatcher and watch for the Changed event.

I haven't used this myself, but it might be worth a shot. If the filesystemwatcher turns out to be a bit heavy for this case, I would go for the try/catch/sleep loop.

SQL Current month/ year question

select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());

Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Restart android machine

I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.

How to find index of STRING array in Java from a given value?

No built-in method. But you can implement one easily:

public static int getIndexOf(String[] strings, String item) {
    for (int i = 0; i < strings.length; i++) {
        if (item.equals(strings[i])) return i;
    }
    return -1;
}

Printing result of mysql query from variable

This will print out the query:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());
print $query;

This will print out the results:

$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";

$dave= mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($dave)){
    foreach($row as $cname => $cvalue){
        print "$cname: $cvalue\t";
    }
    print "\r\n";
}

Django - Static file not found

{'document_root', settings.STATIC_ROOT} needs to be {'document_root': settings.STATIC_ROOT}

or you'll get an error like dictionary update sequence element #0 has length 6; 2 is required

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

Spring Data JPA map the native query result to Non-Entity POJO

You can write your native or non-native query the way you want, and you can wrap JPQL query results with instances of custom result classes. Create a DTO with the same names of columns returned in query and create an all argument constructor with same sequence and names as returned by the query. Then use following way to query the database.

@Query("SELECT NEW example.CountryAndCapital(c.name, c.capital.name) FROM Country AS c")

Create DTO:

package example;

public class CountryAndCapital {
    public String countryName;
    public String capitalName;

    public CountryAndCapital(String countryName, String capitalName) {
        this.countryName = countryName;
        this.capitalName = capitalName;
    }
}

change image opacity using javascript

I'm not sure if you can do this in every browser but you can set the css property of the specified img.
Try to work with jQuery which allows you to make css changes much faster and efficiently.
in jQuery you will have the options of using .animate(),.fadeTo(),.fadeIn(),.hide("slow"),.show("slow") for example.
I mean this CSS snippet should do the work for you:

img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}

Also check out this website where everything further is explained:
http://www.w3schools.com/css/css_image_transparency.asp

Parse JSON from JQuery.ajax success data

input type Button

<input type="button" Id="update" value="Update">

I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below

$(function() {

    $('#Search').click(function() {
        var query = $('#query').val();
        var update = $('#update').val();

        $.ajax({
            type: 'POST',
            url: '/Products/Search/',
            data: {
                'insert': update,
                'query': address,
            },
            success: function(res) {
                $('#ProductList').empty('');
                console.log(res);
                json = JSON.parse(res);
                for (var i in json) {
                    var row = $('<tr>');
                    row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
                    row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
                    $('</tr>');
                    $('#ProductList').append(row);
                }
            },
            error: function() {
                alert("did not work");
                location.reload(true);
            }
        });
    });
});

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

Convert a Python list with strings all to lowercase or uppercase

For this sample the comprehension is fastest

$ python -m timeit -s 's=["one","two","three"]*1000' '[x.upper for x in s]'
1000 loops, best of 3: 809 usec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(str.upper,s)'
1000 loops, best of 3: 1.12 msec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(lambda x:x.upper(),s)'
1000 loops, best of 3: 1.77 msec per loop

How to get thread id of a pthread in linux c program?

I think not only is the question not clear but most people also are not cognizant of the difference. Examine the following saying,

POSIX thread IDs are not the same as the thread IDs returned by the Linux specific gettid() system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid() is a number (similar to a process ID) that is assigned by the kernel. Although each POSIX thread has a unique kernel thread ID in the Linux NPTL threading implementation, an application generally doesn’t need to know about the kernel IDs (and won’t be portable if it depends on knowing them).

Excerpted from: The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Michael Kerrisk

IMHO, there is only one portable way that pass a structure in which define a variable holding numbers in an ascending manner e.g. 1,2,3... to per thread. By doing this, threads' id can be kept track. Nonetheless, int pthread_equal(tid1, tid2) function should be used.

if (pthread_equal(tid1, tid2)) printf("Thread 2 is same as thread 1.\n");
else printf("Thread 2 is NOT same as thread 1.\n");

Implement Validation for WPF TextBoxes

When it comes to Muhammad Mehdi's answer, it is better to do:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
     Regex regex = new Regex ( "[^0-9]+" );
     if(regex.IsMatch(e.Text))
     {
         MessageBox.Show("Error");
     }
}

Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.

Add one day to date in javascript

Just for the sake of adding functions to the Date prototype:

In a mutable fashion / style:

Date.prototype.addDays = function(n) {
   this.setDate(this.getDate() + n);
};

// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
   this.addDays(1);
};

Date.prototype.addMonths = function(n) {
   this.setMonth(this.getMonth() + n);
};

Date.prototype.addYears = function(n) {
   this.setFullYear(this.getFullYear() + n);
}

// etc...

var currentDate = new Date();
currentDate.nextDay();

How to Populate a DataTable from a Stored Procedure

Use the SqlDataAdapter, this would simplify everything.

//Your code to this point
DataTable dt = new DataTable();

using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
  using(var da = new SqlDataAdapter(cmd))
  {
      da.Fill(dt):
  }
}

and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).

Check if string begins with something?

You can use string.match() and a regular expression for this too:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

string.match() will return an array of matching substrings if found, otherwise null.

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Send and receive messages through NSNotificationCenter in Objective-C?

There is also the possibility of using blocks:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] 
     addObserverForName:@"notificationName" 
     object:nil
     queue:mainQueue
     usingBlock:^(NSNotification *notification)
     {
          NSLog(@"Notification received!");
          NSDictionary *userInfo = notification.userInfo;

          // ...
     }];

Apple's documentation

Using IF ELSE statement based on Count to execute different Insert statements

IF exists

IF exists (select * from table_1 where col1 = 'value')
BEGIN
    -- one or more
    insert into table_1 (col1) values ('valueB')
END
ELSE
    -- zero
    insert into table_1 (col1) values ('value') 

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

Just for the record if somebody needs a way to handle signals on Windows. I had a requirement to handle from prog A calling prog B through os/exec but prog B never was able to terminate gracefully because sending signals through ex. cmd.Process.Signal(syscall.SIGTERM) or other signals are not supported on Windows. The way I handled is by creating a temp file as a signal ex. .signal.term through prog A and prog B needs to check if that file exists on interval base, if file exists it will exit the program and handle a cleanup if needed, I'm sure there are other ways but this did the job.

How to transition to a new view controller with code only using Swift

SWIFT

Usually for normal transition we use,

let next:SecondViewController = SecondViewController()
self.presentViewController(next, animated: true, completion: nil)

But sometimes when using navigation controller, you might face a black screen. In that case, you need to use like,

let next:ThirdViewController = storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController
self.navigationController?.pushViewController(next, animated: true)

Moreover none of the above solution preserves navigationbar when you call from storyboard or single xib to another xib. If you use nav bar and want to preserve it just like normal push, you have to use,

Let's say, "MyViewController" is identifier for MyViewController

let viewController = MyViewController(nibName: "MyViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)

How do I add FTP support to Eclipse?

have you checked RSE (Remote System Explorer) ? I think it's pretty close to what you want to achieve.

a blog post about it, with screenshots

Find and kill a process in one line using bash and regex

Use pgrep - available on many platforms:

kill -9 `pgrep -f cps_build`

pgrep -f will return all PIDs with coincidence "cps_build"

Code signing is required for product type 'Application' in SDK 'iOS5.1'

I have same problem because option In-App Purchase was ON in project's Capabilities. If your app is not need in-app purchases - turn it off, or you need to set a correct provision profile to Debug scheme.

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9