Programs & Examples On #Reloaddata

How to tell when UITableView has completed ReloadData?

Try this way it will work

[tblViewTerms performSelectorOnMainThread:@selector(dataLoadDoneWithLastTermIndex:) withObject:lastTermIndex waitUntilDone:YES];waitUntilDone:YES];

@interface UITableView (TableViewCompletion)

-(void)dataLoadDoneWithLastTermIndex:(NSNumber*)lastTermIndex;

@end

@implementation UITableView(TableViewCompletion)

-(void)dataLoadDoneWithLastTermIndex:(NSNumber*)lastTermIndex
{
    NSLog(@"dataLoadDone");


NSIndexPath* indexPath = [NSIndexPath indexPathForRow: [lastTermIndex integerValue] inSection: 0];

[self selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

}
@end

I will execute when table is completely loaded

Other Solution is you can subclass UITableView

How do I create a shortcut via command-line in Windows?

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

Shell Script — Get all files modified after <date>

If you have GNU find, then there are a legion of relevant options. The only snag is that the interface to them is less than stellar:

  • -mmin n (modification time in minutes)
  • -mtime n (modification time in days)
  • -newer file (modification time newer than modification time of file)
  • -daystart (adjust start time from current time to start of day)
  • Plus alternatives for access time and 'change' or 'create' time.

The hard part is determining the number of minutes since a time.

One option worth considering: use touch to create a file with the required modification time stamp; then use find with -newer.

touch -t 200901031231.43 /tmp/wotsit
find . -newer /tmp/wotsit -print
rm -f /tmp/wotsit

This looks for files newer than 2009-01-03T12:31:43. Clearly, in a script, /tmp/wotsit would be a name with the PID or other value to make it unique; and there'd be a trap to ensure it gets removed even if the user interrupts, and so on and so forth.

Importing packages in Java

For the second class file, add "package Dan;" like the first one, so as to make sure they are in the same package; modify "import Dan.Vik.disp;" to be "import Dan.Vik;"

Programmatically check Play Store for app updates

enter image description here

Google has introduced in-app updates API

The API currently supports two flows:

  • The “immediate” flow is a full-screen user experience that guides the user from download to update before they can use your app.
  • The “flexible flow” allows users to download the update while continuing to use your app.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

enter image description here

I want to change or update my ContactNo to 8018070999 where there is 8018070777 using Case statement

update [Contacts] set contactNo=(case 
when contactNo=8018070777 then 8018070999
else
contactNo
end)

enter image description here

How to check if multiple array keys exists

This is the function I wrote for myself to use within a class.

<?php
/**
 * Check the keys of an array against a list of values. Returns true if all values in the list
 is not in the array as a key. Returns false otherwise.
 *
 * @param $array Associative array with keys and values
 * @param $mustHaveKeys Array whose values contain the keys that MUST exist in $array
 * @param &$missingKeys Array. Pass by reference. An array of the missing keys in $array as string values.
 * @return Boolean. Return true only if all the values in $mustHaveKeys appear in $array as keys.
 */
    function checkIfKeysExist($array, $mustHaveKeys, &$missingKeys = array()) {
        // extract the keys of $array as an array
        $keys = array_keys($array);
        // ensure the keys we look for are unique
        $mustHaveKeys = array_unique($mustHaveKeys);
        // $missingKeys = $mustHaveKeys - $keys
        // we expect $missingKeys to be empty if all goes well
        $missingKeys = array_diff($mustHaveKeys, $keys);
        return empty($missingKeys);
    }


$arrayHasStoryAsKey = array('story' => 'some value', 'some other key' => 'some other value');
$arrayHasMessageAsKey = array('message' => 'some value', 'some other key' => 'some other value');
$arrayHasStoryMessageAsKey = array('story' => 'some value', 'message' => 'some value','some other key' => 'some other value');
$arrayHasNone = array('xxx' => 'some value', 'some other key' => 'some other value');

$keys = array('story', 'message');
if (checkIfKeysExist($arrayHasStoryAsKey, $keys)) { // return false
    echo "arrayHasStoryAsKey has all the keys<br />";
} else {
    echo "arrayHasStoryAsKey does NOT have all the keys<br />";
}

if (checkIfKeysExist($arrayHasMessageAsKey, $keys)) { // return false
    echo "arrayHasMessageAsKey has all the keys<br />";
} else {
    echo "arrayHasMessageAsKey does NOT have all the keys<br />";
}

if (checkIfKeysExist($arrayHasStoryMessageAsKey, $keys)) { // return false
    echo "arrayHasStoryMessageAsKey has all the keys<br />";
} else {
    echo "arrayHasStoryMessageAsKey does NOT have all the keys<br />";
}

if (checkIfKeysExist($arrayHasNone, $keys)) { // return false
    echo "arrayHasNone has all the keys<br />";
} else {
    echo "arrayHasNone does NOT have all the keys<br />";
}

I am assuming you need to check for multiple keys ALL EXIST in an array. If you are looking for a match of at least one key, let me know so I can provide another function.

Codepad here http://codepad.viper-7.com/AKVPCH

Modal width (increase)

Bootstrap 4 includes sizing utilities. You can change the size to 25/50/75/100% of the page width (I wish there were even more increments).

To use these we will replace the modal-lg class. Both the default width and modal-lg use css max-width to control the modal's width, so first add the mw-100 class to effectively disable max-width. Then just add the width class you want, e.g. w-75.

Note that you should place the mw-100 and w-75 classes in the div with the modal-dialog class, not the modal div e.g.,

<div class='modal-dialog mw-100 w-75'>
    ...
</div>

Passing on command line arguments to runnable JAR

When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

Replace all occurrences of a string in a data frame

late to the party. but if you only want to get rid of leading/trailing white space, R base has a function trimws

For example:

data <- apply(X = data, MARGIN = 2, FUN = trimws) %>% as.data.frame()

How can I remove a commit on GitHub?

You'll need to clear out your cache to have it completely wiped. this help page from git will help you out. (it helped me) http://help.github.com/remove-sensitive-data/

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

How can I exclude multiple folders using Get-ChildItem -exclude?

may be in your case you could reach this with the following:

    mv excluded_dir ..\
    ls -R 
    mv ..\excluded_dir .

c# open file with default application and parameters

this should be close!

public static void OpenWithDefaultProgram(string path)
{
    Process fileopener = new Process();
    fileopener.StartInfo.FileName = "explorer";
    fileopener.StartInfo.Arguments = "\"" + path + "\"";
    fileopener.Start();
}

How to see the CREATE VIEW code for a view in PostgreSQL?

select definition from pg_views where viewname = 'my_view'

Create a directory if it doesn't exist

You can use cstdlib

Although- http://www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>

const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}

you can also check if the directory exists already by using

#include <dirent.h>

What is a good way to handle exceptions when trying to read a file in python?

How about this:

try:
    f = open(fname, 'rb')
except OSError:
    print "Could not open/read file:", fname
    sys.exit()

with f:
    reader = csv.reader(f)
    for row in reader:
        pass #do stuff here

Send file using POST from a Python script

I am trying to test django rest api and its working for me:

def test_upload_file(self):
        filename = "/Users/Ranvijay/tests/test_price_matrix.csv"
        data = {'file': open(filename, 'rb')}
        client = APIClient()
        # client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
        response = client.post(reverse('price-matrix-csv'), data, format='multipart')

        print response
        self.assertEqual(response.status_code, status.HTTP_200_OK)

How can I specify a display?

When you are connecting to another machine over SSH, you can enable X-Forwarding in SSH, so that X windows are forwarded encrypted through the SSH tunnel back to your machine. You can enable X forwarding by appending -X to the ssh command line or setting ForwardX11 yes in your SSH config file.

To check if the X-Forwarding was set up successfully (the server might not allow it), just try if echo $DISPLAY outputs something like localhost:10.0.

fatal error: iostream.h no such file or directory

You should be using iostream without the .h.

Early implementations used the .h variants but the standard mandates the more modern style.

Sorting std::map using value

I needed something similar, but the flipped map wouldn't work for me. I just copied out my map (freq below) into a vector of pairs, then sorted the pairs however I wanted.

std::vector<std::pair<int, int>> pairs;
for (auto itr = freq.begin(); itr != freq.end(); ++itr)
    pairs.push_back(*itr);

sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b)
{
    return a.second < b.second;
}
);

Android new Bottom Navigation bar or BottomNavigationView

I have referred this github post and I have set the three layouts for three fragment pages in bottom tab bar.

FourButtonsActivity.java:

bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
            new BottomBarFragment(LibraryFragment.newInstance(R.layout.library_fragment_layout), R.drawable.ic_update_white_24dp, "Recents"),
            new BottomBarFragment(PhotoEffectFragment.newInstance(R.layout.photo_effect_fragment), R.drawable.ic_local_dining_white_24dp, "Food"),
            new BottomBarFragment(VideoFragment.newInstance(R.layout.video_layout), R.drawable.ic_favorite_white_24dp, "Favorites")

    );

To set the badge count :

  BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(1, "#E91E63", 4);
  unreadMessages.show();
  unreadMessages.setCount(4);
  unreadMessages.setAnimationDuration(200);
  unreadMessages.setAutoShowAfterUnSelection(true);

LibraryFragment.java:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LibraryFragment extends Fragment {
    private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";

    public LibraryFragment() {
    }

    public static LibraryFragment newInstance(int resource) {
        Bundle args = new Bundle();
        args.putInt(STARTING_TEXT, resource);

        LibraryFragment sampleFragment = new LibraryFragment();
        sampleFragment.setArguments(args);

        return sampleFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        View view = LayoutInflater.from(getActivity()).inflate(
                getArguments().getInt(STARTING_TEXT), null);
        return view;


    }

Is there a "not equal" operator in Python?

You can simply do:

if hi == hi:
    print "hi"
elif hi != bye:
     print "no hi"

C++ - Decimal to binary converting

here a simple converter by using std::string as container. it allows a negative value.

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int x = -14;

    int n = std::numeric_limits<int>::digits - 1;

    std::string s;
    s.reserve(n + 1);

    do
        s.push_back(((x >> n) & 1) + '0');
    while(--n > -1);

    std::cout << s << '\n';
}

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

