Programs & Examples On #Datasourceview

cancelling a handler.postdelayed process

Hope this gist help https://gist.github.com/imammubin/a587192982ff8db221da14d094df6fb4

MainActivity as Screen Launcher with handler & runnable function, the Runnable run to login page or feed page with base preference login user with firebase.

How to call a method in another class of the same package?

You can either create a static method or use the other class as a member of your class calling the function in the constructor.

public class aClass {
      private SomeOtherClass oc;
      public class aClass( SomeOtherClass otherClass) {
         oc = otherClass;
      }

      public callOtherClassMethod() {
         oc.otherClassMethod();
       }
    }

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Is there a way I can retrieve sa password in sql server 2005

Wait!

There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password


How to use the tool to retrieve the password

To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer

"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user

name for which you want to retrieve password.Copy the password field (Hashed Code) and

paste here (in Hashed code Field) and click on start button to retrieve

I checked the tool on SQLServer 2000 and it's working fine.

AngularJS 1.2 $injector:modulerr

I have just experienced the same error, in my case it was caused by the second parameter in angular.module being missing- hopefully this may help someone with the same issue.

angular.module('MyApp');

angular.module('MyApp', []);

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

You can change the send line to this:

c.send(b'Thank you for connecting')

The b makes it bytes instead.

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

How to add a default include path for GCC in Linux?

A gcc spec file can do the job, however all users on the machine will be affected.

See here

Modulo operation with negative numbers

The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z

Here's the reference

http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html

Integer Division

This section describes functions for performing integer division. These functions are redundant in the GNU C library, since in GNU C the '/' operator always rounds towards zero. But in other C implementations, '/' may round differently with negative arguments. div and ldiv are useful because they specify how to round the quotient: towards zero. The remainder has the same sign as the numerator.

How to select the rows with maximum values in each group with dplyr?

df %>% group_by(A,B) %>% slice(which.max(value))

How to write both h1 and h2 in the same line?

<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />

Hope this helps!

How do I encrypt and decrypt a string in python?

Try this:

Python Cryptography Toolkit (pycrypto) is required

$ pip install pycrypto

Code:

from Crypto.Cipher import AES
from base64 import b64encode, b64decode


class Crypt:

    def __init__(self, salt='SlTKeYOpHygTYkP3'):
        self.salt = salt.encode('utf8')
        self.enc_dec_method = 'utf-8'

    def encrypt(self, str_to_enc, str_key):
        try:
            aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
            hx_enc = aes_obj.encrypt(str_to_enc.encode('utf8'))
            mret = b64encode(hx_enc).decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Encryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Encryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

    def decrypt(self, enc_str, str_key):
        try:
            aes_obj = AES.new(str_key.encode('utf8'), AES.MODE_CFB, self.salt)
            str_tmp = b64decode(enc_str.encode(self.enc_dec_method))
            str_dec = aes_obj.decrypt(str_tmp)
            mret = str_dec.decode(self.enc_dec_method)
            return mret
        except ValueError as value_error:
            if value_error.args[0] == 'IV must be 16 bytes long':
                raise ValueError('Decryption Error: SALT must be 16 characters long')
            elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
                raise ValueError('Decryption Error: Encryption key must be either 16, 24, or 32 characters long')
            else:
                raise ValueError(value_error)

Usage:

        test_crpt = Crypt()
        test_text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""

        test_key = 'MyKey4TestingYnP'
        test_enc_text = test_crpt.encrypt(test_text, test_key)
        test_dec_text = test_crpt.decrypt(test_enc_text, test_key)
        print(f'Encrypted:{test_enc_text}  Decrypted:{test_dec_text}')

SQL Query - Using Order By in UNION

(SELECT table1.field1 FROM table1 
UNION
SELECT table2.field1 FROM table2) ORDER BY field1 

Work? Remember think sets. Get the set you want using a union and then perform your operations on it.

Strip / trim all strings of a dataframe

You can try:

df[0] = df[0].str.strip()

or more specifically for all string columns

non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())

Export query result to .csv file in SQL Server 2008

You could use QueryToDoc (http://www.querytodoc.com). It lets you write a query against a SQL database and export the results - after you pick the delimiter - to Excel, Word, HTML, or CSV

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

Or if you want all PS1 files to work the way VBS files do, you can edit the registry like this:

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command

Edit the Default value to be something like so...

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"

Then you can just double click all your .PS1 files like you would like to. in my humble opinion, be able to out of the box.

I'm going to call this "The Powershell De-castration Hack". LOL enjoy!

Register DLL file on Windows Server 2008 R2

You need the full path to the regsvr32 so %windir$\system32\regsvr32 <*.dll>

How to align td elements in center

Give a style inside the td element or in your scss file, like this:

vertical-align: 
    middle;

jQuery table sort

My vote! jquery.sortElements.js and simple jquery
Very simple, very easy, thanks nandhp...

            $('th').live('click', function(){

            var th = $(this), thIndex = th.index(), var table = $(this).parent().parent();

                switch($(this).attr('inverse')){
                case 'false': inverse = true; break;
                case 'true:': inverse = false; break;
                default: inverse = false; break;
                }
            th.attr('inverse',inverse)

            table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sortElements(function(a, b){
                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;
            }, function(){
                // parentNode is the element we want to move
                return this.parentNode; 
            });
            inverse = !inverse;     
            });

Dei uma melhorada do código
One cod better! Function for All tables in all Th in all time... Look it!
DEMO

How to check if a variable is not null?

Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:

if(myvar) { }

It also mentions what's considered 'falsey' that you might not realise.

Python: Figure out local timezone

Based on Thoku's answer above, here's an answer that resolves the time zone to the nearest half hour (which is relevant for some timezones eg South Australia's) :

from datetime import datetime
round((round((datetime.now()-datetime.utcnow()).total_seconds())/1800)/2)

ASP.net Repeater get current index, pointer, or counter

To display the item number on the repeater you can use the Container.ItemIndex property.

<asp:repeater id="rptRepeater" runat="server">
    <itemtemplate>
        Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
    </itemtemplate>
    <separatortemplate>
        <br />
    </separatortemplate>
</asp:repeater>

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

How to check if my string is equal to null?

I prefer to use:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

Read StringUtils.isBlank() vs String.isEmpty().

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Angular ng-repeat add bootstrap row every 3 or 4 cols

Based on Alpar solution, using only templates with anidated ng-repeat. Works with both full and partially empty rows:

<div data-ng-app="" data-ng-init="products='soda','beer','water','milk','wine']" class="container">
    <div ng-repeat="product in products" ng-if="$index % 3 == 0" class="row">
        <div class="col-xs-4" 
            ng-repeat="product in products.slice($index, ($index+3 > products.length ? 
            products.length : $index+3))"> {{product}}</div>
    </div>
</div>

JSFiddle

Which comes first in a 2D array, rows or columns?

In java the rows are done first, because a 2 dimension array is considered two separate arrays. Starts with the first row 1 dimension array.

How to determine if one array contains all elements of another array

This can be achieved by doing

(a2 & a1) == a2

This creates the intersection of both arrays, returning all elements from a2 which are also in a1. If the result is the same as a2, you can be sure you have all elements included in a1.

This approach only works if all elements in a2 are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).

Disable same origin policy in Chrome

For Windows users:

The problem with the solution accepted here, in my opinion is that if you already have Chrome open and try to run this it won't work.

However, when researching this, I came across a post on Super User, Is it possible to run Chrome with and without web security at the same time?.

Basically, by running the following command (or creating a shortcut with it and opening Chrome through that)

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

you can open a new "insecure" instance of Chrome at the same time as you keep your other "secure" browser instances open and working as normal. Important: delete/clear C:/Chrome dev session folder every time when you open a window as second time --disable-web-security is not going to work. So you cannot save your changes and then open it again as a second insecure instance of Chrome with --disable-web-security.

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

I use an Android Studio plug-in called "adb idea" -- has a drop down menu for various functions (Uninstall, Kill, Start, etc) that you can target at any connected or simulated device. One could argue it takes me a step away from having a deeper understanding of the power of adb commands and I'd probably agree....though I'm really operating at a lower level of understanding anyway so for me it helps to have a helper. ADB Idea enter image description here

Vim multiline editing like in sublimetext?

Do yourself a favor by dropping the Windows compatibility layer.

The normal shortcut for entering Visual-Block mode is <C-v>.

Others have dealt with recording macros, here are a few other ideas:

Using only visual-block mode.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    
  3. Hit I"<Esc> to obtain:

    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  4. Put the cursor on the last char of the third word:

    asd "asd as|d| asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  5. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    
  6. Hit A"<Esc> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-block mode and Surround.vim.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom and the right:

    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    
  3. Hit S" to surround your selection with ":

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-line mode and :normal.

  1. Hit V to select the whole line and expand it toward the bottom:

    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    
  2. Execute this command: :'<,'>norm ^wi"<C-v><Esc>eea"<CR> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    
    • :norm[al] allows you to execute normal mode commands on a range of lines (the '<,'> part is added automatically by Vim and means "act on the selected area")

    • ^ puts the cursor on the first char of the line

    • w moves to the next word

    • i" inserts a " before the cursor

    • <C-v><Esc> is Vim's way to input a control character in this context, here it's <Esc> used to exit insert mode

    • ee moves to the end of the next word

    • a" appends a " after the cursor

    • <CR> executes the command

    Using Surround.vim, the command above becomes

    :'<,'>norm ^wvees"<CR>
    

How to solve privileges issues when restore PostgreSQL Database

To solve the issue you must assign the proper ownership permissions. Try the below which should resolve all permission related issues for specific users but as stated in the comments this should not be used in production:

root@server:/var/log/postgresql# sudo -u postgres psql
psql (8.4.4)
Type "help" for help.

postgres=# \du
               List of roles
    Role name    | Attributes  | Member of
-----------------+-------------+-----------
 <user-name>    | Superuser   | {}
                 : Create DB
 postgres       | Superuser   | {}
                 : Create role
                 : Create DB

postgres=# alter role <user-name> superuser;
ALTER ROLE
postgres=#

