Programs & Examples On #Traffic

Term used to refer to the amount or flow of data around a network or website

What HTTP traffic monitor would you recommend for Windows?

I now use CharlesProxy for development, but previously I have used Fiddler

Android emulator: How to monitor network traffic?

For OS X you can use Charles, it's simple and easy to use.

For more information, please have a look at Android Emulator and Charles Proxy blog post.

Add UIPickerView & a Button in Action sheet - How?

One more solution:

  • no toolbar but a segmented control (eyecandy)

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                        delegate:nil
                                                        cancelButtonTitle:nil
                                                        destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
    
    [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    
    [actionSheet addSubview:pickerView];
    [pickerView release];
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:closeButton];
    [closeButton release];
    
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
    

How to run a Python script in the background even after I logout SSH?

If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.

Ctrl+Z (suspend the process)

bg (restart the process in the background

disown %1 (assuming this is job #1, use jobs to determine)

Change/Get check state of CheckBox

I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:

<td>
    <input type="radio" name="bob" />
</td>

You can easily get/set checked state as such:

$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!

Importing a Maven project into Eclipse from Git

I have been testing this out for my project.

  1. Eclispe Indigo
  2. "Help > Install New Software" Enable/Install official Git plug-ins at "Eclipse Git Plugin .." and install the lot.
  3. Enable the Maven/EGit connector with these instructions How do you get git integration working with m2eclipse?
  4. Switch to the Git Repository perspective. Right click paste the project git url. The defaults should all work. You may want to change the install folder it guesses.
  5. Expand the cloned repository and right click on "Working Tree" and pick "Import Maven Projects...".
  6. Switch to the Java perspective. Right click on the project and choose "Team > Share Project". Select "Git" and be sure to tick the box "Use or create repository in parent folder of project".

Hide Button After Click (With Existing Form on Page)

CSS code:

.hide{
display:none;
}

.show{
display:block;
}

Html code:

<button onclick="block_none()">Check Availability</button>

Javascript Code:

function block_none(){
 document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}

SQL Server: SELECT only the rows with MAX(DATE)

The best way is Mikael Eriksson, if ROW_NUMBER() is available to you.

The next best is to join on a query, as per Cularis' answer.

Alternatively, the most simple and straight forward way is a correlated-sub-query in the WHERE clause.

SELECT
  *
FROM
  yourTable AS [data]
WHERE
  DateEntered = (SELECT MAX(DateEntered) FROM yourTable WHERE orderNo = [data].orderNo)

Or...

WHERE
  ID = (SELECT TOP 1 ID FROM yourTable WHERE orderNo = [data].orderNo ORDER BY DateEntered DESC)

Gradle finds wrong JAVA_HOME even though it's correctly set

If your GRADLE_HOME and JAVA_HOME environment are set properly then check your JDK directory and make sure you have java.exe file under below path.

C:\Program Files (x86)\Java\jdk1.8.0_181\bin

As error mentioned in gradle.bat file

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

It is not able to locate your java installation. So find and set

java.exe

under %JAVA_HOME%/bin if everything is correct.

This works for me (my account got disabled by client and their admin has removed java.exe from my directory.)

How to redirect to another page using PHP

The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.

If the login is valid you'll redirect using the "header" function.

Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.

<?php
ob_start();
if (FORMPOST) {
    if (POSTED_DATA_VALID) {
        header("Location: https://www.yoursite.com/profile/");
        ob_end_flush();
        exit;
    }
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>

Change directory command in Docker?

I was wondering if two times WORKDIR will work or not, but it worked :)

FROM ubuntu:18.04

RUN apt-get update && \
    apt-get install -y python3.6

WORKDIR /usr/src

COPY ./ ./

WORKDIR /usr/src/src

CMD ["python3", "app.py"]

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

How to split data into 3 sets (train, validation and test)?

Here is a Python function that splits a Pandas dataframe into train, validation, and test dataframes with stratified sampling. It performs this split by calling scikit-learn's function train_test_split() twice.

import pandas as pd
from sklearn.model_selection import train_test_split

def split_stratified_into_train_val_test(df_input, stratify_colname='y',
                                         frac_train=0.6, frac_val=0.15, frac_test=0.25,
                                         random_state=None):
    '''
    Splits a Pandas dataframe into three subsets (train, val, and test)
    following fractional ratios provided by the user, where each subset is
    stratified by the values in a specific column (that is, each subset has
    the same relative frequency of the values in the column). It performs this
    splitting by running train_test_split() twice.

    Parameters
    ----------
    df_input : Pandas dataframe
        Input dataframe to be split.
    stratify_colname : str
        The name of the column that will be used for stratification. Usually
        this column would be for the label.
    frac_train : float
    frac_val   : float
    frac_test  : float
        The ratios with which the dataframe will be split into train, val, and
        test data. The values should be expressed as float fractions and should
        sum to 1.0.
    random_state : int, None, or RandomStateInstance
        Value to be passed to train_test_split().

    Returns
    -------
    df_train, df_val, df_test :
        Dataframes containing the three splits.
    '''

    if frac_train + frac_val + frac_test != 1.0:
        raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \
                         (frac_train, frac_val, frac_test))

    if stratify_colname not in df_input.columns:
        raise ValueError('%s is not a column in the dataframe' % (stratify_colname))

    X = df_input # Contains all columns.
    y = df_input[[stratify_colname]] # Dataframe of just the column on which to stratify.

    # Split original dataframe into train and temp dataframes.
    df_train, df_temp, y_train, y_temp = train_test_split(X,
                                                          y,
                                                          stratify=y,
                                                          test_size=(1.0 - frac_train),
                                                          random_state=random_state)

    # Split the temp dataframe into val and test dataframes.
    relative_frac_test = frac_test / (frac_val + frac_test)
    df_val, df_test, y_val, y_test = train_test_split(df_temp,
                                                      y_temp,
                                                      stratify=y_temp,
                                                      test_size=relative_frac_test,
                                                      random_state=random_state)

    assert len(df_input) == len(df_train) + len(df_val) + len(df_test)

    return df_train, df_val, df_test

Below is a complete working example.

Consider a dataset that has a label upon which you want to perform the stratification. This label has its own distribution in the original dataset, say 75% foo, 15% bar and 10% baz. Now let's split the dataset into train, validation, and test into subsets using a 60/20/20 ratio, where each split retains the same distribution of the labels. See the illustration below:

enter image description here

Here is the example dataset:

df = pd.DataFrame( { 'A': list(range(0, 100)),
                     'B': list(range(100, 0, -1)),
                     'label': ['foo'] * 75 + ['bar'] * 15 + ['baz'] * 10 } )

df.head()
#    A    B label
# 0  0  100   foo
# 1  1   99   foo
# 2  2   98   foo
# 3  3   97   foo
# 4  4   96   foo

df.shape
# (100, 3)

df.label.value_counts()
# foo    75
# bar    15
# baz    10
# Name: label, dtype: int64

Now, let's call the split_stratified_into_train_val_test() function from above to get train, validation, and test dataframes following a 60/20/20 ratio.

df_train, df_val, df_test = \
    split_stratified_into_train_val_test(df, stratify_colname='label', frac_train=0.60, frac_val=0.20, frac_test=0.20)

The three dataframes df_train, df_val, and df_test contain all the original rows but their sizes will follow the above ratio.

df_train.shape
#(60, 3)

df_val.shape
#(20, 3)

df_test.shape
#(20, 3)

Further, each of the three splits will have the same distribution of the label, namely 75% foo, 15% bar and 10% baz.

df_train.label.value_counts()
# foo    45
# bar     9
# baz     6
# Name: label, dtype: int64

df_val.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

df_test.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

Setting a divs background image to fit its size?

If you'd like to use CSS3, you can do it pretty simply using background-size, like so:

background-size: 100%;

It is supported by all major browsers (including IE9+). If you'd like to get it working in IE8 and before, check out the answers to this question.

Change bundle identifier in Xcode when submitting my first app in IOS

Just edit the Project name by single click on the Top of project navigator window, will work in this case. You need not to try any other thing. :)

Provide an image for WhatsApp link sharing

Following actions helped in my case.

Putting image under the same host.

<meta property="og:url" content="https://www.same-host.com/whatsapp-image.png" />

Passing needed image to WhatsApp specifically by detecting its user agent by leading substring, example

WhatsApp/2.18.380 A

Waiting few seconds before actually pushing send button, so WhatsApp will have time to retrieve image and description from og metadata.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)

Real differences between "java -server" and "java -client"?

Last time I had a look at this, (and admittedly it was a while back) the biggest difference I noticed was in the garbage collection.

IIRC:

  • The server heap VM has a differnt number of generations than the Client VM, and a different garbage collection algorithm. This may not be true anymore
  • The server VM will allocate memory and not release it to the OS
  • The server VM will use more sophisticated optimisation algorithms, and hence have bigger time and memory requirements for optimisation

If you can compare two java VMs, one client, one server using the jvisualvm tool, you should see a difference in the frequency and effect of the garbage collection, as well as in the number of generations.