The problem is related with your file - you are trying to create a DB using a copy - at the top of your file you will find something like this:

CREATE DATABASE IF NOT EXISTS *THE_NAME_OF_YOUR_DB* DEFAULT CHARACTER SET latin1 COLLATE latin1_general_ci; USE *THE_NAME_OF_YOUR_DB*;

and I'm sure that you already have a DB with this name - IN THE SAME SERVER - please check. Just change the name OR ERASE THIS LINE!

Press enter in textbox to and execute button command

You could register to the KeyDown-Event of the Textbox, look if the pressed key is Enter and then execute the EventHandler of the button:

private void buttonTest_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hello World");
}

private void textBoxTest_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        buttonTest_Click(this, new EventArgs());
    }
}

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:

$.get('/service', function(data) {  
  var obj = data;

      /* 
         "obj" is evaluated at this point if server responded 
         with "application/json" or similar.
       */
      for (var i = 0; i < obj.length; i++) {
        console.log(obj[i].Name);
      }
    });

Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify:

var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);

But in this case I don't understand why you can't just take the json variable and refer to it instead of stringifying and parsing.

How do I install soap extension?

In Ubuntu with php7.3:

sudo apt install php7.3-soap 
sudo service apache2 restart

How to write ternary operator condition in jQuery?

I think Dan and Nicola have suitable corrected code, however you may not be clear on why the original code didn't work.

What has been called here a "ternary operator" is called a conditional operator in ECMA-262 section 11.12. It has the form:

LogicalORExpression ? AssignmentExpression : AssignmentExpression

The LogicalORExpression is evaluated and the returned value converted to Boolean (just like an expression in an if condition). If it evaluates to true, then the first AssignmentExpression is evaluated and the returned value returned, otherwise the second is evaluated and returned.

The error in the original code is the extra semi-colons that change the attempted conditional operator into a series of statements with syntax errors.

How to remove button shadow (android)

Using this as the background for your button might help, change the color to your needs

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_light" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_dark" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
</selector>

how to remove the first two columns in a file using shell (awk, sed, whatever)

Thanks for posting the question. I'd also like to add the script that helped me.

awk '{ $1=""; print $0 }' file

Can I recover a branch after its deletion in Git?

If you don't have a reflog, eg. because you're working in a bare repository which does not have the reflog enabled and the commit you want to recover was created recently, another option is to find recently created commit objects and look through them.

From inside the .git/objects directory run:

find . -ctime -12h -type f | sed 's/[./]//g' | git cat-file --batch-check | grep commit

This finds all objects (commits, files, tags etc.) created in the last 12 hours and filters them to show only commits. Checking these is then a quick process.

I'd try the git-ressurect.sh script mentioned in Jakub's answer first though.

How to get a jqGrid cell value when editing

I think that Aidan's answer is by far the best.

$('#yourgrid').jqGrid("editCell", 0, 0, false);

This commits any current edits, giving you access to the real value. I prefer it because:

  • You don't have to hard-code any cell references in.
    • It is particularly well suited to using getRowData() to get the entire grid, as it doesn't care which cell you've just been editing.
    • You're not trying to parse some markup generated by jqGrid which may change in future.
    • If the user is saving, then ending the edit session is likely the behaviour they would want anyway.

New features in java 7

The following list contains links to the the enhancements pages in the Java SE 7.

Swing
IO and New IO
Networking
Security
Concurrency Utilities
Rich Internet Applications (RIA)/Deployment
    Requesting and Customizing Applet Decoration in Dragg able Applets
    Embedding JNLP File in Applet Tag
    Deploying without Codebase
    Handling Applet Initialization Status with Event Handlers
Java 2D
Java XML – JAXP, JAXB, and JAX-WS
Internationalization
java.lang Package
    Multithreaded Custom Class Loaders in Java SE 7
Java Programming Language
    Binary Literals
    Strings in switch Statements
    The try-with-resources Statement
    Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
    Underscores in Numeric Literals
    Type Inference for Generic Instance Creation
    Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
Java Virtual Machine (JVM)
    Java Virtual Machine Support for Non-Java Languages
    Garbage-First Collector
    Java HotSpot Virtual Machine Performance Enhancements
JDBC

Reference 1 Reference 2

How do I add a placeholder on a CharField in Django?

The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It also allows the placeholder to depend on the instance for ModelForms with instance specified.

IE8 css selector

you can use like this. it's better than

<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
<!--[if IE 7]><link rel="stylesheet" type="text/css" media="screen" href="css/ie7.css"  /><![endif]-->
<!--[if IE 6]><link rel="stylesheet" type="text/css" media="screen" href="css/ie6.css"  /><![endif]-->
-------------------------------------------------------------

<!--[if lt IE 7 ]> <body class="ie6"> <![endif]-->
  <!--[if IE 7 ]> <body class="ie7"> <![endif]-->
  <!--[if IE 8 ]> <body class="ie8"> <![endif]-->
  <!--[if !IE]>--> <body> <!--<![endif]-->

div.foo { color: inherit;} .ie7 div.foo { color: #ff8000; }

How do I connect to a specific Wi-Fi network in Android programmatically?

The earlier answer works, but the solution can actually be simpler. Looping through the configured networks list is not required as you get the network id when you add the network through the WifiManager.

So the complete, simplified solution would look something like this:

WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);

WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

Breaking up long strings on multiple lines in Ruby without stripping newlines

You can use \ to indicate that any line of Ruby continues on the next line. This works with strings too:

string = "this is a \
string that spans lines"

puts string.inspect

will output "this is a string that spans lines"

How to use _CRT_SECURE_NO_WARNINGS

If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General

Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.

It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.

SDL checks in vs2012 and later

Show div when radio button selected

var switchData = $('#show-me');
switchData.hide();
$('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});

JSFIDDLE

Redirect stdout to a file in Python?

If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

import sys
sys.stdout = open('file', 'w')
print('test')
sys.stdout.close()

A far more common method is to use shell redirection when executing (same on Windows and Linux):

$ python foo.py > file

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

Counting words in string

The answer given by @7-isnotbad is extremely close, but doesn't count single-word lines. Here's the fix, which seems to account for every possible combination of words, spaces and newlines.

function countWords(s){
    s = s.replace(/\n/g,' '); // newlines to space
    s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
    s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
    return s.split(' ').length; 
}

How do I create a link using javascript?

_x000D_
_x000D_
    <script>_x000D_
      _$ = document.querySelector  .bind(document) ;_x000D_
_x000D_
        var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs_x000D_
        var a   =  document.createElement( 'a' )_x000D_
        a.text  = "Download example" _x000D_
        a.href  = "//bit\.do/DeezerDL"_x000D_
_x000D_
        AppendLinkHere.appendChild( a )_x000D_
        _x000D_
_x000D_
     // a.title = 'Well well ... _x000D_
        a.setAttribute( 'title', _x000D_
                         'Well well that\'s a link'_x000D_
                      );_x000D_
    </script>
_x000D_
_x000D_
_x000D_

  1. The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear! Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")

  2. Leave the protocol open. Instead of http://example.com/path consider to just use //example.com/path. Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.

  3. OffTopic: That's not really relevant about creating links in JS but maybe good to know: Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

CORS: credentials mode is 'include'

Just add Axios.defaults.withCredentials=true instead of ({credentials: true}) in client side, and change app.use(cors()) to

app.use(cors(
  {origin: ['your client side server'],
  methods: ['GET', 'POST'],
  credentials:true,
}
))

How to output (to a log) a multi-level array in a format that is human-readable?

Drupal's Devel module has other useful functions including ones that can print formatted arrays and objects to log files. See the guide at http://ratatosk.net/drupal/tutorials/debugging-drupal.html

dd()

Logs any variable to a file named “drupal_debug.txt” in the site’s temp directory. All output from this function is appended to the log file, making it easy to see how the contents of a variable change as you modify your code.

If you’re using Mac OS X you can use the Logging Console to monitor the contents of the log file.

If you’re using a flavor of Linux you can use the command “tail -f drupal_debug.txt” to watch the data being logged to the file.

Can you hide the controls of a YouTube embed without enabling autoplay?

To remove you tube controls and title you can do something like this

_x000D_
_x000D_
<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>
_x000D_
_x000D_
_x000D_

code with output

showinfo=0 is used to remove title and &controls=0 is used for remove controls like volume,play,pause,expend.

Get string character by index - Java

You could use the String.charAt(int index) method result as the parameter for String.valueOf(char c).

String.valueOf(myString.charAt(3)) // This will return a string of the character on the 3rd position.

'IF' in 'SELECT' statement - choose output value based on column values

You can try this also

 SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table

how to update the multiple rows at a time using linq to sql?

To update one column here are some syntax options:

Option 1

var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>a.status=true);
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
     db.SomeTable
       .Where(x=>ls.Contains(x.friendid))
       .ToList()
       .ForEach(a=>a.status=true);

     db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
    }
    db.SubmitChanges();
}

Update

As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status at ones. We want to update name and status where the friendid is matching. Here are some syntax options for that:

Option 1

var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
    db.SomeTable
        .Where(x=>ls.Contains(x.friendid))
        .ToList()
        .ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
        some.name=name;
    }
    db.SubmitChanges();
}

Update 2

In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:

db.SubmitChanges();

But for Entity Framework to commit the changes it is:

db.SaveChanges()

MySQL Workbench: How to keep the connection alive