So connect to the database under a Superuser account sudo -u postgres psql and execute a ALTER ROLE <user-name> Superuser; statement.

Keep in mind this is not the best solution on multi-site hosting server so take a look at assigning individual roles instead: https://www.postgresql.org/docs/current/static/sql-set-role.html and https://www.postgresql.org/docs/current/static/sql-alterrole.html.

How can I read input from the console using the Scanner class in Java?

Here is the complete class which performs the required operation:

import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        final int valid = 6;

        Scanner one = new Scanner(System.in);
        System.out.println("Enter your username: ");
        String s = one.nextLine();

        if (s.length() < valid) {
            System.out.println("Enter a valid username");
            System.out.println(
                "User name must contain " + valid + " characters");
            System.out.println("Enter again: ");
            s = one.nextLine();
        }

        System.out.println("Username accepted: " + s);

        Scanner two = new Scanner(System.in);
        System.out.println("Enter your age: ");
        int a = two.nextInt();
        System.out.println("Age accepted: " + a);

        Scanner three = new Scanner(System.in);
        System.out.println("Enter your sex: ");
        String sex = three.nextLine();
        System.out.println("Sex accepted: " + sex);
    }
}

How can I view the shared preferences file using Android Studio?

You could simply create a special Activity for debugging purpose:

@SuppressWarnings("unchecked")
public void loadPreferences() {
// create a textview with id (tv_pref) in Layout.
TextView prefTextView;
prefTextView = (TextView) findViewById(R.id.tv_pref);
    Map<String, ?> prefs = PreferenceManager.getDefaultSharedPreferences(
            context).getAll();
    for (String key : prefs.keySet()) {
        Object pref = prefs.get(key);
        String printVal = "";
        if (pref instanceof Boolean) {
            printVal =  key + " : " + (Boolean) pref;
        }
        if (pref instanceof Float) {
            printVal =  key + " : " + (Float) pref;
        }
        if (pref instanceof Integer) {
            printVal =  key + " : " + (Integer) pref;
        }
        if (pref instanceof Long) {
            printVal =  key + " : " + (Long) pref;
        }
        if (pref instanceof String) {
            printVal =  key + " : " + (String) pref;
        }
        if (pref instanceof Set<?>) {
            printVal =  key + " : " + (Set<String>) pref;
        }
        // Every new preference goes to a new line
        prefTextView.append(printVal + "\n\n");     
    }
}
// call loadPreferences() in the onCreate of your Activity.

How to save image in database using C#

Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.

ADO.NET can do all of the hard work of mapping, escaping etc for you.

Either create a Stored Procedure, or use SqlParameter to do the binding.

As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.

Node.js - Maximum call stack size exceeded

I thought of another approach using function references that limits call stack size without using setTimeout() (Node.js, v10.16.0):

testLoop.js

let counter = 0;
const max = 1000000000n  // 'n' signifies BigInteger
Error.stackTraceLimit = 100;

const A = () => {
  fp = B;
}

const B = () => {
  fp = A;
}

let fp = B;

const then = process.hrtime.bigint();

for(;;) {
  counter++;
  if (counter > max) {
    const now = process.hrtime.bigint();
    const nanos = now - then;

    console.log({ "runtime(sec)": Number(nanos) / (1000000000.0) })
    throw Error('exit')
  }
  fp()
  continue;
}

output:

$ node testLoop.js
{ 'runtime(sec)': 18.947094799 }
C:\Users\jlowe\Documents\Projects\clearStack\testLoop.js:25
    throw Error('exit')
    ^

Error: exit
    at Object.<anonymous> (C:\Users\jlowe\Documents\Projects\clearStack\testLoop.js:25:11)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

How to use QTimer

mytimer.h:

    #ifndef MYTIMER_H
    #define MYTIMER_H

    #include <QTimer>

    class MyTimer : public QObject
    {
        Q_OBJECT
    public:
        MyTimer();
        QTimer *timer;

    public slots:
        void MyTimerSlot();
    };

    #endif // MYTIME

mytimer.cpp:

#include "mytimer.h"
#include <QDebug>

MyTimer::MyTimer()
{
    // create a timer
    timer = new QTimer(this);

    // setup signal and slot
    connect(timer, SIGNAL(timeout()),
          this, SLOT(MyTimerSlot()));

    // msec
    timer->start(1000);
}

void MyTimer::MyTimerSlot()
{
    qDebug() << "Timer...";
}

main.cpp:

#include <QCoreApplication>
#include "mytimer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create MyTimer instance
    // QTimer object will be created in the MyTimer constructor
    MyTimer timer;

    return a.exec();
}

If we run the code:

Timer...
Timer...
Timer...
Timer...
Timer...
...

resources

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

It can be due to a number of reasons happening when configuring the listener. Best way is to log and see the actual error. You can do this by adding a logging.properties file to the root of your classpath with the following contents:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

Add Header and Footer for PDF using iTextsharp

This link will help you out completely(the Shortest and Most Elegant way):

Header Footer with PageEvent

        PdfPTable tbheader = new PdfPTable(3);
        tbheader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbheader.DefaultCell.Border = 0;
        tbheader.AddCell(new Paragraph());
        tbheader.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my header", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbheader.AddCell(_cell2);
        float[] widths = new float[] { 20f, 20f, 60f };
        tbheader.SetWidths(widths);
        tbheader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin), writer.DirectContent);

        PdfPTable tbfooter = new PdfPTable(3);
        tbfooter.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbfooter.DefaultCell.Border = 0;
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my footer", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbfooter.AddCell(_cell2);
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _celly = new PdfPCell(new Paragraph(writer.PageNumber.ToString()));//For page no.
        _celly.HorizontalAlignment = Element.ALIGN_RIGHT;
        _celly.Border = 0;
        tbfooter.AddCell(_celly);
        float[] widths1 = new float[] { 20f, 20f, 60f };
        tbfooter.SetWidths(widths1);
        tbfooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);

Comparing two byte arrays in .NET

This is almost certainly much slower than any other version given here, but it was fun to write.

static bool ByteArrayEquals(byte[] a1, byte[] a2) 
{
    return a1.Zip(a2, (l, r) => l == r).All(x => x);
}

How to get an MD5 checksum in PowerShell

This site has an example: Using Powershell for MD5 Checksums. It uses the .NET framework to instantiate an instance of the MD5 hash algorithm to calculate the hash.

Here's the code from the article, incorporating Stephen's comment:

param
(
  $file
)

$algo = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
$stream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open,
    [System.IO.FileAccess]::Read)

$md5StringBuilder = New-Object System.Text.StringBuilder
$algo.ComputeHash($stream) | % { [void] $md5StringBuilder.Append($_.ToString("x2")) }
$md5StringBuilder.ToString()

$stream.Dispose()

Changing SVG image color with javascript

If it is just about the color and there is no specific need for JavaScript, you could also convert them to a font. This link gives you an opportunity to create a font based on the SVG. However, it is not possible to use img attributes afterwards - like "alt". This also limits the accessibility of your website for blind people and so on.

Angular.js How to change an elements css class on click and to remove all others

have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?

    <span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
    <span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>

How do you detect/avoid Memory leaks in your (Unmanaged) code?

Memory debugging tools are worth their weight in gold but over the years I've found that two simple ideas can be used to prevent most memory/resource leaks from being coded in the first place.

  1. Write release code immediatly after writing the acquisition code for the resources you want to allocate. With this method its harder to "forget" and in some sense forces one to seriously think of the lifecycle of resources being used upfront instead of as an aside.

  2. Use return as sparringly as possible. What is allocated should only be freed in one place if possible. The conditional path between acquisition of resource and release should be designed to be as simple and obvious as possible.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Might not be relevant for everyone but this little detail was causing mine not to work:

Change div from this:

<div class="map">

To this:

<div id="map">

How do I enumerate the properties of a JavaScript object?

Python's dict has 'keys' method, and that is really useful. I think in JavaScript we can have something this:

function keys(){
    var k = [];
    for(var p in this) {
        if(this.hasOwnProperty(p))
            k.push(p);
    }
    return k;
}
Object.defineProperty(Object.prototype, "keys", { value : keys, enumerable:false });

EDIT: But the answer of @carlos-ruana works very well. I tested Object.keys(window), and the result is what I expected.

EDIT after 5 years: it is not good idea to extend Object, because it can conflict with other libraries that may want to use keys on their objects and it will lead unpredictable behavior on your project. @carlos-ruana answer is the correct way to get keys of an object.

How to make a Div appear on top of everything else on the screen?

Try setting position to absolute, ie.

#yourDiv{
    position: absolute;
    z-index: 10;
};

MySQL CURRENT_TIMESTAMP on create and on update

i think it is possible by using below technique