I had a pair of screenshots that showed the difference really well, but I can't reproduce as I have a 64 bit JVM which only implements the server VM. (And I can't be bothered to download and wrangle the 32 bit version on my system as well.)

This doesn't seem to be the case anymore, having tried running some code on windows with both server and client VMs, I seem to get the same generation model for both...

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

How do I create a folder in a GitHub repository?

Here is an easy and quick, presently available browser approach to creating folders inside a repository

1)Click the repository / create a new repository.

2)Click create Add file and then create a new file.

3)Give the folder name you want to create with a ' / ' mark and then add a file in it

4)Commit the changes

Click here for the visual representation of the above steps in order.

Android: how to parse URL String with spaces to URI object?

URL url = Test.class.getResource(args[0]);  // reading demo file path from                                                   
                                            // same location where class                                    
File input=null;
try {
    input = new File(url.toURI());
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

What is the best practice for creating a favicon on a web site?

There are several ways to create a favicon. The best way for you depends on various factors:

  • The time you can spend on this task. For many people, this is "as quick as possible".
  • The efforts you are willing to make. Like, drawing a 16x16 icon by hand for better results.
  • Specific constraints, like supporting a specific browser with odd specs.

First method: Use a favicon generator

If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.

Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.

Second method: Create a favicon.ico (desktop browsers only)

As you suggest, you can create a favicon.ico file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).

Then, declare it in your HTML code:

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">

This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.

About your suggestion of placing the favicon.ico file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).

Third method: Create a favicon.ico, a PNG icon and an Apple Touch icon (all browsers)

In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.

You can achieve a good compatibility with:

  • favicon.ico, see above.
  • A 192x192 PNG icon for Android Chrome
  • A 180x180 Apple Touch icon (for iPhone 6 Plus; other device will scale it down as needed).

Declare them with

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">

This is not the full story, but it's good enough in most cases.

Count number of matches of a regex in Javascript

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

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

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

return count;

How can I update my ADT in Eclipse?

Reason to that is with the new update, they changed the URL for the Android Developer Tools update site to require HTTPS. If you are updating ADT, make sure you use HTTPS in the URL for the Android Developer Tools update site.

location.host vs location.hostname and cross-browser compatibility?

If you are insisting to use the window.location.origin You can put this in top of your code before reading the origin

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

Solution

PS: For the record, it was actually the original question. It was already edited :)

jQuery select element in parent window

You can also use,

parent.jQuery("#testdiv").attr("style", content from form);

How to get form values in Symfony2 controller

If you have extra fields in the form that not defined in Entity , $form->getData() doesn't work , one way could be this :

$request->get("form")["foo"] 

Or :

$form->get('foo')->getData();

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

How do I use jQuery to redirect?

Via Jquery:

$(location).attr('href','http://example.com/Registration/Success/');

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

How to include multiple js files using jQuery $.getScript() method

This function will make sure that a file is loaded after the dependency file is loaded completely. You just need to provide the files in a sequence keeping in mind the dependencies on other files.

function loadFiles(files, fn) {
    if (!files.length) {
        files = [];
    }
    var head = document.head || document.getElementsByTagName('head')[0];

    function loadFile(index) {
        if (files.length > index) {
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", files[index]);
            head.appendChild(fileref);
            index = index + 1;
            // Used to call a callback function
            fileref.onload = function () {
                loadFile(index);
            }
        } else if(fn){
            fn();
        }
    }
    loadFile(0);
}

Regex any ASCII character

Accepts / Matches only ASCII characters

/^[\x00-\x7F]*$/

Javascript loop through object array?

Here is a generic way to loop through the field objects in an object (person):

for (var property in person) {
    console.log(property,":",person[property]);
}

The person obj looks like this:

var person={
    first_name:"johnny",
    last_name: "johnson",
    phone:"703-3424-1111"
};

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.

Best way to unselect a <select> in jQuery?

Simplest Method

$('select').val('')

I simply used this on the select itself and it did the trick.

I'm on jQuery 1.7.1.

time delayed redirect?

<meta http-equiv="refresh" content="2; url=http://example.com/" />

Here 2 is delay in seconds.

How can I rename a conda environment?

You can rename your Conda env by just renaming the env folder. Here is the proof:

Conda env renaming

You can find your Conda env folder inside of C:\ProgramData\Anaconda3\envs or you can enter conda env list to see the list of conda envs and its location.

Android EditText delete(backspace) key event

This question may be old but the answer is really simple using a TextWatcher.

int lastSize=0;
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    //2. compare the old length of the text with the new one
    //3. if the length is shorter, then backspace was clicked
    if (lastSize > charSequence.length()) {
        //4. Backspace was clicked
        //5. perform action
    }
    //1. get the current length of of the text
    lastSize = charSequence.length();
}

How to get margin value of a div in plain JavaScript?

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).

Example:

var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);

display("Current marginTop: " + style.marginTop);

Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".

Live Copy | Source

When to use throws in a Java method declaration?

You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.

Using node.js as a simple web server

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(9615);

//Just Change The CONTENT TYPE to 'html'

how to do file upload using jquery serialization

Use FormData object.It works for any type of form

$(document).on("submit", "form", function(event)
{
    event.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            

        }
    });        

});

UITextView that expands to text using auto layout

Here's a quick solution:

This problem may occur if you have set clipsToBounds property to false of your textview. If you simply delete it, the problem goes away.

myTextView.clipsToBounds = false //delete this line

Recursively find all files newer than a given time

Maybe someone can use it. Find all files which were modified within a certain time frame recursively, just run:

find . -type f -newermt "2013-06-01" \! -newermt "2013-06-20"

Using openssl to get the certificate from a server

While I agree with Ari's answer (and upvoted it :), I needed to do an extra step to get it to work with Java on Windows (where it needed to be deployed):

openssl s_client -showcerts -connect www.example.com:443 < /dev/null | openssl x509 -outform DER > derp.der

Before adding the openssl x509 -outform DER conversion, I was getting an error from keytool on Windows complaining about the certificate's format. Importing the .der file worked fine.

How do I connect to an MDF database file?

Go to server explorer > Your Database > Right Click > properties > ConnectionString and copy the connection string and past the copied to connectiongstring code :)

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

In apache2.conf, replace or delete <Directory /> AllowOverride None Require all denied </Directory>, like suggested Jan Czarny.

For example:

<Directory />
    Options FollowSymLinks
    AllowOverride None
    #Require all denied
    Require all granted
</Directory>

This worked in Ubuntu 14.04 (Trusty Tahr).

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

How to access ssis package variables inside script component

I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.

After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.

So to access the variable, I type

string fp = Variables.FilePath;

In the PreExecute() method of the Script Component.

Calculate mean across dimension in a 2D array

a.mean() takes an axis argument:

In [1]: import numpy as np

In [2]: a = np.array([[40, 10], [50, 11]])

In [3]: a.mean(axis=1)     # to take the mean of each row
Out[3]: array([ 25. ,  30.5])

In [4]: a.mean(axis=0)     # to take the mean of each col
Out[4]: array([ 45. ,  10.5])

Or, as a standalone function:

In [5]: np.mean(a, axis=1)
Out[5]: array([ 25. ,  30.5])

The reason your slicing wasn't working is because this is the syntax for slicing:

In [6]: a[:,0].mean() # first column
Out[6]: 45.0

In [7]: a[:,1].mean() # second column
Out[7]: 10.5

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

Questions every good Database/SQL developer should be able to answer

Knowing not to use, and WHY not to use:

SELECT *

MAC addresses in JavaScript

Nope. The reason ActiveX can do it is because ActiveX is a little application that runs on the client's machine.

I would imagine access to such information via JavaScript would be a security vulnerability.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

That error message means the server to which you are connecting does not reply to SSH connection attempts on port 22. There are three possible reasons for that:

  1. You're not running an SSH server on the machine. You'll need to install it to be able to ssh to it.

2.You are running an SSH server on that machine, but on a different port. You need to figure out on which port it is running; say it's on port 1234, you then run ssh -p 1234 hostname.

  1. You are running an SSH server on that machine, and it does use the port on which you are trying to connect, but the machine has a firewall that does not allow you to connect to it. You'll need to figure out how to change the firewall, or maybe you need to ssh from a different host to be allowed in.

EDIT: as (correctly) pointed out in the comments, the third is certainly the case; the other two would result in the server sending a TCP "reset" package back upon the client's connection attempt, resulting in a "connection refused" error message, rather than the timeout you're getting. The other two might also be the case, but you need to fix the third first before you can move on.

Switch php versions on commandline ubuntu 16.04

I think you should try this

From php5.6 to php7.1

sudo a2dismod php5.6
sudo a2enmod php7.1
sudo service apache2 restart

sudo update-alternatives --set php /usr/bin/php7.1
sudo update-alternatives --set phar /usr/bin/phar7.1
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.1

From php7.1 to php5.6

sudo a2dismod php7.1
sudo a2enmod php5.6
sudo service apache2 restart

