Programs & Examples On #Posix api

Chaining multiple filter() in Django, is this a bug?

Sometimes you don't want to join multiple filters together like this:

def your_dynamic_query_generator(self, event: Event):
    qs \
    .filter(shiftregistrations__event=event) \
    .filter(shiftregistrations__shifts=False)

And the following code would actually not return the correct thing.

def your_dynamic_query_generator(self, event: Event):
    return Q(shiftregistrations__event=event) & Q(shiftregistrations__shifts=False)

What you can do now is to use an annotation count-filter.

In this case we count all shifts which belongs to a certain event.

qs: EventQuerySet = qs.annotate(
    num_shifts=Count('shiftregistrations__shifts', filter=Q(shiftregistrations__event=event))
)

Afterwards you can filter by annotation.

def your_dynamic_query_generator(self):
    return Q(num_shifts=0)

This solution is also cheaper on large querysets.

Hope this helps.

Using putty to scp from windows to Linux

You need to tell scp where to send the file. In your command that is not working:

scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~

You have not mentioned a remote server. scp uses : to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c from the host C to your local home directory.

The correct upload command, based on your comments, should be something like:

C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:

If you are running the command from your home directory, you can use a relative path:

C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:

You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:

C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/

jQuery return ajax result into outside variable

'async': false says it's depreciated. I did notice if I run console.log('test1'); on ajax success, then console.log('test2'); in normal js after the ajax function, test2 prints before test1 so the issue is an ajax call has a small delay, but doesn't stop the rest of the function to get results. The variable simply, was not set "yet", so you need to delay the next function.

function runPHP(){
    var input = document.getElementById("input1");
    var result = 'failed to run php';

    $.ajax({ url: '/test.php',
        type: 'POST',
        data: {action: 'test'},
        success: function(data) {
            result = data;
        }
    });

    setTimeout(function(){
        console.log(result);
    }, 1000);
}

on test.php (incase you need to test this function)

function test(){
    print 'ran php';
}

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = htmlentities($_POST['action']);
    switch($action) {
        case 'test' : test();break;
    }
}

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

In addition to others' proposals, there is another option to handle that issue.

If your application should behave the same in case of lack of "href" attribute, as in case of it being empty, just replace this:

var theHref = $(obj.mainImg_select).attr('href');

with this:

var theHref = $(obj.mainImg_select).attr('href') || '';

which will treat empty string ('') as the default, if the attribute has not been found.

But it really depends, on how you want to handle undefined "href" attribute. This answer assumes you will want to handle it as if it was empty string.

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

How to set RelativeLayout layout params in code not in xml?

    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    layout.setLayoutParams(labelLayoutParams);


   // If you want to add some controls in this Relative Layout
    labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);


    ImageView mImage = new ImageView(this);
    mImage.setBackgroundResource(R.drawable.popupnew_bg);        
    layout.addView(mImage,labelLayoutParams);

    setContentView(layout);

Change Row background color based on cell value DataTable

Callback for whenever a TR element is created for the table's body.

$('#example').dataTable( {
      "createdRow": function( row, data, dataIndex ) {
        if ( data[4] == "A" ) {
          $(row).addClass( 'important' );
        }
      }
    } );

https://datatables.net/reference/option/createdRow

Clearing my form inputs after submission

var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
 
btnClear.addEventListener('click', () => {
    inputs.forEach(input =>  input.value = '');
});

Firing events on CSS class changes in jQuery

Just a proof of concept:

Look at the gist to see some annotations and stay up-to-date:

https://gist.github.com/yckart/c893d7db0f49b1ea4dfb

(function ($) {
  var methods = ['addClass', 'toggleClass', 'removeClass'];

  $.each(methods, function (index, method) {
    var originalMethod = $.fn[method];

    $.fn[method] = function () {
      var oldClass = this[0].className;
      var result = originalMethod.apply(this, arguments);
      var newClass = this[0].className;

      this.trigger(method, [oldClass, newClass]);

      return result;
    };
  });
}(window.jQuery || window.Zepto));

The usage is quite simple, just add a new listender on the node you want to observe and manipulate the classes as usually:

var $node = $('div')

// listen to class-manipulation
.on('addClass toggleClass removeClass', function (e, oldClass, newClass) {
  console.log('Changed from %s to %s due %s', oldClass, newClass, e.type);
})

// make some changes
.addClass('foo')
.removeClass('foo')
.toggleClass('foo');

How do I list loaded plugins in Vim?

The problem with :scriptnames, :commands, :functions, and similar Vim commands, is that they display information in a large slab of text, which is very hard to visually parse.

To get around this, I wrote Headlights, a plugin that adds a menu to Vim showing all loaded plugins, TextMate style. The added benefit is that it shows plugin commands, mappings, files, and other bits and pieces.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

how to set font size based on container size?

Here is the function:

document.body.setScaledFont = function(f) {
  var s = this.offsetWidth, fs = s * f;
  this.style.fontSize = fs + '%';
  return this
};

Then convert all your documents child element font sizes to em's or %.

Then add something like this to your code to set the base font size.

document.body.setScaledFont(0.35);
window.onresize = function() {
    document.body.setScaledFont(0.35);
}

http://jsfiddle.net/0tpvccjt/

How to get VM arguments from inside of Java application?

With this code you can get the JVM arguments:

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
...
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();

Byte array to image conversion

In one line:

Image.FromStream(new MemoryStream(byteArrayIn));

Correct way to try/except using Python requests module?

One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)

Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah

vs

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)     

OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah

get the titles of all open windows

Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows function:

public class InfoWindow
{
            public IntPtr Handle = IntPtr.Zero;
            public FileInfo File = new FileInfo( Application.ExecutablePath );
            public string Title = Application.ProductName;
            public override string ToString() {
                return  File.Name + "\t>\t" + Title;
            }
 }//CLASS

/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{   
            internal static event EventHandler WindowActivatedChanged;    
            internal static Timer TimerWatcher = new Timer();    
            internal static InfoWindow WindowActive = new InfoWindow();       
            internal static void DoStartWatcher() {
                TimerWatcher.Interval = 500;
                TimerWatcher.Tick += TimerWatcher_Tick;
                TimerWatcher.Start();    
            }                    

            /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
            /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
            public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
            {
                IntPtr shellWindow = GetShellWindow();
                Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();

                EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
                    if ( hWnd == shellWindow ) return true;
                    if ( !IsWindowVisible( hWnd ) ) return true;    
                    int length = GetWindowTextLength( hWnd );
                    if ( length == 0 ) return true;    
                    StringBuilder builder = new StringBuilder( length );
                    GetWindowText( hWnd , builder , length + 1 );    
                    var info = new InfoWindow();
                    info.Handle = hWnd;
                    info.File = new FileInfo( GetProcessPath( hWnd ) );
                    info.Title = builder.ToString();    
                    windows[hWnd] = info;
                    return true;    
                } ) , 0 );    
                return windows;
            }

            private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );  

            public static string GetProcessPath( IntPtr hwnd )
            {
                uint pid = 0;
                GetWindowThreadProcessId( hwnd , out pid );
                if ( hwnd != IntPtr.Zero ) {
                    if ( pid != 0 ) {
                        var process = Process.GetProcessById( (int) pid );
                        if ( process != null ) {
                            return process.MainModule.FileName.ToString();
                        }
                    }
                }
                return "";
            }    

            [DllImport( "USER32.DLL" )]
            private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowTextLength( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern bool IsWindowVisible( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern IntPtr GetShellWindow();

            [DllImport( "user32.dll" )]
            private static extern IntPtr GetForegroundWindow();

            //WARN: Only for "Any CPU":
            [DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
            private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );    


            static void TimerWatcher_Tick( object sender , EventArgs e )
            {
                var windowActive = new InfoWindow();
                windowActive.Handle = GetForegroundWindow();
                string path = GetProcessPath( windowActive.Handle );
                if ( string.IsNullOrEmpty( path ) ) return;
                windowActive.File = new FileInfo( path );
                int length = GetWindowTextLength( windowActive.Handle );
                if ( length == 0 ) return;
                StringBuilder builder = new StringBuilder( length );
                GetWindowText( windowActive.Handle , builder , length + 1 );
                windowActive.Title = builder.ToString();
                if ( windowActive.ToString() != WindowActive.ToString() ) {
                    //fire:
                    WindowActive = windowActive;
                    if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
                    Console.WriteLine( "Window: " + WindowActive.ToString() );
                }
            }

}//CLASS

Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...

How to solve SyntaxError on autogenerated manage.py?

After testing with precise instructions (using python2 or python3 instead of just "python") I've constated that no matter what the tutorial says, this works ONLY with python3.

Uncaught TypeError: Cannot assign to read only property

When you use Object.defineProperties, by default writable is set to false, so _year and edition are actually read only properties.

Explicitly set them to writable: true:

_year: {
    value: 2004,
    writable: true
},

edition: {
    value: 1,
    writable: true
},

Check out MDN for this method.

writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

Notepad++ add to every line

Well, I am posting this after such a long time but this will the easiest of all.

  1. To add text at the beginning/a-certain-place-from-start for all lines, just click there and do ALT+C and you will get the below box. Type in your text and click OK and it's done.

    enter image description here

  2. To add a certain text at end of all lines, do CTRL+F, and choose REPLACE. You will get the below box. Put in '$' in 'find what' and in 'replace with' type in your text.Make sure you choose 'regular expression' in the search mode (left down). Finally click 'replace all' and you are done.

enter image description here

Can I have onScrollListener for a ScrollView?

you can define a custom ScrollView class, & add an interface be called when scrolling like this:

public class ScrollChangeListenerScrollView extends HorizontalScrollView {


private MyScrollListener mMyScrollListener;

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

public ScrollChangeListenerScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public ScrollChangeListenerScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}


public void setOnMyScrollListener(MyScrollListener myScrollListener){
    this.mMyScrollListener = myScrollListener;
}


@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    super.onScrollChanged(l, t, oldl, oldt);
    if(mMyScrollListener!=null){
        mMyScrollListener.onScrollChange(this,l,t,oldl,oldt);
    }

}

public interface MyScrollListener {
    void onScrollChange(View view,int scrollX,int scrollY,int oldScrollX, int oldScrollY);
}

}

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

HTML list-style-type dash

You can just set li::marker like so:

li::marker {
   content: '- ';
}

How to specify credentials when connecting to boto3 S3?

I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI to create a config file. The reason is, with the config file, the CLI or the SDK will automatically look for credentials in the ~/.aws folder. And the good thing is that AWS CLI is written in python.

You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After this you can access boto and any of the api without having to specify keys (unless you want to use a different credentials).

Encrypt Password in Configuration Files?

A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password.

This basically means initializing a javax.crypto.Cipher with algorithm "AES/CBC/PKCS5Padding" and getting a key from javax.crypto.SecretKeyFactory with the "PBKDF2WithHmacSHA512" algorithm.