`ts_create` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`ts_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Run java jar file on a server as background process

If you're using Ubuntu and have "Upstart" (http://upstart.ubuntu.com/) you can try this:

Create /var/init/yourservice.conf

with the following content

description "Your Java Service"  
author "You"  

start on runlevel [3]  
stop on shutdown  

expect fork  

script     
    cd /web 
    java -jar server.jar >/var/log/yourservice.log 2>&1  
    emit yourservice_running  
end script  

Now you can issue the service yourservice start and service yourservice stop commands. You can tail /var/log/yourservice.log to verify that it's working.

If you just want to run your jar from the console without it hogging the console window, you can just do:

java -jar /web/server.jar > /var/log/yourservice.log 2>&1

How to drop a list of rows from Pandas dataframe?

If the DataFrame is huge, and the number of rows to drop is large as well, then simple drop by index df.drop(df.index[]) takes too much time.

In my case, I have a multi-indexed DataFrame of floats with 100M rows x 3 cols, and I need to remove 10k rows from it. The fastest method I found is, quite counterintuitively, to take the remaining rows.

Let indexes_to_drop be an array of positional indexes to drop ([1, 2, 4] in the question).

indexes_to_keep = set(range(df.shape[0])) - set(indexes_to_drop)
df_sliced = df.take(list(indexes_to_keep))

In my case this took 20.5s, while the simple df.drop took 5min 27s and consumed a lot of memory. The resulting DataFrame is the same.

Git removing upstream from local repository

Using git version 1.7.9.5 there is no "remove" command for remote. Use "rm" instead.

$ git remote rm upstream
$ git remote add upstream https://github.com/Foo/repos.git

or, as noted in the previous answer, set-url works.

I don't know when the command changed, but Ubuntu 12.04 shipped with 1.7.9.5.

SQL Server dynamic PIVOT query?

Dynamic SQL PIVOT

Different approach for creating columns string

create table #temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into #temp values ('1/1/2012', 'ABC', 1000.00)
insert into #temp values ('2/1/2012', 'DEF', 500.00)
insert into #temp values ('2/1/2012', 'GHI', 800.00)
insert into #temp values ('2/10/2012', 'DEF', 700.00)
insert into #temp values ('3/1/2012', 'ABC', 1100.00)

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query = 
'SELECT * from 
(
    select date, amount, category from #temp
) src
pivot 
(
    max(amount) for category in (' + @cols + ')
) piv'

execute(@query)
drop table #temp

Result

date                    ABC     DEF     GHI
2012-01-01 00:00:00.000 1000.00 NULL    NULL
2012-02-01 00:00:00.000 NULL    500.00  800.00
2012-02-10 00:00:00.000 NULL    700.00  NULL
2012-03-01 00:00:00.000 1100.00 NULL    NULL

iPhone 5 CSS media query

/* iPad */
@media screen and (min-device-width: 768px) {
    /* ipad-portrait */
    @media screen and (max-width: 896px) { 
        .logo{
            display: none !important;
        }
    }
    /* ipad-landscape */
    @media screen and (min-width: 897px) { 

    }
}
/* iPhone */
@media screen and (max-device-width: 480px) {
    /* iphone-portrait */
    @media screen and (max-width: 400px) { 

    }
    /* iphone-landscape */
    @media screen and (min-width: 401px) { 

    }
}

Why does range(start, end) not include end?

Basically in python range(n) iterates n times, which is of exclusive nature that is why it does not give last value when it is being printed, we can create a function which gives inclusive value it means it will also print last value mentioned in range.

def main():
    for i in inclusive_range(25):
        print(i, sep=" ")


def inclusive_range(*args):
    numargs = len(args)
    if numargs == 0:
        raise TypeError("you need to write at least a value")
    elif numargs == 1:
        stop = args[0]
        start = 0
        step = 1
    elif numargs == 2:
        (start, stop) = args
        step = 1
    elif numargs == 3:
        (start, stop, step) = args
    else:
        raise TypeError("Inclusive range was expected at most 3 arguments,got {}".format(numargs))
    i = start
    while i <= stop:
        yield i
        i += step


if __name__ == "__main__":
    main()

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

Namespace for [DataContract]

First, I add the references to my Model, then I use them in my code. There are two references you should add:

using System.ServiceModel;
using System.Runtime.Serialization;

then, this problem was solved in my program. I hope this answer can help you. Thanks.

Deploying just HTML, CSS webpage to Tomcat

If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:

zip -r <AppName>.war *

I've tested it with Tomcat 8 on the Mac, but it should work anywhere

How to get browser width using JavaScript code?

From W3schools and its cross browser back to the dark ages of IE!

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";

alert("Browser inner window width: " + w + ", height: " + h + ".");

</script>

</body>
</html>

Removing "NUL" characters

Open Notepad++
Select Replace (Ctrl/H)
Find what: \x00
Replace with:
Click on radio button Regular expression
Click on Replace All

invalid target release: 1.7

You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:

  • "C:\Program Files\Java\jdk1.7.0_40"

or on OS X:

  • /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home

How to select only 1 row from oracle sql?

we have 3 choices to get the first row in Oracle DB table.

1) select * from table_name where rownum= 1 is the best way

2) select * from table_name where id = ( select min(id) from table_name)

3)

select * from 
    (select * from table_name order by id)
where rownum = 1

How can I search Git branches for a file or directory?

A quite decent implementation of the find command for Git repositories can be found here:

https://github.com/mirabilos/git-find

Linux command to check if a shell script is running or not

pgrep -f aa.sh 

To do something with the id, you pipe it. Here I kill all its child tasks.

pgrep aa.sh | xargs pgrep -P ${} | xargs kill

If you want to execute a command if the process is running do this

pgrep aa.sh && echo Running

Is it possible to apply CSS to half of a character?

Closest I can get:

_x000D_
_x000D_
$(function(){_x000D_
  $('span').width($('span').width()/2);_x000D_
  $('span:nth-child(2)').css('text-indent', -$('span').width());_x000D_
});
_x000D_
body{_x000D_
  font-family: arial;_x000D_
}_x000D_
span{_x000D_
  display: inline-block;_x000D_
  overflow: hidden;_x000D_
}_x000D_
span:nth-child(2){_x000D_
  color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span>X</span><span>X</span>
_x000D_
_x000D_
_x000D_

Demo: http://jsfiddle.net/9wxfY/2/

Heres a version that just uses one span: http://jsfiddle.net/9wxfY/4/

SQL Query for Student mark functionality

My attempt - I'd start with the max mark and build from there

Schema:

CREATE TABLE Student (
  StudentId int,
  Name nvarchar(30),
  Details nvarchar(30)
)
CREATE TABLE Subject (
  SubjectId int,
  Name nvarchar(30)
)
CREATE TABLE Marks (
  StudentId int,
  SubjectId int,
  Mark int
)

Data:

INSERT INTO Student (StudentId, Name, Details) 
VALUES (1,'Alfred','AA'), (2,'Betty','BB'), (3,'Chris','CC')

INSERT INTO Subject (SubjectId, Name)
VALUES (1,'Maths'), (2, 'Science'), (3, 'English')

INSERT INTO Marks (StudentId, SubjectId, Mark)
VALUES 
(1,1,61),(1,2,75),(1,3,87),
(2,1,82),(2,2,64),(2,3,77),
(3,1,82),(3,2,83),(3,3,67)
GO

My query would have been:

;WITH MaxMarks AS (
  SELECT SubjectId, MAX(Mark) as MaxMark
    FROM Marks
    GROUP BY SubjectId
 )
SELECT s.Name as [StudentName], sub.Name AS [SubjectName],m.Mark
FROM MaxMarks mm
INNER JOIN Marks m 
ON m.SubjectId = mm.SubjectId 
AND m.Mark = mm.MaxMark
INNER JOIN Student s
ON s.StudentId = m.StudentId
INNER JOIN Subject sub
ON sub.SubjectId = mm.SubjectId

SQL Fiddle Example

  1. Find the max mark for each subject
  2. Join Marks, Student and Subject to find the relevant details of that highest mark

This also take care of duplicate students with the highest mark

Results:

STUDENTNAME SUBJECTNAME     MARK
Alfred  English     87
Betty   Maths           82
Chris   Maths           82
Chris   Science     83

Creating an abstract class in Objective-C

If you are used to the compiler catching abstract instantiation violations in other languages, then the Objective-C behavior is disappointing.

As a late binding language it is clear that Objective-C cannot make static decisions on whether a class truly is abstract or not (you might be adding functions at runtime...), but for typical use cases this seems like a shortcoming. I would prefer the compiler flat-out prevented instantiations of abstract classes instead of throwing an error at runtime.

Here is a pattern we are using to get this type of static checking using a couple of techniques to hide initializers:

//
//  Base.h
#define UNAVAILABLE __attribute__((unavailable("Default initializer not available.")));

@protocol MyProtocol <NSObject>
-(void) dependentFunction;
@end

@interface Base : NSObject {
    @protected
    __weak id<MyProtocol> _protocolHelper; // Weak to prevent retain cycles!
}

- (instancetype) init UNAVAILABLE; // Prevent the user from calling this
- (void) doStuffUsingDependentFunction;
@end

//
//  Base.m
#import "Base.h"

// We know that Base has a hidden initializer method.
// Declare it here for readability.
@interface Base (Private)
- (instancetype)initFromDerived;
@end

@implementation Base
- (instancetype)initFromDerived {
    // It is unlikely that this becomes incorrect, but assert
    // just in case.
    NSAssert(![self isMemberOfClass:[Base class]],
             @"To be called only from derived classes!");
    self = [super init];
    return self;
}

- (void) doStuffUsingDependentFunction {
    [_protocolHelper dependentFunction]; // Use it
}
@end

//
//  Derived.h
#import "Base.h"

@interface Derived : Base
-(instancetype) initDerived; // We cannot use init here :(
@end

//
//  Derived.m
#import "Derived.h"

// We know that Base has a hidden initializer method.
// Declare it here.
@interface Base (Private)
- (instancetype) initFromDerived;
@end

// Privately inherit protocol
@interface Derived () <MyProtocol>
@end

@implementation Derived
-(instancetype) initDerived {
    self= [super initFromDerived];
    if (self) {
        self->_protocolHelper= self;
    }
    return self;
}

// Implement the missing function
-(void)dependentFunction {
}
@end

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

Using jQuery to see if a div has a child with a certain class

Simple Way

if ($('#text-field > p.filled-text').length != 0)

Set Matplotlib colorbar size to match graph

This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.

plt.colorbar(im,fraction=0.046, pad=0.04)

It also does not require sharing the axis which can get the plot out of square.

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Next to being in the wrong directory I just tripped about another variant:

I had a File.open(my_file).each {|line| puts line} exploding but there was something by that name in the directory I was working in (ls in the command line showed the name). I checked with a File.exists?(my_file) which strangely returned false. Explanation: my_file was a symlink which target didn't exist anymore! Since File.exists? will follow a symlink it will say false though the link is still there.

VBA - how to conditionally skip a for loop iteration

You can use a kind of continue by using a nested Do ... Loop While False:

'This sample will output 1 and 3 only

Dim i As Integer

For i = 1 To 3: Do

    If i = 2 Then Exit Do 'Exit Do is the Continue

    Debug.Print i

Loop While False: Next i

How to wait for a process to terminate to execute another process in batch file

This works and is even simpler. If you remove ECHO-s, it will be even smaller:

REM
REM DEMO - how to launch several processes in parallel, and wait until all of them finish.
REM

@ECHO OFF
start "!The Title!" Echo Close me manually!
start "!The Title!" Echo Close me manually!
:waittofinish
echo At least one process is still running...
timeout /T 2 /nobreak >nul
tasklist.exe /fi "WINDOWTITLE eq !The Title!" | find ":" >nul
if errorlevel 1 goto waittofinish
echo Finished!
PAUSE

How do I increase modal width in Angular UI Bootstrap?

Use max-width on modal-dialog for angular 5

.mod-class .modal-dialog {
    max-width: 1000px;
}

and use windowClass as others recommended, TS eg:

this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
        (result) => {
            // this.closeResult = `Closed with: ${result}`;
         }, (reason) => {
            // this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});

Also, I had to put the css code in global styles > styles.css.

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:

protected void Application_Error(object sender, EventArgs e) {
  Exception exception = Server.GetLastError();
  Response.Clear();

  HttpException httpException = exception as HttpException;

  if (httpException != null) {
    string action;

    switch (httpException.GetHttpCode()) {
      case 404:
        // page not found
        action = "HttpError404";
        break;
      case 500:
        // server error
        action = "HttpError500";
        break;
      default:
        action = "General";
        break;
      }

      // clear error on server
      Server.ClearError();

      Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
    }

Then your controller will receive whatever you want:

// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
   return View("SomeView", message);
}

There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the asp.net pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavily used systems.

How to pass argument to Makefile from command line?

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".

Http 415 Unsupported Media type error with JSON

HttpVerb needs its headers as a dictionary of key-value pairs

headers = {'Content-Type': 'application/json', 'charset': 'utf-8'}

Taking pictures with camera on Android programmatically

There are two ways to take a photo:

1 - Using an Intent to make a photo

2 - Using the camera API

I think you should use the second way and there is a sample code here for two of them.

Using a list as a data source for DataGridView

this Func may help you . it add every list object to grid view

private void show_data()
        {
            BindingSource Source = new BindingSource();

            for (int i = 0; i < CC.Contects.Count; i++)
            {
                Source.Add(CC.Contects.ElementAt(i));
            };


            Data_View.DataSource = Source;

        }

I write this for simple database app

Iterate over the lines of a string

Regex-based searching is sometimes faster than generator approach:

RRR = re.compile(r'(.*)\n')
def f4(arg):
    return (i.group(1) for i in RRR.finditer(arg))

"ImportError: No module named" when trying to run Python script

Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

pip install pathlib

Simple InputBox function

Probably the simplest way is to use the InputBox method of the Microsoft.VisualBasic.Interaction class:

[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

$title = 'Demographics'
$msg   = 'Enter your demographics:'

$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)

How can I read an input string of unknown length?

I've seen only one simple way of reading an arbitrarily long string, but I've never used it. I think it goes like this:

char *m = NULL;
printf("please input a string\n");
scanf("%ms",&m);
if (m == NULL)
    fprintf(stderr, "That string was too long!\n");
else
{
    printf("this is the string %s\n",m);
    /* ... any other use of m */
    free(m);
}

The m between % and s tells scanf() to measure the string and allocate memory for it and copy the string into that, and to store the address of that allocated memory in the corresponding argument. Once you're done with it you have to free() it.

This isn't supported on every implementation of scanf(), though.

As others have pointed out, the easiest solution is to set a limit on the length of the input. If you still want to use scanf() then you can do so this way:

char m[100];
scanf("%99s",&m);

Note that the size of m[] must be at least one byte larger than the number between % and s.

If the string entered is longer than 99, then the remaining characters will wait to be read by another call or by the rest of the format string passed to scanf().

Generally scanf() is not recommended for handling user input. It's best applied to basic structured text files that were created by another application. Even then, you must be aware that the input might not be formatted as you expect, as somebody might have interfered with it to try to break your program.

How can I get my Twitter Bootstrap buttons to right align?

Sorry for replying to an older already answered question, but I thought I'd point out a couple of reasons that your jsfiddle does not work, in case others check it out and wonder why the pull-right class as described in the accepted answer doesn't work there.

  1. the url to the bootstrap.css file is invalid. (perhaps it worked when you asked the question).
  2. you should add the attribute: type="button" to your input element, or it won't be rendered as a button - it will be rendered as an input box. Better yet, use the <button> element instead.
  3. Additionally, because pull-right uses floats, you will get some staggering of the button layout because each LI does not have enough height to accommodate the height of the button. Adding some line-height or min-height css to the LI would address that.

working fiddle: http://jsfiddle.net/3ejqufp6/

<ul>
  <li>One <input type="button" class="btn pull-right" value="test"/></li>
  <li>Two <input type="button" class="btn pull-right" value="test2"/></li>
</ul>

(I also added a min-width to the buttons as I couldn't stand the look of a ragged right-justified look to the buttons because of varying widths :) )

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

Store that objects into Array  and then iterate the Array
export class AppComponent {

 public obj: object =null;
 public myArr=[];

  constructor(){

    this.obj = {
      jon : {username: 'Jon', genrePref: 'rock'},
      lucy : {username: 'Lucy', genrePref: 'pop'},
      mike : {username: 'Mike', genrePref: 'rock'},
      luke : {username: 'Luke', genrePref: 'house'},
      james : {username: 'James', genrePref: 'house'},
      dave : {username: 'Dave', genrePref: 'bass'},
      sarah : {username: 'Sarah', genrePref: 'country'},
      natalie : {username: 'Natalie', genrePref: 'bass'}
  }
  }
  ngOnInit(){
    this.populateCode();
  }

  populateCode(){
    for( let i in this.obj) {   //Pay attention to the 'in'
    console.log(this.obj[i]);
    this.myArr.push(this.obj[i]);
  }
  }
 }



<div *ngFor="let item of myArr ">
    {{item.username}}
    {{item.genrePref}}
  </div>

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

bundle install fails with SSL certificate verification error

The only thing that worked for me on legacy windows system and ruby 1.9 version is downloading cacert file from http://guides.rubygems.org/ssl-certificate-update/

And then running below command before running bundle install

bundle config --global ssl_ca_cert /path/to/file.pem

Can you target <br /> with css?

Try the following, I put it together using Update 2 from another answer with high votes, and it worked perfectly for me:

br
{   content: "A" !important;
    display: block !important;
    margin-bottom: 1.5em !important;
}

How to get Current Timestamp from Carbon in Laravel 5

You can try this if you want date time string:

use Carbon\Carbon;
$current_date_time = Carbon::now()->toDateTimeString(); // Produces something like "2019-03-11 12:25:00"

If you want timestamp, you can try:

use Carbon\Carbon;
$current_timestamp = Carbon::now()->timestamp; // Produces something like 1552296328

See the official Carbon documentation here.

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.

You can use JavaScript/Canvas to do the job but it is still experimental.

data.table vs dplyr: can one do something well the other can't or does poorly?

In direct response to the Question Title...

dplyr definitely does things that data.table can not.

Your point #3

dplyr abstracts (or will) potential DB interactions

is a direct answer to your own question but isn't elevated to a high enough level. dplyr is truly an extendable front-end to multiple data storage mechanisms where as data.table is an extension to a single one.

Look at dplyr as a back-end agnostic interface, with all of the targets using the same grammer, where you can extend the targets and handlers at will. data.table is, from the dplyr perspective, one of those targets.

You will never (I hope) see a day that data.table attempts to translate your queries to create SQL statements that operate with on-disk or networked data stores.

dplyr can possibly do things data.table will not or might not do as well.

Based on the design of working in-memory, data.table could have a much more difficult time extending itself into parallel processing of queries than dplyr.


In response to the in-body questions...

Usage

Are there analytical tasks that are a lot easier to code with one or the other package for people familiar with the packages (i.e. some combination of keystrokes required vs. required level of esotericism, where less of each is a good thing).

This may seem like a punt but the real answer is no. People familiar with tools seem to use the either the one most familiar to them or the one that is actually the right one for the job at hand. With that being said, sometimes you want to present a particular readability, sometimes a level of performance, and when you have need for a high enough level of both you may just need another tool to go along with what you already have to make clearer abstractions.

Performance

Are there analytical tasks that are performed substantially (i.e. more than 2x) more efficiently in one package vs. another.

Again, no. data.table excels at being efficient in everything it does where dplyr gets the burden of being limited in some respects to the underlying data store and registered handlers.

This means when you run into a performance issue with data.table you can be pretty sure it is in your query function and if it is actually a bottleneck with data.table then you've won yourself the joy of filing a report. This is also true when dplyr is using data.table as the back-end; you may see some overhead from dplyr but odds are it is your query.

When dplyr has performance issues with back-ends you can get around them by registering a function for hybrid evaluation or (in the case of databases) manipulating the generated query prior to execution.

Also see the accepted answer to when is plyr better than data.table?

Access a JavaScript variable from PHP

Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:

// -- index.php

<?php
  if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">  
  var d = new Date(); 
  var timezoneOffset = d.getTimezoneOffset() / 60;
  // the cookie expired in 3 hours
  d.setTime(d.getTime()+(3*60*60*1000));
  var expires = "; expires="+d.toGMTString();
  document.cookie = "timezone=" +  timezoneOffset + expires + "; path=/";
  document.location.href="index.php"
</script>
</html>
<?php
} else {
  ?>

  <html>
  <head>
  <body>

  <?php 
  if(isset($_COOKIE['timezone'])){ 
    dump_var($_COOKIE['timezone']); 
  } 
}
?>

How to use hex() without 0x in Python?

You can simply write

hex(x)[2:]

to get the first two characters removed.

Firebase Permission Denied

OK, but you don`t want to open the whole realtime database! You need something like this.

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": "auth.uid !=null",
    ".write": "auth.uid !=null"
  }
}