sudo update-alternatives --set php /usr/bin/php5.6
sudo update-alternatives --set phar /usr/bin/phar5.6
sudo update-alternatives --set phar.phar /usr/bin/phar.phar5.6

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How can I upgrade NumPy?

When you already have an older version of NumPy, use this:

pip install numpy --upgrade

If it still doesn't work, try:

pip install numpy --upgrade --ignore-installed

I lose my data when the container exits

None of the answers address the point of this design choice. I think docker works this way to prevent these 2 errors:

  • Repeated restart
  • Partial error

Pushing value of Var into an Array

jQuery is not the same as an array. If you want to append something at the end of a jQuery object, use:

$('#fruit').append(veggies);

or to append it to the end of a form value like in your example:

 $('#fruit').val($('#fruit').val()+veggies);

In your case, fruitvegbasket is a string that contains the current value of #fruit, not an array.

jQuery (jquery.com) allows for DOM manipulation, and the specific function you called val() returns the value attribute of an input element as a string. You can't push something onto a string.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

You can increase the size of the memory through the use of commandline arguments.

See this link.

eclipse -vmargs -Xmx1024m

Edit: Also see see this excellent question

How to implement a material design circular progress bar in android

With the Material Components library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
      android:indeterminate="true"          
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:indicatorColor="@array/progress_colors"
      app:indicatorSize="xxdp"
      app:showAnimationBehavior="inward"/>

where array/progress_colors is an array with the colors:

  <integer-array name="progress_colors">
    <item>@color/yellow_500</item>
    <item>@color/blue_700</item>
    <item>@color/red_500</item>
  </integer-array>

enter image description here

Note: it requires at least the version 1.3.0

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The problem is an issue of semantic meaning (as BoltClock mentions) and visual rendering.

Originally HTML used <b> and <i> for these purposes, entirely stylistic commands, laid down in the semantic environment of the document markup. CSS is an attempt to separate out as far as possible the stylistic elements of the medium. Thus style information such as bold and italics should go in CSS.

<strong> and <em> were introduced to fill the semantic need for text to be marked as more important or stressed. They have default stylistic interpretations akin to bold and italic, but they are not bound to that fate.

How to add hours to current time in python

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you're only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments - strftime

Call a url from javascript

Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.

In jQuery:

$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):

var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}

Rails 4: List of available datatypes

It is important to know not only the types but the mapping of these types to the database types, too:

enter image description here

enter image description here


Source added - Agile Web Development with Rails 4

How to create a blank/empty column with SELECT query in oracle?

In DB2, using single quotes instead of your double quotes will work. So that could translate the same in Oracle..

SELECT CustomerName AS Customer, '' AS Contact 
FROM Customers;

os.walk without digging into directories below

You can use this snippet

for root, dirs, files in os.walk(directory):
    if level > 0:
        # do some stuff
    else:
        break
    level-=1

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

jQuery UI themes and HTML tables

There are a bunch of resources out there:

Plugins with ThemeRoller support:

jqGrid

DataTables.net

UPDATE: Here is something I put together that will style the table:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            };
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);
                input.addClass(options.css);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                        $(this).children("td").addClass("ui-state-hover");
                    } else {
                        $(this).children("td").removeClass("ui-state-hover");
                    }
                });

                input.find("th").addClass("ui-state-default");
                input.find("td").addClass("ui-widget-content");

                input.find("tr").each(function () {
                    $(this).children("td:not(:first)").addClass("first");
                    $(this).children("th:not(:first)").addClass("first");
                });
            });
        };
    })(jQuery);

    $(document).ready(function () {
        $("#Table1").styleTable();
    });

</script>

<table id="Table1" class="full">
    <tr>
        <th>one</th>
        <th>two</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
</table>

The CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

How to group by week in MySQL?

You can get the concatenated year and week number (200945) using the YEARWEEK() function. If I understand your goal correctly, that should enable you to group your multi-year data.

If you need the actual timestamp for the start of the week, it's less nice:

DATE_SUB( field, INTERVAL DAYOFWEEK( field ) - 1 DAY )

For monthly ordering, you might consider the LAST_DAY() function - sort would be by last day of the month, but that should be equivalent to sorting by first day of the month ... shouldn't it?

Remove last character from string. Swift language

I'd recommend using NSString for strings that you want to manipulate. Actually come to think of it as a developer I've never run into a problem with NSString that Swift String would solve... I understand the subtleties. But I've yet to have an actual need for them.

var foo = someSwiftString as NSString

or

var foo = "Foo" as NSString

or

var foo: NSString = "blah"

And then the whole world of simple NSString string operations is open to you.

As answer to the question

// check bounds before you do this, e.g. foo.length > 0
// Note shortFoo is of type NSString
var shortFoo = foo.substringToIndex(foo.length-1)

Get a worksheet name using Excel VBA

You can use below code to get the Active Sheet name and change it to yours preferred name.

Sub ChangeSheetName()

Dim shName As String
Dim currentName As String
currentName = ActiveSheet.Name
shName = InputBox("What name you want to give for your sheet")
ThisWorkbook.Sheets(currentName).Name = shName

End Sub

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

  1. Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR

  2. set these variables:

    export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
    export PATH=$JAVA_HOME/bin:$PATH
    
  3. Run your app and fun :)

(Minor update: put variable value in quote)

JSON.NET Error Self referencing loop detected for type

My Problem Solved With Custom Config JsonSerializerSettings:

services.AddMvc(
  // ...
               ).AddJsonOptions(opt =>
                 {
                opt.SerializerSettings.ReferenceLoopHandling =
                    Newtonsoft.Json.ReferenceLoopHandling.Serialize;
                opt.SerializerSettings.PreserveReferencesHandling =
                    Newtonsoft.Json.PreserveReferencesHandling.Objects;
                 });

PHP Redirect to another page after form submit

Once had this issue, thought it reasonable to share how I resolved it;

I think the way to do that in php is to use the header function as:

header ("Location: exampleFile.php");

You could just enclose that header file in an if statement so that it redirects only when a certain condition is met, as in:

if (isset($_POST['submit'])){   header("Location: exampleFile.php")   }

Hope that helps.

What are the differences between a program and an application?

i guess you mean System Programs and Application programs

System Programs makes the hardware run , Applications are for specific tasks

an Example for System Programs are Device Drivers

as for the Applications you can say web browsers , word porcessros etc

How to get a password from a shell script without echoing

A POSIX compliant answer. Notice the use of /bin/sh instead of /bin/bash. (It does work with bash, but it does not require bash.)

#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"

Changing CSS style from ASP.NET code

As a NOT TO DO - Another way would be to use:

divControl.Attributes.Add("style", "height: number");

But don't use this as its messy and the answer by AviewAnew is the correct way.

Convert PEM to PPK file format

I used a trial version of ZOC Terminal Emulator and it worked. It readily accepts the Amazon's *.pem files.

The trick is though, that you need to specify "ec2-user" instead of "root" for the username - despite the example shown in the EC2 console, which is wrong! ;-)

Transfer data from one HTML file to another

I use this to set Profile image on each page.

On first page set value as:

localStorage.setItem("imageurl", "ur image url");

or on second page get value as :

var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

Creating a DateTime in a specific Time Zone in c#

Using TimeZones class makes it easy to create timezone specific date.

TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(TimeZones.Paris.Id));

Remove numbers from string sql server

This one works for me

CREATE Function [dbo].[RemoveNumericCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @NumRange as varchar(50) = '%[0-9]%'
    While PatIndex(@NumRange, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '')

    Return @Temp
End

and you can use it like so

SELECT dbo.[RemoveNumericCharacters](Name) FROM TARGET_TABLE

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

For those who had trouble with the apt-get, or with the long instruction. I solved it in a relatively painless way.

  1. Download the installer from here, or direct download link
  2. $ sudo dpkg -i oracle-java8-installer_8u51+8u51arm-1-webupd8-0_all.deb

How do I change UIView Size?

You can do this in Interface Builder:

1) Control-drag from a frame view (e.g. questionFrame) to main View, in the pop-up select "Equal heights".

2)Then go to size inspector of the frame, click edit "Equal height to Superview" constraint, set the multiplier to 0.7 and hit return.

You'll see that constraint has changed from "Equal height to..." to "Proportional height to...".

How to create PDFs in an Android app?

PDFJet offers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.

How to get the selected item from ListView?

Using setOnItemClickListener is the correct answer, but if you have a keyboard you can change selection even with arrows (no click is performed), so, you need to implement also setOnItemSelectedListener :

myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
     MyObject tmp=(MyObject) adapterView.getItemAtPosition(position);
         }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // your stuff
            }
        });

Detect key input in Python

You could make a little Tkinter app:

import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

How to delete an element from an array in C#

You can also convert your array to a list and call remove on the list. You can then convert back to your array.

int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);

How to make Excel VBA variables available to multiple macros?

Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.

How to overcome TypeError: unhashable type: 'list'

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

Your password does not satisfy the current policy requirements