Here is a code example (updated to replace the less secure MD5-based variant):

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class ProtectedConfigFile {

    public static void main(String[] args) throws Exception {
        String password = System.getProperty("password");
        if (password == null) {
            throw new IllegalArgumentException("Run with -Dpassword=<password>");
        }

        // The salt (probably) can be stored along with the encrypted data
        byte[] salt = new String("12345678").getBytes();

        // Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers
        int iterationCount = 40000;
        // Other values give me java.security.InvalidKeyException: Illegal key size or default parameters
        int keyLength = 128;
        SecretKeySpec key = createSecretKey(password.toCharArray(),
                salt, iterationCount, keyLength);

        String originalPassword = "secret";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword, key);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword, key);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(keyTmp.getEncoded(), "AES");
    }

    private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
        byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8"));
        byte[] iv = ivParameterSpec.getIV();
        return base64Encode(iv) + ":" + base64Encode(cryptoText);
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
        String iv = string.split(":")[0];
        String property = string.split(":")[1];
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        return Base64.getDecoder().decode(property);
    }
}

One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (-DpropertyProtectionPassword=...).

The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect.

How can I jump to class/method definition in Atom text editor?

I had the same issue and atom-goto-definition (package name goto-definition) worked like charm for me. Please try once. You can download directly from Atom.

This package is DEPRECATED. Please check it in Github.

Start index for iterating Python list

If all you want is to print from Monday onwards, you can use list's index method to find the position where "Monday" is in the list, and iterate from there as explained in other posts. Using list.index saves you hard-coding the index for "Monday", which is a potential source of error:

days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
for d in days[days.index('Monday'):] :
   print d

Python: avoid new line with print command

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')

Access parent URL from iframe

You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...), but other JS APIs are intentionally made inaccessible.

It's also still possible to get the URL depending on the context. See other answers for more details.

How to resize images proportionally / keeping the aspect ratio?

If the image is proportionate then this code will fill the wrapper with image. If image is not in proportion then extra width/height will get cropped.

    <script type="text/javascript">
        $(function(){
            $('#slider img').each(function(){
                var ReqWidth = 1000; // Max width for the image
                var ReqHeight = 300; // Max height for the image
                var width = $(this).width(); // Current image width
                var height = $(this).height(); // Current image height
                // Check if the current width is larger than the max
                if (width > height && height < ReqHeight) {

                    $(this).css("min-height", ReqHeight); // Set new height
                }
                else 
                    if (width > height && width < ReqWidth) {

                        $(this).css("min-width", ReqWidth); // Set new width
                    }
                    else 
                        if (width > height && width > ReqWidth) {

                            $(this).css("max-width", ReqWidth); // Set new width
                        }
                        else 
                            (height > width && width < ReqWidth)
                {

                    $(this).css("min-width", ReqWidth); // Set new width
                }
            });
        });
    </script>

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

How to get all of the IDs with jQuery?

It's a late answer but now there is an easy way. Current version of jquery lets you search if attribute exists. For example

$('[id]')

will give you all the elements if they have id. If you want all spans with id starting with span you can use

$('span[id^="span"]')

How to disable text selection using jQuery?

In jQuery 1.8, this can be done as follows:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

How to correct indentation in IntelliJ

Code ? Reformat Code... (default Ctrl + Alt + L) for the whole file or Code ? Auto-Indent Lines (default Ctrl + Alt + I) for the current line or selection.

You can customise the settings for how code is auto-formatted under File ? Settings ? Editor ? Code Style.


To ensure comments are also indented to the same level as the code, you can simply do as follows:

UI screenshot (example for JavaScript)

Pod install is staying on "Setting up CocoaPods Master repo"

What I tried and faster than clonning the repo:

  1. pod setup
  2. Ctrl +C after creating the master directory
  3. Download .zip from https://github.com/CocoaPods/Specs master
  4. Copy the content to ~/.cocoapods/repos
  5. pod install --no-repo-update in my project folder

After that I finally could see the pods being installed

Good luck!

EDIT: The zip size is 144 MB (Jul 6 2017)

ImportError: No module named 'encodings'

I could also fix this. PYTHONPATH and PYTHONHOME were in cause.

run this in a terminal

   touch ~/.bash_profile
   open ~/.bash_profile

and then delete all useless parts of this file, and save. I do not know how recommended it is to do that !

How do I clone a generic List in Java?

ArrayList newArrayList = (ArrayList) oldArrayList.clone();

php - push array into array - key issue

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}


array_push == $res_arr_values[] = $row;

example 

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
?>

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

I have same problem but with different situation. I can compile without any issue with maven in command line (mvn clean install), but in Intellij I always got "java: diamond operator is not supported in -source 1.5" compile error despite I have set the maven-compiler-plugin with java 1.8 in the pom.xml.

It turned out I have remote repository setting in my maven's settings.xml which the project depends on, but Intellij uses his own maven which doesn't have same setting with my local maven.

So my solution was changing the Intellij's maven setting (Settings -> Build, execution, Deployment -> Maven -> Maven home directory) to use the local maven.

Python convert decimal to hex

I recently made this python program to convert Decimal to Hexadecimal, please check this out. This is my first Answer in stack overflow .

decimal = int(input("Enter the Decimal no that you want to convert to Hexadecimal : "))
intact = decimal
hexadecimal = ''
dictionary = {1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}

while(decimal!=0):
    c = decimal%16 
    hexadecimal =  dictionary[c] + hexadecimal 
    decimal = int(decimal/16)

print(f"{intact} is {hexadecimal} in Hexadecimal")

When you Execute this code this will give output as:

Enter the Decimal no that you want to convert to Hexadecimal : 2766

2766 is ACE in Hexadecimal

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

The only thing that worked for me:

g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);    

PHP Echo a large block of text

$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);

How to detect if numpy is installed

Option 1:

Use following command in python ide.:

import numpy

Option 2:

Go to Python -> site-packages folder. There you should be able to find numpy and the numpy distribution info folder.

If any of the above is true then you installed numpy successfully.

What is IllegalStateException?

package com.concepttimes.java;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IllegalStateExceptionDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List al = new ArrayList();
        al.add("Sachin");
        al.add("Rahul");
        al.add("saurav");
        Iterator itr = al.iterator();  
        while (itr.hasNext()) {           
            itr.remove();
        }
    }
}

IllegalStateException signals that method has been invoked at the wrong time. In this below example, we can see that. remove() method is called at the same time element is being used in while loop.

Please refer to below link for more details. http://www.elitmuszone.com/elitmus/illegalstateexception-in-java/

How do I check if a Socket is currently connected in Java?

Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.

TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.

See Do I need to heartbeat to keep a TCP connection open? for more discussion.

Can I get the name of the current controller in the view?

#to get controller name:
<%= controller.controller_name %>
#=> 'users'

#to get action name, it is the method:
<%= controller.action_name %>
#=> 'show'


#to get id information:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
#=> '23'

# or display nicely
<%= debug Rails.application.routes.recognize_path(request.url) %>

reference

popup form using html/javascript/css

Just replacing "Please enter your name" to your desired content would do the job. Am I missing something?

How to process POST data in Node.js?

If you are using Express.js, before you can access to the req.body, you must add middleware bodyParser:

app.use(express.bodyParser());

Then you can ask for

req.body.user

Angular 4 - Select default value in dropdown [Reactive Forms]

You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)] and further in component file assign default value to it.

In your_component_file.ts

this.selectedCountry = default;

In your_component_template.html

<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select> 

Plunker link

Loading DLLs at runtime in C#

foreach (var f in Directory.GetFiles(".", "*.dll"))
            Assembly.LoadFrom(f);

That loads all the DLLs present in your executable's folder.

In my case I was trying to use Reflection to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.

EDIT: I timed it, and it only seems to load them the first time.

Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
    stopwatch.Restart();
    foreach (var f in Directory.GetFiles(".", "*.dll"))
        Assembly.LoadFrom(f);
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}

Output: 34 0 0 0

So one could potentially run that code before any Reflection searches just in case.

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

I tried to change target sdk to 13 but does not works!! then when I changed compileSdkVersion 13 to compileSdkVersion 14 is compiled successfully :)

NOTE: I Work with Android Studio not Eclipse

Enabling HTTPS on express.js

This is my working code for express 4.0.

express 4.0 is very different from 3.0 and others.

4.0 you have /bin/www file, which you are going to add https here.

"npm start" is standard way you start express 4.0 server.

readFileSync() function should use __dirname get current directory

while require() use ./ refer to current directory.

First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.

How can I replace a regex substring match in Javascript?

I think the simplest way to achieve your goal is this:

var str   = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);

Swift Set to Array

call this method and pass your set

func getArrayFromSet(set:NSSet)-> NSArray {

return set.map ({ String($0) })
}

Like This :

var letters:Set = Set<String>(arrayLiteral: "test","test") // your set
print(self.getArrayFromSet(letters))

How to declare an array in Python?

You can create lists and convert them into arrays or you can create array using numpy module. Below are few examples to illustrate the same. Numpy also makes it easier to work with multi-dimensional arrays.

import numpy as np
a = np.array([1, 2, 3, 4])

#For custom inputs
a = np.array([int(x) for x in input().split()])

You can also reshape this array into a 2X2 matrix using reshape function which takes in input as the dimensions of the matrix.

mat = a.reshape(2, 2)

Outline effect to text

Easy! SVG to the rescue.

This is a simplified method:

_x000D_
_x000D_
svg{
  font   : bold 70px Century Gothic, Arial;
  width  : 100%;
  height : 120px;
}

text{
  fill            : none;
  stroke          : black;
  stroke-width    : .5px;
  stroke-linejoin : round;
  animation       : 2s pulsate infinite;
}

@keyframes pulsate {
  50%{ stroke-width:5px }
}
_x000D_
<svg viewBox="0 0 450 50">
  <text y="50">Scalable Title</text>
</svg>
_x000D_
_x000D_
_x000D_

Here's a more complex demo.

How do I search a Perl array for a matching string?

I guess

@foo = ("aAa", "bbb");
@bar = grep(/^aaa/i, @foo);
print join ",",@bar;

would do the trick.

How can I divide two integers to get a double?

Convert one of them to a double first. This form works in many languages:

 real_result = (int_numerator + 0.0) / int_denominator

java.io.IOException: Server returned HTTP response code: 500

I had this problem i.e. works fine when pasted into browser but 505s when done through java. It was simply the spaces that needed to be escaped/encoded.

How to check whether java is installed on the computer

If java not installed yet. Then program written by java cannot be run to check if java is installed or not.

changing minDate option in JQuery DatePicker not working

There is no need to destroy current instance, just refresh.

$('#datepicker')
    .datepicker('option', 'minDate', new Date)
    .datepicker('refresh');

How to swap String characters in Java?

'In' a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1");

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

How to remove leading zeros from alphanumeric text?

You could replace "^0*(.*)" to "$1" with regex

Meaning of *& and **& in C++

First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.

void foo(int*& x, int**& y) {
    // modifying x or y here will modify a or b in main
}

int main() {
    int val = 42;
    int *a  = &val;
    int **b = &a;

    foo(a, b);
    return 0;
}

How to remove non UTF-8 characters from text file