or

{
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid"
      }
    }
  }
}

Python Pandas Replacing Header with Top Row

The best practice and Best OneLiner:

df.to_csv(newformat,header=1)

Notice the header value:

Header refer to the Row number(s) to use as the column names. Make no mistake, the row number is not the df but from the excel file(0 is the first row, 1 is the second and so on).

This way, you will get the column name you want and won't have to write additional codes or create new df.

Good thing is, it drops the replaced row.

Prevent Caching in ASP.NET MVC for specific actions using an attribute

In the controller action append to the header the following lines

    public ActionResult Create(string PositionID)
    {
        Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
        Response.AppendHeader("Expires", "0"); // Proxies.

HTML Upload MAX_FILE_SIZE does not appear to work

MAX_FILE_SIZE is in KB not bytes. You were right, it is in bytes. So, for a limit of 4MB convert 4MB in bytes {1024 * (1024 * 4)} try:

<input type="hidden" name="MAX_FILE_SIZE" value="4194304" /> 

enter image description here

Update 1

As explained by others, you will never get a warning for this. It's there just to impose a soft limit on server side.

Update 2

To answer your sub-question. Yes, there is a difference, you NEVER trust the user input. If you want to always impose a limit, you always must check its size. Don't trust what MAX_FILE_SIZE does, because it can be changed by a user. So, yes, you should check to make sure it's always up to or above the size you want it to be.

The difference is that if you have imposed a MAX_FILE_SIZE of 2MB and the user tries to upload a 4MB file, once they reach roughly the first 2MB of upload, the transfer will terminate and the PHP will stop accepting more data for that file. It will report the error on the files array.

How to filter array when object key value is in array

Fastest way (will take extra memory):

var empid=[1,4,5]
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] ;