Step 1: check your default authentication plugin

SHOW VARIABLES LIKE 'default_authentication_plugin';

Step 2: veryfing your password validation requirements

SHOW VARIABLES LIKE 'validate_password%';

Step 3: setting up your user with correct password requirements

CREATE USER '<your_user>'@'localhost' IDENTIFIED WITH '<your_default_auth_plugin>' BY 'password';

How to read a text file into a list or an array with Python

You can also use numpy loadtxt like

from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)

How to align center the text in html table row?

Selector > child:

_x000D_
_x000D_
.text-center-row>th,_x000D_
.text-center-row>td {_x000D_
  text-align: center;_x000D_
}
_x000D_
<table border="1" width='500px'>_x000D_
  <tr class="text-center-row">_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
    <th>Text</th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
  </tr>_x000D_
  <tr class="text-center-row">_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
    <td>Text</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Convert from days to milliseconds

public static double toMilliSeconds(double day)
{
    return day * 24 * 60 * 60 * 1000;
}

or as long:

public static long toMilliSeconds(double day)
{
    return (long) (day * 24 * 60 * 60 * 1000);
}

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

Zoom to fit: PDF Embedded in HTML

This method uses "object", it also has "embed". Either method works:

<div id="pdf">
    <object id="pdf_content" width="100%" height="1500px" type="application/pdf" trusted="yes" application="yes" title="Assembly" data="Assembly.pdf?#zoom=100&scrollbar=1&toolbar=1&navpanes=1">
    <!-- <embed src="Assembly.pdf" width="100%" height="100%" type="application/x-pdf" trusted="yes" application="yes" title="Assembly">
    </embed> -->
    <p>System Error - This PDF cannot be displayed, please contact IT.</p>
    </object>
</div>

Laravel: How do I parse this json data in view blade?

Just Remove $ in to compact method ,
return view('page',compact('member'))

If statement in select (ORACLE)

So simple you can use case statement here.

CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 
         CASE WHEN  ISSUE_DIVISION is null then "Null Value found" //give your option
         Else 1 End
ELSE 0 END As Issue_Division_Result

Programmatically relaunch/recreate an activity?

Call the recreate() method from where you want to recreate your activity . This method will destroy current instance of Activity with onDestroy() and then recreate activity with onCreate().

Php - testing if a radio button is selected and get the value

my form:

<form method="post" action="radio.php">
   select your gender: 
    <input type="radio" name="radioGender" value="female">
    <input type="radio" name="radioGender" value="male">
    <input type="submit" name="btnSubmit" value="submit">
</form>

my php:

   <?php
      if (isset($_POST["btnSubmit"])) {
        if (isset($_POST["radioGender"])) {
        $answer = $_POST['radioGender'];
           if ($answer == "female") {
               echo "female";
           } else {
               echo "male";
           }    
        }else{
            echo "please select your gender";
             }
      }
  ?>

How many bytes is unsigned long long?

Executive summary: it's 64 bits, or larger.

unsigned long long is the same as unsigned long long int. Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits. There was no long long in C89, but apparently even MSVC supports it, so it's quite portable.

In the current C++ standard (issued in 2003), there is no long long, though many compilers support it as an extension. The upcoming C++0x standard will support it and its size will be the same as in C, so at least 64 bits.

You can get the exact size, in bytes (8 bits on typical platforms) with the expression sizeof(unsigned long long). If you want exactly 64 bits, use uint64_t, which is defined in the header <stdint.h> along with a bunch of related types (available in C99, C++11 and some current C++ compilers).

Fetch API request timeout?

Using a promise race solution will leave the request hanging and still consume bandwidth in the background and lower the max allowed concurrent request being made while it's still in process.

Instead use the AbortController to actually abort the request, Here is an example

const controller = new AbortController()

// 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 5000)

fetch(url, { signal: controller.signal }).then(response => {
  // completed request before timeout fired

  // If you only wanted to timeout the request, not the response, add:
  // clearTimeout(timeoutId)
})

AbortController can be used for other things as well, not only fetch but for readable/writable streams as well. More newer functions (specially promise based ones) will use this more and more. NodeJS have also implemented AbortController into its streams/filesystem as well. I know web bluetooth are looking into it also. Now it can also be used with addEventListener option and have it stop listening when the signal ends

Does an HTTP Status code of 0 have any meaning?

status 0 appear when an ajax call was cancelled before getting the response by refreshing the page or requesting a URL that is unreachable.

this status is not documented but exist over ajax and makeRequest call's from gadget.io.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

There is a single BEXTR (Bit field extract (with register)) x86 instruction on Intel and AMD CPUs and UBFX on ARM. There are intrinsic functions such as _bextr_u32() (link requires sign-in) that allow to invoke this instruction explicitly.

They implement (source >> offset) & ((1 << n) - 1) C code: get n continuous bits from source starting at the offset bit. Here's a complete function definition that handles edge cases:

#include <limits.h>

unsigned getbits(unsigned value, unsigned offset, unsigned n)
{
  const unsigned max_n = CHAR_BIT * sizeof(unsigned);
  if (offset >= max_n)
    return 0; /* value is padded with infinite zeros on the left */
  value >>= offset; /* drop offset bits */
  if (n >= max_n)
    return value; /* all  bits requested */
  const unsigned mask = (1u << n) - 1; /* n '1's */
  return value & mask;
}

For example, to get 3 bits from 2273 (0b100011100001) starting at 5-th bit, call getbits(2273, 5, 3)—it extracts 7 (0b111).

For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?

unsigned first_bits = value & ((1u << 17) - 1); // & 0x1ffff

Assuming CHAR_BIT * sizeof(unsigned) is 32 on your system.

I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits

unsigned last8bitsvalue  = value & ((1u <<  8) - 1); // & 0xff
unsigned last16bitsvalue = value & ((1u << 16) - 1); // & 0xffff

If the offset is always zero as in all your examples in the question then you don't need the more general getbits(). There is a special cpu instruction BLSMSK that helps to compute the mask ((1 << n) - 1).

can't access mysql from command line mac

On OSX 10.11, you can sudo nano /etc/paths and add the path(s) you want here, one per line. Way simpler than figuring which of ~/.bashrc, /etc/profile, '~/.bash_profile` etc... you should add to. Besides, why export and append $PATH to itself when you can just go and modify PATH directly...?

Avoid Adding duplicate elements to a List C#

Use a HashSet along with your List:

List<string> myList = new List<string>();
HashSet<string> myHashSet = new HashSet<string>();

public void addToList(string s) {
    if (myHashSet.Add(s)) {
        myList.Add(s);
    }
}

myHashSet.Add(s) will return true if s is not exist in it.

Efficient way to remove keys with empty strings from a dict

Here is an option if you are using pandas:

import pandas as pd

d = dict.fromkeys(['a', 'b', 'c', 'd'])
d['b'] = 'not null'
d['c'] = ''  # empty string

print(d)

# convert `dict` to `Series` and replace any blank strings with `None`;
# use the `.dropna()` method and
# then convert back to a `dict`
d_ = pd.Series(d).replace('', None).dropna().to_dict()

print(d_)

How do I compare version numbers in Python?

Posting my full function based on Kindall's solution. I was able to support any alphanumeric characters mixed in with the numbers by padding each version section with leading zeros.