cat foo.txt | strings -n 8 > bar.txt

will do the job.

How to embed a Google Drive folder in a website

For business/Gsuite apps or whatever they call them, you can specify the domain (had problem with 500 errors with the original answer when logged into multiple Google accounts).

<iframe 
  src="https://drive.google.com/a/YOUR_COMPANY_DOMAIN/embeddedfolderview?id=FOLDER-ID" 
  style="width:100%; height:600px; border:0;"
>
</iframe>

Plotting a fast Fourier transform in Python

I've built a function that deals with plotting FFT of real signals. The extra bonus in my function relative to the previous answers is that you get the actual amplitude of the signal.

Also, because of the assumption of a real signal, the FFT is symmetric, so we can plot only the positive side of the x-axis:

import matplotlib.pyplot as plt
import numpy as np
import warnings


def fftPlot(sig, dt=None, plot=True):
    # Here it's assumes analytic signal (real signal...) - so only half of the axis is required

    if dt is None:
        dt = 1
        t = np.arange(0, sig.shape[-1])
        xLabel = 'samples'
    else:
        t = np.arange(0, sig.shape[-1]) * dt
        xLabel = 'freq [Hz]'

    if sig.shape[0] % 2 != 0:
        warnings.warn("signal preferred to be even in size, autoFixing it...")
        t = t[0:-1]
        sig = sig[0:-1]

    sigFFT = np.fft.fft(sig) / t.shape[0]  # Divided by size t for coherent magnitude

    freq = np.fft.fftfreq(t.shape[0], d=dt)

    # Plot analytic signal - right half of frequence axis needed only...
    firstNegInd = np.argmax(freq < 0)
    freqAxisPos = freq[0:firstNegInd]
    sigFFTPos = 2 * sigFFT[0:firstNegInd]  # *2 because of magnitude of analytic signal

    if plot:
        plt.figure()
        plt.plot(freqAxisPos, np.abs(sigFFTPos))
        plt.xlabel(xLabel)
        plt.ylabel('mag')
        plt.title('Analytic FFT plot')
        plt.show()

    return sigFFTPos, freqAxisPos


if __name__ == "__main__":
    dt = 1 / 1000

    # Build a signal within Nyquist - the result will be the positive FFT with actual magnitude
    f0 = 200  # [Hz]
    t = np.arange(0, 1 + dt, dt)
    sig = 1 * np.sin(2 * np.pi * f0 * t) + \
        10 * np.sin(2 * np.pi * f0 / 2 * t) + \
        3 * np.sin(2 * np.pi * f0 / 4 * t) +\
        7.5 * np.sin(2 * np.pi * f0 / 5 * t)

    # Result in frequencies
    fftPlot(sig, dt=dt)
    # Result in samples (if the frequencies axis is unknown)
    fftPlot(sig)

Analytic FFT plot result

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

How to create our own Listener interface in android?

I have done it something like below for sending my model class from the Second Activity to First Activity. I used LiveData to achieve this, with the help of answers from Rupesh and TheCodeFather.

Second Activity

public static MutableLiveData<AudioListModel> getLiveSong() {
        MutableLiveData<AudioListModel> result = new MutableLiveData<>();
        result.setValue(liveSong);
        return result;
    }

"liveSong" is AudioListModel declared globally

Call this method in the First Activity

PlayerActivity.getLiveSong().observe(this, new Observer<AudioListModel>() {
            @Override
            public void onChanged(AudioListModel audioListModel) {
                if (PlayerActivity.mediaPlayer != null && PlayerActivity.mediaPlayer.isPlaying()) {
                    Log.d("LiveSong--->Changes-->", audioListModel.getSongName());
                }
            }
        });

May this help for new explorers like me.

Splitting a C++ std::string using tokens, e.g. ";"

I find std::getline() is often the simplest. The optional delimiter parameter means it's not just for reading "lines":

#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> strings;
    istringstream f("denmark;sweden;india;us");
    string s;    
    while (getline(f, s, ';')) {
        cout << s << endl;
        strings.push_back(s);
    }
}

Getting all types in a namespace via reflection

Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!

Play audio from a stream using C#

I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.

I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.

CSS for grabbing cursors (drag & drop)

I may be late, but you can try the following code, which worked for me for Drag and Drop.

.dndclass{
    cursor: url('../images/grab1.png'), auto; 

}

.dndclass:active {
    cursor: url('../images/grabbing1.png'), auto;
}

You can use the images below in the URL above. Make sure it is a PNG transparent image. If not, download one from google.

enter image description here enter image description here

How can I INSERT data into two tables simultaneously in SQL Server?

You could write a stored procedure that iterates over the transaction that you have proposed. The iterator would be the cursor for the table that contains the source data.

Convert string to date in Swift

In Swift 4.1 you can do:

func getDate() -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.locale = Locale.current
    return dateFormatter.date(from: "2015-04-01T11:42:00") // replace Date String
}

How can I export the schema of a database in PostgreSQL?

In Linux you can do like this

pg_dump -U postgres -s postgres > exportFile.dmp

Maybe it can work in Windows too, if not try the same with pg_dump.exe

pg_dump.exe -U postgres -s postgres > exportFile.dmp

Angular bootstrap datepicker date format does not format ng-model value

After checking the above answers, I came up with this and it worked perfectly without having to add an extra attribute to your markup

angular.module('app').directive('datepickerPopup', function(dateFilter) {
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {
            ngModel.$parsers.push(function(viewValue) {
                return dateFilter(viewValue, 'yyyy-MM-dd');
            });
        }
    }
});

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

Change div height on button click

Look at to vwphillips' post from 03-06-2010, 03:35 PM in http://www.codingforums.com/archive/index.php/t-190887.html

<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

      <script type="text/javascript">

        function Div(id,ud) {
           var div=document.getElementById(id);
           var h=parseInt(div.style.height)+ud;
           if (h>=1){
              div.style.height = h + "em"; // I'm using "em" instead of "px", but you can use px like measure...
           }
        }
      </script>

   </head>
   <body>
      <div>
         <input type="button" value="+" onclick="Div('my_div', 1);">&nbsp;&nbsp; 
         <input type="button" value="-" onclick="Div('my_div', -1);"></div>
      </div>

      <div id="my_div" style="height: 1em; width: 1em; overflow: auto;"></div>

   </body>
</html>

This worked for me :)

Best regards!

jQuery ajax post file field

I tried this code to accept files using Ajax and on submit file gets store using my php file. Code modified slightly to work. (Uploaded Files: PDF,JPG)

function verify1() {
    jQuery.ajax({
        type: 'POST',
        url:"functions.php",
        data: new FormData($("#infoForm1")[0]),
        processData: false, 
        contentType: false, 
        success: function(returnval) {
             $("#show1").html(returnval);
             $('#show1').show();
         }
    });
}

Just print the file details and check. You will get Output. If error let me know.

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

Converting two lists into a matrix

Assuming lengths of portfolio and index are the same:

matrix = []
for i in range(len(portfolio)):
    matrix.append([portfolio[i], index[i]])

Or a one-liner using list comprehension:

matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]

How can you encode a string to Base64 in JavaScript?

While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.

If you can get your data into a Blob, then you can use the FileReader.readAsDataURL() function to get a data:// URL and chop off the front of it to get at the base64 data.

You may have to do further processing however to urldecode the data, as I'm not sure whether + characters are escaped or not for the data:// URL, but this should be pretty trivial.

Android open pdf file

String dir="/Attendancesystem";

 public void displaypdf() {

        File file = null;
            file = new File(Environment.getExternalStorageDirectory()+dir+ "/sample.pdf");
        Toast.makeText(getApplicationContext(), file.toString() , Toast.LENGTH_LONG).show();
        if(file.exists()) {
            Intent target = new Intent(Intent.ACTION_VIEW);
            target.setDataAndType(Uri.fromFile(file), "application/pdf");
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            Intent intent = Intent.createChooser(target, "Open File");
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                // Instruct the user to install a PDF reader here, or something
            }
        }
        else
            Toast.makeText(getApplicationContext(), "File path is incorrect." , Toast.LENGTH_LONG).show();
    }

Get a timestamp in C in microseconds?

use an unsigned long long (i.e. a 64 bit unit) to represent the system time:

typedef unsigned long long u64;

u64 u64useconds;
struct timeval tv;

gettimeofday(&tv,NULL);
u64useconds = (1000000*tv.tv_sec) + tv.tv_usec;

How to call a method function from another class?

You need a reference to the class that contains the method you want to call. Let's say we have two classes, A and B. B has a method you want to call from A. Class A would look like this:

public class A
{
    B b; // A reference to B

    b = new B(); // Creating object of class B

    b.doSomething();  // Calling a method contained in class B from class A
}

B, which contains the doSomething() method would look like this:

public class B
{
    public void doSomething()
    {
        System.out.println("Look, I'm doing something in class B!");
    }
}

Creating an Arraylist of Objects

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

java.net.SocketTimeoutException: Read timed out under Tomcat

I am using 11.2 and received timeouts.

I resolved by using the version of jsoup below.

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
        <scope>compile</scope>
    </dependency>

PHP How to find the time elapsed since a date time?

To find out time elapsed i usually use time() instead of date() and formatted time stamps. Then get the difference between the latter value and the earlier value and format accordingly. time() is differently not a replacement for date() but it totally helps when calculating elapsed time.

example:

The value of time() looks something like this 1274467343 increments every second. So you could have $erlierTime with value 1274467343 and $latterTime with value 1274467500, then just do $latterTime - $erlierTime to get time elapsed in seconds.

Wrap text in <td> tag

.tbl {
    table-layout:fixed;
    border-collapse: collapse;
    background: #fff;
 }

.tbl td {
    text-overflow:ellipsis;
    overflow:hidden;
    white-space:nowrap;
}

Credits to http://www.blakems.com/archives/000077.html

How do you do block comments in YAML?

YAML supports inline comments, but does not support block comments.

From Wikipedia:

Comments begin with the number sign ( # ), can start anywhere on a line, and continue until the end of the line

A comparison with JSON, also from Wikipedia:

The syntax differences are subtle and seldom arise in practice: JSON allows extended charactersets like UTF-32, YAML requires a space after separators like comma, equals, and colon while JSON does not, and some non-standard implementations of JSON extend the grammar to include Javascript's /* ... */ comments. Handling such edge cases may require light pre-processing of the JSON before parsing as in-line YAML.

# If you want to write
# a block-commented Haiku
# you'll need three pound signs

How to center HTML5 Videos?

Try this:

video {
display:block;
margin:0 auto;
}

Firefox setting to enable cross domain Ajax request

If you just don't want to waste your time on cross-domain issues during development and testing of your app you can use addon Force CORS for FF.

UPDATE: It seems that this addon no longer exists. But there is another option - this Chrome extension

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

Check, 1. In Module settings, whether, SDK location is proper. 2. If Yes, check for local.properties file (Not the one placed inside app module, but the one placed outside the app module, at parent level). If not present add it with below lines inside it.

sdk.dir=/path/to/sdk/../Android/Sdk

Getting a list item by index

Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array.

List[index]

See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx

How to give a time delay of less than one second in excel vba?

I have try this and it works for me:

Private Sub DelayMs(ms As Long)
    Debug.Print TimeValue(Now)
    Application.Wait (Now + (ms * 0.00000001))
    Debug.Print TimeValue(Now)
End Sub

Private Sub test()
    Call DelayMs (2000)  'test code with delay of 2 seconds, see debug window
End Sub

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

add this permission in your manifest and than use the above code to change WiFi state:

 <!--permission ge enable and disable WIFI in android-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

Is there a float input type in HTML5?

The number type has a step value controlling which numbers are valid (along with max and min), which defaults to 1. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step).

Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:

<input type="number" step="0.01">

(I'd also set min=0 if it can only be positive)

If you'd prefer to allow any number of decimal places, you can use step="any" (though for currencies, I'd recommend sticking to 0.01). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any. (thanks to Michal Stefanow's answer for pointing out any, and see the relevant spec here)

Here's a playground showing how various steps affect various input types:

_x000D_
_x000D_
<form>_x000D_
  <input type=number step=1 /> Step 1 (default)<br />_x000D_
  <input type=number step=0.01 /> Step 0.01<br />_x000D_
  <input type=number step=any /> Step any<br />_x000D_
  <input type=range step=20 /> Step 20<br />_x000D_
  <input type=datetime-local step=60 /> Step 60 (default)<br />_x000D_
  <input type=datetime-local step=1 /> Step 1<br />_x000D_
  <input type=datetime-local step=any /> Step any<br />_x000D_
  <input type=datetime-local step=0.001 /> Step 0.001<br />_x000D_
  <input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />_x000D_
  <input type=datetime-local step=86400 /> Step 86400 (1 day)<br />_x000D_
  <input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />_x000D_
</form>
_x000D_
_x000D_
_x000D_


As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

For scoop users:

"terminal.integrated.shell.windows": "C:\\Users\\[YOUR-NAME]\\scoop\\apps\\git\\current\\usr\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": [
  "-l",
  "-i"
],

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

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

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

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

How to set the 'selected option' of a select dropdown list with jquery

You have to replace YourID and value="3" for your current ones.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#YourID option[value="3"]').attr("selected", "selected");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
  <option value="1">A</option>_x000D_
  <option value="2">B</option>_x000D_
  <option value="3">C</option>_x000D_
  <option value="4">D</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

and value="3" for your current ones.

$('#YourID option[value="3"]').attr("selected", "selected");

<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>

Binding to static property

You can use ObjectDataProvider class and it's MethodName property. It can look like this:

<Window.Resources>
   <ObjectDataProvider x:Key="versionManager" ObjectType="{x:Type VersionManager}" MethodName="get_FilterString"></ObjectDataProvider>
</Window.Resources>

Declared object data provider can be used like this:

<TextBox Text="{Binding Source={StaticResource versionManager}}" />

What is the best way to merge mp3 files?

The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into account as the entire file is copied.

Do you have a language of choice that you want to use or doesn't it matter? That will affect what libraries are available that support the operations you want.

What characters are forbidden in Windows and Linux directory names?

Let's keep it simple and answer the question, first.

  1. The forbidden printable ASCII characters are:

    • Linux/Unix:

      / (forward slash)
      
    • Windows:

      < (less than)
      > (greater than)
      : (colon - sometimes works, but is actually NTFS Alternate Data Streams)
      " (double quote)
      / (forward slash)
      \ (backslash)
      | (vertical bar or pipe)
      ? (question mark)
      * (asterisk)
      
  2. Non-printable characters

    If your data comes from a source that would permit non-printable characters then there is more to check for.

    • Linux/Unix:

      0 (NULL byte)
      
    • Windows:

      0-31 (ASCII control characters)
      

    Note: While it is legal under Linux/Unix file systems to create files with control characters in the filename, it might be a nightmare for the users to deal with such files.

  3. Reserved file names

    The following filenames are reserved:

    • Windows:

      CON, PRN, AUX, NUL 
      COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9
      LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9
      

      (both on their own and with arbitrary file extensions, e.g. LPT1.txt).

  4. Other rules

    • Windows:

      Filenames cannot end in a space or dot.

Setting up Vim for Python

Some time ago I installed Valloric/YouCompleteMe and I find it really awesome. It provides you completion for file paths, function names, methods, variable names... Together with davidhalter/jedi-vim it makes vim great for python programming (the only thing missing now is a linter).

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

'this' vs $scope in AngularJS controllers

I just read a pretty interesting explanation on the difference between the two, and a growing preference to attach models to the controller and alias the controller to bind models to the view. http://toddmotto.com/digging-into-angulars-controller-as-syntax/ is the article.

NOTE: The original link still exists, but changes in formatting have made it hard to read. It's easier to view in the original.

He doesn't mention it but when defining directives, if you need to share something between multiple directives and don't want a service (there are legitimate cases where services are a hassle) then attach the data to the parent directive's controller.

The $scope service provides plenty of useful things, $watch being the most obvious, but if all you need to bind data to the view, using the plain controller and 'controller as' in the template is fine and arguably preferable.

Generate MD5 hash string with T-SQL

Solution:

SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)

Hide element by class in pure Javascript

var appBanners = document.getElementsByClassName('appBanner');

for (var i = 0; i < appBanners.length; i ++) {
    appBanners[i].style.display = 'none';
}

JSFiddle.

Difference between webdriver.get() and webdriver.navigate()

navigate().to() and get() will work same when you use for the first time. When you use it more than once then using navigate().to() you can come to the previous page at any time whereas you can do the same using get().

Conclusion: navigate().to() holds the entire history of the current window and get() just reload the page and hold any history.

What is the difference between Scala's case class and class?

Apart from what people have already said, there are some more basic differences between class and case class

1.Case Class doesn't need explicit new, while class need to be called with new

val classInst = new MyClass(...)  // For classes
val classInst = MyClass(..)       // For case class

2.By Default constructors parameters are private in class , while its public in case class

// For class
class MyClass(x:Int) { }
val classInst = new MyClass(10)

classInst.x   // FAILURE : can't access

// For caseClass
case class MyClass(x:Int) { }
val classInst = MyClass(10)

classInst.x   // SUCCESS

3.case class compare themselves by value

// case Class
class MyClass(x:Int) { }

val classInst = new MyClass(10)
val classInst2 = new MyClass(10)

classInst == classInst2 // FALSE

// For Case Class
case class MyClass(x:Int) { }

val classInst = MyClass(10)
val classInst2 = MyClass(10)

classInst == classInst2 // TRUE

Android design support library for API 28 (P) not working

Google has introduced new AndroidX dependencies. You need to migrate to AndroidX, it's simple.

I replaced all dependencies to AndroidX dependencies

Old design dependency

implementation 'com.android.support:design:28.0.0'

New AndroidX design dependency

implementation 'com.google.android.material:material:1.0.0-rc01'

you can find AndroidX dependencies here https://developer.android.com/jetpack/androidx/migrate


Automatic AndroidX migration option (supported on android studio 3.3+)

Migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.

Boolean checking in the 'if' condition

First style is better. Though you should use better variable name

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

How to disable Python warnings?

You can also define an environment variable (new feature in 2010 - i.e. python 2.7)

export PYTHONWARNINGS="ignore"

Test like this: Default

$ export PYTHONWARNINGS="default"
$ python
>>> import warnings
>>> warnings.warn('my warning')
__main__:1: UserWarning: my warning
>>>

Ignore warnings

$ export PYTHONWARNINGS="ignore"
$ python
>>> import warnings
>>> warnings.warn('my warning')
>>> 

For deprecation warnings have a look at how-to-ignore-deprecation-warnings-in-python

Copied here...

From documentation of the warnings module:

 #!/usr/bin/env python -W ignore::DeprecationWarning

If you're on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.

(Note that in Python 3.2, deprecation warnings are ignored by default.)

Or:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=DeprecationWarning)
    import md5, sha

yourcode()

Now you still get all the other DeprecationWarnings, but not the ones caused by:

import md5, sha

HttpClient 4.0.1 - how to release connection?

If the response is not to be consumed, then the request can be aborted using the code below:

// Low level resources should be released before initiating a new request
HttpEntity entity = response.getEntity();

if (entity != null) {
    // Do not need the rest
    httpPost.abort();
}

Reference: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e143

Apache HttpClient Version: 4.1.3

Getting selected value of a combobox

The problem you have with the SelectedValue is not converting into integer. This is the main problem so usinge the following code snippet will help you:

int selectedValue;
bool parseOK = Int32.TryParse(cmb.SelectedValue.ToString(), out selectedValue);

not:first-child selector

You can use any selector with not

p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}

Python: convert string from UTF-8 to Latin-1

Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:

>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'

Factorial in numpy and scipy

enter image description here

after running different aforementioned functions for factorial, by different people, turns out that math.factorial is the fastest to calculate the factorial.

find running times for different functions in the attached image

Combine two ActiveRecord::Relation objects

If you have an array of activerecord relations and want to merge them all, you can do

array.inject(:merge)

How to load a controller from another controller in codeigniter?

I had a similar problem. I wanted to have two controllers:

homepage.php - public facing homepage

home.php - home screen once a user was logged in

and I wanted them both to read from 'mydomain.com'

I was able to accomplish this by setting 'hompepage' as the default controller in my routes config and adding a remap function to homepage.php

function _remap()
{
  if(user_is_logged_in())
  {
    require_once(APPPATH.'controllers/home.php'); 
    $oHome =  new Home();
    $oHome->index();
  }
  else
  {
    $this->index();
  }
}

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

Error Running React Native App From Terminal (iOS)

In my case the SDKROOT environment variable was wrong, which referred to an old version of iPhoneOSxx.x.sdk. (Perhaps this would have automatically resolved itself after a reboot?)

You can check by running echo $SDKROOT and verifying that it's a valid path.

I fixed it by updating in .bash_profile:

export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.2.sdk

Getting each individual digit from a whole integer

//this can be easily understandable for beginners     
int score=12344534;
int div;
for (div = 1; div <= score; div *= 10)
{

}
/*for (div = 1; div <= score; div *= 10); for loop with semicolon or empty body is same*/
while(score>0)
{
    div /= 10;
    printf("%d\n`enter code here`", score / div);
    score %= div;
}

Securing a password in a properties file

enter image description here

Jasypt provides the org.jasypt.properties.EncryptableProperties class for loading, managing and transparently decrypting encrypted values in .properties files, allowing the mix of both encrypted and not-encrypted values in the same file.

http://www.jasypt.org/encrypting-configuration.html

By using an org.jasypt.properties.EncryptableProperties object, an application would be able to correctly read and use a .properties file like this:

datasource.driver=com.mysql.jdbc.Driver 
datasource.url=jdbc:mysql://localhost/reportsdb 
datasource.username=reportsUser 
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm) 

Note that the database password is encrypted (in fact, any other property could also be encrypted, be it related with database configuration or not).

How do we read this value? like this:

/*
* First, create (or ask some other component for) the adequate encryptor for   
* decrypting the values in our .properties file.   
*/  
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();     
encryptor.setPassword("jasypt"); // could be got from web, env variable...    
/*   
* Create our EncryptableProperties object and load it the usual way.   
*/  
Properties props = new EncryptableProperties(encryptor);  
props.load(new FileInputStream("/path/to/my/configuration.properties"));

/*   
* To get a non-encrypted value, we just get it with getProperty...   
*/  
String datasourceUsername = props.getProperty("datasource.username");

/*   
* ...and to get an encrypted value, we do exactly the same. Decryption will   
* be transparently performed behind the scenes.   
*/ 
String datasourcePassword = props.getProperty("datasource.password");

 // From now on, datasourcePassword equals "reports_passwd"...

Get the last item in an array

In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.

Syntax:

arr.lastItem // get last item
arr.lastItem = 'value' // set last item

arr.lastIndex // get last index

You can use polyfill.

Proposal author: Keith Cirkel(chai autor)

Python 3: EOF when reading a line (Sublime Text 2 is angry)

I had the same problem. The problem with the Sublime Text's default console is that it does not support input.

To solve it, you have to install a package called SublimeREPL. SublimeREPL provides a Python interpreter which accepts input.

There is an article that explains the solution in detail.

GitHub page for SublimeREPL

Not equal to != and !== in PHP

You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php

It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

Hot to get all form elements values using jQuery?

Add this on to the end of it:

var array = $("#hidAll").html();

x = array.split(',');
key=s="";
for (i=0; i<x.length; i++) {
  oldkey = key;
  key = x[i].split('|')[0];
  if (oldkey==key) s+='!';
  else s+=',\n'+key+'|';
  s+=x[i].split('|')[1];
}
s = s.substring(1);
$('#hidAll').html(a);

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

Git pushing to remote branch

git push --set-upstream origin <branch_name>_test

--set-upstream sets the association between your local branch and the remote. You only have to do it the first time. On subsequent pushes you can just do:

git push

If you don't have origin set yet, use:

git remote add origin <repository_url> then retry the above command.

How to get temporary folder for current user

I have this same requirement - we want to put logs in a specific root directory that should exist within the environment.

public static readonly string DefaultLogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

If I want to combine this with a sub-directory, I should be able to use Path.Combine( ... ).

The GetFolderPath method has an overload for special folder options which allows you to control whether the specified path be created or simply verified.

Updating and committing only a file's permissions using git version control

Not working for me.

The mode is true, the file perms have been changed, but git says there's no work to do.

git init
git add dir/file
chmod 440 dir/file
git commit -a

The problem seems to be that git recognizes only certain permission changes.

How to copy an object in Objective-C

I don't know the difference between that code and mine, but I have problems with that solution, so I read a little bit more and found that we have to set the object before return it. I mean something like:

#import <Foundation/Foundation.h>

@interface YourObject : NSObject <NSCopying>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *line;
@property (strong, nonatomic) NSMutableString *tags;
@property (strong, nonatomic) NSString *htmlSource;
@property (strong, nonatomic) NSMutableString *obj;

-(id) copyWithZone: (NSZone *) zone;

@end


@implementation YourObject


-(id) copyWithZone: (NSZone *) zone
{
    YourObject *copy = [[YourObject allocWithZone: zone] init];

    [copy setNombre: self.name];
    [copy setLinea: self.line];
    [copy setTags: self.tags];
    [copy setHtmlSource: self.htmlSource];

    return copy;
}

I added this answer because I have a lot of problems with this issue and I have no clue about why is it happening. I don't know the difference, but it's working for me and maybe it can be useful for others too : )

X-Frame-Options Allow-From multiple domains

Necromancing.
The provided answers are incomplete.

First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.

It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.

This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.

// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{

    public System.Web.HttpBrowserCapabilities Browser { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public string Platform { get; set; }
    public bool IsMobileDevice { get; set; }
    public string MobileBrand { get; set; }
    public string MobileModel { get; set; }


    public BrowserInfo(System.Web.HttpRequest request)
    {
        if (request.Browser != null)
        {
            if (request.UserAgent.Contains("Edge")
                && request.Browser.Browser != "Edge")
            {
                this.Name = "Edge";
            }
            else
            {
                this.Name = request.Browser.Browser;
                this.Version = request.Browser.MajorVersion.ToString();
            }
            this.Browser = request.Browser;
            this.Platform = request.Browser.Platform;
            this.IsMobileDevice = request.Browser.IsMobileDevice;
            if (IsMobileDevice)
            {
                this.Name = request.Browser.Browser;
            }
        }
    }


}


void context_EndRequest(object sender, System.EventArgs e)
{
    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

        try
        {
            // response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
            // response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            // response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");

            // response.AppendHeader("X-Frame-Options", "DENY");
            // response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
            // response.AppendHeader("X-Frame-Options", "AllowAll");

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                // "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome 
                string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
                            + System.Web.HttpContext.Current.Request.UrlReferrer.Authority
                ;

                string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
                string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;

                // SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);

                if (IsHostAllowed(refAuth))
                {
                    BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);

                    // bi.Name = Firefox
                    // bi.Name = InternetExplorer
                    // bi.Name = Chrome

                    // Chrome wants entire path... 
                    if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
                        response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);    

                    // unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
                    // unsafe-inline: styles
                    // data: url(data:image/png:...)

                    // https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
                    // https://www.ietf.org/rfc/rfc7034.txt
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

                    // https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
                    // https://content-security-policy.com/
                    // http://rehansaeed.com/content-security-policy-for-asp-net-mvc/

                    // This is for Chrome:
                    // response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);


                    System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
                    ls.Add("default-src");
                    ls.Add("'self'");
                    ls.Add("'unsafe-inline'");
                    ls.Add("'unsafe-eval'");
                    ls.Add("data:");

                    // http://az416426.vo.msecnd.net/scripts/a/ai.0.js

                    // ls.Add("*.msecnd.net");
                    // ls.Add("vortex.data.microsoft.com");

                    ls.Add(selfAuth);
                    ls.Add(refAuth);

                    string contentSecurityPolicy = string.Join(" ", ls.ToArray());
                    response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
                }
                else
                {
                    response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
                }

            }
            else
                response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
        }
        catch (System.Exception ex)
        {
            // WTF ? 
            System.Console.WriteLine(ex.Message); // Suppress warning
        }

    } // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)

} // End Using context_EndRequest


private static string[] s_allowedHosts = new string[] 
{
     "localhost:49533"
    ,"localhost:52257"
    ,"vmcompany1"
    ,"vmcompany2"
    ,"vmpostalservices"
    ,"example.com"
};


public static bool IsHostAllowed(string host)
{
    return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed 


public static bool Contains(string[] allowed, string current)
{
    for (int i = 0; i < allowed.Length; ++i)
    {
        if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
            return true;
    } // Next i 

    return false;
} // End Function Contains 

You need to register the context_EndRequest function in the HTTP-module Init function.

public class RequestLanguageChanger : System.Web.IHttpModule
{


    void System.Web.IHttpModule.Dispose()
    {
        // throw new NotImplementedException();
    }


    void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
    {
        // https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
        context.EndRequest += new System.EventHandler(context_EndRequest);
    }

    // context_EndRequest Code from above comes here


}

Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:

namespace ChangeRequestLanguage
{


    public class Global : System.Web.HttpApplication
    {

        System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();

        public override void Init()
        {
            mod.Init(this);
            base.Init();
        }



        protected void Application_Start(object sender, System.EventArgs e)
        {

        }

        protected void Session_Start(object sender, System.EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_Error(object sender, System.EventArgs e)
        {

        }

        protected void Session_End(object sender, System.EventArgs e)
        {

        }

        protected void Application_End(object sender, System.EventArgs e)
        {

        }


    }


}

or you can add entries to Web.config if you don't own the application source-code:

      <httpModules>
        <add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
      </httpModules>
    </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>

    <modules runAllManagedModulesForAllRequests="true">
      <add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
    </modules>
  </system.webServer>
</configuration>

The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.

The string in type is in the format "Namespace.Class, Assembly". Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like

"[DefaultNameSpace.Namespace].Class, Assembly"

If you want to avoid this problem, write the DLL in C#.

How to execute a shell script from C in Linux?

If you're ok with POSIX, you can also use popen()/pclose()

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

int main(void) {
/* ls -al | grep '^d' */
  FILE *pp;
  pp = popen("ls -al", "r");
  if (pp != NULL) {
    while (1) {
      char *line;
      char buf[1000];
      line = fgets(buf, sizeof buf, pp);
      if (line == NULL) break;
      if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
    }
    pclose(pp);
  }
  return 0;
}

unique object identifier in javascript

So far as my observation goes, any answer posted here can have unexpected side effects.

In ES2015-compatible enviroment, you can avoid any side effects by using WeakMap.

const id = (() => {
    let currentId = 0;
    const map = new WeakMap();

    return (object) => {
        if (!map.has(object)) {
            map.set(object, ++currentId);
        }

        return map.get(object);
    };
})();

id({}); //=> 1

Drawing rotated text on a HTML5 canvas

Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.

First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.

Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.

You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.

Why resize the canvas? I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display. For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);).

IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.

Hope this helps!

_x000D_
_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
_x000D_
_x000D_

Bitwise and in place of modulus operator

In this specific case (mod 7), we still can replace %7 with bitwise operators:

// Return X%7 for X >= 0.
int mod7(int x)
{
  while (x > 7) x = (x&7) + (x>>3);
  return (x == 7)?0:x;
}

It works because 8%7 = 1. Obviously, this code is probably less efficient than a simple x%7, and certainly less readable.

Number of days between two dates in Joda-Time

DateTime  dt  = new DateTime(laterDate);        

DateTime newDate = dt.minus( new  DateTime ( previousDate ).getMillis());

System.out.println("No of days : " + newDate.getDayOfYear() - 1 );    

Parsing a CSV file using NodeJS

I used this way:-

var fs = require('fs'); 
var parse = require('csv-parse');

var csvData=[];
fs.createReadStream(req.file.path)
    .pipe(parse({delimiter: ':'}))
    .on('data', function(csvrow) {
        console.log(csvrow);
        //do something with csvrow
        csvData.push(csvrow);        
    })
    .on('end',function() {
      //do something with csvData
      console.log(csvData);
    });

How to get the server path to the web directory in Symfony2 from inside the controller?

UPDATE: Since 2.8 this no longer works because assetic is no longer included by default. Although if you're using assetic this will work.

You can use the variable %assetic.write_to%.

$this->getParameter('assetic.write_to');

Since your assets depend on this variable to be dumped to your web directory, it's safe to assume and use to locate your web folder.

http://symfony.com/doc/current/reference/configuration/assetic.html

How can I check if a string contains ANY letters from the alphabet?

I tested each of the above methods for finding if any alphabets are contained in a given string and found out average processing time per string on a standard computer.

~250 ns for

import re

~3 ”s for

re.search('[a-zA-Z]', string)

~6 ”s for

any(c.isalpha() for c in string)

~850 ns for

string.upper().isupper()