in mysql-workbech 5.7 edit->preference-> SSH -> SSH Connect timeout (for SSH DB connection) enter image description here

Why does a base64 encoded string have an = sign at the end

http://www.hcidata.info/base64.htm

Encoding "Mary had" to Base 64

In this example we are using a simple text string ("Mary had") but the principle holds no matter what the data is (e.g. graphics file). To convert each 24 bits of input data to 32 bits of output, Base 64 encoding splits the 24 bits into 4 chunks of 6 bits. The first problem we notice is that "Mary had" is not a multiple of 3 bytes - it is 8 bytes long. Because of this, the last group of bits is only 4 bits long. To remedy this we add two extra bits of '0' and remember this fact by putting a '=' at the end. If the text string to be converted to Base 64 was 7 bytes long, the last group would have had 2 bits. In this case we would have added four extra bits of '0' and remember this fact by putting '==' at the end.

LINQ's Distinct() on a particular property

What if I want to obtain a distinct list based on one or more properties?

Simple! You want to group them and pick a winner out of the group.

List<Person> distinctPeople = allPeople
  .GroupBy(p => p.PersonId)
  .Select(g => g.First())
  .ToList();

If you want to define groups on multiple properties, here's how:

List<Person> distinctPeople = allPeople
  .GroupBy(p => new {p.PersonId, p.FavoriteColor} )
  .Select(g => g.First())
  .ToList();

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:

.unbind() deprecated

Replace all instances of .unbind with .off

.removeAttribute() is not a function

Change lines 580-581 to use jQuery's .removeAttr() instead:

Old code:

580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');

New code:

580: content.removeAttr('filter');
581: wrap.removeAttr('filter');

This combined with the other patch mentioned above solved my compatibility issues.

Trying to merge 2 dataframes but get ValueError

It happens when common column in both table are of different data type.

Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

you can use LocalRegistry such as:

Registry rgsty = LocateRegistry.createRegistry(1888);
rgsty.rebind("hello", hello);

ggplot2 plot without axes, legends, etc

Late to the party, but might be of interest...

I find a combination of labs and guides specification useful in many cases:

You want nothing but a grid and a background:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  labs(x = NULL, y = NULL) + 
  guides(x = "none", y = "none")

enter image description here

You want to only suppress the tick-mark label of one or both axes:

ggplot(diamonds, mapping = aes(x = clarity)) + 
  geom_bar(aes(fill = cut)) + 
  guides(x = "none", y = "none")

enter image description here

Is unsigned integer subtraction defined behavior?

When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:

enter image description here

9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned, then modular arithmetic takes place.


Now look at the following operations storing the result as an unsigned int:

unsigned int five = 5, seven = 7;
unsigned int a = five - seven;      // a = (-2 % 2^32) = 4294967294 

int one = 1, six = 6;
unsigned int b = one - six;         // b = (-5 % 2^32) = 4294967291

When you want to make sure that the result is signed, then stored it into signed variable or cast it to signed. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs() function defined in stdlib.h:

int c = five - seven;       // c = -2
int d = abs(five - seven);  // d =  2

Be very careful, especially while writing conditions, because:

if (abs(five - seven) < seven)  // = if (2 < 7)
    // ...

if (five - seven < -1)          // = if (-2 < -1)
    // ...

if (one - six < 1)              // = if (-5 < 1)
    // ...

if ((int)(five - seven) < 1)    // = if (-2 < 1)
    // ...

but

if (five - seven < 1)   // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
    // ...

if (one - six < five)   // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
    // ...

How to clear variables in ipython?

An quit option in the Console Panel will also clear all variables in variable explorer

*** Note that you will be loosing all the code which you have run in Console Panel

foreach for JSON array , syntax

You can do something like

for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

Java decimal formatting using String.format?

Here is a small code snippet that does the job:

double a = 34.51234;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);

System.out.println(df.format(a));

Check for special characters in string

Check if a string contains at least one password special character:

For reference: ASCII Table -- Printable Characters

Special character ranges in the ASCII table are:

  • Space to /
  • : to @
  • [ to `
  • { to ~

Therefore, use this:

/[ -/:-@[-`{-~]/.test(string)

Removing MySQL 5.7 Completely

First of all, do a backup of your needed databases with mysqldump

Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).

In total, do this:

sudo service mysql stop  #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql

All above commands in single line (just copy and paste):

sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql

Moment JS - check if a date is today or in the future

if firstDate is same or after(future) secondDate return true else return false. Toda is firstDate = new Date();

  static isFirstDateSameOrAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isSameOrBefore(date2,'day');
    }
    return false;
  }

There is isSame, isBefore and isAfter for day compare moment example;

  static isFirstDateSameSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if (date1 && date2) {
      return date1.isSame(date2,'day');
    }
    return false;
  }

  static isFirstDateAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isAfter(date2,'day');
    }
    return false;
  }

  static isFirstDateBeforeSecondDate(firstDate: Date, secondDate: Date): boolean {
    var date1 = moment(firstDate);
    var date2 = moment(secondDate);
    if(date1 && date2){
      return date1.isBefore(date2,'day');
    }
    return false;
  }

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Access to ES6 array element index inside for-of loop

For those using objects that are not an Array or even array-like, you can build your own iterable easily so you can still use for of for things like localStorage which really only have a length:

function indexerator(length) {
    var output = new Object();
    var index = 0;
    output[Symbol.iterator] = function() {
        return {next:function() {
            return (index < length) ? {value:index++} : {done:true};
        }};
    };
    return output;
}

Then just feed it a number:

for (let index of indexerator(localStorage.length))
    console.log(localStorage.key(index))

How to change dataframe column names in pyspark?

Method 1:

df = df.withColumnRenamed("new_column_name", "old_column_name")

Method 2: If you want to do some computation and rename the new values

df = df.withColumn("old_column_name", F.when(F.col("old_column_name") > 1, F.lit(1)).otherwise(F.col("old_column_name"))
df = df.drop("new_column_name", "old_column_name")

Python: Remove division decimal

def division(a, b):
    return a / b if a % b else a // b

How to construct a set out of list items in python?

If you have a list of hashable objects (filenames would probably be strings, so they should count):

lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]

you can construct the set directly:

s = set(lst)

In fact, set will work this way with any iterable object! (Isn't duck typing great?)


If you want to do it iteratively:

s = set()
for item in iterable:
    s.add(item)

But there's rarely a need to do it this way. I only mention it because the set.add method is quite useful.

How to implement "Access-Control-Allow-Origin" header in asp.net

Another option is to add it on the web.config directly:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>

... I found this in here

Why doesn't wireshark detect my interface?

In Windows, with Wireshark 2.0.4, running as Administrator did not solve this for me. What did was restarting the NetGroup Packet Filter Driver (npf) service:

  1. Open a Command Prompt with administrative privileges.
  2. Execute the command sc query npf and verify if the service is running.
  3. Execute the command sc stop npf followed by the command sc start npf.
  4. Open WireShark and press F5.

Source: http://dynamic-datacenter.be/?p=1279

How can I pass parameters to a partial view in mvc 4

Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.

If you just render a partial with just the partial name:

@Html.Partial("_SomePartial")

It will actually pass your model as an implicit parameter, the same as if you were to call:

@Html.Partial("_SomePartial", Model)

Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:

@model Namespace.To.Your.Model

@Html.Action("MemberProfile", "Member", new { id = Model.Id })

Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary

@Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } });

And then:

@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })

As with the model, Razor will implicitly pass your partial the view's ViewData by default, so if you had ViewBag.Id in your view, then you can reference the same thing in your partial.

How do I check if an index exists on a table field in MySQL?

Use the following statement: SHOW INDEX FROM your_table

And then check the result for the fields: row["Table"], row["Key_name"]

Make sure you write "Key_name" correctly

Check if a string has white space

A few others have posted answers. There are some obvious problems, like it returns false when the Regex passes, and the ^ and $ operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).

Besides that, the issue is just a typo.

Change this...

var reWhiteSpace = new RegExp("/^\s+$/");

To this...

var reWhiteSpace = new RegExp("\\s+");

When using a regex within RegExp(), you must do the two following things...

  • Omit starting and ending / brackets.
  • Double-escape all sequences code, i.e., \\s in place of \s, etc.

Full working demo from source code....

_x000D_
_x000D_
$(document).ready(function(e) { function hasWhiteSpace(s) {
        var reWhiteSpace = new RegExp("\\s+");
    
        // Check for white space
        if (reWhiteSpace.test(s)) {
            //alert("Please Check Your Fields For Spaces");
            return 'true';
        }
    
        return 'false';
    }
  
  $('#whitespace1').html(hasWhiteSpace(' '));
  $('#whitespace2').html(hasWhiteSpace('123'));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
" ": <span id="whitespace1"></span><br>
"123": <span id="whitespace2"></span>
_x000D_
_x000D_
_x000D_

Getting View's coordinates relative to the root layout

You can use `

view.getLocationOnScreen(int[] location)

;` to get location of your view correctly.

But there is a catch if you use it before layout has been inflated you will get wrong position.

Solution to this problem is adding ViewTreeObserver like this :-

Declare globally the array to store x y position of your view

 int[] img_coordinates = new int[2];

and then add ViewTreeObserver on your parent layout to get callback for layout inflation and only then fetch position of view otherwise you will get wrong x y coordinates

  // set a global layout listener which will be called when the layout pass is completed and the view is drawn
            parentViewGroup.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        public void onGlobalLayout() {
                            //Remove the listener before proceeding
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                parentViewGroup.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            } else {
                                parentViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            }

                            // measure your views here
                            fab.getLocationOnScreen(img_coordinates);
                        }
                    }
            );

and then use it like this

xposition = img_coordinates[0];
yposition =  img_coordinates[1];

jQuery Show-Hide DIV based on Checkbox Value