While certainly not as pretty as his one-liner function, it seems to work well with alpha-numeric version numbers. (Just be sure to set the zfill(#) value appropriately if you have long strings in your versioning system.)

def versiontuple(v):
   filled = []
   for point in v.split("."):
      filled.append(point.zfill(8))
   return tuple(filled)

.

>>> versiontuple("10a.4.5.23-alpha") > versiontuple("2a.4.5.23-alpha")
True


>>> "10a.4.5.23-alpha" > "2a.4.5.23-alpha"
False

Restart node upon changing a file

You can also try nodemon

To Install Nodemon

npm install -g nodemon

To use Nodemon

Normally we start node program like:

node server.js

But here you have to do like:

nodemon server.js

Adding a splash screen to Flutter apps

For Android
app -> src -> main -> res ->drawble->launch_background.xml and uncomment the commented block like this

<item>
  <bitmap
      android:gravity="center"
      android:src="@mipmap/launch_image" /></item>

is there any one face any error after coding like this
Use sync with system in android studio or invalidate cache and reset.This solved my problem In flutter debug mode take some time take for splash screen .After build it will reduce like native android

How to remove unused dependencies from composer?

In fact, it is very easy.

composer update

will do all this for you, but it will also update the other packages.

To remove a package without updating the others, specifiy that package in the command, for instance:

composer update monolog/monolog

will remove the monolog/monolog package.

Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.

Extract directory path and filename

bash:

fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Export SQL query data to Excel

I see that you’re trying to export SQL data to Excel to avoid copy-pasting your very large data set into Excel.

You might be interested in learning how to export SQL data to Excel and update the export automatically (with any SQL database: MySQL, Microsoft SQL Server, PostgreSQL).

To export data from SQL to Excel, you need to follow 2 steps:

  • Step 1: Connect Excel to your SQL database? (Microsoft SQL Server, MySQL, PostgreSQL...)
  • Step 2: Import your SQL data into Excel

The result will be the list of tables you want to query data from your SQL database into Excel:

?

Step1: Connect Excel to an external data source: your SQL database

  1. Install An ODBC
  2. Install A Driver
  3. Avoid A Common Error
  4. Create a DSN

Step 2: Import your SQL data into Excel

  1. Click Where You Want Your Pivot Table
  2. Click Insert
  3. Click Pivot Table
  4. Click Use an external data source, then Choose Connection
  5. Click on the System DSN tab
  6. Select the DSN created in ODBC Manager
  7. Fill the requested username and password
  8. Avoid a Common Error
  9. Access The Microsoft Query Dialog Box
  10. Click on the arrow to see the list of tables in your database
  11. Select the table you want to query data from your SQL database into Excel
  12. Click on Return Data when you’re done with your selection

To update the export automatically, there are 2 additional steps:

  1. Create a Pivot Table with an external SQL data source
  2. Automate Your SQL Data Update In Excel With The GETPIVOTDATA Function

I’ve created a step-by-step tutorial about this whole process, from connecting Excel to SQL, up to having the whole thing automatically updated. You might find the detailed explanations and screenshots useful.

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

How to add 10 days to current time in Rails

This definitely works and I use this wherever I need to add days to the current date:

Date.today + 5

How to stop a setTimeout loop?

SIMPLIEST WAY TO HANDLE TIMEOUT LOOP

function myFunc (terminator = false) {
    if(terminator) {
        clearTimeout(timeOutVar);
    } else {
        // do something
        timeOutVar = setTimeout(function(){myFunc();}, 1000);
    }
}   
myFunc(true); //  -> start loop
myFunc(false); //  -> end loop

How do I change the background color with JavaScript?

You can change background of a page by simply using:

function changeBodyBg(color){
    document.body.style.background = color;
}

Read more @ Changing the Background Color

Getting time and date from timestamp with php

$timestamp='2014-11-21 16:38:00';

list($date,$time)=explode(' ',$timestamp);

// just time

preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];

get list of packages installed in Anaconda

To check if a specific package is installed:

conda list html5lib

which outputs something like this if installed:

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0

or something like this if not installed:

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel

you don't need to type the exact package name. Partial matches are supported:

conda list html

This outputs all installed packages containing 'html':

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0
sphinxcontrib-htmlhelp    1.0.2                      py_0
sphinxcontrib-serializinghtml 1.1.3                      py_0

Determine which element the mouse pointer is on top of in JavaScript

You can use this selector to undermouse object and then manipulate it as a jQuery object:

$(':hover').last();

Scripting Language vs Programming Language

The differences are becoming fewer and less important. Traditionally, scripting languages extend existing programs... I think that's the main definition of "scripting" is that it refers to writing a set of instructions for an existing entity to perform. However, where scripting languages started with proprietary and colloquial syntax, most of the prevalent ones these days owe some relationship to C.

I think the "interpreted vs compiled" distinction is really a symptom of extending an existing program (with a built in interpreter), rather than an intrinsic difference. What programmers and laymen are more concerned about is, "what is the programmer doing?" The fact that one program is interpreted and another is compiled means very little in determining the difference in activity by the creator. You don't judge a playwright on whether his plays are more commonly read aloud or performed on stage, do you?

What do the return values of Comparable.compareTo mean in Java?

Answer in short: (search your situation)

  • 1.compareTo(0) (return: 1)
  • 1.compareTo(1) (return: 0)
  • 0.comapreTo(1) (return: -1)

Example of Named Pipes

For someone who is new to IPC and Named Pipes, I found the following NuGet package to be a great help.

GitHub: Named Pipe Wrapper for .NET 4.0

To use first install the package:

PS> Install-Package NamedPipeWrapper

Then an example server (copied from the link):

var server = new NamedPipeServer<SomeClass>("MyServerPipe");
server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn)
    {
        Console.WriteLine("Client {0} is now connected!", conn.Id);
        conn.PushMessage(new SomeClass { Text: "Welcome!" });
    };

server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text);
    };

server.Start();

Example client:

var client = new NamedPipeClient<SomeClass>("MyServerPipe");
client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Server says: {0}", message.Text);
    };

client.Start();

Best thing about it for me is that unlike the accepted answer here it supports multiple clients talking to a single server.

maven compilation failure

Inside in yours classses on which is complain maven is some dependecy which belongs to some jar's try right these jars re-build with maven command, i use this command mvn clean install -DskipTests=true should be work in this case when some symbols from classes is missing

UINavigationBar Hide back Button Text

My solution: - XCode: 10.2.1 - Swift: 5

  • Parent viewcontroller:
    • self.title = ""
  • Child viewcontroller:
    • self.navigationItem.title = "Your title" // to set title for viewcontroller

back button callback in navigationController in iOS

Maybe it's a little too late, but I also wanted the same behavior before. And the solution I went with works quite well in one of the apps currently on the App Store. Since I haven't seen anyone goes with similar method, I would like to share it here. The downside of this solution is that it requires subclassing UINavigationController. Though using Method Swizzling might help avoiding that, I didn't go that far.

So, the default back button is actually managed by UINavigationBar. When a user taps on the back button, UINavigationBar ask its delegate if it should pop the top UINavigationItem by calling navigationBar(_:shouldPop:). UINavigationController actually implement this, but it doesn't publicly declare that it adopts UINavigationBarDelegate (why!?). To intercept this event, create a subclass of UINavigationController, declare its conformance to UINavigationBarDelegate and implement navigationBar(_:shouldPop:). Return true if the top item should be popped. Return false if it should stay.

There are two problems. The first is that you must call the UINavigationController version of navigationBar(_:shouldPop:) at some point. But UINavigationBarController doesn't publicly declare it conformance to UINavigationBarDelegate, trying to call it will result in a compile time error. The solution I went with is to use Objective-C runtime to get the implementation directly and call it. Please let me know if anyone has a better solution.

The other problem is that navigationBar(_:shouldPop:) is called first follows by popViewController(animated:) if the user taps on the back button. The order reverses if the view controller is popped by calling popViewController(animated:). In this case, I use a boolean to detect if popViewController(animated:) is called before navigationBar(_:shouldPop:) which mean that the user has tapped on the back button.

Also, I make an extension of UIViewController to let the navigation controller ask the view controller if it should be popped if the user taps on the back button. View controllers can return false and do any necessary actions and call popViewController(animated:) later.

class InterceptableNavigationController: UINavigationController, UINavigationBarDelegate {
    // If a view controller is popped by tapping on the back button, `navigationBar(_:, shouldPop:)` is called first follows by `popViewController(animated:)`.
    // If it is popped by calling to `popViewController(animated:)`, the order reverses and we need this flag to check that.
    private var didCallPopViewController = false

    override func popViewController(animated: Bool) -> UIViewController? {
        didCallPopViewController = true
        return super.popViewController(animated: animated)
    }

    func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        // If this is a subsequence call after `popViewController(animated:)`, we should just pop the view controller right away.
        if didCallPopViewController {
            return originalImplementationOfNavigationBar(navigationBar, shouldPop: item)
        }

        // The following code is called only when the user taps on the back button.

        guard let vc = topViewController, item == vc.navigationItem else {
            return false
        }

        if vc.shouldBePopped(self) {
            return originalImplementationOfNavigationBar(navigationBar, shouldPop: item)
        } else {
            return false
        }
    }

    func navigationBar(_ navigationBar: UINavigationBar, didPop item: UINavigationItem) {
        didCallPopViewController = false
    }

    /// Since `UINavigationController` doesn't publicly declare its conformance to `UINavigationBarDelegate`,
    /// trying to called `navigationBar(_:shouldPop:)` will result in a compile error.
    /// So, we'll have to use Objective-C runtime to directly get super's implementation of `navigationBar(_:shouldPop:)` and call it.
    private func originalImplementationOfNavigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        let sel = #selector(UINavigationBarDelegate.navigationBar(_:shouldPop:))
        let imp = class_getMethodImplementation(class_getSuperclass(InterceptableNavigationController.self), sel)
        typealias ShouldPopFunction = @convention(c) (AnyObject, Selector, UINavigationBar, UINavigationItem) -> Bool
        let shouldPop = unsafeBitCast(imp, to: ShouldPopFunction.self)
        return shouldPop(self, sel, navigationBar, item)
    }
}

extension UIViewController {
    @objc func shouldBePopped(_ navigationController: UINavigationController) -> Bool {
        return true
    }
}

And in you view controllers, implement shouldBePopped(_:). If you don't implement this method, the default behavior will be to pop the view controller as soon as the user taps on the back button just like normal.

class MyViewController: UIViewController {
    override func shouldBePopped(_ navigationController: UINavigationController) -> Bool {
        let alert = UIAlertController(title: "Do you want to go back?",
                                      message: "Do you really want to go back? Tap on \"Yes\" to go back. Tap on \"No\" to stay on this screen.",
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in
            navigationController.popViewController(animated: true)
        }))
        present(alert, animated: true, completion: nil)
        return false
    }
}