Opposite to as alleged, importing re takes negligible time, and searching with re takes just about half time as compared to iterating isalpha() even for a relatively small string.
Hence for larger strings and greater counts, re would be significantly more efficient.

But converting string to a case and checking case (i.e. any of upper().isupper() or lower().islower() ) wins here. In every loop it is significantly faster than re.search() and it doesn't even require any additional imports.

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Sounds like you want a simple imagemap, I'd recommend to not make it more complex than it needs to be. Here's an article on how to improve imagemaps with svg. It's very easy to do clickable regions in svg itself, just add some <a> elements around the shapes you want to have clickable.

A couple of options if you need something more advanced:

What is EOF in the C programming language?

Couple of typos:

while((c = getchar())!= EOF)

in place of:

while((c = getchar() != EOF))

Also getchar() treats a return key as a valid input, so you need to buffer it too.EOF is a marker to indicate end of input. Generally it is an int with all bits set.


#include <stdio.h>
int main()
{
 int c;
 while((c = getchar())!= EOF)
 {
  if( getchar() == EOF )
    break;
  printf(" %d\n", c);
 }
  printf("%d %u %x- at EOF\n", c , c, c);
}

prints:

49
50
-1 4294967295 ffffffff- at EOF

for input:

1
2
<ctrl-d>

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

Is there a way to get rid of accents and convert a whole string to regular letters?

I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.

Passing null arguments to C# methods

From C# 2.0:

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

How to make an introduction page with Doxygen

Following syntax may help for adding a main page and related subpages for doxygen:

/*! \mainpage Drawing Shapes
 *
 * This project helps user to draw shapes.
 * Currently two types of shapes can be drawn:
 * - \subpage drawingRectanglePage "How to draw rectangle?"
 *
 * - \subpage drawingCirclePage "How to draw circle?"
 *
 */ 

/*! \page drawingRectanglePage How to draw rectangle?
 *
 * Lorem ipsum dolor sit amet
 *
 */

/*! \page drawingCirclePage How to draw circle?
 *
 * This page is about how to draw a circle.
 * Following sections describe circle:
 * - \ref groupCircleDefinition "Definition of Circle"
 * - \ref groupCircleClass "Circle Class"
 */

Creating groups as following also help for designing pages:

/** \defgroup groupCircleDefinition Circle Definition
 * A circle is a simple shape in Euclidean geometry.
 * It is the set of all points in a plane that are at a given distance from a given point, the centre;
 * equivalently it is the curve traced out by a point that moves so that its distance from a given point is constant.
 * The distance between any of the points and the centre is called the radius.
 */

An example can be found here

Git push existing repo to a new and different remote repo server?

  1. Create a new repo at github.
  2. Clone the repo from fedorahosted to your local machine.
  3. git remote rename origin upstream
  4. git remote add origin URL_TO_GITHUB_REPO
  5. git push origin master

Now you can work with it just like any other github repo. To pull in patches from upstream, simply run git pull upstream master && git push origin master.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

As of Swift 2.0, you can add a protocol extension. In my opinion, this is a better approach because the return type is Self rather than UIView, so the caller doesn't need to cast to the view class.

import UIKit

protocol UIViewLoading {}
extension UIView : UIViewLoading {}

extension UIViewLoading where Self : UIView {

  // note that this method returns an instance of type `Self`, rather than UIView
  static func loadFromNib() -> Self {
    let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
    let nib = UINib(nibName: nibName, bundle: nil)
    return nib.instantiateWithOwner(self, options: nil).first as! Self
  }

}

What is the email subject length limit?

RFC2322 states that the subject header "has no length restriction"

but to produce long headers but you need to split it across multiple lines, a process called "folding".

subject is defined as "unstructured" in RFC 5322

here's some quotes ([...] indicate stuff i omitted)

3.6.5. Informational Fields
  The informational fields are all optional.  The "Subject:" and
  "Comments:" fields are unstructured fields as defined in section
  2.2.1, [...]

2.2.1. Unstructured Header Field Bodies
  Some field bodies in this specification are defined simply as
  "unstructured" (which is specified in section 3.2.5 as any printable
  US-ASCII characters plus white space characters) with no further
  restrictions.  These are referred to as unstructured field bodies.
  Semantically, unstructured field bodies are simply to be treated as a
  single line of characters with no further processing (except for
  "folding" and "unfolding" as described in section 2.2.3).

2.2.3  [...]  An unfolded header field has no length restriction and
  therefore may be indeterminately long.

How to find longest string in the table column data

You can:

SELECT CR 
FROM table1 
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)

Having just recieved an upvote more than a year after posting this, I'd like to add some information.

  • This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not desired.
  • This query must probably read the table twice: a full table scan to get the maximum length and another full table scan to get all values of that length. These operations, however, are very simple operations and hence rather fast. With a TOP 1 query a DBMS reads all records from the table and then sorts them. So the table is read only once, but a sort operation on a whole table is quite some task and can be very slow on large tables.
  • One would usually add DISTINCT to my query (SELECT DISTINCT CR FROM ...), so as to get every value just once. That would be a sort operation, but only on the few records already found. Again, no big deal.
  • If the string lengths have to be dealt with quite often, one might think of creating a computed column (calculated field) for it. This is available as of Ms Access 2010. But reading up on this shows that you cannot index calculated fields in MS Access. As long as this holds true, there is hardly any benefit from them. Applying LEN on the strings is usually not what makes such queries slow.

Setting HTTP headers

Do not use '*' for Origin, until You really need a completely public behavior.
As Wikipedia says:

"The value of "*" is special in that it does not allow requests to supply credentials, meaning HTTP authentication, client-side SSL certificates, nor does it allow cookies to be sent."

That means, you'll get a lot of errors, especially in Chrome when you'll try to implement for example a simple authentication.

Here is a corrected wrapper:

// Code has not been tested.
func addDefaultHeaders(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if origin := r.Header.Get("Origin"); origin != "" {
            w.Header().Set("Access-Control-Allow-Origin", origin)
        }
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token")
        w.Header().Set("Access-Control-Allow-Credentials", "true")
        fn(w, r)
    }
}

And don't forget to reply all these headers to the preflight OPTIONS request.

Daylight saving time and time zone best practices

One other thing, make sure the servers have the up to date daylight savings patch applied.

We had a situation last year where our times were consistently out by one hour for a three-week period for North American users, even though we were using a UTC based system.

It turns out in the end it was the servers. They just needed an up-to-date patch applied (Windows Server 2003).

javac : command not found

Worked for me with this command:

yum install java-devel

How to convert minutes to hours/minutes and add various time values together using jQuery?

This code can be used with timezone

javascript:

_x000D_
_x000D_
let minToHm = (m) => {_x000D_
  let h = Math.floor(m / 60);_x000D_
  h += (h < 0) ? 1 : 0;_x000D_
  let m2 = Math.abs(m % 60);_x000D_
  m2 = (m2 < 10) ? '0' + m2 : m2;_x000D_
  return (h < 0 ? '' : '+') + h + ':' + m2;_x000D_
}_x000D_
_x000D_
console.log(minToHm(210)) // "+3:30"_x000D_
console.log(minToHm(-210)) // "-3:30"_x000D_
console.log(minToHm(0)) // "+0:00"
_x000D_
_x000D_
_x000D_

minToHm(210)
"+3:30"

minToHm(-210)
"-3:30"

minToHm(0)
"+0:00"

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Go to Eclipse --> Help

and click--->Install new software

then you can see a window ...There a click add

Then put below url in url box: http://download.eclipse.org/webtools/repository/juno/

i am having juno

if u have any other means put that name . then click ok.

S3 Static Website Hosting Route All Paths to Index.html

It's tangential, but here's a tip for those using Rackt's React Router library with (HTML5) browser history who want to host on S3.

Suppose a user visits /foo/bear at your S3-hosted static web site. Given David's earlier suggestion, redirect rules will send them to /#/foo/bear. If your application's built using browser history, this won't do much good. However your application is loaded at this point and it can now manipulate history.

Including Rackt history in our project (see also Using Custom Histories from the React Router project), you can add a listener that's aware of hash history paths and replace the path as appropriate, as illustrated in this example:

import ReactDOM from 'react-dom';

/* Application-specific details. */
const route = {};

import { Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';

const history = useRouterHistory(createHistory)();

history.listen(function (location) {
  const path = (/#(\/.*)$/.exec(location.hash) || [])[1];
  if (path) history.replace(path);
});

ReactDOM.render(
  <Router history={history} routes={route}/>,
  document.body.appendChild(document.createElement('div'))
);

To recap:

  1. David's S3 redirect rule will direct /foo/bear to /#/foo/bear.
  2. Your application will load.
  3. The history listener will detect the #/foo/bear history notation.
  4. And replace history with the correct path.

Link tags will work as expected, as will all other browser history functions. The only downside I've noticed is the interstitial redirect that occurs on initial request.

This was inspired by a solution for AngularJS, and I suspect could be easily adapted to any application.

what is the use of $this->uri->segment(3) in codeigniter pagination

Let's say you have a url like this http://www.example.com/controller/action/arg1/arg2

If you want to know what are the arguments that are being passed in this url

$param_offset=0;
$params = array_slice($this->uri->rsegment_array(), $param_offset);
var_dump($params);

Output will be:

array (size=2)
  0 => string 'arg1'
  1 => string 'arg2'

What does PermGen actually stand for?

Not really related match to the original question, but may be someone will find it useful. PermGen is indeed an area in memory where Java used to keep its classes. So, many of us have came across OOM in PermGen, if there were, for example a lot of classes.

Since Java 8, PermGen area has been replaced by MetaSpace area, which is more efficient and is unlimited by default (or more precisely - limited by amount of native memory, depending on 32 or 64 bit jvm and OS virtual memory availability) . However it is possible to tune it in some ways, by for example specifying a max limit for the area. You can find more useful information in this blog post.

angular.js ng-repeat li items with html content

ng-bind-html-unsafe is deprecated from 1.2. The correct answer should be currently:

HTML-side: (the same as the accepted answer stated):

<div ng-app ng-controller="MyCtrl">
   <ul>
      <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
        {{ opt.text }}
      </li>
   </ul>

   <p>{{opt}}</p>
</div>

But in the controller-side:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
// ...
   $scope.opts.map(function(opt) { 
      opt = $sce.trustAsHtml(opt);
   });
}

How can I write a byte array to a file in Java?

No need for external libs to bloat things - especially when working with Android. Here is a native solution that does the trick. This is a pice of code from an app that stores a byte array as an image file.

    // Byte array with image data.
    final byte[] imageData = params[0];

    // Write bytes to tmp file.
    final File tmpImageFile = new File(ApplicationContext.getInstance().getCacheDir(), "scan.jpg");
    FileOutputStream tmpOutputStream = null;
    try {
        tmpOutputStream = new FileOutputStream(tmpImageFile);
        tmpOutputStream.write(imageData);
        Log.d(TAG, "File successfully written to tmp file");
    }
    catch (FileNotFoundException e) {
        Log.e(TAG, "FileNotFoundException: " + e);
        return null;
    }
    catch (IOException e) {
        Log.e(TAG, "IOException: " + e);
        return null;
    }
    finally {
        if(tmpOutputStream != null)
            try {
                tmpOutputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e);
            }
    }

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