`Display

$('#cbxShowHide').click(function(){ this.checked?$('#block').show(1000):$('#block').hide(1000); //time for show });`

How To Convert A Number To an ASCII Character?

To get ascii to a number, you would just cast your char value into an integer.

char ascii = 'a'
int value = (int)ascii

Variable value will now have 97 which corresponds to the value of that ascii character

(Use this link for reference) http://www.asciitable.com/index/asciifull.gif

Bash: Syntax error: redirection unexpected

Docker:

I was getting this problem from my Dockerfile as I had:

RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

However, according to this issue, it was solved:

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.

Note

To use a different shell, other than /bin/sh, use the exec form passing in the desired shell. For example,

RUN ["/bin/bash", "-c", "echo hello"]

Solution:

RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]

Notice the quotes around each parameter.

Multiple conditions in ngClass - Angular 4

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">    

MySQL: is a SELECT statement case sensitive?

String fields with the binary flag set will always be case sensitive. Should you need a case sensitive search for a non binary text field use this: SELECT 'test' REGEXP BINARY 'TEST' AS RESULT;

make arrayList.toArray() return more specific types

I got the answer...this seems to be working perfectly fine

public int[] test ( int[]b )
{
    ArrayList<Integer> l = new ArrayList<Integer>();
    Object[] returnArrayObject = l.toArray();
    int returnArray[] = new int[returnArrayObject.length];
    for (int i = 0; i < returnArrayObject.length; i++){
         returnArray[i] = (Integer)  returnArrayObject[i];
    }

    return returnArray;
}

How to serve up images in Angular2?

Just put your images in the assets folder refer them in your html pages or ts files with that link.

Why does GitHub recommend HTTPS over SSH?

Enabling SSH connections over HTTPS if it is blocked by firewall

Test if SSH over the HTTPS port is possible, run this SSH command:

$ ssh -T -p 443 [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.

If that worked, great! If not, you may need to follow our troubleshooting guide.

If you are able to SSH into [email protected] over port 443, you can override your SSH settings to force any connection to GitHub to run though that server and port.

To set this in your ssh config, edit the file at ~/.ssh/config, and add this section:

Host github.com
  Hostname ssh.github.com
  Port 443

You can test that this works by connecting once more to GitHub:

$ ssh -T [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.

From Authenticating to GitHub / Using SSH over the HTTPS port

Sending string via socket (python)

import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')

serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

Using C++ filestreams (fstream), how can you determine the size of a file?

You can open the file using the ios::ate flag (and ios::binary flag), so the tellg() function will give you directly the file size:

ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Disable clipboard prompt in Excel VBA on workbook close

I have hit this problem in the past - from the look of it if you don't actually need the clipboard at the point that you exit, so you can use the same simple solution I had. Just clear the clipboard. :)

ActiveCell.Copy

How to auto-size an iFrame?

This solution worked best for me. It uses jQuery and the iframe's ".load" event.

Read file from line 2 or skip header row

If you want the first line and then you want to perform some operation on file this code will helpful.

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

eslint: error Parsing error: The keyword 'const' is reserved

In my case, it was unable to find the .eslintrc file so I copied from node_modules/.bin to root.

Adding Multiple Values in ArrayList at a single index

How about

  1. First adding your desired result as arraylist and
  2. and convert to double array as you want.

Try like this..

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

    public class ArrayTest {

        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub

            // Your Prepared data. 
            List<double[]> values = new ArrayList<double[]>(2);

            double[] element1 = new double[] { 100, 100, 100, 100, 100 };
            double[] element2 = new double[] { 50, 35, 25, 45, 65 };

            values.add(element1);
            values.add(element2);

            // Add the result to arraylist.
            List<Double> temp = new ArrayList<Double>();
            for(int j=0;j<values.size(); j++) {
                for (int i = 0; i < values.get(0).length; i++) {
                    temp.add(values.get(0)[i]);
                    temp.add(values.get(1)[i]);
                }
            }

            // Convert arraylist to int[].
            Double[] result = temp.toArray(new Double[temp.size()]);
            double[] finalResult = new double[result.length]; // This hold final result.
            for (int i = 0; i < result.length; i++) {
                finalResult[i] = result[i].doubleValue();
            }

            for (int i = 0; i < finalResult.length; i++) {
                System.out.println(finalResult[i]);
            }
        }
    }

Regex to get the words after matching string

This might work out for you depending on which language you are using:

(?<=Object Name:).*

It's a positive lookbehind assertion. More information could be found here.

It won't work with JavaScript though. In your comment I read that you're using it for logstash. If you are using GROK parsing for logstash then it would work. You can verify it yourself here:

https://grokdebug.herokuapp.com/

Enter image description here

JUnit 5: How to assert an exception is thrown?

Actually I think there is a error in the documentation for this particular example. The method that is intended is expectThrows

public static void assertThrows(
public static <T extends Throwable> T expectThrows(

How to merge two files line by line in Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

How to combine two strings together in PHP?

combine two strings together in PHP?

$result = $data1 . ' ' . $data2;

400 vs 422 response to POST of data

Firstly this is a very good question.

400 Bad Request - When a critical piece of information is missing from the request

e.g. The authorization header or content type header. Which is absolutely required by the server to understand the request. This can differ from server to server.

422 Unprocessable Entity - When the request body can't be parsed.

This is less severe than 400. The request has reached the server. The server has acknowledged the request has got the basic structure right. But the information in the request body can't be parsed or understood.

e.g. Content-Type: application/xml when request body is JSON.

Here's an article listing status codes and its use in REST APIs. https://metamug.com/article/status-codes-for-rest-api.php

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old.
  • The speed tests quoted below are comparing an older version of Json.Nt (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


Update since .Net Core 3.0

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .


I would recommend Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file


Why? Here's a feature comparison between common serialisers as well as benchmark tests .

Below is a graph of performance taken from the linked article:

enter image description here

This separate post, states that:

Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer


Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned

These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.

Count rows with not empty value

For me, none of the answers worked for ranges that include both virgin cells and cells that are empty based on a formula (e.g. =IF(1=2;"";""))

What solved it for me is this:

=COUNTA(FILTER(range, range <> ""))

Unit tests vs Functional tests

AFAIK, unit testing is NOT functional testing. Let me explain with a small example. You want to test if the login functionality of an email web app is working or not, just as a user would. For that, your functional tests should be like this.

1- existing email, wrong password -> login page should show error "wrong password"!
2- non-existing email, any password -> login page should show error "no such email".
3- existing email, right password -> user should be taken to his inbox page.
4- no @symbol in email, right password -> login page should say "errors in form, please fix them!" 

Should our functional tests check if we can login with invalid inputs ? Eg. Email has no @ symbol, username has more than one dot (only one dot is permitted), .com appears before @ etc. ? Generally, no ! That kind of testing goes into your unit tests.

You can check if invalid inputs are rejected inside unit tests as shown in the tests below.

class LoginInputsValidator
  method validate_inputs_values(email, password)
    1-If email is not like [email protected], then throw error.
    2-If email contains abusive words, then throw error.
    3-If password is less than 10 chars, throw error.

Notice that the functional test 4 is actually doing what unit test 1 is doing. Sometimes, functional tests can repeat some (not all) of the testing done by unit tests, for different reasons. In our example, we use functional test 4 to check if a particular error message appears on entering invalid input. We don't want to test if all bad inputs are rejected or not. That is the job of unit tests.

Git: How to remove file from index without deleting files from any repository

After doing the git rm --cached command, try adding myfile to the .gitignore file (create one if it does not exist). This should tell git to ignore myfile.

The .gitignore file is versioned, so you'll need to commit it and push it to the remote repository.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

What you are referring to is metadata, data about data. I had this same issue for the project I am currently working on and had to spend some time trying to figure it out. It's too much information to post here, but below are two links you may find useful. They do reference the Symfony framework, but are based on the Doctrine ORM.

http://melikedev.com/2010/04/06/symfony-saving-metadata-during-form-save-sort-ids/

http://melikedev.com/2009/12/09/symfony-w-doctrine-saving-many-to-many-mm-relationships/

Good luck, and nice Metallica references!

Paused in debugger in chrome?

At the right upper corner second last icon (encircled red in attached image) is for activate/deactivate debugging. Click it to toggle debugging anytime.

Chrome Debug console

How do you use the "WITH" clause in MySQL?

MySQL prior to version 8.0 doesn't support the WITH clause (CTE in SQL Server parlance; Subquery Factoring in Oracle), so you are left with using:

  • TEMPORARY tables
  • DERIVED tables
  • inline views (effectively what the WITH clause represents - they are interchangeable)

The request for the feature dates back to 2006.

As mentioned, you provided a poor example - there's no need to perform a subselect if you aren't altering the output of the columns in any way:

  SELECT * 
    FROM ARTICLE t
    JOIN USERINFO ui ON ui.user_userid = t.article_ownerid
    JOIN CATEGORY c ON c.catid =  t.article_categoryid
   WHERE t.published_ind = 0
ORDER BY t.article_date DESC 
   LIMIT 1, 3

Here's a better example:

SELECT t.name,
       t.num
  FROM TABLE t
  JOIN (SELECT c.id
               COUNT(*) 'num'
          FROM TABLE c
         WHERE c.column = 'a'
      GROUP BY c.id) ta ON ta.id = t.id

Is it possible to run CUDA on AMD GPUs?

You can run NVIDIA® CUDA™ code on Mac, and indeed on OpenCL 1.2 GPUs in general, using Coriander . Disclosure: I'm the author. Example usage:

cocl cuda_sample.cu
./cuda_sample

Result: enter image description here

How do I convert a double into a string in C++?

You may want to read my prior posting on SO. (Macro'ed version with a temporary ostringstream object.)

For the record: In my own code, I favor snprintf(). With a char array on the local stack, it's not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice...)

(I've also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code...)

TOMCAT - HTTP Status 404

You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.8\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or ../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Source: HTTP Status 404 error in tomcat

How do I wrap text in a pre tag?

Try using

<pre style="white-space:normal;">. 

Or better throw CSS.

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

Is bool a native C type?

stdbool.h defines macros true and false, but remember they are defined to be 1 and 0.

That is why sizeof(true) is 4.

How to remove a field completely from a MongoDB document?

Checking if "words" exists and then removing from the document

    db.users.update({"tags.words" :{$exists: true}},
                                           {$unset:{"tags.words":1}},false,true);

true indicates update multiple documents if matched.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

How to access POST form fields

Given some form:

<form action='/somepath' method='post'>
   <input type='text' name='name'></input>
</form>

Using express

app.post('/somepath', function(req, res) {

    console.log(JSON.stringify(req.body));

    console.log('req.body.name', req.body['name']);
});

Output:

{"name":"x","description":"x"}
req.param.name x

How to support UTF-8 encoding in Eclipse

Just right click the Project -- Properties and select Resource on the left side menu.

You can now change the Text-file encoding to whatever you wish.

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

Web application context, specified by the WebApplicationContext interface, is a Spring application context for a web applications. It has all the properties of a regular Spring application context, given that the WebApplicationContext interface extends the ApplicationContext interface, and add a method for retrieving the standard Servlet API ServletContext for the web application.

In addition to the standard Spring bean scopes singleton and prototype, there are three additional scopes available in a web application context:

  • request - scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition
  • session - scopes a single bean definition to the lifecycle of an HTTP Session
  • application - scopes a single bean definition to the lifecycle of a ServletContext

Instagram API to fetch pictures with specific hashtags

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

You can query results for a particular hashtag (snowy in this case) using the following url

It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour

https://api.instagram.com/v1/tags/snowy/media/recent

Sample response

{
  "pagination":  {
    "next_max_tag_id": "1370433362010",
    "deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
    "next_max_id": "1370433362010",
    "next_min_id": "1370443976800",
    "min_tag_id": "1370443976800",
    "next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
  },
  "meta":  {
    "code": 200
  },
  "data":  [
     {
      "attribution": null,
      "tags":  [
        "snowy"
      ],
      "type": "image",
      "location": null,
      "comments":  {
        "count": 0,
        "data":  []
      },
      "filter": null,
      "created_time": "1370418343",
      "link": "http://instagram.com/p/aK1yrGRi3l/",
      "likes":  {
        "count": 1,
        "data":  [
           {
            "username": "iri92lol",
            "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
            "id": "404174490",
            "full_name": "Iri"
          }
        ]
      },
      "images":  {
        "low_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
          "width": 306,
          "height": 306
        },
        "thumbnail":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
          "width": 150,
          "height": 150
        },
        "standard_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
          "width": 612,
          "height": 612
        }
      },
      "users_in_photo":  [],
      "caption":  {
        "created_time": "1370418353",
        "text": "#snowy",
        "from":  {
          "username": "iri92lol",
          "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
          "id": "404174490",
          "full_name": "Iri"
        },
        "id": "471425773832908504"
      },
      "user_has_liked": false,
      "id": "471425689728724453_404174490",
      "user":  {
        "username": "iri92lol",
        "website": "",
        "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
        "full_name": "Iri",
        "bio": "",
        "id": "404174490"
      }
    }
}

You can play around here :

https://apigee.com/console/instagram?req=%7B%22resource%22%3A%22get_tags_media_recent%22%2C%22params%22%3A%7B%22query%22%3A%7B%7D%2C%22template%22%3A%7B%22tag-name%22%3A%22snowy%22%7D%2C%22headers%22%3A%7B%7D%2C%22body%22%3A%7B%22attachmentFormat%22%3A%22mime%22%2C%22attachmentContentDisposition%22%3A%22form-data%22%7D%7D%2C%22verb%22%3A%22get%22%7D

You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.

All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.

How to ignore the first line of data when processing CSV data?

Python 2.x

csvreader.next()

Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

csv_data = csv.reader(open('sample.csv'))
csv_data.next() # skip first row
for row in csv_data:
    print(row) # should print second row

Python 3.x

csvreader.__next__()

Return the next row of the reader’s iterable object as a list (if the object was returned from reader()) or a dict (if it is a DictReader instance), parsed according to the current dialect. Usually you should call this as next(reader).

csv_data = csv.reader(open('sample.csv'))
csv_data.__next__() # skip first row
for row in csv_data:
    print(row) # should print second row

Split List into Sublists with LINQ

Try the following code.

public static IList<IList<T>> Split<T>(IList<T> source)
{
    return  source
        .Select((x, i) => new { Index = i, Value = x })
        .GroupBy(x => x.Index / 3)
        .Select(x => x.Select(v => v.Value).ToList())
        .ToList();
}

The idea is to first group the elements by indexes. Dividing by three has the effect of grouping them into groups of 3. Then convert each group to a list and the IEnumerable of List to a List of Lists

bash: npm: command not found?

Just go into npm page and follow the instructions.

How to store file name in database, with other info while uploading image to server using PHP?

Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.

Firstly the form you need:

    <form method="post" action="addMember.php" enctype="multipart/form-data">
    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
          </form>

Then this code processes you data from the form:

   <?php

// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];


// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;

// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?> 

Code edited from www.about.com

Android: textview hyperlink

This is my working implementation

private void showMessage()
    {

        lblMessage.setText("");

        List<String> messages = db.getAllGCMMessages();

        for (int k = messages.size() - 1; k >= 0; --k)
         {

            String message  =  messages.get(k).toString();
            lblMessage.append(message + "\n\n");

         }
     Linkify.addLinks(lblMessage, Linkify.ALL);
  }

and to change color of hyperlinks , i editted my xml for textview -

 android:textColorLink="#69463d"

How to open .dll files to see what is written inside?

Open .dll file with visual studio. Or resource editor.

Finding the id of a parent div using Jquery

JQUery has a .parents() method for moving up the DOM tree you can start there.

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />
</p>

and

$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);
    $("#messages").html(feedback);
});

Not quite sure how your validate and feedback are working, but you get the idea.

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

JAXB Exception: Class not known to this context

I had the same problem with spring boot. It resolved when i set package to marshaller.

@Bean
public Jaxb2Marshaller marshaller() throws Exception
{
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setPackagesToScan("com.octory.ws.dto");
    return marshaller;
}

@Bean
public WebServiceTemplate webServiceTemplate(final Jaxb2Marshaller marshaller)   
{
    WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
    webServiceTemplate.setMarshaller(marshaller);
    webServiceTemplate.setUnmarshaller(marshaller);
    return webServiceTemplate;
}

Squash my last X commits together using Git

To do this you can use following git command.

 git rebase -i HEAD~n

n(=4 here) is the number of last commit. Then you got following options,

pick 01d1124 Message....
pick 6340aaa Message....
pick ebfd367 Message....
pick 30e0ccb Message....

Update like below pick one commit and squash the others into the most recent,

p 01d1124 Message....
s 6340aaa Message....
s ebfd367 Message....
s 30e0ccb Message....

For details click on the Link

How to convert integer to string in C?

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

Node.js - SyntaxError: Unexpected token import

My project uses node v10.21.0, which still does not support ES6 import keyword. There are multiple ways to make node recognize import, one of them is to start node with node --experimental-modules index.mjs (The mjs extension is already covered in one of the answers here). But, this way, you will not be able to use node specific keyword like require in your code. If there is need to use both nodejs's require keyword along with ES6's import, then the way out is to use the esm npm package. After adding esm package as a dependency, node needs to be started with a special configuration like: node -r esm index.js

Better way to find index of item in ArrayList?

ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index

int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
    Log.e(TAG, "Object not found in List");
} else {
    Log.i(TAG, "" + position);
}