You can look at my demo here.

enter image description here

How do I reference the input of an HTML <textarea> control in codebehind?

You need to use runat="server" like this:

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

You can use the runat=server attribute with any standard HTML element, and later use it from codebehind.

Capture close event on Bootstrap Modal

I was having this same problem in a web app using Microsoft Visual Studio 2019, Asp.Net 3.1 and Bootstrap 4.5. I had a modal form open to add a new staff person (only a few input fields) and the Add Staff button would invoke an ajax call to create the staff records in the database. Upon successful return the code would refresh the partial razor page of staff (so the new staff person would appear in the list).

Just before the refresh I would close the Add Staff modal and display a Please Wait modal which only had a bootstrap spinner button on it. What happened is that the Please Wait modal would stay displayed and not close after the staff refresh and the modal('hide') function on this modal was called. Some times the modal would disappear but the modal backdrop would remain effectively locking the Staff List form.

Since Bootstrap has issues with multiple modals open at once, I thought maybe the Add Staff modal was still open when the Please Wait modal was displayed and this was causing problems. I made a function to display the Please Wait modal and do the refresh, and called it using the Javascript function setTimeout() to wait 1/2 second after closing/hiding the Add Staff modal:

//hide the modal form
$("#addNewStaffModal").modal('hide');
setTimeout(RefreshStaffListAfterAddingStaff, 500); //wait for 1/2 second

Here is the code for the refresh function:

function RefreshStaffListAfterAddingStaff() {
    // refresh the staff list in our partial view

    //show the please wait message
    $('#PleaseWaitModal').modal('show');

    //refresh the partial view
    $('#StaffAccountsPartialView').load('StaffAccounts?handler=StaffAccountsPartial',
        function (data, status, jqXGR) {

            //hide the wait modal
            $('#PleaseWaitModal').modal('hide');
            // enable all the fields on our form
            $("#StaffAccountsForm :input").prop("disabled", false);

            //scroll to the top of the staff list window
            window.scroll({
                top: 0,
                left: 0,
                behavior: 'smooth'
            });

        });
}

This seems to have totally solved my problem!

Convert string to variable name in JavaScript

As far as eval vs. global variable solutions...

I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.

var tempNamespace = {};
var myString = "myVarProperty";

tempNamespace[myString] = 5;

Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Javascript Regex: How to put a variable inside a regular expression?

It's only necessary to prepare the string variable first and then convert it to the RegEx.

for example:

You want to add minLength and MaxLength with the variable to RegEx:

function getRegEx() {
    const minLength = "5"; // for exapmle: min is 5
    const maxLength = "12"; // for exapmle: man is 12

    var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
    regEx = new RegExp(regEx, "g"); // now we convert it to RegEx

    return regEx; // In the end, we return the RegEx
}

now if you change value of MaxLength or MinLength, It will change in all RegExs.

Hope to be useful. Also sorry about my English.

Change URL parameters

Here is a simple solution using the query-string library.