var empIdObj={};

empid.forEach(function(element) {
empIdObj[element]=true;
});

var filteredArray=[];

records.forEach(function(element) {
if(empIdObj[element.empid])
    filteredArray.push(element)
});

DB2 Date format

This isn't straightforward, but

SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1

returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.

SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1

How to render an ASP.NET MVC view as a string?

If you want to forgo MVC entirely, thereby avoiding all the HttpContext mess...

using RazorEngine;
using RazorEngine.Templating; // For extension methods.

string razorText = System.IO.File.ReadAllText(razorTemplateFileLocation);
string emailBody = Engine.Razor.RunCompile(razorText, "templateKey", typeof(Model), model);

This uses the awesome open source Razor Engine here: https://github.com/Antaris/RazorEngine

Negation in Python

try instead:

if not os.path.exists(pathName):
    do this

CSS/HTML: Create a glowing border around an Input Field

_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
    $(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
    $(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
  color:red;   _x000D_
}_x000D_
.form-fild {_x000D_
 position: relative;_x000D_
 margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
 position: absolute;_x000D_
 top: 5px;_x000D_
 left: 10px;_x000D_
 padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
 top: -25px;_x000D_
 left: 10px;_x000D_
 /*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
 padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
 padding: 10px;_x000D_
 width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
 -webkit-transition: all 0.2s ease-in-out;_x000D_
       -moz-transition: all 0.2s ease-in-out;_x000D_
         -o-transition: all 0.2s ease-in-out;_x000D_
            transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
 <div class="row">_x000D_
     <form>_x000D_
        <div class="form-fild">_x000D_
            <label>Name :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Email :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Number :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Message :</label>_x000D_
            <textarea cols="10" rows="5"></textarea>_x000D_
        </div>_x000D_
    </form>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to install the current version of Go in Ubuntu Precise

You can also use the update-golang script:

update-golang is a script to easily fetch and install new Golang releases with minimum system intrusion

git clone https://github.com/udhos/update-golang
cd update-golang
sudo ./update-golang.sh

link button property to open in new tab?

This is not perfect, but it works.

<asp:LinkButton id="lbnkVidTtile1" runat="Server" 
    CssClass="bodytext" Text='<%# Eval("newvideotitle") %>'
    OnClientClick="return PostToNewWindow();"  />

<script type="text/javascript">
function PostToNewWindow()
{
    originalTarget = document.forms[0].target;
    document.forms[0].target='_blank';
    window.setTimeout("document.forms[0].target=originalTarget;",300);
    return true;
}
</script>

Naming returned columns in Pandas aggregate function?

For pandas >= 0.25

The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func'). Detailed example from the PR linked above:

In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
   ...:                    'height': [9.1, 6.0, 9.5, 34.0],
   ...:                    'weight': [7.9, 7.5, 9.9, 198.0]})
   ...:

In [3]: df
Out[3]:
  kind  height  weight
0  cat     9.1     7.9
1  dog     6.0     7.5
2  cat     9.5     9.9
3  dog    34.0   198.0

In [4]: df.groupby('kind').agg(min_height=('height', 'min'), 
                               max_weight=('weight', 'max'))
Out[4]:
      min_height  max_weight
kind
cat          9.1         9.9
dog          6.0       198.0

It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:

In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})

In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
         B
  <lambda> <lambda 1>
A
a        0          1

and then .rename(), or in one go:

In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
   b  c
A
a  0  0

For pandas < 0.25

The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.

Series:

FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version

DataFrames:

FutureWarning: using a dict with renaming is deprecated and will be removed in a future version

According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.

# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
                   'B': range(5),
                   'C': range(5)})

# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})

# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
    .agg({'B': 'sum', 'C': 'min'})
    .rename(columns={'B': 'foo', 'C': 'bar'})
)

Please see the 0.20 changelog for additional details.

Update 2017-01-03 in response to @JunkMechanic's comment.

With the old style dictionary syntax, it was possible to pass multiple lambda functions to .agg, since these would be renamed with the key in the passed dictionary:

>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})

    B    
  max min
A        
1   2   0
2   4   3

Multiple functions can also be passed to a single column as a list:

>>> df.groupby('A').agg({'B': [np.min, np.max]})

     B     
  amin amax
A          
1    0    2
2    3    4

However, this does not work with lambda functions, since they are anonymous and all return <lambda>, which causes a name collision:

>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>

To avoid the SpecificationError, named functions can be defined a priori instead of using lambda. Suitable function names also avoid calling .rename on the data frame afterwards. These functions can be passed with the same list syntax as above:

>>> def my_min(x):
>>>     return x.min()

>>> def my_max(x):
>>>     return x.max()

>>> df.groupby('A').agg({'B': [my_min, my_max]})

       B       
  my_min my_max
A              
1      0      2
2      3      4

How to programmatically move, copy and delete files and directories on SD?

Use standard Java I/O. Use Environment.getExternalStorageDirectory() to get to the root of external storage (which, on some devices, is an SD card).

How to retrieve field names from temporary table (SQL Server 2008)

Anthony

try the below one. it will give ur expected output

select c.name as Fields from 
tempdb.sys.columns c
    inner join tempdb.sys.tables t
 ON c.object_id = t.object_id
where t.name like '#MyTempTable%'

Now() function with time trim

I would prefer to make a function that doesn't work with strings:

'---------------------------------------------------------------------------------------
' Procedure : RemoveTimeFromDate
' Author    : berend.nieuwhof
' Date      : 15-8-2013
' Purpose   : removes the time part of a String and returns the date as a date
'---------------------------------------------------------------------------------------
'
Public Function RemoveTimeFromDate(DateTime As Date) As Date


    Dim dblNumber As Double

    RemoveTimeFromDate = CDate(Floor(CDbl(DateTime)))

End Function

Private Function Floor(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
    Floor = Int(x / Factor) * Factor
End Function

Debugging "Element is not clickable at point" error

Explanation of error message:

The error message simply says, that the element you want to click on is present, but it is not visible. It could be covered by something or temporary not visible.

There could be many reasons why the element is not visible in the moment of the test. Please re-analyse your page and find proper solution for your case.

Solution for particular case:

In my case, this error occures, when a tooltip of the screen element i just clicked on, was poping over the element I wanted to click next. Defocus was a solution I needed.

  • Quick solution how to defocus would be to click to some other element in another part of the screen which does "nothing" resp. nothing happens after a click action.
  • Proper solution would be to call element.blur() on the element poping the tooltip, which would make the tooltip disapear.

Read a zipped file as a pandas DataFrame

https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial

Please follow this link.

import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
                                 header=1, sep='\t', quotechar='"')

#traffic_station_df['Address'] = 'address'

#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)

Counting array elements in Python

len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.Description.Behaviors.Add(behavior);
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;
}

Using the above URI I can add a reference in my client to the web service.

Implements vs extends: When to use? What's the difference?

We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

class AnimalClass {

public void doEat() {
    
    System.out.println("Animal Eating...");
}

public void sleep() {
    
    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {
    
    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();
    
    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {
    
    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub
    
}

@Override
public void herbiEating() {
    
    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub
    
}


}

Defined Interfaces :

public interface AnimalInterface {

public void eating();

}


interface Herbi {

public void herbiEating();

}

How to make child element higher z-index than parent?

This is impossible as a child's z-index is set to the same stacking index as its parent.

You have already solved the problem by removing the z-index from the parent, keep it like this or make the element a sibling instead of a child.

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

Redirect stderr to stdout in C shell

As paxdiablo said you can use >& to redirect both stdout and stderr. However if you want them separated you can use the following:

(command > stdoutfile) >& stderrfile

...as indicated the above will redirect stdout to stdoutfile and stderr to stderrfile.

What is the effect of encoding an image in base64?

The answer is: It depends.

Although base64-images are larger, there a few conditions where base64 is the better choice.

Size of base64-images

Base64 uses 64 different characters and this is 2^6. So base64 stores 6bit per 8bit character. So the proportion is 6/8 from unconverted data to base64 data. This is no exact calculation, but a rough estimate.

Example:

An 48kb image needs around 64kb as base64 converted image.

Calculation: (48 / 6) * 8 = 64

Simple CLI calculator on Linux systems:

$ cat /dev/urandom|head -c 48000|base64|wc -c
64843

Or using an image:

$ cat my.png|base64|wc -c

Base64-images and websites

This question is much more difficult to answer. Generally speaking, as larger the image as less sense using base64. But consider the following points:

  • A lot of embedded images in an HTML-File or CSS-File can have similar strings. For PNGs you often find repeated "A" chars. Using gzip (sometimes called "deflate"), there might be even a win on size. But it depends on image content.
  • Request overhead of HTTP1.1: Especially with a lot of cookies you can easily have a few kilobytes overhead per request. Embedding base64 images might save bandwith.
  • Do not base64 encode SVG images, because gzip is more effective on XML than on base64.
  • Programming: On dynamically generated images it is easier to deliver them in one request as to coordinate two dependent requests.
  • Deeplinks: If you want to prevent downloading the image, it is a little bit trickier to extract an image from an HTML page.

How to debug (only) JavaScript in Visual Studio?

First open Visual studio ..select your project in solution explorer..Right click and choose option "browse with" then set IE as default browser.

enter image description here Now open IE ..go to
Tools >> Internet option >> Advance>> uncheck the checkbox having "Disable Script Debugging (Internet Explorer). and then click Apply and OK and you are done ..

Now you can set breakpoints in your JS file and then hit the debug button in VS..

enter image description here

EDIT:- For asp.net web application right click on the page which is your startup page(say default.aspx) and perform the same steps. :)

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

lexers vs parsers

There are a number of reasons why the analysis portion of a compiler is normally separated into lexical analysis and parsing ( syntax analysis) phases.

  1. Simplicity of design is the most important consideration. The separation of lexical and syntactic analysis often allows us to simplify at least one of these tasks. For example, a parser that had to deal with comments and white space as syntactic units would be. Considerably more complex than one that can assume comments and white space have already been removed by the lexical analyzer. If we are designing a new language, separating lexical and syntactic concerns can lead to a cleaner overall language design.
  2. Compiler efficiency is improved. A separate lexical analyzer allows us to apply specialized techniques that serve only the lexical task, not the job of parsing. In addition, specialized buffering techniques for reading input characters can speed up the compiler significantly.
  3. Compiler portability is enhanced. Input-device-specific peculiarities can be restricted to the lexical analyzer.

resource___Compilers (2nd Edition) written by- Alfred V. Abo Columbia University Monica S. Lam Stanford University Ravi Sethi Avaya Jeffrey D. Ullman Stanford University

How to rename with prefix/suffix?

In my case I have a group of files which needs to be renamed before I can work with them. Each file has its own role in group and has its own pattern.

As result I have a list of rename commands like this:

f=`ls *canctn[0-9]*`   ;  mv $f  CNLC.$f
f=`ls *acustb[0-9]*`   ;  mv $f  CATB.$f
f=`ls *accusgtb[0-9]*` ;  mv $f  CATB.$f
f=`ls *acus[0-9]*`     ;  mv $f  CAUS.$f

Try this also :

f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}

This will produce all combinations with prefixes and suffixes:

pref1.MyFileName.suf1
...
pref2.MyFileName.suf2

Another way to solve same problem is to create mapping array and add corespondent prefix for each file type as shown below:

#!/bin/bash
unset masks
typeset -A masks
masks[ip[0-9]]=ip
masks[iaf_usg[0-9]]=ip_usg
masks[ipusg[0-9]]=ip_usg
...
for fileMask in ${!masks[*]}; 
do  
registryEntry="${masks[$fileMask]}";
fileName=*${fileMask}*
[ -e ${fileName} ] &&  mv ${fileName} ${registryEntry}.${fileName}  
done

Remove multiple objects with rm()

An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

How can I add a username and password to Jenkins?

Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.

For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

Why is using a wild card with a Java import statement bad?

In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.

A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.

jQuery 1.9 .live() is not a function

When i will getting this error on my site .it will stop some functionality on my site, after research i find the solution for this problem ,

$colorpicker_inputs.live('focus', function(e) {
    jQuery(this).next('.farb-popup').show();
    jQuery(this).parents('li').css( {
        position : 'relative',
        zIndex : '9999'
    })
    jQuery('#tabber').css( {
        overflow : 'visible'
    });
});

$colorpicker_inputs.live('blur', function(e) {
    jQuery(this).next('.farb-popup').hide();
    jQuery(this).parents('li').css( {
        zIndex : '0'
    })
});

Should be replace 'live' to 'on' check below

    $colorpicker_inputs.on('focus', function(e) {
    jQuery(this).next('.farb-popup').show();
    jQuery(this).parents('li').css( {
        position : 'relative',
        zIndex : '9999'
    })
    jQuery('#tabber').css( {
        overflow : 'visible'
    });
});

$colorpicker_inputs.on('blur', function(e) {
    jQuery(this).next('.farb-popup').hide();
    jQuery(this).parents('li').css( {
        zIndex : '0'
    })
});

One more basic exmaple below :

.live(event, selector, function) 

Change it to :

.on(event, selector, function)

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Index inside map() function

  • suppose you have an array like

_x000D_
_x000D_
   const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    
    arr.map((myArr, index) => {
      console.log(`your index is -> ${index} AND value is ${myArr}`);
    })
_x000D_
_x000D_
_x000D_

> output will be
 index is -> 0 AND value is 1
 index is -> 1 AND value is 2
 index is -> 2 AND value is 3
 index is -> 3 AND value is 4
 index is -> 4 AND value is 5
 index is -> 5 AND value is 6
 index is -> 6 AND value is 7
 index is -> 7 AND value is 8
 index is -> 8 AND value is 9

Java - How to create a custom dialog box?

If you use the NetBeans IDE (latest version at this time is 6.5.1), you can use it to create a basic GUI java application using File->New Project and choose the Java category then Java Desktop Application.

Once created, you will have a simple bare bones GUI app which contains an about box that can be opened using a menu selection. You should be able to adapt this to your needs and learn how to open a dialog from a button click.

You will be able to edit the dialog visually. Delete the items that are there and add some text areas. Play around with it and come back with more questions if you get stuck :)

Update multiple rows in same query using PostgreSQL

You can also use update ... from syntax and use a mapping table. If you want to update more than one column, it's much more generalizable:

update test as t set
    column_a = c.column_a
from (values
    ('123', 1),
    ('345', 2)  
) as c(column_b, column_a) 
where c.column_b = t.column_b;

You can add as many columns as you like:

update test as t set
    column_a = c.column_a,
    column_c = c.column_c
from (values
    ('123', 1, '---'),
    ('345', 2, '+++')  
) as c(column_b, column_a, column_c) 
where c.column_b = t.column_b;

sql fiddle demo

Release generating .pdb files, why?

Without the .pdb files it is virtually imposible to step through the production code; you have to rely on other tools which can be costly and time consuming. I understand you can use tracing or windbg for instance but it really depends on what you want to achieve. In certain scenarios you just want to step through the remote code (no errors or exceptions) using the production data to observe particular behaviour, and this is where .pdb files come handy. Without them running the debugger on that code is impossible.

Select first occurring element after another element

#many .more.selectors h4 + p { ... }

This is called the adjacent sibling selector.

check if a key exists in a bucket in s3 using boto3

Use this concise oneliner, makes it less intrusive when you have to throw it inside an existing project without modifying much of the code.

s3_file_exists = lambda filename: bool(list(bucket.objects.filter(Prefix=filename)))

The above function assumes the bucket variable was already declared.

You can extend the lambda to support additional parameter like

s3_file_exists = lambda filename, bucket: bool(list(bucket.objects.filter(Prefix=filename)))

Simple PowerShell LastWriteTime compare

Slightly easier - use the new-timespan cmdlet, which creates a time interval from the current time.

ls | where-object {(new-timespan $_.LastWriteTime).days -ge 1}

shows all files not written to today.

Create a text file for download on-the-fly

Use below code to generate files on fly..

<? //Generate text file on the fly

   header("Content-type: text/plain");
   header("Content-Disposition: attachment; filename=savethis.txt");

   // do your Db stuff here to get the content into $content
   print "This is some text...\n";
   print $content;
 ?>

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

How do you receive a url parameter with a spring controller mapping

You have a lot of variants for using @RequestParam with additional optional elements, e.g.

@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr

If you don't put required = false - param will be required by default.

defaultValue = "someValue" - the default value to use as a fallback when the request parameter is not provided or has an empty value.

If request and method param are the same - you don't need value = "someAttr"

How to concatenate strings with padding in sqlite

The || operator is "concatenate" - it joins together the two strings of its operands.

From http://www.sqlite.org/lang_expr.html

For padding, the seemingly-cheater way I've used is to start with your target string, say '0000', concatenate '0000423', then substr(result, -4, 4) for '0423'.

Update: Looks like there is no native implementation of "lpad" or "rpad" in SQLite, but you can follow along (basically what I proposed) here: http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/

-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable

select substr('0000000000' || mycolumn, -10, 10) from mytable

-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable

select substr(mycolumn || '0000000000', 1, 10) from mytable

Here's how it looks:

SELECT col1 || '-' || substr('00'||col2, -2, 2) || '-' || substr('0000'||col3, -4, 4)

it yields

"A-01-0001"
"A-01-0002"
"A-12-0002"
"C-13-0002"
"B-11-0002"

React Native: How to select the next TextInput after pressing the "next" keyboard button?

Here is how achieved this for reactjs phone code inputs

import React, { useState, useRef } from 'react';

function Header(props) {

  const [state , setState] = useState({
        phone_number:"",
        code_one:'',
        code_two:'',
        code_three:'',
        code_four:'',
        submitted:false,

  })

   const codeOneInput = useRef(null);
   const codeTwoInput = useRef(null);
   const codeThreeInput = useRef(null);
   const codeFourInput = useRef(null);

   const handleCodeChange = (e) => {
        const {id , value} = e.target
        if(value.length < 2){
            setState(prevState => ({
                ...prevState,
                [id] : value
            }))
            if(id=='code_one' && value.length >0){
                codeTwoInput.current.focus();
            }
            if(id=='code_two'  && value.length >0){
                codeThreeInput.current.focus();
            }
            if(id=='code_three'  && value.length >0){
                codeFourInput.current.focus();
            }
        }
    }

    const sendCodeToServer = () => {

         setState(prevState => ({
                ...prevState,
                submitted : true,
          }))
  let codeEnteredByUser = state.code_one + state.code_two + state.code_three + state.code_four

        axios.post(API_BASE_URL, {code:codeEnteredByUser})
        .then(function (response) {
            console.log(response)
        })

   }

   return(
        <>

           <div className="are">
                 <div className="POP-INN-INPUT">
                                        <input type="text" id="code_one" ref={codeOneInput}    value={state.code_one}  onChange={handleCodeChange} autoFocus/>
                                        <input type="text" id="code_two"  ref={codeTwoInput}  value={state.code_two} onChange={handleCodeChange}/>
                                        <input type="text" id="code_three"  ref={codeThreeInput} value={state.code_three}  onChange={handleCodeChange}/>
                                        <input type="text" id="code_four" ref={codeFourInput}  value={state.code_four}  onChange={handleCodeChange}/>
                                    </div>

            <button disabled={state.submitted} onClick={sendCodeToServer}>
   
    </div>

       </>
    )
}
export default

enter image description here

how to get yesterday's date in C#

Something like this should work

var yesterday = DateTime.Now.Date.AddDays(-1);

DateTime.Now gives you the current date and time.

If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.

Finally .AddDays(-1) removes 1 day to give you yesterday.

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

How to have jQuery restrict file types on upload?

for my case i used the following codes :

    if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {              
    alert('You must select an image file only');               
    }

Difference between Node object and Element object?

Node is used to represent tags in general. Divided to 3 types:

Attribute Note: is node which inside its has attributes. Exp: <p id=”123”></p>

Text Node: is node which between the opening and closing its have contian text content. Exp: <p>Hello</p>

Element Node : is node which inside its has other tags. Exp: <p><b></b></p>

Each node may be types simultaneously, not necessarily only of a single type.

Element is simply a element node.

get unique machine id

Check out this article. It is very exhaustive and you will find how to extract various hardware information.

Quote from the article:

To get hardware information, you need to create an object of ManagementObjectSearcher class.

using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
foreach (ManagementObject share in searcher.Get()) {
    // Some Codes ...
}

The Key on the code above, is a variable that is replaced with appropriate data. For example, to get the information of the CPU, you have to replace the Key with Win32_Processor.

How do you specify the Java compiler version in a pom.xml file?

maven-compiler-plugin it's already present in plugins hierarchy dependency in pom.xml. Check in Effective POM.

For short you can use properties like this:

<properties>
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
</properties>

I'm using Maven 3.2.5.

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

jQuery: keyPress Backspace won't fire?

If you want to fire the event only on changes of your input use:

$('.s').bind('input', function(){
  console.log("search!");
  doSearch();
});

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/

The response content cannot be parsed because the Internet Explorer engine is not available, or

You can disable need to run Internet Explorer's first launch configuration by running this PowerShell script, it will adjust corresponding registry property:

Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2

After this, WebClient will work without problems

Matplotlib discrete colorbar

I think you'd want to look at colors.ListedColormap to generate your colormap, or if you just need a static colormap I've been working on an app that might help.

Deleting an SVN branch

You can delete the features folder just like any other in your checkout then commit the change.

To prevent this in the future I suggest you follow the naming conventions for SVN layout.

Either give each project a trunk, branches, tags folder when they are created.

svn
+ project1
  + trunk
    + src
    + etc...
  + branches
    + features
      + src
      + etc...
  + tags
+ project2
  + trunk
  + branches
  + tags

Remove quotes from a character vector in R

Try this: (even [1] will be removed)

> cat(noquote("love"))
love

else just use noquote

> noquote("love")
[1] love

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

create or replace PROCEDURE PROC_USER_EXP 
AS
duplicate_exp EXCEPTION;
PRAGMA EXCEPTION_INIT( duplicate_exp, -20001 );
LVCOUNT NUMBER;
BEGIN
  SELECT COUNT(*) INTO LVCOUNT FROM JOBS WHERE JOB_TITLE='President';
  IF LVCOUNT >1 THEN 
   raise_application_error( -20001, 'Duplicate president customer excetpion' );
  END IF;

  EXCEPTION 
  WHEN duplicate_exp THEN 
  DBMS_OUTPUT.PUT_LINE(sqlerrm);
END PROC_USER_EXP;

ORACLE 11g output will be like this:

Connecting to the database HR. 
ORA-20001: Duplicate president customer excetpion 
Process exited. 
Disconnecting from the database HR

Increase max execution time for php

Try to set a longer max_execution_time:

<IfModule mod_php5.c>
    php_value max_execution_time 300
</IfModule>

<IfModule mod_php7.c>
    php_value max_execution_time 300
</IfModule>

trigger body click with jQuery

You should have something like this:

$('body').click(function() {
   // do something here
});

The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:

$('body').trigger('click');

How to install a python library manually

I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.

In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add

export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.

A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.

If, on the other hand, it did provide a setup.py file, simply run

python setup.py install --user

for Python 2.6+.

Apache shutdown unexpectedly

It means port 80 is already used by another one.

Simply follow these steps:

  1. Open windows -> click on Run (win + R) -> type services.msc
  2. Goto IIS Admin -> Right click on it and click on Stop Option.
  3. Open XAMPP click on Start Action of Apache Module, Apache Module is run.

OR

For find the port of Apache (80) in Command Prompt simply type netstat -aon it displays present used ports on windows, under Local Address column it shown as 0.0.0.0:80. If it displays this port another connection is already used this port number.

Active Connections in Windows XP:

Active Connections in Windows XP

I solved my problem after installing xampp-win32-1.6.5-installer previously I used xampp version xampp-win32-1.8.2-0-VC9-installer at that time I got this error. Now it resolved my problem.

jQuery equivalent of JavaScript's addEventListener method

_x000D_
_x000D_
$( "button" ).on( "click", function(event) {_x000D_
_x000D_
    alert( $( this ).html() );_x000D_
    console.log( event.target );_x000D_
_x000D_
} );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<button>test 1</button>_x000D_
<button>test 2</button>
_x000D_
_x000D_
_x000D_

HQL "is null" And "!= null" on an Oracle column

No. You have to use is null and is not null in HQL.

How can I call a method in Objective-C?

calling the method is like this

[className methodName] 

however if you want to call the method in the same class you can use self

[self methodName] 

all the above is because your method was not taking any parameters

however if your method takes parameters you will need to do it like this

[self methodName:Parameter]

How to disable the parent form when a child form is active?

Why not just have the parent wait for the child to close. This is more than you need.

// Execute child process
System.Diagnostics.Process proc = 
    System.Diagnostics.Process.Start("notepad.exe");
proc.WaitForExit();

Remove a fixed prefix/suffix from a string in Bash

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"

$ #remove "hell" from "hello-world" if "hell" is found at the beginning.
$ prefix_removed_string=${string/#$prefix}

$ #remove "ld" from "o-world" if "ld" is found at the end.
$ suffix_removed_String=${prefix_removed_string/%$suffix}
$ echo $suffix_removed_String
o-wor

Notes:

#$prefix : adding # makes sure that substring "hell" is removed only if it is found in beginning. %$suffix : adding % makes sure that substring "ld" is removed only if it is found in end.

Without these, the substrings "hell" and "ld" will get removed everywhere, even it is found in the middle.

Can I force a UITableView to hide the separator between empty cells?

For Swift:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()  // it's just 1 line, awesome!
}

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

cannot import name patterns

As of Django 1.10, the patterns module has been removed (it had been deprecated since 1.8).

Luckily, it should be a simple edit to remove the offending code, since the urlpatterns should now be stored in a plain-old list:

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    # ... your url patterns
]

Nexus 5 USB driver

You should install Google Drivers from: http://developer.android.com/sdk/win-usb.html#top That works for me every time

Why does corrcoef return a matrix?

corrcoef returns the normalised covariance matrix.

The covariance matrix is the matrix

Cov( X, X )    Cov( X, Y )

Cov( Y, X )    Cov( Y, Y )

Normalised, this will yield the matrix:

Corr( X, X )    Corr( X, Y )

Corr( Y, X )    Corr( Y, Y )

correlation1[0, 0 ] is the correlation between Strategy1Returns and itself, which must be 1. You just want correlation1[ 0, 1 ].

Detecting when the 'back' button is pressed on a navbar

(SWIFT)

finaly found solution.. method we were looking for is "willShowViewController" which is delegate method of UINavigationController

//IMPORT UINavigationControllerDelegate !!
class PushedController: UIViewController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        //set delegate to current class (self)
        navigationController?.delegate = self
    }

    func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
        //MyViewController shoud be the name of your parent Class
        if var myViewController = viewController as? MyViewController {
            //YOUR STUFF
        }
    }
}

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

if you debug and loook at ctx=null,maybe your username hava proble ,you shoud write like "ac\administrator"(double "\") or "administrator@ac"

How to resolve the error on 'react-native start'

Go to

\node_modules\metro-config\src\defaults\blacklist.js

and replace this

var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];

to

var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];

This is not a best practice and my recommendation is: downgrade node version into 12.9 OR update metro-config since they are fixing the Node issue.

Understanding timedelta

why do I have to pass seconds = uptime to timedelta

Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int is superfluous as they could also accept floats.

and why does the string casting works so nicely that I get HH:MM:SS ?

It's not the typecasting that formats, is the internal __str__ method of the object. In fact you will achieve the same result if you write:

print datetime.timedelta(seconds=int(uptime))

Creating a JSON Array in node js

Build up a JavaScript data structure with the required information, then turn it into the json string at the end.

Based on what I think you're doing, try something like this:

var result = [];
for (var name in goals) {
  if (goals.hasOwnProperty(name)) {
    result.push({name: name, goals: goals[name]});
  }
}

res.contentType('application/json');
res.send(JSON.stringify(result));

or something along those lines.

How do I export a project in the Android studio?

Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.

You don't need to harcode android:debuggable="false" in your application tag. Infact for me studio complaints -

Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)

It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.

The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.

Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.

enter image description here

Now you should see a prompt to select release build or debug build.

For production always select release build!

enter image description here

And you are done. Signed APK exported.

enter image description here

PS : Don't forget to increment your versionCode in manifest file before uploading to playstore :)

Reading a string with scanf

I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

char str[]  
  1. array of values of type char, with its own address in memory
  2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
  3. including termination null character '\0' &str, &str[0] and str, all three represent the same location in memory which is address of the first element of the array str

    char *strPtr = &str[0]; //declaration and initialization

alternatively, you can split this in two:

char *strPtr; strPtr = &str[0];
  1. strPtr is a pointer to a char
  2. strPtr points at array str
  3. strPtr is a variable with its own address in memory
  4. strPtr is a variable that stores value of address &str[0]
  5. strPtr own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
  6. &strPtr represents the address of strPtr itself

I think that you could declare a pointer to a pointer as:

char **vPtr = &strPtr;  

declares and initializes with address of strPtr pointer

Alternatively you could split in two:

char **vPtr;
*vPtr = &strPtr
  1. *vPtr points at strPtr pointer
  2. *vPtr is a variable with its own address in memory
  3. *vPtr is a variable that stores value of address &strPtr
  4. final comment: you can not do str++, str address is a const, but you can do strPtr++

Full Screen Theme for AppCompat

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

    //to remove "information bar" above the action bar
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //to remove the action bar (title bar)
    getSupportActionBar().hide();
}

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Go in xampp/apache/conf/httpd.conf and open it. Then just chang 2 lines

Listen 80
to
Listen 81

And

ServerName localhost:80
to
ServerName localhost:81

Then start using admin privileges.

As I am working in a corporate environment where developers faces firewall issues, none of the other answers resolved my issue.

As the port is not used by Skype, but by some other internal applications, I followed the below steps to resolve the issue:

Step 1 - From the XAMPP Control Panel, under Apache, click the Config button, and select the Apache (httpd.conf).

Inside the httpd.conf file, somehow I found a line that says:

Listen 80 And change the 80 into any number / port you want. In my scenario I’m using port 8080.

Listen 8080 Still from the httpd.conf file,

You should also do this in the same process Still from the httpd-ssl.conf file, find another line that says

ServerName localhost:443 And change 443 to 4433.

ServerName localhost:4433 Remember to save the httpd.conf and httpd-ssl.conf files after performing some changes. Then restart the Apache service.

Insert php variable in a href

in php

echo '<a href="' . $folder_path . '">Link text</a>';

or

<a href="<?=$folder_path?>">Link text</a>;

or

<a href="<?php echo $folder_path ?>">Link text</a>;

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

From my looking you give a null value to a textbox and return in a ToString() as it is a static method. You can replace it with Convert.ToString() that can enable null value.

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

Good to see lots of love for zip in the answers here.

However it should be noted that if you are using a python version before 3.0, the itertools module in the standard library contains an izip function which returns an iterable, which is more appropriate in this case (especially if your list of latt/longs is quite long).

In python 3 and later zip behaves like izip.

How to list only top level directories in Python?

Filter the list using os.path.isdir to detect directories.

filter(os.path.isdir, os.listdir(os.getcwd()))

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

TypeError: Router.use() requires middleware function but got a Object

I had this error and solution help which was posted by Anirudh. I built a template for express routing and forgot about this nuance - glad it was an easy fix.

I wanted to give a little clarification to his answer on where to put this code by explaining my file structure.

My typical file structure is as follows:

/lib

/routes

---index.js (controls the main navigation)

/page-one



/page-two



     ---index.js

(each file [in my case the index.js within page-two, although page-one would have an index.js too]- for each page - that uses app.METHOD or router.METHOD needs to have module.exports = router; at the end)

If someone wants I will post a link to github template that implements express routing using best practices. let me know

Thanks Anirudh!!! for the great answer.

react hooks useEffect() cleanup for only componentWillUnmount?

you can use more than one useEffect

for example if my variable is data1 i can use all of this in my component

useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );

How do I check if a number is a palindrome?

int is_palindrome(unsigned long orig)
{
    unsigned long reversed = 0, n = orig;

    while (n > 0)
    {
        reversed = reversed * 10 + n % 10;
        n /= 10;
    }

    return orig == reversed;
}

How to reset AUTO_INCREMENT in MySQL?

There are good options given in How To Reset MySQL Autoincrement Column

Note that ALTER TABLE tablename AUTO_INCREMENT = value; does not work for InnoDB

How to create an empty R vector to add new items

To create an empty vector use:

vec <- c();

Please note, I am not making any assumptions about the type of vector you require, e.g. numeric.

Once the vector has been created you can add elements to it as follows:

For example, to add the numeric value 1:

vec <- c(vec, 1);

or, to add a string value "a"

vec <- c(vec, "a");

Rounded table corners CSS only

Firstly, you'll need more than just -moz-border-radius if you want to support all browsers. You should specify all variants, including plain border-radius, as follows:

-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;

Secondly, to directly answer your question, border-radius doesn't actually display a border; it just sets how the corners look of the border, if there is one.

To turn on the border, and thus get your rounded corners, you also need the border attribute on your td and th elements.

td, th {
   border:solid black 1px;
}

You will also see the rounded corners if you have a background colour (or graphic), although of course it would need to be a different background colour to the surrounding element in order for the rounded corners to be visible without a border.

It's worth noting that some older browsers don't like putting border-radius on tables/table cells. It may be worth putting a <div> inside each cell and styling that instead. However this shouldn't affect current versions of any browsers (except IE, that doesn't support rounded corners at all - see below)

Finally, not that IE doesn't support border-radius at all (IE9 beta does, but most IE users will be on IE8 or less). If you want to hack IE to support border-radius, look at http://css3pie.com/

[EDIT]

Okay, this was bugging me, so I've done some testing.

Here's a JSFiddle example I've been playing with

It seems like the critical thing you were missing was border-collapse:separate; on the table element. This stops the cells from linking their borders together, which allows them to pick up the border radius.

Hope that helps.

Get the time difference between two datetimes

It is very simple with moment below code will return diffrence in hour from current time:

moment().diff('2021-02-17T14:03:55.811000Z', "h")

Change the location of the ~ directory in a Windows install of Git Bash

I faced exactly the same issue. My home drive mapped to a network drive. Also

  1. No Write access to home drive
  2. No write access to Git bash profile
  3. No admin rights to change environment variables from control panel.

However below worked from command line and I was able to add HOME to environment variables.

rundll32 sysdm.cpl,EditEnvironmentVariables

commons httpclient - Adding query string parameters to GET/POST request

This is how I implemented my URL builder. I have created one Service class to provide the params for the URL

public interface ParamsProvider {

    String queryProvider(List<BasicNameValuePair> params);

    String bodyProvider(List<BasicNameValuePair> params);
}

The Implementation of methods are below

@Component
public class ParamsProviderImp implements ParamsProvider {
    @Override
    public String queryProvider(List<BasicNameValuePair> params) {
        StringBuilder query = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                query.append("?");
                query.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                query.append("&");
                query.append(basicNameValuePair.toString());
            }
        });
        return query.toString();
    }

    @Override
    public String bodyProvider(List<BasicNameValuePair> params) {
        StringBuilder body = new StringBuilder();
        AtomicBoolean first = new AtomicBoolean(true);
        params.forEach(basicNameValuePair -> {
            if (first.get()) {
                body.append(basicNameValuePair.toString());
                first.set(false);
            } else {
                body.append("&");
                body.append(basicNameValuePair.toString());
            }
        });
        return body.toString();
    }
}

When we need the query params for our URL, I simply call the service and build it. Example for that is below.

Class Mock{
@Autowired
ParamsProvider paramsProvider;
 String url ="http://www.google.lk";
// For the query params price,type
 List<BasicNameValuePair> queryParameters = new ArrayList<>();
 queryParameters.add(new BasicNameValuePair("price", 100));
 queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider

}

Update rows in one table with data from another table based on one column in each being equal

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      );

Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
    and
      rownum = 1    
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      ); 

Python coding standards/best practices

PEP 8 is good, the only thing that i wish it came down harder on was the Tabs-vs-Spaces holy war.

Basically if you are starting a project in python, you need to choose Tabs or Spaces and then shoot all offenders on sight.

How do you make Git work with IntelliJ?

git.exe is common for any git based applications like GitHub, Bitbucket etc. Some times it is possible that you have already installed another git based application so git.exe will be present in the bin folder of that application.

For example if you installed bitbucket before github in your PC, you will find git.exe in C:\Users\{username}\AppData\Local\Atlassian\SourceTree\git_local\bin instead of C:\Users\{username}\AppData\Local\GitHub\PortableGit.....\bin.

Close all infowindows in Google Maps API v3

When dealing with marker clusters this one worked for me.

var infowindow = null;

google.maps.event.addListener(marker, "click", function () {

        if (infowindow) {
            infowindow.close();
        }
        var markerMap = this.getMap();
        infowindow = this.info;
        this.info.open(markerMap, this);


    });

SQL MERGE statement to update data

THE CORRECT WAY IS :

UPDATE test1
INNER JOIN test2 ON (test1.id = test2.id)
SET test1.data = test2.data

.prop('checked',false) or .removeAttr('checked')?

jQuery 3

As of jQuery 3, removeAttr does not set the corresponding property to false anymore:

Prior to jQuery 3.0, using .removeAttr() on a boolean attribute such as checked, selected, or readonly would also set the corresponding named property to false. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.

It is almost always a mistake to use .removeAttr( "checked" ) on a DOM element. The only time it might be useful is if the DOM is later going to be serialized back to an HTML string. In all other cases, .prop( "checked", false ) should be used instead.

Changelog

Hence only .prop('checked',false) is correct way when using this version.


Original answer (from 2011):

For attributes which have underlying boolean properties (of which checked is one), removeAttr automatically sets the underlying property to false. (Note that this is among the backwards-compatibility "fixes" added in jQuery 1.6.1).

So, either will work... but the second example you gave (using prop) is the more correct of the two. If your goal is to uncheck the checkbox, you really do want to affect the property, not the attribute, and there's no need to go through removeAttr to do that.