How to convert CharSequence to String?

By invoking its toString() method.

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

Uploading an Excel sheet and importing the data into SQL Server database

using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;

protected void Button1_Click(object sender, EventArgs e)

{

    //Upload and save the file

    string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);

    FileUpload1.SaveAs(excelPath);



    string conString = string.Empty;

    string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);

    switch (extension)

    {

        case ".xls": //Excel 97-03

            conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;

            break;

        case ".xlsx": //Excel 07 or higher

            conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;

            break;



    }

    conString = string.Format(conString, excelPath);

    using (OleDbConnection excel_con = new OleDbConnection(conString))

    {

        excel_con.Open();

        string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();

        DataTable dtExcelData = new DataTable();



        //[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.

        dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),

            new DataColumn("Name", typeof(string)) });



        using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))

        {

            oda.Fill(dtExcelData);

        }

        excel_con.Close();



        string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;

        using (SqlConnection con = new SqlConnection(consString))

        {

            using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))

            {

                //Set the database table name

                sqlBulkCopy.DestinationTableName = "dbo.Table1";



                //[OPTIONAL]: Map the Excel columns with that of the database table

                sqlBulkCopy.ColumnMappings.Add("Sl", "Id");

                sqlBulkCopy.ColumnMappings.Add("Name", "Name");

                con.Open();

                sqlBulkCopy.WriteToServer(dtExcelData);

                con.Close();

            }

        }

    }

}

Copy this in web config

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html

Get the generated SQL statement from a SqlCommand object?

I needed a similar command to string transformer to allow for more verbose logging, so I wrote this one. It will produce the text needed to re-execute the command in a new session including output parameters and structured parameters. It is lightly tested, but caveat emptor.

Example:

SqlCommand cmd = new SqlCommand("GetEntity", con);
cmd.Parameters.AddWithValue("@foobar", 1);
cmd.Parameters.Add(new SqlParameter(){
    ParameterName = "@outParam",
    Direction = ParameterDirection.Output,
    SqlDbType = System.Data.SqlDbType.Int
});
cmd.Parameters.Add(new SqlParameter(){
    Direction = ParameterDirection.ReturnValue
});
cmd.CommandType = CommandType.StoredProcedure;

Will produce:

-- BEGIN COMMAND
DECLARE @foobar INT = 1;
DECLARE @outParam INT = NULL;
DECLARE @returnValue INT;
-- END PARAMS
EXEC @returnValue = GetEntity @foobar = @foobar, @outParam = @outParam OUTPUT
-- RESULTS
SELECT 1 as Executed, @returnValue as ReturnValue, @outParam as [@outParam];
-- END COMMAND

Implementation:

public class SqlCommandDumper
{
    public static string GetCommandText(SqlCommand sqc)
    {
        StringBuilder sbCommandText = new StringBuilder();

        sbCommandText.AppendLine("-- BEGIN COMMAND");

        // params
        for (int i = 0; i < sqc.Parameters.Count; i++)
            logParameterToSqlBatch(sqc.Parameters[i], sbCommandText);
        sbCommandText.AppendLine("-- END PARAMS");

        // command
        if (sqc.CommandType == CommandType.StoredProcedure)
        {
            sbCommandText.Append("EXEC ");

            bool hasReturnValue = false;
            for (int i = 0; i < sqc.Parameters.Count; i++)
            {
                if (sqc.Parameters[i].Direction == ParameterDirection.ReturnValue)
                    hasReturnValue = true;
            }
            if (hasReturnValue)
            {
                sbCommandText.Append("@returnValue = ");
            }

            sbCommandText.Append(sqc.CommandText);

            bool hasPrev = false;
            for (int i = 0; i < sqc.Parameters.Count; i++)
            {
                var cParam = sqc.Parameters[i];
                if (cParam.Direction != ParameterDirection.ReturnValue)
                {
                    if (hasPrev)
                        sbCommandText.Append(", ");

                    sbCommandText.Append(cParam.ParameterName);
                    sbCommandText.Append(" = ");
                    sbCommandText.Append(cParam.ParameterName);

                    if (cParam.Direction.HasFlag(ParameterDirection.Output))
                        sbCommandText.Append(" OUTPUT");

                    hasPrev = true;
                }
            }
        }
        else
        {
            sbCommandText.AppendLine(sqc.CommandText);
        }

        sbCommandText.AppendLine("-- RESULTS");
        sbCommandText.Append("SELECT 1 as Executed");
        for (int i = 0; i < sqc.Parameters.Count; i++)
        {
            var cParam = sqc.Parameters[i];

            if (cParam.Direction == ParameterDirection.ReturnValue)
            {
                sbCommandText.Append(", @returnValue as ReturnValue");
            }
            else if (cParam.Direction.HasFlag(ParameterDirection.Output))
            {
                sbCommandText.Append(", ");
                sbCommandText.Append(cParam.ParameterName);
                sbCommandText.Append(" as [");
                sbCommandText.Append(cParam.ParameterName);
                sbCommandText.Append(']');
            }
        }
        sbCommandText.AppendLine(";");

        sbCommandText.AppendLine("-- END COMMAND");
        return sbCommandText.ToString();
    }

    private static void logParameterToSqlBatch(SqlParameter param, StringBuilder sbCommandText)
    {
        sbCommandText.Append("DECLARE ");
        if (param.Direction == ParameterDirection.ReturnValue)
        {
            sbCommandText.AppendLine("@returnValue INT;");
        }
        else
        {
            sbCommandText.Append(param.ParameterName);

            sbCommandText.Append(' ');
            if (param.SqlDbType != SqlDbType.Structured)
            {
                logParameterType(param, sbCommandText);
                sbCommandText.Append(" = ");
                logQuotedParameterValue(param.Value, sbCommandText);

                sbCommandText.AppendLine(";");
            }
            else
            {
                logStructuredParameter(param, sbCommandText);
            }
        }
    }

    private static void logStructuredParameter(SqlParameter param, StringBuilder sbCommandText)
    {
        sbCommandText.AppendLine(" {List Type};");
        var dataTable = (DataTable)param.Value;

        for (int rowNo = 0; rowNo < dataTable.Rows.Count; rowNo++)
        {
            sbCommandText.Append("INSERT INTO ");
            sbCommandText.Append(param.ParameterName);
            sbCommandText.Append(" VALUES (");

            bool hasPrev = false;
            for (int colNo = 0; colNo < dataTable.Columns.Count; colNo++)
            {
                if (hasPrev)
                {
                    sbCommandText.Append(", ");
                }
                logQuotedParameterValue(dataTable.Rows[rowNo].ItemArray[colNo], sbCommandText);
                hasPrev = true;
            }
            sbCommandText.AppendLine(");");
        }
    }

    const string DATETIME_FORMAT_ROUNDTRIP = "o";
    private static void logQuotedParameterValue(object value, StringBuilder sbCommandText)
    {
        try
        {
            if (value == null)
            {
                sbCommandText.Append("NULL");
            }
            else
            {
                value = unboxNullable(value);

                if (value is string
                    || value is char
                    || value is char[]
                    || value is System.Xml.Linq.XElement
                    || value is System.Xml.Linq.XDocument)
                {
                    sbCommandText.Append("N'");
                    sbCommandText.Append(value.ToString().Replace("'", "''"));
                    sbCommandText.Append('\'');
                }
                else if (value is bool)
                {
                    // True -> 1, False -> 0
                    sbCommandText.Append(Convert.ToInt32(value));
                }
                else if (value is sbyte
                    || value is byte
                    || value is short
                    || value is ushort
                    || value is int
                    || value is uint
                    || value is long
                    || value is ulong
                    || value is float
                    || value is double
                    || value is decimal)
                {
                    sbCommandText.Append(value.ToString());
                }
                else if (value is DateTime)
                {
                    // SQL Server only supports ISO8601 with 3 digit precision on datetime,
                    // datetime2 (>= SQL Server 2008) parses the .net format, and will 
                    // implicitly cast down to datetime.
                    // Alternatively, use the format string "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"
                    // to match SQL server parsing
                    sbCommandText.Append("CAST('");
                    sbCommandText.Append(((DateTime)value).ToString(DATETIME_FORMAT_ROUNDTRIP));
                    sbCommandText.Append("' as datetime2)");
                }
                else if (value is DateTimeOffset)
                {
                    sbCommandText.Append('\'');
                    sbCommandText.Append(((DateTimeOffset)value).ToString(DATETIME_FORMAT_ROUNDTRIP));
                    sbCommandText.Append('\'');
                }
                else if (value is Guid)
                {
                    sbCommandText.Append('\'');
                    sbCommandText.Append(((Guid)value).ToString());
                    sbCommandText.Append('\'');
                }
                else if (value is byte[])
                {
                    var data = (byte[])value;
                    if (data.Length == 0)
                    {
                        sbCommandText.Append("NULL");
                    }
                    else
                    {
                        sbCommandText.Append("0x");
                        for (int i = 0; i < data.Length; i++)
                        {
                            sbCommandText.Append(data[i].ToString("h2"));
                        }
                    }
                }
                else
                {
                    sbCommandText.Append("/* UNKNOWN DATATYPE: ");
                    sbCommandText.Append(value.GetType().ToString());
                    sbCommandText.Append(" *" + "/ N'");
                    sbCommandText.Append(value.ToString());
                    sbCommandText.Append('\'');
                }
            }
        }

        catch (Exception ex)
        {
            sbCommandText.AppendLine("/* Exception occurred while converting parameter: ");
            sbCommandText.AppendLine(ex.ToString());
            sbCommandText.AppendLine("*/");
        }
    }

    private static object unboxNullable(object value)
    {
        var typeOriginal = value.GetType();
        if (typeOriginal.IsGenericType
            && typeOriginal.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            // generic value, unboxing needed
            return typeOriginal.InvokeMember("GetValueOrDefault",
                System.Reflection.BindingFlags.Public |
                System.Reflection.BindingFlags.Instance |
                System.Reflection.BindingFlags.InvokeMethod,
                null, value, null);
        }
        else
        {
            return value;
        }
    }