const qs = require('query-string')
function addQuery(key, value) {
  const q = qs.parse(location.search)
  const url = qs.stringifyUrl(
    {
      url: location.pathname,
      query: {
      ...q,
      [key]: value,
      },
    },
    { skipEmptyString: true }
  );
  window.location.href = url
  // if you are using Turbolinks
  // add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)

If you are using react without react-router

export function useAddQuery() {
  const location = window.location;
  const addQuery = useCallback(
    (key, value) => {
      const q = qs.parse(location.search);
      const url = qs.stringifyUrl(
        {
          url: location.pathname,
          query: {
            ...q,
            [key]: value,
          },
        },
        { skipEmptyString: true }
      );
      window.location.href = url
    },
    [location]
  );

  return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)

If you are using react with react-router

export function useAddQuery() {
  const location = useLocation();
  const history = useHistory();

  const addQuery = useCallback(
    (key, value) => {
      let pathname = location.pathname;
      let searchParams = new URLSearchParams(location.search);
      searchParams.set(key, value);
      history.push({
        pathname: pathname,
        search: searchParams.toString()
      });
    },
    [location, history]
  );

  return { addQuery };
}

// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)

PS: qs is the import from query-string module.

Fail during installation of Pillow (Python module) in Linux

Working successfuly :

 sudo apt install libjpeg8-dev zlib1g-dev 

Remove characters from C# string

Taking the performance figures from @drzaus, here is an extension method that uses the fastest algorithm.

public static class StringEx
{
    public static string RemoveCharacters(this string s, params char[] unwantedCharacters) 
        => s == null ? null : string.Join(string.Empty, s.Split(unwantedCharacters));
}

Usage

var name = "edward woodward!";
var removeDs = name.RemoveCharacters('d', '!');
Assert.Equal("ewar woowar", removeDs); // old joke

How do I use a regex in a shell script?

the problem is you're trying to use regex features not supported by grep. namely, your \d won't work. use this instead:

REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?

you need the -E flag to get ERE in order to use {#} style.

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Is it possible to create static classes in PHP (like in C#)?

object cannot be defined staticly but this works

final Class B{
  static $var;
  static function init(){
    self::$var = new A();
}
B::init();

List file names based on a filename pattern and file content?

grep LMN20113456 LMN2011*

or if you want to search recursively through subdirectories:

find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;

How to set selected value from Combobox?

A possible solution:

cmbEmployeeStatus.SelectedValue = cmbEmployeeStatus.Items.FindByText("text").Value;

javascript unexpected identifier

It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

How to check if MySQL returns null/empty?

You can use is_null() function.

http://php.net/manual/en/function.is-null.php : in the comments :

mdufour at gmail dot com 20-Aug-2008 04:31 Testing for a NULL field/column returned by a mySQL query.

Say you want to check if field/column “foo” from a given row of the table “bar” when > returned by a mySQL query is null. You just use the “is_null()” function:

[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
     if (is_null($qValues["foo"]))
         echo "No foo data!";
     else
         echo "Foo data=".$qValues["foo"];
[…]

How to get everything after a certain character?

$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"

In a single statement it would be.

echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"

What's the fastest way to convert String to Number in JavaScript?

A fast way to convert strings to an integer is to use a bitwise or, like so:

x | 0

While it depends on how it is implemented, in theory it should be relatively fast (at least as fast as +x) since it will first cast x to a number and then perform a very efficient or.

Username and password in command for git push

For anyone having issues with passwords with special chars just omit the password and it will prompt you for it:

git push https://[email protected]/YOUR_GIT_USERNAME/yourGitFileName.git

How to Rotate a UIImage 90 degrees?

As strange as this seems, the following code solved the problem for me:

+ (UIImage*)unrotateImage:(UIImage*)image {
    CGSize size = image.size;
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0,size.width ,size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

How to create a String with carriage returns?

The fastest way I know to generate a new-line character in Java is: String.format("%n")

Of course you can put whatever you want around the %n like:

String.format("line1%nline2")

Or even if you have a lot of lines:

String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

How do I iterate and modify Java Sets?

Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.

It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet implementation of java.util.Set interface satisfies your rather special requirements.

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html

Can't use method return value in write context

The issue is this, you want to know if the error is not empty.

public function getError() {
    return $this->error;
}

Adding a method isErrorSet() will solve the problem.

public function isErrorSet() {
    if (isset($this->error) && !empty($this->error)) {
        return true;
    } else {
        return false;
    }
}

Now this will work fine with this code with no notice.

if (!($x->isErrorSet())) {
    echo $x->getError();
}

How do I show multiple recaptchas on a single page?

A good option is to generate a recaptcha input for each form on the fly (I've done it with two but you could probably do three or more forms). I'm using jQuery, jQuery validation, and jQuery form plugin to post the form via AJAX, along with the Recaptcha AJAX API -

https://developers.google.com/recaptcha/docs/display#recaptcha_methods

When the user submits one of the forms:

  1. intercept the submission - I used jQuery Form Plugin's beforeSubmit property
  2. destroy any existing recaptcha inputs on the page - I used jQuery's $.empty() method and Recaptcha.destroy()
  3. call Recaptcha.create() to create a recaptcha field for the specific form
  4. return false.

Then, they can fill out the recaptcha and re-submit the form. If they decide to submit a different form instead, well, your code checks for existing recaptchas so you'll only have one recaptcha on the page at a time.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

CSS3 Transition - Fade out effect

You can use transitions instead:

.successfully-saved.hide-opacity{
    opacity: 0;
}

.successfully-saved {
    color: #FFFFFF;
    text-align: center;

    -webkit-transition: opacity 3s ease-in-out;
    -moz-transition: opacity 3s ease-in-out;
    -ms-transition: opacity 3s ease-in-out;
    -o-transition: opacity 3s ease-in-out;
     opacity: 1;
}

Android 'Unable to add window -- token null is not for an application' exception

I got the same exception. what i do to fix this is to pass instance of the dialog as parameter into function and use it instead of pass only context then using getContext(). this solution solve my problem, hope it can help

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

How to rename a directory/folder on GitHub website?

I changed the 'Untitlted Folder' name by going upward one directory where the untitled folder and other docs are listed.

Tick the little white box in front of the 'Untitled Folder', a 'rename' button will show up at the top. Then click and change the folder name into whatever kinky name you want.

See the 'Rename' button?

See the 'Rename' button?

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

asynchronous vs non-blocking

Non-blocking: This function won't wait while on the stack.

Asynchronous: Work may continue on behalf of the function call after that call has left the stack

Oracle query to fetch column names

the point is that in toad u have to write table name capital, like this:

select *
FROM all_tab_columns
where table_name like 'IDECLARATION';

Installing specific laravel version with composer create-project

From the composer help create-project command

The create-project command creates a new project from a given
package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.

[version]
You can also specify the version with the package name using = or : as separator.

To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev).

This command works:

composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

This works with the * notation.

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

As it was said already @INC is an array and you're free to add anything you want.

My CGI REST script looks like:

#!/usr/bin/perl
use strict;
use warnings;
BEGIN {
    push @INC, 'fully_qualified_path_to_module_wiht_our_REST.pm';
}
use Modules::Rest;
gone(@_);

Subroutine gone is exported by Rest.pm.

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

I know this is an old post, but for anyone upgrading to Mountain Lion (10.8) and experiencing similar issues, adding FollowSymLinks to your {username}.conf file (in /etc/apache2/users/) did the trick for me. So the file looks like this:

<Directory "/Users/username/Sites/">
  Options Indexes MultiViews FollowSymLinks
  AllowOverride All
  Order allow,deny
  Allow from all
</Directory>

How to get whole and decimal part of a number?

val = -3.1234

fraction = abs(val - as.integer(val) ) 

What is the string concatenation operator in Oracle?

It is ||, for example:

select 'Mr ' || ename from emp;

The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

How to pass data from child component to its parent in ReactJS?

The idea is to send a callback to the child which will be called to give the data back

A complete and minimal example using functions:

App will create a Child which will compute a random number and send it back directly to the parent, which will console.log the result

const Child = ({ handleRandom }) => {
  handleRandom(Math.random())

  return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>

String contains - ignore case

If you won't go with regex:

"ABCDEFGHIJKLMNOP".toLowerCase().contains("gHi".toLowerCase())

save a pandas.Series histogram plot to file

Use the Figure.savefig() method, like so:

ax = s.hist()  # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

It doesn't have to end in pdf, there are many options. Check out the documentation.

Alternatively, you can use the pyplot interface and just call the savefig as a function to save the most recently created figure:

import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf')  # saves the current figure

Missing Push Notification Entitlement

First App ID

make sure your ID push notification enable in production side

as appear in picture

enter image description here

Second Certificate

from production section create two certificate with your id (push notification enabled)

App Store and Ad Hoc certificate

Apple Push Notification service SSL (Sandbox) certificate

enter image description here

Third Provisioning Profiles

From Distribution section create App Store profile with your id

Finally

while you upload your bin , you must check what provisioning profile used and have many entitlements

enter image description here

this all cases cause this problem hope this be helpful with you

How do I add the contents of an iterable to a set?

for item in items:
   extant_set.add(item)

For the record, I think the assertion that "There should be one-- and preferably only one --obvious way to do it." is bogus. It makes an assumption that many technical minded people make, that everyone thinks alike. What is obvious to one person is not so obvious to another.

I would argue that my proposed solution is clearly readable, and does what you ask. I don't believe there are any performance hits involved with it--though I admit I might be missing something. But despite all of that, it might not be obvious and preferable to another developer.

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.

Read file content from S3 bucket with boto3

If you already know the filename, you can use the boto3 builtin download_fileobj

import boto3

from io import BytesIO

session = boto3.Session()
s3_client = session.client("s3")

f = BytesIO()
s3_client.download_fileobj(bucket_name, filename, f)
f.seek(0)
print(f.getvalue())

SQL Joins Vs SQL Subqueries (Performance)?

Well, I believe it's an "Old but Gold" question. The answer is: "It depends!". The performances are such a delicate subject that it would be too much silly to say: "Never use subqueries, always join". In the following links, you'll find some basic best practices that I have found to be very helpful:

I have a table with 50000 elements, the result i was looking for was 739 elements.

My query at first was this:

SELECT  p.id,
    p.fixedId,
    p.azienda_id,
    p.categoria_id,
    p.linea,
    p.tipo,
    p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND p.anno = (
    SELECT MAX(p2.anno) 
    FROM prodotto p2 
    WHERE p2.fixedId = p.fixedId 
)

and it took 7.9s to execute.

My query at last is this:

SELECT  p.id,
    p.fixedId,
    p.azienda_id,
    p.categoria_id,
    p.linea,
    p.tipo,
    p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN
(
    SELECT p2.fixedId, MAX(p2.anno)
    FROM prodotto p2
    WHERE p.azienda_id = p2.azienda_id
    GROUP BY p2.fixedId
)

and it took 0.0256s

Good SQL, good.

Static Initialization Blocks

It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):

public enum Language { 
  ENGLISH("eng", "en", "en_GB", "en_US"),   
  GERMAN("de", "ge"),   
  CROATIAN("hr", "cro"),   
  RUSSIAN("ru"),
  BELGIAN("be",";-)");

  static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>(); 
  static { 
    for (Language l:Language.values()) { 
      // ignoring the case by normalizing to uppercase
      ALIAS_MAP.put(l.name().toUpperCase(),l); 
      for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l); 
    } 
  } 

  static public boolean has(String value) { 
    // ignoring the case by normalizing to uppercase
    return ALIAS_MAP.containsKey(value.toUpper()); 
  } 

  static public Language fromString(String value) { 
    if (value == null) throw new NullPointerException("alias null"); 
    Language l = ALIAS_MAP.get(value); 
    if (l == null) throw new IllegalArgumentException("Not an alias: "+value); 
    return l; 
  } 

  private List<String> aliases; 
  private Language(String... aliases) { 
    this.aliases = Arrays.asList(aliases); 
  } 
} 

Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.

As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:

  1. The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
  2. static block and initialization of static fields in the order of occurrence.

This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):

public class Foo {
  static { System.out.println("Static Block 1"); }
  public static final Foo FOO = new Foo();
  static { System.out.println("Static Block 2"); }
  public Foo() { System.out.println("Constructor"); }
  static public void main(String p[]) {
    System.out.println("In Main");
    new Foo();
  }
}

What we see is the following output:

Static Block 1
Constructor
Static Block 2
In Main
Constructor

Clear is that the static initialization actually can happen before the constructor, and even after:

Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.

For more info on this see the book "Effective Java".

TypeError: $ is not a function WordPress

I added a custom script file that loaded at the end of the head section, and inserted the following at the top:

(function (jQuery) {
    window.$ = jQuery.noConflict();
})(jQuery);

(This is a modification of Fanky's answer)

Wordpress plugin install: Could not create directory

You need to change the permission of the directory

  1. At first change the user HTML folder (replace yourcomputerusername)

    sudo chown yourcomputerusername:yourcomputerusername /var/www/html

  2. Next change the permission for the user

    cd /var/www/html

    sudo chmod -R goa=rwx wordpress

    or

    sudo chmod -R 777 wordpress/wp-content

strcpy() error in Visual studio 2012

The message you are getting is advice from MS that they recommend that you do not use the standard strcpy function. Their motivation in this is that it is easy to misuse in bad ways (and the compiler generally can't detect and warn you about such misuse). In your post, you are doing exactly that. You can get rid of the message by telling the compiler to not give you that advice. The serious error in your code would remain, however.

You are creating a buffer with room for 10 chars. You are then stuffing 11 chars into it. (Remember the terminating '\0'?) You have taken a box with exactly enough room for 10 eggs and tried to jam 11 eggs into it. What does that get you? Not doing this is your responsibility and the compiler will generally not detect such things.

You have tagged this C++ and included string. I do not know your motivation for using strcpy, but if you use std::string instead of C style strings, you will get boxes that expand to accommodate what you stuff in them.

Best database field type for a URL

VARCHAR(512) (or similar) should be sufficient. However, since you don't really know the maximum length of the URLs in question, I might just go direct to TEXT. The danger with this is of course loss of efficiency due to CLOBs being far slower than a simple string datatype like VARCHAR.

Executing <script> injected by innerHTML after AJAX call

I used this code, it is working fine

var arr = MyDiv.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

What is unit testing and how do you do it?

What is unittesting? It is tricky to define. On a technical level, you build functions that call functions in your codebase and validate the results. Basically, you get a bunch of things like "assert(5+3) == 8", just more complicated (as in DataLayer(MockDatabase()).getUser().name == "Dilbert"). On a tool-view-level, you add an automated, project-specific check if everything still works like you assumed things worked. This is very, very helpful if you refactor and if you implement complicated algorithms. The result generally is a bunch of documentation and a lot less bugs, because the behaviour of the code is pinned down.

I build test cases for all the edge cases and run them similar to the workings of a generational garbage collector. While I implement a class, I only run the test cases that involve the class. Once I am done with working on that class, I run all unittests in order to see if everything still works.

You should test as much as possible, as long as the test code is easy enough to stay untested. Given that, no, not everything is testable in a sane way. Think User interfaces. Think a driver for a space shuttle or a nuclear bomb (at least not with pure JUnit-tests ;) ). However, lots and lots of code is testable. Datastructures are. Algorithms are. Most Applicationlogic-classes are. So test it!

HTH. tetha

Class Not Found Exception when running JUnit test

It's worth mentioning as another answer that if you're using eGit, and your classpath gets updated because of say, a test coverage tool like Clover, that sometimes there's a cleanup hiccup that does not completely delete the contents of /path/to/git/repository/<project name>/bin/

Essentially, I used Eclipse's Error Log View, identified what was causing issues during this cleanup effort, navigated to the source directory, and manually deleted the <project name>/bin directory. Once that finished I went back to Eclipse and refreshed (F5) my project and the error went away.

How to send a POST request from node.js Express?

you can try like this:

var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
               , url: <your URL>, body: <req_body in json> }
               , function(error, response, body){
   console.log(body); 
}); 

Is there a short contains function for lists?

The list method index will return -1 if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if statement you can do the following:

if myItem in list:
    #do things

You can also check if an element is not in a list with the following if statement:

if myItem not in list:
    #do things

Use string in switch case in java

Evaluating String variables with a switch statement have been implemented in Java SE 7, and hence it only works in java 7. You can also have a look at how this new feature is implemented in JDK 7.

How to specify the download location with wget?

Make sure you have the URL correct for whatever you are downloading. First of all, URLs with characters like ? and such cannot be parsed and resolved. This will confuse the cmd line and accept any characters that aren't resolved into the source URL name as the file name you are downloading into.

For example:

wget "sourceforge.net/projects/ebosse/files/latest/download?source=typ_redirect"

will download into a file named, ?source=typ_redirect.

As you can see, knowing a thing or two about URLs helps to understand wget.

I am booting from a hirens disk and only had Linux 2.6.1 as a resource (import os is unavailable). The correct syntax that solved my problem downloading an ISO onto the physical hard drive was:

wget "(source url)" -O (directory where HD was mounted)/isofile.iso" 

One could figure the correct URL by finding at what point wget downloads into a file named index.html (the default file), and has the correct size/other attributes of the file you need shown by the following command:

wget "(source url)"

Once that URL and source file is correct and it is downloading into index.html, you can stop the download (ctrl + z) and change the output file by using:

-O "<specified download directory>/filename.extension"

after the source url.

In my case this results in downloading an ISO and storing it as a binary file under isofile.iso, which hopefully mounts.

What is the difference between mocking and spying when using Mockito?

Difference between a Spy and a Mock

When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

In the following example – we create a mock of the ArrayList class:

@Test
public void whenCreateMock_thenCreated() {
    List mockedList = Mockito.mock(ArrayList.class);

    mockedList.add("one");
    Mockito.verify(mockedList).add("one");

    assertEquals(0, mockedList.size());
}

As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:

@Test
public void whenCreateSpy_thenCreate() {
    List spyList = Mockito.spy(new ArrayList());
    spyList.add("one");
    Mockito.verify(spyList).add("one");

    assertEquals(1, spyList.size());
}

Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.

Source: http://www.baeldung.com/mockito-spy + self notes.

Class 'DOMDocument' not found

this is the lastest for php v 8.0

sudo apt-get install php8.0-xml

How can you tell when a layout has been drawn?

You can add a tree observer to the layout. This should return the correct width and height. onCreate() is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width, put this on the onCreate() method:

    final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID);
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    layout.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 

        } 
    });