Output: List Index : 7

If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.

Done

Java: is there a map function?

There is a wonderful library called Functional Java which handles many of the things you'd want Java to have but it doesn't. Then again, there's also this wonderful language Scala which does everything Java should have done but doesn't while still being compatible with anything written for the JVM.

Create an Excel file using vbscripts

set objExcel = CreateObject("Excel.Application")
objExcel.Application.DisplayAlerts = False
set objWorkbook=objExcel.workbooks.add()
objExcel.cells(1,1).value = "Test value"
objExcel.cells(1,2).value = "Test data"
objWorkbook.Saveas "c:\testXLS.xls"
objWorkbook.Close
objExcel.workbooks.close
objExcel.quit
set objExcel = nothing `

How to get a barplot with several variables side by side grouped by a factor

You can plot the means without resorting to external calculations and additional tables using stat_summary(...). In fact, stat_summary(...) was designed for exactly what you are doing.

library(ggplot2)
library(reshape2)            # for melt(...)
gg <- melt(df,id="gender")   # df is your original table
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  scale_color_discrete("Gender")
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey80",position=position_dodge(1), width=.2)

To add "error bars" you cna also use stat_summary(...) (here, I'm using the min and max value rather than sd because you have so little data).

ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey40",position=position_dodge(1), width=.2) +
  scale_fill_discrete("Gender")

How to get a file directory path from file path?

I was playing with this and came up with an alternative.

$ VAR=/home/me/mydir/file.c

$ DIR=`echo $VAR |xargs dirname`

$ echo $DIR
/home/me/mydir

The part I liked is it was easy to extend backup the tree:

$ DIR=`echo $VAR |xargs dirname |xargs dirname |xargs dirname`

$ echo $DIR
/home

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

How to reload a page using Angularjs?

You need $route defined in your module and change the JS to this.

$scope.backLinkClick = function () {
  window.location.reload(); 
};

that works fine for me.

How do I edit SSIS package files?

You need the Business Intelligence Studio ..I've checked and my version of VS2008 Pro doesn't have them installed.

Have a look at this link:

http://www.microsoft.com/downloads/details.aspx?familyid=3C856B93-369F-4C6F-9357-C35384179543&displaylang=en

Delaying AngularJS route change until model loaded to prevent flicker

I worked from Misko's code above and this is what I've done with it. This is a more current solution since $defer has been changed to $timeout. Substituting $timeout however will wait for the timeout period (in Misko's code, 1 second), then return the data hoping it's resolved in time. With this way, it returns asap.

function PhoneListCtrl($scope, phones) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

PhoneListCtrl.resolve = {

  phones: function($q, Phone) {
    var deferred = $q.defer();

    Phone.query(function(phones) {
        deferred.resolve(phones);
    });

    return deferred.promise;
  }
}

How to get just the date part of getdate()?

try this:

select convert (date ,getdate())

or

select CAST (getdate() as DATE)

or

select convert(varchar(10), getdate(),121)

Storing query results into a variable and modifying it inside a Stored Procedure

Try this example

CREATE PROCEDURE MyProc
BEGIN
    --Stored Procedure variables
    Declare @maxOr int; 
    Declare @maxCa int; 

    --Getting query result in the variable (first variant of syntax)
    SET @maxOr = (SELECT MAX(orId) FROM [order]); 

    --Another variant of seting variable from query
    SELECT @maxCa=MAX(caId) FROM [cart]; 

    --Updating record through the variable
    INSERT INTO [order_cart] (orId,caId)
    VALUES(@maxOr, @maxCa); 

    --return values to the program as dataset
    SELECT
       @maxOr AS maxOr,
       @maxCa AS maxCa

    -- return one int value as "return value"
    RETURN @maxOr
END
GO

SQL-command to call the stored procedure

EXEC MyProc

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

What is a loop invariant?

A loop invariant is an assertion that is true before and after loop execution.

How to Pass Parameters to Activator.CreateInstance<T>()

As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5). See StackOverflow post for stats, info and code:

How to pass ctor args in Activator.CreateInstance or use IL?

How to set gradle home while importing existing project in Android studio

I ran into same problem. I selected location C:\Program Files (x86)\Android\android-studio\plugins\gradle as Gradle Home

require is not defined? Node.js

This can now also happen in Node.js as of version 14.

It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.

To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.

jQuery: Setting select list 'selected' based on text, failing strangely

In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript

document.getElementById("The id of the element").value = "The value"

And that would set the value and make the current value selected in the combo box. Tested in firefox.

it was easier than keep googling a solution for jQuery

What does SQL clause "GROUP BY 1" mean?

It means to group by the first column regardless of what it's called. You can do the same with ORDER BY.

How do I format a date as ISO 8601 in moment.js?

var x = moment();

//date.format(moment.ISO_8601); // error

moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);

Download history stock prices automatically from yahoo finance in python

You can check out the yahoo_fin package. It was initially created after Yahoo Finance changed their API (documentation is here: http://theautomatic.net/yahoo_fin-documentation).

from yahoo_fin import stock_info as si

aapl_data = si.get_data("aapl")

nflx_data = si.get_data("nflx")

aapl_data.head()

nflx_data.head()

aapl.to_csv("aapl_data.csv")

nflx_data.to_csv("nflx_data.csv")

Read XML file into XmlDocument

XmlDocument doc = new XmlDocument();
   doc.Load("MonFichierXML.xml");

    XmlNode node = doc.SelectSingleNode("Magasin");

    XmlNodeList prop = node.SelectNodes("Items");

    foreach (XmlNode item in prop)
    {
        items Temp = new items();
        Temp.AssignInfo(item);
        lstitems.Add(Temp);
    }

How do I revert an SVN commit?

It is impossible to "uncommit" a revision, but you can revert your working copy to version 1943 and commit that as version 1945. The versions 1943 and 1945 will be identical, effectively reverting the changes.

ModelState.IsValid == false, why?

The ModelState property on the controller is actually a ModelStateDictionary object. You can iterate through the keys on the dictionary and use the IsValidField method to check if that particular field is valid.

How do I find numeric columns in Pandas?

You could use select_dtypes method of DataFrame. It includes two parameters include and exclude. So isNumeric would look like:

numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']

newdf = df.select_dtypes(include=numerics)

How can you tell if a value is not numeric in Oracle?

The best answer I found on internet:

SELECT case when trim(TRANSLATE(col1, '0123456789-,.', ' ')) is null
            then 'numeric'
            else 'alpha'
       end
FROM tab1;

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Go to Window-->Preferences-->Java-->Compiler-->Error/Warnings.
Select Deprecated and Restricted API. Change it to warning.
Change forbidden and Discouraged Reference and change it to warning. (or as your need.)

How to set URL query params in Vue with Vue-Router

Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:

addParamsToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path +
      '?' +
      Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
          )
        })
        .join('&')
  )
}

So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.

To add query params to current location without pushing a new history entry, use history.replaceState instead.

Tested with Vue 2.6.10 and Nuxt 2.8.1.

Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.

toggle show/hide div with button?

You could use the following:

mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block');

Is there a "theirs" version of "git merge -s ours"?

See Junio Hamano's widely cited answer: if you're going to discard committed content, just discard the commits, or at any rate keep it out of the main history. Why bother everyone in the future reading commit messages from commits that have nothing to offer?

But sometimes there are administrative requirements, or perhaps some other reason. For those situations where you really have to record commits that contribute nothing, you want:

(edit: wow, did I manage to get this wrong before. This one works.)

git update-ref HEAD $(
        git commit-tree -m 'completely superseding with branchB content' \
                        -p HEAD -p branchB    branchB:
)
git reset --hard

Convert numpy array to tuple

Here's a function that'll do it:

def totuple(a):
    try:
        return tuple(totuple(i) for i in a)
    except TypeError:
        return a

And an example:

>>> array = numpy.array(((2,2),(2,-2)))
>>> totuple(array)
((2, 2), (2, -2))

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

how does multiplication differ for NumPy Matrix vs Array classes?

the key things to know for operations on NumPy arrays versus operations on NumPy matrices are:

  • NumPy matrix is a subclass of NumPy array

  • NumPy array operations are element-wise (once broadcasting is accounted for)

  • NumPy matrix operations follow the ordinary rules of linear algebra

some code snippets to illustrate:

>>> from numpy import linalg as LA
>>> import numpy as NP

>>> a1 = NP.matrix("4 3 5; 6 7 8; 1 3 13; 7 21 9")
>>> a1
matrix([[ 4,  3,  5],
        [ 6,  7,  8],
        [ 1,  3, 13],
        [ 7, 21,  9]])

>>> a2 = NP.matrix("7 8 15; 5 3 11; 7 4 9; 6 15 4")
>>> a2
matrix([[ 7,  8, 15],
        [ 5,  3, 11],
        [ 7,  4,  9],
        [ 6, 15,  4]])

>>> a1.shape
(4, 3)

>>> a2.shape
(4, 3)

>>> a2t = a2.T
>>> a2t.shape
(3, 4)

>>> a1 * a2t         # same as NP.dot(a1, a2t) 
matrix([[127,  84,  85,  89],
        [218, 139, 142, 173],
        [226, 157, 136, 103],
        [352, 197, 214, 393]])

but this operations fails if these two NumPy matrices are converted to arrays:

>>> a1 = NP.array(a1)
>>> a2t = NP.array(a2t)

>>> a1 * a2t
Traceback (most recent call last):
   File "<pyshell#277>", line 1, in <module>
   a1 * a2t
   ValueError: operands could not be broadcast together with shapes (4,3) (3,4) 

though using the NP.dot syntax works with arrays; this operations works like matrix multiplication:

>> NP.dot(a1, a2t)
array([[127,  84,  85,  89],
       [218, 139, 142, 173],
       [226, 157, 136, 103],
       [352, 197, 214, 393]])

so do you ever need a NumPy matrix? ie, will a NumPy array suffice for linear algebra computation (provided you know the correct syntax, ie, NP.dot)?

the rule seems to be that if the arguments (arrays) have shapes (m x n) compatible with the a given linear algebra operation, then you are ok, otherwise, NumPy throws.

the only exception i have come across (there are likely others) is calculating matrix inverse.

below are snippets in which i have called a pure linear algebra operation (in fact, from Numpy's Linear Algebra module) and passed in a NumPy array

determinant of an array:

>>> m = NP.random.randint(0, 10, 16).reshape(4, 4)
>>> m
array([[6, 2, 5, 2],
       [8, 5, 1, 6],
       [5, 9, 7, 5],
       [0, 5, 6, 7]])

>>> type(m)
<type 'numpy.ndarray'>

>>> md = LA.det(m)
>>> md
1772.9999999999995

eigenvectors/eigenvalue pairs:

>>> LA.eig(m)
(array([ 19.703+0.j   ,   0.097+4.198j,   0.097-4.198j,   5.103+0.j   ]), 
array([[-0.374+0.j   , -0.091+0.278j, -0.091-0.278j, -0.574+0.j   ],
       [-0.446+0.j   ,  0.671+0.j   ,  0.671+0.j   , -0.084+0.j   ],
       [-0.654+0.j   , -0.239-0.476j, -0.239+0.476j, -0.181+0.j   ],
       [-0.484+0.j   , -0.387+0.178j, -0.387-0.178j,  0.794+0.j   ]]))

matrix norm:

>>>> LA.norm(m)
22.0227

qr factorization:

>>> LA.qr(a1)
(array([[ 0.5,  0.5,  0.5],
        [ 0.5,  0.5, -0.5],
        [ 0.5, -0.5,  0.5],
        [ 0.5, -0.5, -0.5]]), 
 array([[ 6.,  6.,  6.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]))

matrix rank:

>>> m = NP.random.rand(40).reshape(8, 5)
>>> m
array([[ 0.545,  0.459,  0.601,  0.34 ,  0.778],
       [ 0.799,  0.047,  0.699,  0.907,  0.381],
       [ 0.004,  0.136,  0.819,  0.647,  0.892],
       [ 0.062,  0.389,  0.183,  0.289,  0.809],
       [ 0.539,  0.213,  0.805,  0.61 ,  0.677],
       [ 0.269,  0.071,  0.377,  0.25 ,  0.692],
       [ 0.274,  0.206,  0.655,  0.062,  0.229],
       [ 0.397,  0.115,  0.083,  0.19 ,  0.701]])
>>> LA.matrix_rank(m)
5

matrix condition:

>>> a1 = NP.random.randint(1, 10, 12).reshape(4, 3)
>>> LA.cond(a1)
5.7093446189400954

inversion requires a NumPy matrix though:

>>> a1 = NP.matrix(a1)
>>> type(a1)
<class 'numpy.matrixlib.defmatrix.matrix'>

>>> a1.I
matrix([[ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028]])
>>> a1 = NP.array(a1)
>>> a1.I

Traceback (most recent call last):
   File "<pyshell#230>", line 1, in <module>
   a1.I
   AttributeError: 'numpy.ndarray' object has no attribute 'I'

but the Moore-Penrose pseudoinverse seems to works just fine

>>> LA.pinv(m)
matrix([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
        [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
        [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
        [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
        [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

>>> m = NP.array(m)

>>> LA.pinv(m)
array([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
       [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
       [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
       [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
       [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

Django - Reverse for '' not found. '' is not a valid view function or pattern name

In my case, I don't put namespace_name in the url tag ex: {% url 'url_name or pattern name' %}. you have to specify the namespace_name like: {% url 'namespace_name:url_name or pattern name' %}.

Explanation: In project urls.py path('', include('blog.urls',namespace='blog')), and in app's urls.py you have to specify the app_name. like app_name = 'blog'. namespace_name is the app_name.

How to use unicode characters in Windows command line?

Actually, the trick is that the command prompt actually understands these non-english characters, just can't display them correctly.

When I enter a path in the command prompt that contains some non-english chracters it is displayed as "?? ?????? ?????". When you submit your command (cd "??? ?????? ?????" in my case), everything is working as expected.

How to deploy a Java Web Application (.war) on tomcat?

The tomcat manual says:

Copy the web application archive file into directory $CATALINA_HOME/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.

Python: printing a file to stdout

you can also try this

print ''.join(file('example.txt'))

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

Managing SSH keys within Jenkins for Git

It looks like the github.com host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts. Jenkins runs on most distros as the user jenkins and hence has its own .ssh directory to store the list of public keys and known_hosts.

The easiest solution I can think of to fix this problem is:

# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash

cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL

# Allow adding the SSH host key to your known_hosts

# Exit from su
exit

Recursive file search using PowerShell

To add to @user3303020 answer and output the search results into a file, you can run

Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat > path_to_results_filename.txt

It may be easier to search for the correct file that way.

MySQL: Delete all rows older than 10 minutes

If time_created is a unix timestamp (int), you should be able to use something like this:

DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);

(600 seconds = 10 minutes - obviously)

Otherwise (if time_created is mysql timestamp), you could try this:

DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)

Django: List field in model?

If you are using PostgreSQL, you can use ArrayField with a nested ArrayField: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/

This way, the data structure will be known to the underlying database. Also, the ORM brings special functionality for it.

Note that you will have to create a GIN index by yourself, though (see the above link, further down: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#indexing-arrayfield).

(Edit: updated links to newest Django LTS, this feature exists at least since 1.8.)

javascript check for not null

This should work fine..

   if(val!= null)
    {
       alert("value is "+val.length); //-- this returns 4
    }
    else
    {
       alert("value* is null");
    }

How do I create executable Java program?

If you are using Eclipse , you can try the below 7 steps to get a .exe file for Windows.

step1step2step3

Now you have a JAR file. Use java -jar path/jarname.jar to execute.

enter image description here


If you want to convert this to .exe, you can try http://sourceforge.net/projects/launch4j/files/launch4j-3/

STEP5STEP6

STEP7: Give the .xml file an appropriate name and click "Save". The .xml file is standard, don't worry about it. Your executable file will now be created!

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

Compiling dynamic HTML strings from database

In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.

I fixed that by fetching the attribute from the scope property

 scope: { dynamic: '=dynamic'}, 

My example

angular.module('app')
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'dynamic' , function(html){
          element.html(html);
          $compile(element.contents())(scope);
        });
      }
    };
  });

How to remove undefined and null values from an object using lodash?

You can simply chain _.omit() with _.isUndefined and _.isNull compositions, and get the result with lazy evaluation.

Demo

var result = _(my_object).omit(_.isUndefined).omit(_.isNull).value();

Update March 14, 2016:

As mentioned by dylants in the comment section, you should use the _.omitBy() function since it uses a predicate instead of a property. You should use this for lodash version 4.0.0 and above.

DEMO

var result = _(my_object).omitBy(_.isUndefined).omitBy(_.isNull).value();

Update June 1, 2016:

As commented by Max Truxa, lodash already provided an alternative _.isNil, which checks for both null and undefined:

var result = _.omitBy(my_object, _.isNil);

How can I upload fresh code at github?

If you haven't already created the project in Github, do so on that site. If memory serves, they display a page that tells you exactly how to get your existing code into your new repository. At the risk of oversimplification, though, you'd follow Veeti's instructions, then:

git remote add [name to use for remote] [private URI] # associate your local repository to the remote
git push [name of remote] master # push your repository to the remote

PHPMailer character encoding issues

When non of the above works, and still mails looks like ª הודפסה ×•× ×©×œ:

$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';;

Can I access constants in settings.py from templates in Django?

If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file
    
    def admin_media(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
    
  2. add your context processor to your settings.py file:

    TEMPLATES = [{
        # whatever comes before
        'OPTIONS': {
            'context_processors': [
                # whatever comes before
                "your_app.context_processors.admin_media",
            ],
        }
    }]
    
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render
    
    def my_view(request):
        return render(request, "index.html")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    

OS X Framework Library not loaded: 'Image not found'

I had the same issue for a different reason. I've created a new configuration to Debug and Release (under PROJECT -> Info tab -> Configuration). And I had to change my pod frameworks shell script (Pods-"appName"-frameworks.sh , under Targets Support Files) to make it work.

[Xcode 9]

Why do abstract classes in Java have constructors?

Because another class could extend it, and the child class needs to invoke a superclass constructor.

Trigger to fire only if a condition is met in SQL Server

Given that a WHERE clause did not work, maybe this will:

CREATE TRIGGER 
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON

      If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'
      Begin
          Return
      End

      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      Attribute,
      ParameterValue,
      ParameterDescription,
      ChangeDate
    FROM Inserted AS I
END

If Else in LINQ

 var result = _context.Employees
                .Where(x => !x.IsDeleted)
                .Where(x => x.ClientId > (clientId > 0 ? clientId - 1 : -1))
                .Where(x => x.ClientId < (clientId > 0 ? clientId + 1 : 1000))
                .Where(x => x.ContractorFlag == employeeFlag);
            return result;

If clientId = 0 we want ALL employees,. but for any clientId between 1 and 999 we want only clients with that ID. I was having issues with seperate LINQ statements not being the same (Deleted/Clients filters need to be on all queries), so by add these two lines it works (all be it until we have 999+ clients - which would be a happy re-factor day!!

How to convert HTML to PDF using iTextSharp

As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml

Usage is straightforward:

HtmlConverter.ConvertToPdf(
    new FileInfo(@"Path\to\Html\File.html"),
    new FileInfo(@"Path\to\Pdf\File.pdf")
);

Method has many more overloads.

Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.

How to get WordPress post featured image URL

You can also get the URL for image attachments as follows:

<?php
    "<div><a href=".get_permalink(id).">".wp_get_attachment_url(304, array(50,50), 1)."</a></div>";
?>

Paritition array into N chunks with Numpy

Just some examples on usage of array_split, split, hsplit and vsplit:

n [9]: a = np.random.randint(0,10,[4,4])

In [10]: a
Out[10]: 
array([[2, 2, 7, 1],
       [5, 0, 3, 1],
       [2, 9, 8, 8],
       [5, 7, 7, 6]])

Some examples on using array_split:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'

# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:                                                                                                                       
[array([[2, 2, 7, 1]]),                                                                                                       
 array([[5, 0, 3, 1],                                                                                                         
       [2, 9, 8, 8]]),                                                                                                        
 array([[5, 7, 7, 6]])]

# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)                                                                                           
Out[5]:                                                                                                                       
[array([[2],                                                                                                                  
       [5],                                                                                                                   
       [2],                                                                                                                   
       [5]]),                                                                                                                 
 array([[2, 7, 1],                                                                                                            
       [0, 3, 1],
       [9, 8, 8],
       [7, 7, 6]])]

An integer as second arg. specifies the number of equal chunks:

In [6]: np.array_split(a, 2, axis=1)
Out[6]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

split works the same but raises an exception if an equal split is not possible

In addition to array_split you can use shortcuts vsplit and hsplit.
vsplit and hsplit are pretty much self-explanatry:

In [11]: np.vsplit(a, 2)
Out[11]: 
[array([[2, 2, 7, 1],
       [5, 0, 3, 1]]),
 array([[2, 9, 8, 8],
       [5, 7, 7, 6]])]

In [12]: np.hsplit(a, 2)
Out[12]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

Difference between ApiController and Controller in ASP.NET MVC

The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

You can use data-image for that. using data-image(data-URI) you can access SVG like inline.

Here is rollover effect using pure CSS and SVG.

I know it messy but you can do this way.

_x000D_
_x000D_
 .action-btn {_x000D_
    background-size: 20px 20px;_x000D_
    background-position: center center;_x000D_
    background-repeat: no-repeat;_x000D_
    border-width: 1px;_x000D_
    border-style: solid;_x000D_
    border-radius: 30px;_x000D_
    height: 40px;_x000D_
    width: 60px;_x000D_
    display: inline-block;_x000D_
 }_x000D_
_x000D_
.delete {_x000D_
     background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg version='1.1' id='Capa_1' fill='#FB404B' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='482.428px' height='482.429px' viewBox='0 0 482.428 482.429' style='enable-background:new 0 0 482.428 482.429;' xml:space='preserve'%3e%3cg%3e%3cg%3e%3cpath d='M381.163,57.799h-75.094C302.323,25.316,274.686,0,241.214,0c-33.471,0-61.104,25.315-64.85,57.799h-75.098 c-30.39,0-55.111,24.728-55.111,55.117v2.828c0,23.223,14.46,43.1,34.83,51.199v260.369c0,30.39,24.724,55.117,55.112,55.117 h210.236c30.389,0,55.111-24.729,55.111-55.117V166.944c20.369-8.1,34.83-27.977,34.83-51.199v-2.828 C436.274,82.527,411.551,57.799,381.163,57.799z M241.214,26.139c19.037,0,34.927,13.645,38.443,31.66h-76.879 C206.293,39.783,222.184,26.139,241.214,26.139z M375.305,427.312c0,15.978-13,28.979-28.973,28.979H136.096 c-15.973,0-28.973-13.002-28.973-28.979V170.861h268.182V427.312z M410.135,115.744c0,15.978-13,28.979-28.973,28.979H101.266 c-15.973,0-28.973-13.001-28.973-28.979v-2.828c0-15.978,13-28.979,28.973-28.979h279.897c15.973,0,28.973,13.001,28.973,28.979 V115.744z'/%3e%3cpath d='M171.144,422.863c7.218,0,13.069-5.853,13.069-13.068V262.641c0-7.216-5.852-13.07-13.069-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C158.074,417.012,163.926,422.863,171.144,422.863z'/%3e%3cpath d='M241.214,422.863c7.218,0,13.07-5.853,13.07-13.068V262.641c0-7.216-5.854-13.07-13.07-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C228.145,417.012,233.996,422.863,241.214,422.863z'/%3e%3cpath d='M311.284,422.863c7.217,0,13.068-5.853,13.068-13.068V262.641c0-7.216-5.852-13.07-13.068-13.07 c-7.219,0-13.07,5.854-13.07,13.07v147.154C298.213,417.012,304.067,422.863,311.284,422.863z'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e ");_x000D_
     border-color:#FB404B;_x000D_
     _x000D_
 }_x000D_
 _x000D_
 .delete:hover {_x000D_
     background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg version='1.1' id='Capa_1' fill='#fff' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='482.428px' height='482.429px' viewBox='0 0 482.428 482.429' style='enable-background:new 0 0 482.428 482.429;' xml:space='preserve'%3e%3cg%3e%3cg%3e%3cpath d='M381.163,57.799h-75.094C302.323,25.316,274.686,0,241.214,0c-33.471,0-61.104,25.315-64.85,57.799h-75.098 c-30.39,0-55.111,24.728-55.111,55.117v2.828c0,23.223,14.46,43.1,34.83,51.199v260.369c0,30.39,24.724,55.117,55.112,55.117 h210.236c30.389,0,55.111-24.729,55.111-55.117V166.944c20.369-8.1,34.83-27.977,34.83-51.199v-2.828 C436.274,82.527,411.551,57.799,381.163,57.799z M241.214,26.139c19.037,0,34.927,13.645,38.443,31.66h-76.879 C206.293,39.783,222.184,26.139,241.214,26.139z M375.305,427.312c0,15.978-13,28.979-28.973,28.979H136.096 c-15.973,0-28.973-13.002-28.973-28.979V170.861h268.182V427.312z M410.135,115.744c0,15.978-13,28.979-28.973,28.979H101.266 c-15.973,0-28.973-13.001-28.973-28.979v-2.828c0-15.978,13-28.979,28.973-28.979h279.897c15.973,0,28.973,13.001,28.973,28.979 V115.744z'/%3e%3cpath d='M171.144,422.863c7.218,0,13.069-5.853,13.069-13.068V262.641c0-7.216-5.852-13.07-13.069-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C158.074,417.012,163.926,422.863,171.144,422.863z'/%3e%3cpath d='M241.214,422.863c7.218,0,13.07-5.853,13.07-13.068V262.641c0-7.216-5.854-13.07-13.07-13.07 c-7.217,0-13.069,5.854-13.069,13.07v147.154C228.145,417.012,233.996,422.863,241.214,422.863z'/%3e%3cpath d='M311.284,422.863c7.217,0,13.068-5.853,13.068-13.068V262.641c0-7.216-5.852-13.07-13.068-13.07 c-7.219,0-13.07,5.854-13.07,13.07v147.154C298.213,417.012,304.067,422.863,311.284,422.863z'/%3e%3c/g%3e%3c/g%3e%3c/svg%3e ");        _x000D_
     background-color: #FB404B;_x000D_
    }
_x000D_
<a class="action-btn delete">&nbsp;</a>
_x000D_
_x000D_
_x000D_

You can convert your svg to data url here

  1. https://codepen.io/elliz/full/ygvgay
  2. https://websemantics.uk/tools/svg-to-background-image-conversion/

How to import CSV file data into a PostgreSQL table?

Create table and have required columns that are used for creating table in csv file.

  1. Open postgres and right click on target table which you want to load & select import and Update the following steps in file options section

  2. Now browse your file in filename

  3. Select csv in format

  4. Encoding as ISO_8859_5

Now goto Misc. options and check header and click on import.

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

How do I specify the JDK for a GlassFish domain?

In my case the problem was the JAVA_HOME variable was set an installed jre.

An alternative to setting the AS_JAVA variable is to set JAVA_HOME environment variable to the jdk (i.e. /usr/local/jdk1.7.0.51).

SQL- Ignore case while searching for a string

Use something like this -

SELECT DISTINCT COL_NAME FROM myTable WHERE UPPER(COL_NAME) LIKE UPPER('%PriceOrder%')

or

SELECT DISTINCT COL_NAME FROM myTable WHERE LOWER(COL_NAME) LIKE LOWER('%PriceOrder%')

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

How to loop an object in React?

const tifOptions = [];

for (const [key, value] of Object.entries(tifs)) {
    tifOptions.push(<option value={key} key={key}>{value}</option>);
}

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { tifOptions }          
   </select>
)

CSS - How to Style a Selected Radio Buttons Label?

If you really want to put the checkboxes inside the label, try adding an extra span tag, eg.

HTML

<div class="radio-toolbar">
 <label><input type="radio" value="all" checked><span>All</span></label>
 <label><input type="radio" value="false"><span>Open</span></label>
 <label><input type="radio" value="true"><span>Archived</span></label>
</div>

CSS

.radio-toolbar input[type="radio"]:checked ~ * { 
    background:pink !important;
}

That will set the backgrounds for all siblings of the selected radio button.

ASP.NET MVC ActionLink and post method

You can't use an ActionLink because that just renders an anchor <a> tag.
You can use a jQuery AJAX post.
Or just call the form's submit method with or without jQuery (which would be non-AJAX), perhaps in the onclick event of whatever control takes your fancy.

How to load local html file into UIWebView

EDIT 2016-05-27 - loadRequest exposes "a universal Cross-Site Scripting vulnerability." Make sure you own every single asset that you load. If you load a bad script, it can load anything it wants.

If you need relative links to work locally, use this:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"my" withExtension:@"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];

The bundle will search all subdirectories of the project to find my.html. (the directory structure gets flattened at build time)

If my.html has the tag <img src="some.png">, the webView will load some.png from your project.

JavaScript: Check if mouse button down?

Below jQuery example, when mouse is over $('.element'), color is changing depending on which mouse button is pressed.

var clicableArea = {
    init: function () {
        var self = this;
        ('.element').mouseover(function (e) {
            self.handlemouseClick(e, $(this));
        }).mousedown(function (e) {
            self.handlemouseClick(e, $(this));
        });
    },
    handlemouseClick: function (e, element) {
        if (e.buttons === 1) {//left button
            element.css('background', '#f00');
        }
        if (e.buttons === 2) { //right buttom
            element.css('background', 'none');
        }
    }
};
$(document).ready(function () {
    clicableArea.init();
});

Is there a RegExp.escape function in JavaScript?

There has only ever been and ever will be 12 meta characters that need to be escaped to be considered a literal.

It doesn't matter what is done with the escaped string, inserted into a balanced regex wrapper or appended. It doesn't matter.

Do a string replace using this

var escaped_string = oldstring.replace(/[\\^$.|?*+()[{]/g, '\\$&');

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

The following solution works for me, you can try it:

  • Write to run : regedit

  • Then open

    HKEY_LOCAL_MACHINE -> SOFTWARE -> Microsoft -> Windows NT -> Perflib

  • Under the /009 and /01F files, right click and select new and choose "multi string value" named it as "Counter" and do these steps again to create "Help" named file. (Important!! it is case sensitive)

  • Copy contents of "Counter" and "Help" files under the "CurrentLanguage" to the /009 and /01F files.

Can I have H2 autocreate a schema in an in-memory database?

If you are using Spring Framework with application.yml and having trouble to make the test find the SQL file on the INIT property, you can use the classpath: notation.

For example, if you have a init.sql SQL file on the src/test/resources, just use:

url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

try using return 0;

if it keeps failing change your solution platform to 64x instead of 86x and go to configuration manager(that's were you change the 86x to 64x) and in platform set it to 64 bits

that works for me, hope it work to you