    private static void logParameterType(SqlParameter param, StringBuilder sbCommandText)
    {
        switch (param.SqlDbType)
        {
            // variable length
            case SqlDbType.Char:
            case SqlDbType.NChar:
            case SqlDbType.Binary:
                {
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                    sbCommandText.Append('(');
                    sbCommandText.Append(param.Size);
                    sbCommandText.Append(')');
                }
                break;
            case SqlDbType.VarChar:
            case SqlDbType.NVarChar:
            case SqlDbType.VarBinary:
                {
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                    sbCommandText.Append("(MAX /* Specified as ");
                    sbCommandText.Append(param.Size);
                    sbCommandText.Append(" */)");
                }
                break;
            // fixed length
            case SqlDbType.Text:
            case SqlDbType.NText:
            case SqlDbType.Bit:
            case SqlDbType.TinyInt:
            case SqlDbType.SmallInt:
            case SqlDbType.Int:
            case SqlDbType.BigInt:
            case SqlDbType.SmallMoney:
            case SqlDbType.Money:
            case SqlDbType.Decimal:
            case SqlDbType.Real:
            case SqlDbType.Float:
            case SqlDbType.Date:
            case SqlDbType.DateTime:
            case SqlDbType.DateTime2:
            case SqlDbType.DateTimeOffset:
            case SqlDbType.UniqueIdentifier:
            case SqlDbType.Image:
                {
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                }
                break;
            // Unknown
            case SqlDbType.Timestamp:
            default:
                {
                    sbCommandText.Append("/* UNKNOWN DATATYPE: ");
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                    sbCommandText.Append(" *" + "/ ");
                    sbCommandText.Append(param.SqlDbType.ToString().ToUpper());
                }
                break;
        }
    }
}

jQuery ajax request with json response, how to?

Firstly, it will help if you set the headers of your PHP to serve JSON:

header('Content-type: application/json');

Secondly, it will help to adjust your ajax call:

$.ajax({
    url: "main.php",
    type: "POST",
    dataType: "json",
    data: {"action": "loadall", "id": id},
    success: function(data){
        console.log(data);
    },
    error: function(error){
         console.log("Error:");
         console.log(error);
    }
});

If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.

NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).

Django download a file

You can add "download" attribute inside your tag to download files.

<a  href="/project/download" download> Download Document </a>

https://www.w3schools.com/tags/att_a_download.asp

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

In a private project a wrote this filter

angular.module('myApp')
    .filter('isEmpty', function () {
        var bar;
        return function (obj) {
            for (bar in obj) {
                if (obj.hasOwnProperty(bar)) {
                    return false;
                }
            }
            return true;
        };
    });

usage:

<p ng-hide="items | isEmpty">Some Content</p>

testing:

describe('Filter: isEmpty', function () {

    // load the filter's module
    beforeEach(module('myApp'));

    // initialize a new instance of the filter before each test
    var isEmpty;
    beforeEach(inject(function ($filter) {
        isEmpty = $filter('isEmpty');
    }));

    it('should return the input prefixed with "isEmpty filter:"', function () {
          expect(isEmpty({})).toBe(true);
          expect(isEmpty({foo: "bar"})).toBe(false);
    });

});

regards.

Python can't find module in the same folder

Your code is fine, I suspect your problem is how you are launching it.

You need to launch python from your '2014_07_13_test' directory.

Open up a command prompt and 'cd' into your '2014_07_13_test' directory.

For instance:

$ cd /path/to/2014_07_13_test
$ python test.py

If you cannot 'cd' into the directory like this you can add it to sys.path

In test.py:

import sys, os
sys.path.append('/path/to/2014_07_13_test')

Or set/edit the PYTHONPATH

And all should be well...

...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'

There is a better shebang you should use.

Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.

how can I check if a file exists?

an existing folder will FAIL with FileExists

Function FileExists(strFileName)
' Check if a file exists - returns True or False

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

How to add an extra source directory for maven to compile and include in the build jar?

With recent Maven versions (3) and recent version of the maven compiler plugin (3.7.0), I notice that adding a source folder with the build-helper-maven-plugin is not required if the folder that contains the source code to add in the build is located in the target folder or a subfolder of it.
It seems that the compiler maven plugin compiles any java source code located inside this folder whatever the directory that contains them.
For example having some (generated or no) source code in target/a, target/generated-source/foo will be compiled and added in the outputDirectory : target/classes.

Good Free Alternative To MS Access

VistaDB is the only alternative if you going to run your website at shared hosting (almost all of them won't let you run your websites under Full Trust mode) and also if you need simple x-copy deployment enabled website.

How to fix broken paste clipboard in VNC on Windows

I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).

  1. I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.

    [Desktop Entry]
    Name=No name
    Encoding=UTF-8
    Version=1.0
    Exec=vncconfig -nowin
    X-GNOME-Autostart-enabled=true

  2. Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.

  3. Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.

What is the best collation to use for MySQL with PHP?

Be very, very aware of this problem that can occur when using utf8_general_ci.

MySQL will not distinguish between some characters in select statements, if the utf8_general_ci collation is used. This can lead to very nasty bugs - especially for example, where usernames are involved. Depending on the implementation that uses the database tables, this problem could allow malicious users to create a username matching an administrator account.

This problem exposes itself at the very least in early 5.x versions - I'm not sure if this behaviour as changed later.

I'm no DBA, but to avoid this problem, I always go with utf8-bin instead of a case-insensitive one.

The script below describes the problem by example.

-- first, create a sandbox to play in
CREATE DATABASE `sandbox`;
use `sandbox`;

-- next, make sure that your client connection is of the same 
-- character/collate type as the one we're going to test next:
charset utf8 collate utf8_general_ci

-- now, create the table and fill it with values
CREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )
    CHARACTER SET utf8 COLLATE utf8_general_ci;

INSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valĂșe');

-- (verify)
SELECT * FROM `test`;

-- now, expose the problem/bug:
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get BOTH keys here! MySQLs UTF8 collates that are 
-- case insensitive (ending with _ci) do not distinguish between 
-- both values!
--
-- collate 'utf8_bin' doesn't have this problem, as I'll show next:
--

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get just one key now, as you'd expect.
--
-- This problem appears to be specific to utf8. Next, I'll try to 
-- do the same with the 'latin1' charset:
--

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_general_ci

-- next, convert the values that we've previously inserted
-- in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected). This shows 
-- that the problem with utf8/utf8_generic_ci isn't present 
-- in latin1/latin1_general_ci
--
-- To complete the example, I'll check with the binary collate
-- of latin1 as well:

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected).
--
-- Finally, I'll re-introduce the problem in the exact same 
-- way (for any sceptics out there):

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_generic_ci

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

-- now, re-check for the problem/bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Two keys.
--

DROP DATABASE sandbox;

How do you open an SDF file (SQL Server Compact Edition)?

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

Localhost not working in chrome and firefox

Steps

  1. Search IIS In Visual Studio 2015 Search IIS image

  2. Chose (Use the 64 bit of version of IIS Express for web site and project Use 64 bit image )

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

How to best display in Terminal a MySQL SELECT returning too many fields?

I wrote pspg - https://github.com/okbob/pspg

This pager is designed for tabular data - and MySQL is supported too.

MariaDB [sakila]> pager pspg -s 14 -X --force-uniborder --quit-if-one-screen
PAGER set to 'pspg -s 14 -X --force-uniborder --quit-if-one-screen'
MariaDB [sakila]> select now();
MariaDB [sakila]> select * from nicer_but_slower_film_list limit 100;

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How to execute .sql script file using JDBC

You can read the script line per line with a BufferedReader and append every line to a StringBuilder so that the script becomes one large string.

Then you can create a Statement object using JDBC and call statement.execute(stringBuilder.toString()).

What is the opposite of evt.preventDefault();

You can always use this attached to some click event in your script:

location.href = this.href;

example of usage is:

jQuery('a').click(function(e) {
    location.href = this.href;
});

why windows 7 task scheduler task fails with error 2147942667

This can happen for more than one reason. In my case this happened due to a permissions issue. The user that the task was running as didn't have permission to write to the logs directory so it failed with this error.

how to set default method argument values?

You can't declare default values for the parameters like C# (I believe) lets you, but you could simply just create an overload.

public int doSomething(int arg1, int arg2) {
    //some logic here
    return 0;
}

//overload supplies default values of 1 and 2
public int doSomething() {
    return doSomething(1, 2);
}

If you are going to do something like this please do everyone else who works with your code a favor and make sure you mention in Javadoc comments what the default values you are using are!

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

Max length UITextField

Swift 5

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let MAX_LENGTH = 4
        let updatedString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        return updatedString.count <= MAX_LENGTH
    }

Writing to a TextBox from another thread?

I would use BeginInvoke instead of Invoke as often as possible, unless you are really required to wait until your control has been updated (which in your example is not the case). BeginInvoke posts the delegate on the WinForms message queue and lets the calling code proceed immediately (in your case the for-loop in the SampleFunction). Invoke not only posts the delegate, but also waits until it has been completed.

So in the method AppendTextBox from your example you would replace Invoke with BeginInvoke like that:

public void AppendTextBox(string value)
{
    if (InvokeRequired)
    {
        this.BeginInvoke(new Action<string>(AppendTextBox), new object[] {value});
        return;
    }
    textBox1.Text += value;
}

Well and if you want to get even more fancy, there is also the SynchronizationContext class, which lets you basically do the same as Control.Invoke/Control.BeginInvoke, but with the advantage of not needing a WinForms control reference to be known. Here is a small tutorial on SynchronizationContext.

Why is &#65279; appearing in my HTML?

If you have a lot of files to review, you can use this tool: https://www.mannaz.at/codebase/utf-byte-order-mark-bom-remover/

Credits to Maurice

It help me to clean a system, with MVC in CakePhp, as i work in Linux, Windows, with different tools.. in some files my design was break.. so after checkin in Chrome with debug tool find the &#65279 error

How to stop a function

In this example, the line do_something_else() will not be executed if do_not_continue is True. Control will return, instead, to whichever function called some_function.

def some_function():
    if do_not_continue:
        return  # implicitly, this is the same as saying `return None` 
    do_something_else()

Where does application data file actually stored on android device?

This is a simple way to identify the application related storage paths of a particular app.

Steps:

  1. Have the android device connected to your mac or android emulator open
  2. Open the terminal
  3. adb shell
  4. find .

The "find ." command will list all the files with their paths in the terminal.

./apex/com.android.media.swcodec
./apex/com.android.media.swcodec/etc
./apex/com.android.media.swcodec/etc/init.rc
./apex/com.android.media.swcodec/etc/seccomp_policy
./apex/com.android.media.swcodec/etc/seccomp_policy/mediaswcodec.policy
./apex/com.android.media.swcodec/etc/ld.config.txt
./apex/com.android.media.swcodec/etc/media_codecs.xml
./apex/com.android.media.swcodec/apex_manifest.json
./apex/com.android.media.swcodec/lib
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_common.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_vorbisdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263dec.so
./apex/com.android.media.swcodec/lib/libhidltransport.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263enc.so
./apex/com.android.media.swcodec/lib/libcodec2_vndk.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libmedia_codecserviceregistrant.so
./apex/com.android.media.swcodec/lib/libhidlbase.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_aacdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_vp9dec.so
.....

After this, just search for your app with the bundle identifier and you can use adb pull command to download the files to your local directory.

How to style a clicked button in CSS

There are three states of button

  • Normal : You can select like this button
  • Hover : You can select like this button:hover
  • Pressed/Clicked : You can select like this button:active

Normal:

.button
 {
     //your css
 }

Active

 .button:active
{
        //your css
}

Hover

 .button:hover
{
        //your css
}

SNIPPET:

Use :active to style the active state of button.

_x000D_
_x000D_
button:active{_x000D_
   background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
_x000D_
_x000D_