How do you loop through each line in a text file using a windows batch file?

To print all lines in text file from command line (with delayedExpansion):

set input="path/to/file.txt"

for /f "tokens=* delims=[" %i in ('type "%input%" ^| find /v /n ""') do (
set a=%i
set a=!a:*]=]!
echo:!a:~1!)

Works with leading whitespace, blank lines, whitespace lines.

Tested on Win 10 CMD

Test text

Accessing Imap in C#

MailSystem.NET contains all your need for IMAP4. It's free & open source.

(I'm involved in the project)

How do I raise the same Exception with a custom message in Python?

The current answer did not work good for me, if the exception is not re-caught the appended message is not shown.

But doing like below both keeps the trace and shows the appended message regardless if the exception is re-caught or not.

try:
  raise ValueError("Original message")
except ValueError as err:
  t, v, tb = sys.exc_info()
  raise t, ValueError(err.message + " Appended Info"), tb

( I used Python 2.7, have not tried it in Python 3 )

Best way to work with dates in Android SQLite

SQLite can use text, real, or integer data types to store dates. Even more, whenever you perform a query, the results are shown using format %Y-%m-%d %H:%M:%S.

Now, if you insert/update date/time values using SQLite date/time functions, you can actually store milliseconds as well. If that's the case, the results are shown using format %Y-%m-%d %H:%M:%f. For example:

sqlite> create table test_table(col1 text, col2 real, col3 integer);
sqlite> insert into test_table values (
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123')
        );
sqlite> insert into test_table values (
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126'),
            strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126')
        );
sqlite> select * from test_table;
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126

Now, doing some queries to verify if we are actually able to compare times:

sqlite> select * from test_table /* using col1 */
           where col1 between 
               strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.121') and
               strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.125');
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123

You can check the same SELECT using col2 and col3 and you will get the same results. As you can see, the second row (126 milliseconds) is not returned.

Note that BETWEEN is inclusive, therefore...

sqlite> select * from test_table 
            where col1 between 
                 /* Note that we are using 123 milliseconds down _here_ */
                strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123') and
                strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.125');

... will return the same set.

Try playing around with different date/time ranges and everything will behave as expected.

What about without strftime function?

sqlite> select * from test_table /* using col1 */
           where col1 between 
               '2014-03-01 13:01:01.121' and
               '2014-03-01 13:01:01.125';
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123

What about without strftime function and no milliseconds?

sqlite> select * from test_table /* using col1 */
           where col1 between 
               '2014-03-01 13:01:01' and
               '2014-03-01 13:01:02';
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126

What about ORDER BY?

sqlite> select * from test_table order by 1 desc;
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
sqlite> select * from test_table order by 1 asc;
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126

Works just fine.

Finally, when dealing with actual operations within a program (without using the sqlite executable...)

BTW: I'm using JDBC (not sure about other languages)... the sqlite-jdbc driver v3.7.2 from xerial - maybe newer revisions change the behavior explained below... If you are developing in Android, you don't need a jdbc-driver. All SQL operations can be submitted using the SQLiteOpenHelper.

JDBC has different methods to get actual date/time values from a database: java.sql.Date, java.sql.Time, and java.sql.Timestamp.

The related methods in java.sql.ResultSet are (obviously) getDate(..), getTime(..), and getTimestamp() respectively.

For example:

Statement stmt = ... // Get statement from connection
ResultSet rs = stmt.executeQuery("SELECT * FROM TEST_TABLE");
while (rs.next()) {
    System.out.println("COL1 : "+rs.getDate("COL1"));
    System.out.println("COL1 : "+rs.getTime("COL1"));
    System.out.println("COL1 : "+rs.getTimestamp("COL1"));
    System.out.println("COL2 : "+rs.getDate("COL2"));
    System.out.println("COL2 : "+rs.getTime("COL2"));
    System.out.println("COL2 : "+rs.getTimestamp("COL2"));
    System.out.println("COL3 : "+rs.getDate("COL3"));
    System.out.println("COL3 : "+rs.getTime("COL3"));
    System.out.println("COL3 : "+rs.getTimestamp("COL3"));
}
// close rs and stmt.

Since SQLite doesn't have an actual DATE/TIME/TIMESTAMP data type all these 3 methods return values as if the objects were initialized with 0:

new java.sql.Date(0)
new java.sql.Time(0)
new java.sql.Timestamp(0)

So, the question is: how can we actually select, insert, or update Date/Time/Timestamp objects? There's no easy answer. You can try different combinations, but they will force you to embed SQLite functions in all the SQL statements. It's far easier to define an utility class to transform text to Date objects inside your Java program. But always remember that SQLite transforms any date value to UTC+0000.

In summary, despite the general rule to always use the correct data type, or, even integers denoting Unix time (milliseconds since epoch), I find much easier using the default SQLite format ('%Y-%m-%d %H:%M:%f' or in Java 'yyyy-MM-dd HH:mm:ss.SSS') rather to complicate all your SQL statements with SQLite functions. The former approach is much easier to maintain.

TODO: I will check the results when using getDate/getTime/getTimestamp inside Android (API15 or better)... maybe the internal driver is different from sqlite-jdbc...

How do I hide an element on a click event anywhere outside of the element?

If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.