Programs & Examples On #Option

DO NOT USE THIS TAG. It is ambiguous and not helpful.

html select option SELECTED

foreach ($array as $value => $name) {
     echo '<option value="' . htmlentities($value) . '"' . (($_GET['sel'] === $value) ? ' selected="selected"') . '>' . htmlentities($name) . '</option>';
}

This is fairly neat, and, I think, self-explanatory.

How to implement the --verbose or -v option into a script?

What I do in my scripts is check at runtime if the 'verbose' option is set, and then set my logging level to debug. If it's not set, I set it to info. This way you don't have 'if verbose' checks all over your code.

How to check if an option is selected?

use

 $("#mySelectBox option:selected");

to test if its a particular option myoption:

 if($("#mySelectBox option:selected").text() == myoption){
          //...
 }

using href links inside <option> tag

The accepted solution looks good, but there is one case it cannot handle:

The "onchange" event will not be triggered when the same option is reselected. So, I came up with the following improvement:

HTML

<select id="sampleSelect" >
  <option value="Home.php">Home</option>
  <option value="Contact.php">Contact</option>
  <option value="Sitemap.php">Sitemap</option>
</select>

jQuery

$("select").click(function() {
  var open = $(this).data("isopen");
  if(open) {
    window.location.href = $(this).val()
  }
  //set isopen to opposite so next time when use clicked select box
  //it wont trigger this event
  $(this).data("isopen", !open);
});

How to preSelect an html dropdown list with php?

you can use this..

<select name="select_name">
    <option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
    <option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
    <option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>

How do you remove all the options of a select box and then add one option and select it with jQuery?

$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;

jQuery remove selected option from this

This should do the trick:

$('#some_select_box').click(function() {
  $('option:selected', this ).remove();
});

android: changing option menu items programmatically

Kotlin Code for accessing toolbar OptionsMenu items programmatically & change the text/icon ,..:

1-We have our menu item in menu items file like: menu.xml, sample code for this:

 <?xml version="1.0" encoding="utf-8"?> 
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/balance"
      android:title="0"
      android:orderInCategory="100"
      app:showAsAction="always" />
 </menu>

2- Define a variable for accessing menu object in class :

var menu: Menu? = null

3- initial it in onCreateOptionsMenu :

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    this.menu = menu
    return true
}

4- Access the menu items inside your code or fun :

private fun initialBalanceMenuItemOnToolbar() {
var menuItemBalance = menu?.findItem(R.id.balance)
    menuItemBalance?.title = Balance?.toString() ?: 0.toString()
    // for change icon : menuWalletBalance?.icon
}

Get Selected value from dropdown using JavaScript

Maybe it's the comma in your if condition.

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

You can also write it like this.

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}

set option "selected" attribute from dynamic created option

To set value in JavaScript using set attribute , for selected option tag

var newvalue = 10;
var x = document.getElementById("optionid").selectedIndex;
    document.getElementById("optionid")[x].setAttribute('value', newvalue);

Table border left and bottom

You need to use the border property as seen here: jsFiddle

HTML:

<table width="770">
    <tr>
        <td class="border-left-bottom">picture (border only to the left and bottom ) </td>
        <td>text</td>
    </tr>
    <tr>
        <td>text</td>
        <td class="border-left-bottom">picture (border only to the left and bottom) </td>
    </tr>
</table>`

CSS:

td.border-left-bottom{
    border-left: solid 1px #000;
    border-bottom: solid 1px #000;
}

Using the Underscore module with Node.js

As of today (April 30, 2012) you can use Underscore as usual on your Node.js code. Previous comments are right pointing that REPL interface (Node's command line mode) uses the "_" to hold the last result BUT on you are free to use it on your code files and it will work without a problem by doing the standard:

var _ = require('underscore');

Happy coding!

How do I get the calling method name and type using reflection?

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

You should write something like that :

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

How do I find the duplicates in a list and create another list with them?

I would do this with pandas, because I use pandas a lot

import pandas as pd
a = [1,2,3,3,3,4,5,6,6,7]
vc = pd.Series(a).value_counts()
vc[vc > 1].index.tolist()

Gives

[3,6]

Probably isn't very efficient, but it sure is less code than a lot of the other answers, so I thought I would contribute

Using prepared statements with JDBCTemplate

By default, the JDBCTemplate does its own PreparedStatement internally, if you just use the .update(String sql, Object ... args) form. Spring, and your database, will manage the compiled query for you, so you don't have to worry about opening, closing, resource protection, etc. One of the saving graces of Spring. A link to Spring 2.5's documentation on this. Hope it makes things clearer. Also, statement caching can be done at the JDBC level, as in the case of at least some of Oracle's JDBC drivers. That will go into a lot more detail than I can competently.

How do I implement a progress bar in C#?

Some people may not like it, but this is what I do:

private void StartBackgroundWork() {
    if (Application.RenderWithVisualStyles)
        progressBar.Style = ProgressBarStyle.Marquee;
    else {
        progressBar.Style = ProgressBarStyle.Continuous;
        progressBar.Maximum = 100;
        progressBar.Value = 0;
        timer.Enabled = true;
    }
    backgroundWorker.RunWorkerAsync();
}

private void timer_Tick(object sender, EventArgs e) {
    if (progressBar.Value < progressBar.Maximum)
        progressBar.Increment(5);
    else
        progressBar.Value = progressBar.Minimum;
}

The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.

Best way to make a shell script daemon?

Here is the minimal change to the original proposal to create a valid daemon in Bourne shell (or Bash):

#!/bin/sh
if [ "$1" != "__forked__" ]; then
    setsid "$0" __forked__ "$@" &
    exit
else
    shift
fi

trap 'siguser1=true' SIGUSR1
trap 'echo "Clean up and exit"; kill $sleep_pid; exit' SIGTERM
exec > outfile
exec 2> errfile
exec 0< /dev/null

while true; do
    (sleep 30000000 &>/dev/null) &
    sleep_pid=$!
    wait
    kill $sleep_pid &>/dev/null
    if [ -n "$siguser1" ]; then
        siguser1=''
        echo "Wait was interrupted by SIGUSR1, do things here."
    fi
done

Explanation:

  • Line 2-7: A daemon must be forked so it doesn't have a parent. Using an artificial argument to prevent endless forking. "setsid" detaches from starting process and terminal.
  • Line 9: Our desired signal needs to be differentiated from other signals.
  • Line 10: Cleanup is required to get rid of dangling "sleep" processes.
  • Line 11-13: Redirect stdout, stderr and stdin of the script.
  • Line 16: sleep in the background
  • Line 18: wait waits for end of sleep, but gets interrupted by (some) signals.
  • Line 19: Kill sleep process, because that is still running when signal is caught.
  • Line 22: Do the work if SIGUSR1 has been caught.

Guess it does not get any simpler than that.

How to simulate key presses or a click with JavaScript?

you can raise the click event on an element by doing

// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");

if (element) element.click();

Example here

How to use the ProGuard in Android Studio?

NB.: Now instead of

runProguard false

you'll need to use

minifyEnabled false

How can I access an internal class from an external assembly?

Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Find the maximum value in a list of tuples in Python

You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...

num=(0, 0)
for item in tuplelist:
  if item[1]>num[1]:
    num=item #num has the whole tuple with the highest y value and its x value

How to dynamically add rows to a table in ASP.NET?

You can use the asp:Table in your web form and build it via code:

http://msdn.microsoft.com/en-us/library/7bewx260.aspx

Also, check out asp.net for tutorials and such.

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

How to access command line arguments of the caller inside a function?

Ravi's comment is essentially the answer. Functions take their own arguments. If you want them to be the same as the command-line arguments, you must pass them in. Otherwise, you're clearly calling a function without arguments.

That said, you could if you like store the command-line arguments in a global array to use within other functions:

my_function() {
    echo "stored arguments:"
    for arg in "${commandline_args[@]}"; do
        echo "    $arg"
    done
}

commandline_args=("$@")

my_function

You have to access the command-line arguments through the commandline_args variable, not $@, $1, $2, etc., but they're available. I'm unaware of any way to assign directly to the argument array, but if someone knows one, please enlighten me!

Also, note the way I've used and quoted $@ - this is how you ensure special characters (whitespace) don't get mucked up.

What's the quickest way to multiply multiple cells by another number?

To multiply a column of numbers with a constant(same number), I have done like this.

Let C2 to C12 be different numbers which need to be multiplied by a single number (constant). Then type the numbers from C2 to C12.

In D2 type 1 (unity) and in E2 type formula =PRODUCT(C2:C12,CONSTANT). SELECT RIGHT ICON TO APPLY. NOW DRAG E2 THROUGH E12. YOU HAVE DONE IT.

C       D       E=PRODUCT(C2:C12,20)

25  1   500
30      600
35      700
40      800
45      900
50      1000
55      1100
60      1200
65      1300
70      1400
75      1500

Adding a new entry to the PATH variable in ZSH

Here, add this line to .zshrc:

export PATH=/home/david/pear/bin:$PATH

EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH. This approach is standard for bash, but as far as I know, there is no reason to use it when ZSH provides better alternatives.

How do I properly clean up Excel interop objects?

This is the only way that really works for me

        foreach (Process proc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            proc.Kill();
        }

How to close TCP and UDP ports via windows command line

  1. open cmd

    • type in netstat -a -n -o

    • find TCP [the IP address]:[port number] .... #[target_PID]# (ditto for UDP)

    • (Btw, kill [target_PID] didn't work for me)

  2. CTRL+ALT+DELETE and choose "start task manager"

    • Click on "Processes" tab

    • Enable "PID" column by going to: View > Select Columns > Check the box for PID

    • Find the PID of interest and "END PROCESS"

  3. Now you can rerun the server on [the IP address]:[port number] without a problem

Warning :-Presenting view controllers on detached view controllers is discouraged

Wait for viewDidAppear():

This error can also arise if you are trying to present view controller before view actually did appear, for example presenting view in viewWillAppear() or earlier. Try to present another view after viewDidAppear() or inside of it.

':app:lintVitalRelease' error when generating signed apk

You should add the code in project level gradle file for generating apk overwriting over errors

What is the difference between bool and Boolean types in C#

Note that Boolean will only work were you have using System; (which is usually, but not necessarily, included) (unless you write it out as System.Boolean). bool does not need using System;

Add to integers in a list

Here is an example where the things to add come from a dictionary

>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
...     L[item['idx']] += item['amount']
... 
>>> L
[0, 1, 1, 0]

Here is an example adding elements from another list

>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

You could also achieve the above with a list comprehension and zip

L[:] = [sum(i) for i in zip(L, things_to_add)]

Here is an example adding from a list of tuples

>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

Uninstalling Android ADT

I found a solution by myself after doing some research:

  • Go to Eclipse home folder.
  • Search for 'android' => In Windows 7 you can use search bar.
  • Delete all the file related to android, which is shown in the results.
  • Restart Eclipse.
  • Install the ADT plugin again and Restart plugin.

Now everything works fine.

clearing a char array c

set the first element to NULL. printing the char array will give you nothing back.

Laravel: Auth::user()->id trying to get a property of a non-object

If anyone is looking for laravel 5 >

 Auth::id() 

give id of the authorized user

How to set password for Redis?

How to set redis password ?

step 1. stop redis server using below command /etc/init.d/redis-server stop

step 2.enter command : sudo nano /etc/redis/redis.conf

step 3.find # requirepass foobared word and remove # and change foobared to YOUR PASSWORD

ex. requirepass root

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

How to completely remove Python from a Windows machine?

Uninstall the python program using the windows GUI. Delete the containing folder e.g if it was stored in C:\python36\ make sure to delete that folder

Why should you use strncpy instead of strcpy?

That depends on our requirement. For windows users

We use strncpy whenever we don't want to copy entire string or we want to copy only n number of characters. But strcpy copies the entire string including terminating null character.

These links will help you more to know about strcpy and strncpy and where we can use.

about strcpy

about strncpy

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

How to make ng-repeat filter out duplicate results

If you want to get unique data based on the nested key:

app.filter('unique', function() {
        return function(collection, primaryKey, secondaryKey) { //optional secondary key
          var output = [], 
              keys = [];

          angular.forEach(collection, function(item) {
                var key;
                secondaryKey === undefined ? key = item[primaryKey] : key = item[primaryKey][secondaryKey];

                if(keys.indexOf(key) === -1) {
                  keys.push(key);
                  output.push(item);
                }
          });

          return output;
        };
    });

Call it like this :

<div ng-repeat="notify in notifications | unique: 'firstlevel':'secondlevel'">

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Insert a background image in CSS (Twitter Bootstrap)

Put the background url in quotes.

It should be background: url('background.png');

See here for working demo.

You also have an issue with the background-repeat line missing a semicolon in between two statements. If your background is really tiny you won't see it because of that issue.

Just to update on the solution, among the other issues, the background file was being refrenced with .../background.jpg when it should have been ../background.jpg (2 dots, not 3).

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

How to resolve Value cannot be null. Parameter name: source in linq?

Error message clearly says that source parameter is null. Source is the enumerable you are enumerating. In your case it is ListMetadataKor object. And its definitely null at the time you are filtering it second time. Make sure you never assign null to this list. Just check all references to this list in your code and look for assignments.

What's the difference between unit, functional, acceptance, and integration tests?

Depending on where you look, you'll get slightly different answers. I've read about the subject a lot, and here's my distillation; again, these are slightly wooly and others may disagree.

Unit Tests

Tests the smallest unit of functionality, typically a method/function (e.g. given a class with a particular state, calling x method on the class should cause y to happen). Unit tests should be focussed on one particular feature (e.g., calling the pop method when the stack is empty should throw an InvalidOperationException). Everything it touches should be done in memory; this means that the test code and the code under test shouldn't:

  • Call out into (non-trivial) collaborators
  • Access the network
  • Hit a database
  • Use the file system
  • Spin up a thread
  • etc.

Any kind of dependency that is slow / hard to understand / initialise / manipulate should be stubbed/mocked/whatevered using the appropriate techniques so you can focus on what the unit of code is doing, not what its dependencies do.

In short, unit tests are as simple as possible, easy to debug, reliable (due to reduced external factors), fast to execute and help to prove that the smallest building blocks of your program function as intended before they're put together. The caveat is that, although you can prove they work perfectly in isolation, the units of code may blow up when combined which brings us to ...

Integration Tests

Integration tests build on unit tests by combining the units of code and testing that the resulting combination functions correctly. This can be either the innards of one system, or combining multiple systems together to do something useful. Also, another thing that differentiates integration tests from unit tests is the environment. Integration tests can and will use threads, access the database or do whatever is required to ensure that all of the code and the different environment changes will work correctly.

If you've built some serialization code and unit tested its innards without touching the disk, how do you know that it'll work when you are loading and saving to disk? Maybe you forgot to flush and dispose filestreams. Maybe your file permissions are incorrect and you've tested the innards using in memory streams. The only way to find out for sure is to test it 'for real' using an environment that is closest to production.

The main advantage is that they will find bugs that unit tests can't such as wiring bugs (e.g. an instance of class A unexpectedly receives a null instance of B) and environment bugs (it runs fine on my single-CPU machine, but my colleague's 4 core machine can't pass the tests). The main disadvantage is that integration tests touch more code, are less reliable, failures are harder to diagnose and the tests are harder to maintain.

Also, integration tests don't necessarily prove that a complete feature works. The user may not care about the internal details of my programs, but I do!

Functional Tests

Functional tests check a particular feature for correctness by comparing the results for a given input against the specification. Functional tests don't concern themselves with intermediate results or side-effects, just the result (they don't care that after doing x, object y has state z). They are written to test part of the specification such as, "calling function Square(x) with the argument of 2 returns 4".

Acceptance Tests

Acceptance testing seems to be split into two types:

Standard acceptance testing involves performing tests on the full system (e.g. using your web page via a web browser) to see whether the application's functionality satisfies the specification. E.g. "clicking a zoom icon should enlarge the document view by 25%." There is no real continuum of results, just a pass or fail outcome.

The advantage is that the tests are described in plain English and ensures the software, as a whole, is feature complete. The disadvantage is that you've moved another level up the testing pyramid. Acceptance tests touch mountains of code, so tracking down a failure can be tricky.

Also, in agile software development, user acceptance testing involves creating tests to mirror the user stories created by/for the software's customer during development. If the tests pass, it means the software should meet the customer's requirements and the stories can be considered complete. An acceptance test suite is basically an executable specification written in a domain specific language that describes the tests in the language used by the users of the system.

Conclusion

They're all complementary. Sometimes it's advantageous to focus on one type or to eschew them entirely. The main difference for me is that some of the tests look at things from a programmer's perspective, whereas others use a customer/end user focus.

Keyboard shortcut to change font size in Eclipse?

I know it has been long since the original question was posted, but for future reference: check this project, https://github.com/gkorland/Eclipse-Fonts I have used it, and it's very simple and efficient.

Add quotation at the start and end of each line in Notepad++

  1. Put your cursor at the begining of line 1.
  2. click Edit>ColumnEditor. Put " in the text and hit enter.
  3. Repeat 2 but put the cursor at the end of line1 and put ", and hit enter.

Splitting String with delimiter

dependencies {
   compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
     ['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
       def (g, m) = i.tokenize( ':' )
       dep.exclude group: g  , module: m
     }
   }
}

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Add this code to the beginning:

    Application.ScreenUpdating = False
     With ThisWorkbook
      Dim ws As Worksheet
       For Each ws In Worksheets: ws.Visible = True: Next ws
     End With

Add this code to the end:

    With ThisWorkbook
     Dim ws As Worksheet
      For Each ws In Worksheets: ws.Visible = False: Next ws
    End With
     Application.ScreenUpdating = True

Adjust Code at the end if you want more than the first sheet to be active and visible. Such as the following:

     Dim ws As Worksheet
      For Each ws In Worksheets
       If ws.Name = "_DataRecords" Then

         Else: ws.Visible = False
       End If
      Next ws

To ensure the new sheet is the one renamed, adjust your code similar to the following:

     Sheets(Me.cmbxSheetCopy.value).Copy After:=Sheets(Sheets.Count)
     Sheets(Me.cmbxSheetCopy.value & " (2)").Select
     Sheets(Me.cmbxSheetCopy.value & " (2)").Name = txtbxNewSheetName.value

This code is from my user form that allows me to copy a particular sheet (chosen from a dropdown box) with the formatting and formula's that I want to a new sheet and then rename new sheet with the user Input. Note that every time a sheet is copied it is automatically given the old sheet name with the designation of " (2)". Example "OldSheet" becomes "OldSheet (2)" after the copy and before the renaming. So you must select the Copied sheet with the programs naming before renaming.

Where does the iPhone Simulator store its data?

if anyone is still experiencing this problem in lion, there is a great article with 19 different tips to view your ~/Library dir. find the article by Dan Frakes here http://www.macworld.com/article/161156/2011/07/view_library_folder_in_lion.html

Remember the directory to the simulator is given below

~/Library/Application Support/iPhone Simulator/User/

Issue with background color and Google Chrome

I had the same issue on a couple of sites and fixed it by moving the background styling from body to html (which I guess is a variation of the body {} to html, body{} technique already mentioned but shows that you can make do with the style on html only), e.g.

body {
   background-color:#000000;
   background-image:url('images/bg.png');
   background-repeat:repeat-x;
   font-family:Arial,Helvetica,sans-serif;
   font-size:85%;
   color:#cccccc;

}

becomes

html {
   background-color:#000000;
   background-image:url('images/bg.png');
   background-repeat:repeat-x;
}
body {
   font-family:Arial,Helvetica,sans-serif;
   font-size:85%;
   color:#cccccc;
}

This worked in IE6-8, Chrome 4-5, Safari 4, Opera 10 and Firefox 3.x with no obvious nasty side-effects.

Get year, month or day from numpy datetime64

I find the following tricks give between 2x and 4x speed increase versus the pandas method described above (i.e. pd.DatetimeIndex(dates).year etc.). The speed of [dt.year for dt in dates.astype(object)] I find to be similar to the pandas method. Also these tricks can be applied directly to ndarrays of any shape (2D, 3D etc.)

dates = np.arange(np.datetime64('2000-01-01'), np.datetime64('2010-01-01'))
years = dates.astype('datetime64[Y]').astype(int) + 1970
months = dates.astype('datetime64[M]').astype(int) % 12 + 1
days = dates - dates.astype('datetime64[M]') + 1

How can I select an element with multiple classes in jQuery?

If you want to match only elements with both classes (an intersection, like a logical AND), just write the selectors together without spaces in between:

$('.a.b')

The order is not relevant, so you can also swap the classes:

$('.b.a')

So to match a div element that has an ID of a with classes b and c, you would write:

$('div#a.b.c')

(In practice, you most likely don't need to get that specific, and an ID or class selector by itself is usually enough: $('#a').)

datatable jquery - table header width not aligned with body width

I solved this problem by wrapping the "dataTable" Table with a div with overflow:auto:

.dataTables_scroll
{
    overflow:auto;
}

and adding this JS after your dataTable initialization:

jQuery('.dataTable').wrap('<div class="dataTables_scroll" />');

Don't use sScrollX or sScrollY, remove them and add a div wrapper yourself which does the same thing.

invalid byte sequence for encoding "UTF8"

copy tablename from 'filepath\filename' DELIMITERS '=' ENCODING 'WIN1252';

you can try this to handle UTF8 encoding.

Eclipse - java.lang.ClassNotFoundException

I tried everything I read in this long post and, incredibly, what worked for me was, rather than clicking on the test class and selecting Run as JUnit test, clicking on the test method and running as JUnit test. I have no idea why?

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

You still have access to StreamWriter:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
    file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}

From the MSDN documentation: Writing to a Text File (Visual C#).

For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText method.

System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

various option are available such as:

 Double d= 123.12;
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64); // b = 123.1200000
b = b.setScale(2, BigDecimal.ROUND_HALF_UP);  // b = 123.12

BigDecimal b1 =new BigDecimal(collectionFileData.getAmount(), MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_HALF_UP)  // b1= 123.12

 d = (double) Math.round(d * 100) / 100;
BigDecimal b2 = new BigDecimal(d.toString());  // b2= 123.12



How to custom switch button?

With the Material Components Library you can use the MaterialButtonToggleGroup:

        <com.google.android.material.button.MaterialButtonToggleGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:checkedButton="@id/b1"
            app:selectionRequired="true"
            app:singleSelection="true">

            <Button
                style="?attr/materialButtonOutlinedStyle"
                android:id="@+id/b1"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="OPT1" />

            <Button
                style="?attr/materialButtonOutlinedStyle"
                android:id="@+id/b2"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="OPT2" />

        </com.google.android.material.button.MaterialButtonToggleGroup>

enter image description here

Get value of a specific object property in C# without knowing the class behind

Simply try this for all properties of an object,

foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
   var propertyName = prop.Name;
   var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);

   //Debug.Print(prop.Name);
   //Debug.Print(Functions.convertNullableToString(propertyValue));

   Debug.Print(string.Format("Property Name={0} , Value={1}", prop.Name, Functions.convertNullableToString(propertyValue)));
}

NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.

python xlrd unsupported format, or corrupt file.

there's nothing wrong with your file. xlrd does not yet support xlsx (excel 2007+) files although it's purported to have supported this for some time.

Simplistix github

2-days ago they committed a pre-alpha version to their git which integrates xlsx support. Other forums suggest that you use a DOM parser for xlsx files since the xlsx file type is just a zip archive containing XML. I have not tried this. there is another package with similar functionality as xlrd and this is called openpyxl which you can get from easy_install or pip. I have not tried this either, however, its API is supposed to be similar to xlrd.

Is there a CSS selector for the first direct child only?

The CSS selector for the direct first-child in your case is:

.section > :first-child

The direct selector is > and the first child selector is :first-child

No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:

div.section > :first-child

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

System.setProperty("webdriver.chrome.driver",
         "D:\\Lib\\chrome_driver_latest\\chromedriver_win32\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--allow-running-insecure-content");
chromeOptions.addArguments("--window-size=1920x1080");
chromeOptions.addArguments("--disable-gpu"); 
chromeOptions.setHeadless(true);
ChromeDriver driver = new ChromeDriver(chromeOptions);

Order of items in classes: Fields, Properties, Constructors, Methods

I prefer to put the private fields up at the top along with the constructor(s), then put the public interface bits after that, then the private interface bits.

Also, if your class definition is long enough for the ordering of items to matter much, that's probably a code smell indicating your class is too bulky and complex and you should refactor.

Java - Change int to ascii

There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:

private static String toASCII(int value) {
    int length = 4;
    StringBuilder builder = new StringBuilder(length);
    for (int i = length - 1; i >= 0; i--) {
        builder.append((char) ((value >> (8 * i)) & 0xFF));
    }
    return builder.toString();
}

For example, the ASCII text for "TEST" can be represented as the byte array:

byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };

Then you could do the following:

int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"

...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Add repository annotation before your DAO Implementation Class. example:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}

How to get the wsdl file from a webservice's URL

By postfixing the URL with ?WSDL

If the URL is for example:

http://webservice.example:1234/foo

You use:

http://webservice.example:1234/foo?WSDL

And the wsdl will be delivered.

Modulo operation with negative numbers

I don't think there isn't any need to check if the number is negative.

A simple function to find the positive modulo would be this -

Edit: Assuming N > 0 and N + N - 1 <= INT_MAX

int modulo(int x,int N){
    return (x % N + N) %N;
}

This will work for both positive and negative values of x.

Original P.S: also as pointed out by @chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int with long long int.

And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.

HTML Submit-button: Different value / button-text?

Following the @greg0ire suggestion in comments:

<input type="submit" name="add_tag" value="Lägg till tag" />

In your server side, you'll do something like:

if (request.getParameter("add_tag") != null)
    tags.addTag( /*...*/ );

(Since I don't know that language (java?), there may be syntax errors.)

I would prefer the <button> solution, but it doesn't work as expected on IE < 9.

Mock functions in Go

Considering unit test is the domain of this question, highly recommend you to use monkey. This Package make you to mock test without changing your original source code. Compare to other answer, it's more "non-intrusive".

main

type AA struct {
 //...
}
func (a *AA) OriginalFunc() {
//...
}

mock test

var a *AA

func NewFunc(a *AA) {
 //...
}

monkey.PatchMethod(reflect.TypeOf(a), "OriginalFunc", NewFunc)

Bad side is:

  • Reminded by Dave.C, This method is unsafe. So don't use it outside of unit test.
  • Is non-idiomatic Go.

Good side is:

  • Is non-intrusive. Make you do things without changing the main code. Like Thomas said.
  • Make you change behavior of package (maybe provided by third party) with least code.

How to get GET (query string) variables in Express.js on Node.js?

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured domains and ssl. so these two lines would change:

https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

How can I reorder my divs using only CSS?

CSS really shouldn't be used to restructure the HTML backend. However, it is possible if you know the height of both elements involved and are feeling hackish. Also, text selection will be messed up when going between the divs, but that's because the HTML and CSS order are opposite.

#firstDiv { position: relative; top: YYYpx; height: XXXpx; }
#secondDiv { position: relative; top: -XXXpx; height: YYYpx; }

Where XXX and YYY are the heights of firstDiv and secondDiv respectively. This will work with trailing elements, unlike the top answer.

How to print star pattern in JavaScript in a very simple manner?

This is the simplest solution which I came across using only one for loop.

var a = '';
var n = 5;
var m = (n-1); 
for(i=1; i <= n; i++)
{
    a = a.trim();
    a = ' '.repeat(m) + a + (i > 1 ? ' ' : '') + '*';
    console.log(a);
    m--;
}

Output:

/**------------------------


    *
   * *
  * * *
 * * * *
* * * * *

---------------------------*/

Can .NET load and parse a properties file equivalent to Java Properties class?

I've written a method that allows emty lines, outcommenting and quoting within the file.

Examples:

var1="value1"
var2='value2'

'var3=outcommented
;var4=outcommented, too

Here's the method:

public static IDictionary ReadDictionaryFile(string fileName)
{
    Dictionary<string, string> dictionary = new Dictionary<string, string>();
    foreach (string line in File.ReadAllLines(fileName))
    {
        if ((!string.IsNullOrEmpty(line)) &&
            (!line.StartsWith(";")) &&
            (!line.StartsWith("#")) &&
            (!line.StartsWith("'")) &&
            (line.Contains('=')))
        {
            int index = line.IndexOf('=');
            string key = line.Substring(0, index).Trim();
            string value = line.Substring(index + 1).Trim();

            if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                (value.StartsWith("'") && value.EndsWith("'")))
            {
                value = value.Substring(1, value.Length - 2);
            }
            dictionary.Add(key, value);
        }
    }

    return dictionary;
}

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

HTTP response header content disposition for attachments

Problems

The code has the following issues:

  • An Ajax call (<a4j:commandButton .../>) does not work with attachments.
  • Creating the output content must happen first.
  • Displaying the error messages also cannot use Ajax-based a4j tags.

Solution

  1. Change <a4j:commandButton .../> to <h:commandButton .../>.
  2. Update the source code:
    1. Change bw.write( getDomainDocument() ); to bw.write( document );.
    2. Add String document = getDomainDocument(); to the first line of the try/catch.
  3. Change the <a4j:outputPanel.../> (not shown) to <h:messages showDetail="false"/>.

Essentially, remove all the Ajax facilities related to the commandButton. It is still possible to display error messages and leverage the RichFaces UI style.

References

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

How to detect a loop in a linked list?

public boolean isCircular() {

    if (head == null)
        return false;

    Node temp1 = head;
    Node temp2 = head;

    try {
        while (temp2.next != null) {

            temp2 = temp2.next.next.next;
            temp1 = temp1.next;

            if (temp1 == temp2 || temp1 == temp2.next) 
                return true;    

        }
    } catch (NullPointerException ex) {
        return false;

    }

    return false;

}

How to check whether Kafka Server is running?

Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.

I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch sentence.

  def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
    val props = new Properties()
    props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
    props.put("group.id", kafkaParams.get("group.id").get.toString)
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    val simpleConsumer = new KafkaConsumer[String, String](props)
    simpleConsumer.listTopics()
  }

What is the path for the startup folder in windows 2008 server

You can easily reach them by using the Run window and entering:

shell:startup

and

shell:common startup

Source.

Full Screen DialogFragment in Android

To get DialogFragment on full screen

Override onStart of your DialogFragment like this:

@Override
public void onStart()
{
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null)
    {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}

And thanks very much to this post: The-mystery-of-androids-full-screen-dialog-fragments

In Python, how do I read the exif data for an image?

For Python3.x and starting Pillow==6.0.0, Image objects now provide a getexif() method that returns a <class 'PIL.Image.Exif'> instance or None if the image has no EXIF data.

From Pillow 6.0.0 release notes:

getexif() has been added, which returns an Exif instance. Values can be retrieved and set like a dictionary. When saving JPEG, PNG or WEBP, the instance can be passed as an exif argument to include any changes in the output image.

As stated, you can iterate over the key-value pairs of the Exif instance like a regular dictionary. The keys are 16-bit integers that can be mapped to their string names using the ExifTags.TAGS module.

from PIL import Image, ExifTags

img = Image.open("sample.jpg")
img_exif = img.getexif()
print(type(img_exif))
# <class 'PIL.Image.Exif'>

if img_exif is None:
    print('Sorry, image has no exif data.')
else:
    for key, val in img_exif.items():
        if key in ExifTags.TAGS:
            print(f'{ExifTags.TAGS[key]}:{val}')
            # ExifVersion:b'0230'
            # ...
            # FocalLength:(2300, 100)
            # ColorSpace:1
            # ...
            # Model:'X-T2'
            # Make:'FUJIFILM'
            # LensSpecification:(18.0, 55.0, 2.8, 4.0)
            # ...
            # DateTime:'2019:12:01 21:30:07'
            # ...

Tested with Python 3.8.8 and Pillow==8.1.0.

How to call function of one php file from another php file and pass parameters to it?

Yes include the first file into the second. That's all.

See an example below,

File1.php :

<?php
  function first($int, $string){ //function parameters, two variables.
    return $string;  //returns the second argument passed into the function
  }
?>

Now Using include (http://php.net/include) to include the File1.php to make its content available for use in the second file:

File2.php :

<?php
  include 'File1.php';
  echo first(1,"omg lol"); //returns omg lol;
?>

How comment a JSP expression?

your <%= //map.size() %> doesnt simply work because it should have been

<% //= map.size() %>

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

  1. Search "sqlLocalDb" from start menu,
  2. Click on the run command,
  3. Go back to VS 2015 tools/connect to database,
  4. select MSSQL server,
  5. enter (localdb)\MSSQLLocalDB as server name

Select your database and ready to go.

Android: Cancel Async Task

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

Seconds CountDown Timer

enter image description here .

Usage:

CountDownTimer timer = new CountDownTimer();


//set to 30 mins
timer.SetTime(30,0);     

timer.Start();

//update label text
timer.TimeChanged += () => Label1.Text = timer.TimeLeftMsStr; 

// show messageBox on timer = 00:00.000
timer.CountDownFinished += () => MessageBox.Show("Timer finished the work!"); 

//timer step. By default is 1 second
timer.StepMs = 77; // for nice milliseconds time switch

and don't forget to Dispose(); when timer is useless for you;

Source code:

using System;
using System.Diagnostics;
using System.Windows.Forms;

public class CountDownTimer : IDisposable
{
    public Stopwatch _stpWatch = new Stopwatch();

    public Action TimeChanged;
    public Action CountDownFinished;

    public bool IsRunnign => timer.Enabled;

    public int StepMs
    {
        get => timer.Interval;
        set => timer.Interval = value;
    }

    private Timer timer = new Timer();

    private TimeSpan _max = TimeSpan.FromMilliseconds(30000);

    public TimeSpan TimeLeft => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) > 0 ? TimeSpan.FromMilliseconds(_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) : TimeSpan.FromMilliseconds(0);

    private bool _mustStop => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) < 0;

    public string TimeLeftStr => TimeLeft.ToString(@"\mm\:ss");

    public string TimeLeftMsStr => TimeLeft.ToString(@"mm\:ss\.fff");

    private void TimerTick(object sender, EventArgs e)
    {
        TimeChanged?.Invoke();

        if (_mustStop)
        {
            CountDownFinished?.Invoke();
            _stpWatch.Stop();
            timer.Enabled = false;
        }
    }

    public CountDownTimer(int min, int sec)
    {
        SetTime(min, sec);
        Init();
    }

    public CountDownTimer(TimeSpan ts)
    {
        SetTime(ts);
        Init();
    }

    public CountDownTimer()
    {
        Init();
    }

    private void Init()
    {
        StepMs = 1000;
        timer.Tick += new EventHandler(TimerTick);
    }

    public void SetTime(TimeSpan ts)
    {
        _max = ts;
        TimeChanged?.Invoke();
    }

    public void SetTime(int min, int sec = 0) => SetTime(TimeSpan.FromSeconds(min * 60 + sec));

    public void Start() {
        timer.Start();
        _stpWatch.Start();
    }

    public void Pause()
    {
        timer.Stop();
        _stpWatch.Stop();
    }

    public void Stop()
    {
        Reset();
        Pause();
    }

    public void Reset()
    {
        _stpWatch.Reset();
    }

    public void Restart()
    {
        _stpWatch.Reset();
        timer.Start();
    }

    public void Dispose() => timer.Dispose();
}

(updated 6.6.2020, because of problems with time calculation)

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The easiest thing to do is to set the content type of your ajax request to "application/json; charset=utf-8" and then let your API method consume JSON. Like this:

var basicInfo = JSON.stringify({
    firstName: playerProfile.firstName(),
    lastName: playerProfile.lastName(),
    gender: playerProfile.gender(),
    address: playerProfile.address(),
    country: playerProfile.country(),
    bio: playerProfile.bio()
});

$.ajax({
    url: "http://localhost:8080/social/profile/update",
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: basicInfo,
    success: function(data) {
        // ...
    }
});


@RequestMapping(
    value = "/profile/update",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> UpdateUserProfile(
    @RequestBody User usersNewDetails,
    HttpServletRequest request,
    HttpServletResponse response
) {
    // ...
}

I guess the problem is that Spring Boot has issues submitting form data which is not JSON via ajax request.

Note: the default content type for ajax is "application/x-www-form-urlencoded".

Docker error cannot delete docker container, conflict: unable to remove repository reference

you can use -f option to force delete the containers .

sudo docker rmi -f training/webapp

You may stop the containers using sudo docker stop training/webapp before deleting

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

How to make div follow scrolling smoothly with jQuery?

This is my final code .... (based on previous fixes, thank you big time for headstart, saved a lot of time experimenting). What bugged me was scrolling up, as well as scrolling down ... :)

it always makes me wonder how jquery can be elegant!!!

$(document).ready(function(){

    //run once
    var el=$('#scrolldiv');
    var originalelpos=el.offset().top; // take it where it originally is on the page

    //run on scroll
     $(window).scroll(function(){
        var el = $('#scrolldiv'); // important! (local)
        var elpos = el.offset().top; // take current situation
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos+originalelpos;
        el.stop().animate({'top':finaldestination},500);
     });

});

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

Follow below steps:

    1. Ensure to delete all the contents of the jar folder located in your local except the jar that you want to keep.
      For example files like .repositories, .pom, .sha1, .lastUpdated etc.
    1. Execute mvn clean install -o command

This will help to use local repository jar files rather than connecting to any repository.

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")

len() of a numpy array in python

What is the len of the equivalent nested list?

len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension. Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim. X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

How to add property to object in PHP >= 5.3 strict mode without generating error

I always use this way:

$foo = (object)null; //create an empty object
$foo->bar = "12345";

echo $foo->bar; //12345

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

How to insert values in two dimensional array programmatically?

Think about it as array of array.

If you do this str[x][y], then there is array of length x where each element in turn contains array of length y. In java its not necessary for second dimension to have same length. So for x=i you can have y=m and x=j you can have y=n

For this your declaration looks like

String[][] test = new String[4][]; test[0] = new String[3]; test[1] = new String[2];

etc..

Limit String Length

Do a little homework with the php online manual's string functions. You'll want to use strlen in a comparison setting, substr to cut it if you need to, and the concatenation operator with "..." or "&hellip;"

Change an image with onclick()

This script helps to change the image on click the text:

<script>
    $(document).ready(function(){
    $('li').click(function(){
    var imgpath = $(this).attr('dir');
    $('#image').html('<img src='+imgpath+'>');
    });
    $('.btn').click(function(){
    $('#thumbs').fadeIn(500);
    $('#image').animate({marginTop:'10px'},200);
    $(this).hide();
    $('#hide').fadeIn('slow');
    });
    $('#hide').click(function(){
    $('#thumbs').fadeOut(500,function (){
    $('#image').animate({marginTop:'50px'},200);
    });
    $(this).hide();
    $('#show').fadeIn('slow');
    });
    });
    </script>


<div class="sandiv">
<h1 style="text-align:center;">The  Human  Body  Parts :</h1>
<div id="thumbs">
<div class="sanl">
<ul>
<li dir="5.png">Human-body-organ-diag-1</li>
<li dir="4.png">Human-body-organ-diag-2</li>
<li dir="3.png">Human-body-organ-diag-3</li>
<li dir="2.png">Human-body-organ-diag-4</li>
<li dir="1.png">Human-body-organ-diag-5</li>
</ul>
</div>
</div>
<div class="man">
<div id="image">
<img src="2.png" width="348" height="375"></div>
</div>
<div id="thumbs">
<div class="sanr" >
<ul>
<li dir="5.png">Human-body-organ-diag-6</li>
<li dir="4.png">Human-body-organ-diag-7</li>
<li dir="3.png">Human-body-organ-diag-8</li>
<li dir="2.png">Human-body-organ-diag-9</li>
<li dir="1.png">Human-body-organ-diag-10</li>
</ul>
</div>
</div>
<h2><a style="color:#333;" href="http://www.sanwebcorner.com/">sanwebcorner.com</a></h2>
</div>

see the demo here

How do I load a PHP file into a variable?

Theoretically you could just use fopen, then use stream_get_contents.

$stream = fopen("file.php","r");
$string = stream_get_contents($stream);
fclose($stream);

That should read the entire file into $string for you, and should not evaluate it. Though I'm surprised that file_get_contents didn't work when you specified the local path....

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

What is the JavaScript equivalent of var_dump or print_r in PHP?

Most common way:

console.log(object);

However I must mention JSON.stringify which is useful to dump variables in non-browser scripts:

console.log( JSON.stringify(object) );

The JSON.stringify function also supports built-in prettification as pointed out by Simon Zyx.

Example:

var obj = {x: 1, y: 2, z: 3};

console.log( JSON.stringify(obj, null, 2) ); // spacing level = 2

The above snippet will print:

{
  "x": 1,
  "y": 2,
  "z": 3
}

On caniuse.com you can view the browsers that support natively the JSON.stringify function: http://caniuse.com/json

You can also use the Douglas Crockford library to add JSON.stringify support on old browsers: https://github.com/douglascrockford/JSON-js

Docs for JSON.stringify: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

I hope this helps :-)

Laravel Request getting current path with query string

Laravel 4.5

Just use

Request::fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace(Request::url(), '', Request::fullUrl())

Or you can get a array of all the queries with

Request::query()

Laravel >5.1

Just use

$request->fullUrl()

It will return the full url

You can extract the Querystring with str_replace

str_replace($request->url(), '',$request->fullUrl())

Or you can get a array of all the queries with

$request->query()

Right pad a string with variable number of spaces

Whammo blammo (for leading spaces):

SELECT 
    RIGHT(space(60) + cust_name, 60),
    RIGHT(space(60) + cust_address, 60)

OR (for trailing spaces)

SELECT
    LEFT(cust_name + space(60), 60),
    LEFT(cust_address + space(60), 60),

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

Newb move on my part, but I had installed just the JRE instead of JDK. Installed JDK and my problem went immediately away.

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

VBA using ubound on a multidimensional array

You need to deal with the optional Rank parameter of UBound.

Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1)  '? returns 4
Debug.Print UBound(arr, 2)  '? returns 3

More at: UBound Function (Visual Basic)

How to get overall CPU usage (e.g. 57%) on Linux

Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:

$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%

This will use awk to print out 100 minus the 12th field (idle), with a percentage sign after it. awk will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/).

You can also average five samples, one second apart:

$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'

Test it like this:

$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

Examples for string find in Python

Try

myString = 'abcabc'
myString.find('a')

This will give you the index!!!

What is FCM token in Firebase?

What is it exactly?

An FCM Token, or much commonly known as a registrationToken like in . As described in the GCM FCM docs:

An ID issued by the GCM connection servers to the client app that allows it to receive messages. Note that registration tokens must be kept secret.


How can I get that token?

Update: The token can still be retrieved by calling getToken(), however, as per FCM's latest version, the FirebaseInstanceIdService.onTokenRefresh() has been replaced with FirebaseMessagingService.onNewToken() -- which in my experience functions the same way as onTokenRefresh() did.


Old answer:

As per the FCM docs:

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you'll need to access this token.

You can access the token's value by extending FirebaseInstanceIdService. Make sure you have added the service to your manifest, then call getToken in the context of onTokenRefresh, and log the value as shown:

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

The onTokenRefreshcallback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. FirebaseInstanceID.getToken() returns null if the token has not yet been generated.

After you've obtained the token, you can send it to your app server and store it using your preferred method. See the Instance ID API reference for full detail on the API.

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

Error running android: Gradle project sync failed. Please fix your project and try again

Goto File -> Invalidate caches / Restart Shutdown Android Studio Rename/remove .gradle folder in the user home directory Restart Android Studio (It will download gradle metadata and data) Gradle build succeed Rebuild project. Done

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There is no best way, it depends on your use case.

  • Use way 1 if you want to create several similar objects. In your example, Person (you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.
  • Use way 2 if you only need one object of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.
  • Use way 3 if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.

Update: As requested examples for the third way.

Dependent properties:

The following does not work as this does not refer to book. There is no way to initialize a property with values of other properties in a object literal:

var book = {
    price: somePrice * discount,
    pages: 500,
    pricePerPage: this.price / this.pages
};

instead, you could do:

var book = {
    price: somePrice * discount,
    pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;

Dynamic property names:

If the property name is stored in some variable or created through some expression, then you have to use bracket notation:

var name = 'propertyName';

// the property will be `name`, not `propertyName`
var obj = {
    name: 42
}; 

// same here
obj.name = 42;

// this works, it will set `propertyName`
obj[name] = 42;

How to update TypeScript to latest version with npm?

If you are using Windows with very old NodeJS, then uninstall previous NodeJs and NVM (Node Version Manager) in Control Panel (Win7) or Settings/Apps (Win10) if exists. Make sure that they are removed from the PATH.

Reinstall NodeJS: https://nodejs.org/en/download It will install NPM as well.

Install TypeScript globally:

npm install -g typescript

Verify installation:

tsc -v

how to display full stored procedure code?

\ef <function_name> in psql. It will give the whole function with editable text.

Compiling C++ on remote Linux machine - "clock skew detected" warning

According to user m9dhatter on LinuxQuestions.org:

"make" uses the time stamp of the file to determine if the file it is trying to compile is old or new. if your clock is bonked, it may have problems compiling.

if you try to modify files at another machine with a clock time ahead by a few minutes and transfer them to your machine and then try to compile it may cough up a warning that says the file was modified from the future. clock may be skewed or something to that effect ( cant really remember ). you could just ls to the offending file and do this:

#touch <filename of offending file>

javascript password generator

function password_generator( len ) {
    var length = (len)?(len):(10);
    var string = "abcdefghijklmnopqrstuvwxyz"; //to upper 
    var numeric = '0123456789';
    var punctuation = '!@#$%^&*()_+~`|}{[]\:;?><,./-=';
    var password = "";
    var character = "";
    var crunch = true;
    while( password.length<length ) {
        entity1 = Math.ceil(string.length * Math.random()*Math.random());
        entity2 = Math.ceil(numeric.length * Math.random()*Math.random());
        entity3 = Math.ceil(punctuation.length * Math.random()*Math.random());
        hold = string.charAt( entity1 );
        hold = (password.length%2==0)?(hold.toUpperCase()):(hold);
        character += hold;
        character += numeric.charAt( entity2 );
        character += punctuation.charAt( entity3 );
        password = character;
    }
    password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
    return password.substr(0,len);
}

console.log( password_generator() );

This generates a little more robust password that should pass any password strength test. eg: f1&d2?I4(h1&, C1^y1)j1@G2#, j2{h6%b5@R2)

Python: "Indentation Error: unindent does not match any outer indentation level"

I had this same problem and it had nothing to do with tabs. This was my problem code:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

Note the above for is indented with more spaces than the line that starts with if. This is bad. All your indents must be consistent. So I guess you could say I had a stray space and not a stray tab.

Only allow Numbers in input Tag without Javascript

Try this with the + after [0-9]:

input type="text" pattern="[0-9]+" title="number only"

How do I convert Long to byte[] and back in java

 public static long bytesToLong(byte[] bytes) {
        if (bytes.length > 8) {
            throw new IllegalMethodParameterException("byte should not be more than 8 bytes");

        }
        long r = 0;
        for (int i = 0; i < bytes.length; i++) {
            r = r << 8;
            r += bytes[i];
        }

        return r;
    }



public static byte[] longToBytes(long l) {
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        while (l != 0) {
            bytes.add((byte) (l % (0xff + 1)));
            l = l >> 8;
        }
        byte[] bytesp = new byte[bytes.size()];
        for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) {
            bytesp[j] = bytes.get(i);
        }
        return bytesp;
    }

Share application "link" in Android

Thomas,

You would want to provide your users with a market:// link which will bring them directly to the details page of your app. The following is from developer.android.com:

Loading an application's Details page

In Android Market, every application has a Details page that provides an overview of the application for users. For example, the page includes a short description of the app and screen shots of it in use, if supplied by the developer, as well as feedback from users and information about the developer. The Details page also includes an "Install" button that lets the user trigger the download/purchase of the application.

If you want to refer the user to a specific application, your application can take the user directly to the application's Details page. To do so, your application sends an ACTION_VIEW Intent that includes a URI and query parameter in this format:

market://details?id=

In this case, the packagename parameter is target application's fully qualified package name, as declared in the package attribute of the manifest element in the application's manifest file. For example:

market://details?id=com.example.android.jetboy

Source: http://developer.android.com/guide/publishing/publishing.html

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

Extract data from log file in specified range of time

I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:

$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I solved this on Windows 10 by editing an outbound firewall rule. Right click "allow" on rule "Block network access for R local user accounts in SQL Server instance MSSQLSERVER"

from Windows 10 Firewall - Outbound rules- this is what was blocking my instance

Screenshot from Windows 10 Firewall - Outbound rules- this is what was blocking my instance

A SQL Query to select a string between two known strings

select substring(@string,charindex('@first',@string)+1,charindex('@second',@string)-(charindex('@first',@string)+1))

What is a Python egg?

Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.

The easiest way to install and use Python eggs is to use the "Easy Install" Python package manager, which will find, download, build, and install eggs for you; all you do is tell it the name (and optionally, version) of the Python project(s) you want to use.

Python eggs can be used with Python 2.3 and up, and can be built using the setuptools package (see the Python Subversion sandbox for source code, or the EasyInstall page for current installation instructions).

The primary benefits of Python Eggs are:

  • They enable tools like the "Easy Install" Python package manager

  • .egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)

  • They can include package metadata, such as the other eggs they depend on

  • They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)

  • They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.

  • They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).

There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.

What is an unsigned char?

In C++, there are three distinct character types:

  • char
  • signed char
  • unsigned char

If you are using character types for text, use the unqualified char:

  • it is the type of character literals like 'a' or '0'.
  • it is the type that makes up C strings like "abcde"

It also works out as a number value, but it is unspecified whether that value is treated as signed or unsigned. Beware character comparisons through inequalities - although if you limit yourself to ASCII (0-127) you're just about safe.

If you are using character types as numbers, use:

  • signed char, which gives you at least the -127 to 127 range. (-128 to 127 is common)
  • unsigned char, which gives you at least the 0 to 255 range.

"At least", because the C++ standard only gives the minimum range of values that each numeric type is required to cover. sizeof (char) is required to be 1 (i.e. one byte), but a byte could in theory be for example 32 bits. sizeof would still be report its size as 1 - meaning that you could have sizeof (char) == sizeof (long) == 1.

Change keystore password from no password to a non blank password

Add -storepass to keytool arguments.

keytool -storepasswd -storepass '' -keystore mykeystore.jks

But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password

$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

You can press I twice to interrupt the kernel.

This only works if you're in Command mode. If not already enabled, press Esc to enable it.

Is there a JavaScript function that can pad a string to get to a determined length?

/**************************************************************************************************
Pad a string to pad_length fillig it with pad_char.
By default the function performs a left pad, unless pad_right is set to true.

If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place.
**************************************************************************************************/
if(!String.prototype.pad)
String.prototype.pad = function(pad_char, pad_length, pad_right) 
{
   var result = this;
   if( (typeof pad_char === 'string') && (pad_char.length === 1) && (pad_length > this.length) )
   {
      var padding = new Array(pad_length - this.length + 1).join(pad_char); //thanks to http://stackoverflow.com/questions/202605/repeat-string-javascript/2433358#2433358
      result = (pad_right ? result + padding : padding + result);
   }
   return result;
}

And then you can do:

alert( "3".pad("0", 3) ); //shows "003"
alert( "hi".pad(" ", 3) ); //shows " hi"
alert( "hi".pad(" ", 3, true) ); //shows "hi "

Android intent for playing video?

I have come across this with the Hero, using what I thought was a published API. In the end, I used a test to see if the intent could be received:

private boolean isCallable(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 
        PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

In use when I would usually just start the activity:

final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
if (isCallable(intent)) {
    // call the intent as you intended.
} else {
    // make alternative arrangements.
}

obvious: If you go down this route - using non-public APIs - you must absolutely provide a fallback which you know definitely works. It doesn't have to be perfect, it can be a Toast saying that this is unsupported for this handset/device, but you should avoid an uncaught exception. end obvious.


I find the Open Intents Registry of Intents Protocols quite useful, but I haven't found the equivalent of a TCK type list of intents which absolutely must be supported, and examples of what apps do different handsets.

How to set timeout in Retrofit library?

public class ApiModule {
    public WebService apiService(Context context) {
        String mBaseUrl = context.getString(BuildConfig.DEBUG ? R.string.local_url : R.string.live_url);

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectTimeout(120, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                //.addNetworkInterceptor(networkInterceptor)
                .build();

        return new Retrofit.Builder().baseUrl(mBaseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build().create(WebService.class);

    }
}

How to drop columns using Rails migration

remove_column :table_name, :column_name

For instance:

remove_column :users, :hobby

would remove the hobby Column from the users table.

MySQL select query with multiple conditions

You have conditions that are mutually exclusive - if meta_key is 'first_name', it can't also be 'yearofpassing'. Most likely you need your AND's to be OR's:

$result = mysql_query("SELECT user_id FROM wp_usermeta 
WHERE (meta_key = 'first_name' AND meta_value = '$us_name') 
OR (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') 
OR (meta_key = 'u_city' AND meta_value = '$us_reg') 
OR (meta_key = 'us_course' AND meta_value = '$us_course')")

Convert a byte array to integer in Java and vice versa

You can also use BigInteger for variable length bytes. You can convert it to long, int or short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

To get bytes back just:

new BigInteger(bytes).toByteArray()

How to retrieve records for last 30 minutes in MS SQL?

SQL Server uses Julian dates so your 30 means "30 calendar days". getdate() - 0.02083 means "30 minutes ago".

How do I set vertical space between list items?

To apply to an entire list, use

ul.space_list li { margin-bottom: 1em; }

Then, in the html:

<ul class=space_list>
<li>A</li>
<li>B</li>
</ul>

jQuery ajax success callback function definition

I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the sucess: i.e.

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

the handleData function will be called and the parameter passed to it by the ajax function.

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

Can a Byte[] Array be written to a file in C#?

You can do this using System.IO.BinaryWriter which takes a Stream so:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

How do I create a random alpha-numeric string in C++?

Random string, every run file = different string

        auto randchar = []() -> char
    {
        const char charset[] =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "abcdefghijklmnopqrstuvwxyz";

        const size_t max_index = (sizeof(charset) - 1);

        return charset[randomGenerator(0, max_index)];
    };
            std::string custom_string;
            size_t LENGTH_NAME = 6 // length of name
    generate_n(custom_string.begin(), LENGTH_NAME, randchar);

Create a new cmd.exe window from within another cmd.exe prompt

Simply type start in the command prompt:

start

This will open up new cmd windows.

Can anonymous class implement interface?

Casting anonymous types to interfaces has been something I've wanted for a while but unfortunately the current implementation forces you to have an implementation of that interface.

The best solution around it is having some type of dynamic proxy that creates the implementation for you. Using the excellent LinFu project you can replace

select new
{
  A = value.A,
  B = value.C + "_" + value.D
};

with

 select new DynamicObject(new
 {
   A = value.A,
   B = value.C + "_" + value.D
 }).CreateDuck<DummyInterface>();

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

See :hover state in Chrome Developer Tools

In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):

Inspect element and then click on the three white dots in the left gutter:
click on the three white dots

Then choose the desired element state from this dropdown:
this dropdown

Checking if an object is a given type in Swift

Swift 3:

class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}

if aShape.isKind(of: Circle.self) {
}

How can I bind a background color in WPF/XAML?

I figured this out, it was just a naming conflict issue: if you use TheBackground instead of Background it works as posted in the first example. The property Background was interfering with the Window property background.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`) 
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

Where is Android Studio layout preview?

  1. Go to File->Invalidate Caches/ Restart. After restarting the preview window will come.

  2. Still the preview window is not opened, Go to View -> Tool window -> click Preview

How do I insert datetime value into a SQLite database?

Read This: 1.2 Date and Time Datatype best data type to store date and time is:

TEXT best format is: yyyy-MM-dd HH:mm:ss

Then read this page; this is best explain about date and time in SQLite. I hope this help you

Making an array of integers in iOS

If the order of your integers is not required, and if there are only unique values

you can also use NSIndexSet or NSMutableIndexSet You will be able to easily add and remove integers, or check if your array contains an integer with

- (void)addIndex:(NSUInteger)index
- (void)removeIndex:(NSUInteger)index
- (BOOL)containsIndexes:(NSIndexSet *)indexSet

Check the documentation for more info.

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

Change default icon

Go to the Project properties Build the project Locate the .exe file in your favorite file explorer.

ConnectionTimeout versus SocketTimeout

A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.

A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

How to get the first line of a file in a bash script?

This suffices and stores the first line of filename in the variable $line:

read -r line < filename

I also like awk for this:

awk 'NR==1 {print; exit}' file

To store the line itself, use the var=$(command) syntax. In this case, line=$(awk 'NR==1 {print; exit}' file).

Or even sed:

sed -n '1p' file

With the equivalent line=$(sed -n '1p' file).


See a sample when we feed the read with seq 10, that is, a sequence of numbers from 1 to 10:

$ read -r line < <(seq 10) 
$ echo "$line"
1

$ line=$(awk 'NR==1 {print; exit}' <(seq 10))
$ echo "$line"
1

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Is there a good jQuery Drag-and-drop file upload plugin?

Check out the recently1 released upload handler from the guys that created the TinyMCE editor. It has a jQuery widget and looks like it has a nice set of features and fallbacks.

http://www.plupload.com/

Get RETURN value from stored procedure in SQL

Assign after the EXEC token:

DECLARE @returnValue INT

EXEC @returnValue = SP_One

'Best' practice for restful POST response

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API

It includes an answer to your question here: Updates & creation should return a resource representation

It says:

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.

How to remove unused C/C++ symbols with GCC and ld?

You'll want to check your docs for your version of gcc & ld:

However for me (OS X gcc 4.0.1) I find these for ld

-dead_strip

Remove functions and data that are unreachable by the entry point or exported symbols.

-dead_strip_dylibs

Remove dylibs that are unreachable by the entry point or exported symbols. That is, suppresses the generation of load command commands for dylibs which supplied no symbols during the link. This option should not be used when linking against a dylib which is required at runtime for some indirect reason such as the dylib has an important initializer.

And this helpful option

-why_live symbol_name

Logs a chain of references to symbol_name. Only applicable with -dead_strip. It can help debug why something that you think should be dead strip removed is not removed.

There's also a note in the gcc/g++ man that certain kinds of dead code elimination are only performed if optimization is enabled when compiling.

While these options/conditions may not hold for your compiler, I suggest you look for something similar in your docs.

Redirect all to index.php using htaccess

To redirect everything that doesnt exist to index.php , you can also use the FallBackResource directive

FallbackResource /index.php

It works same as the ErrorDocument , when you request a non-existent path or file on the server, the directive silently forwords the request to index.php .

If you want to redirect everything (including existant files or folders ) to index.php , you can use something like the following :

RewriteEngine on

RewriteRule ^((?!index\.php).+)$ /index.php [L]

Note the pattern ^((?!index\.php).+)$ matches any uri except index.php we have excluded the destination path to prevent infinite looping error.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

Add this to your client code :

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
    delegate
    {
        return true;
    });

Throwing exceptions from constructors

It is OK to throw from your constructor, but you should make sure that your object is constructed after main has started and before it finishes:

class A
{
public:
  A () {
    throw int ();
  }
};

A a;     // Implementation defined behaviour if exception is thrown (15.3/13)

int main ()
{
  try
  {
    // Exception for 'a' not caught here.
  }
  catch (int)
  {
  }
}

Difference between two dates in Python

Use - to get the difference between two datetime objects and take the days member.

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

Set the selected index of a Dropdown using jQuery

First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.

$(".myselect")

To answer your question though, there are a few ways to change the select elements value in jQuery

// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0'); 

// sets selected index of a select box to the option with the value ""
$("select#elem").val(''); 

// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;

// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

Lists in ConfigParser

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not pretty but it's functional for most simple lists.

Force DOM redraw/refresh on Chrome/Mac

I wanted to return all the states to the previous state (without reloading) including the elements added by jquery. The above implementation not gonna works. and I did as follows.

// Set initial HTML description
var defaultHTML;
function DefaultSave() {
  defaultHTML = document.body.innerHTML;
}
// Restore HTML description to initial state
function HTMLRestore() {
  document.body.innerHTML = defaultHTML;
}



DefaultSave()
<input type="button" value="Restore" onclick="HTMLRestore()">

jQuery or CSS selector to select all IDs that start with some string

You can use meta characters like * (http://api.jquery.com/category/selectors/). So I think you just can use $('#player_*').

In your case you could also try the "Attribute starts with" selector: http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

How to put scroll bar only for modal-body?

What worked for me is setting the height to 100% the having the overflow on auto hope this will help

   <div style="height: 100%;overflow-y: auto;"> Some text o othre div scroll </div>

javascript if number greater than number

You're comparing strings. JavaScript compares the ASCII code for each character of the string.

To see why you get false, look at the charCodes:

"1300".charCodeAt(0);
49
"999".charCodeAt(0);
57

The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.

The fix is to treat the strings as numbers. You can use a number of methods:

parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes


+"1300"
> 1300


Number("1300")
> 1300

How to darken an image on mouseover?

Make the image 100% bright so it is clear. And then on Img hover reduce it to whatever brightness you want.

_x000D_
_x000D_
img {_x000D_
   -webkit-transition: all 1s ease;_x000D_
   -moz-transition: all 1s ease;_x000D_
   -o-transition: all 1s ease;_x000D_
   -ms-transition: all 1s ease;_x000D_
   transition: all 1s ease;_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
   -webkit-filter: brightness(70%);_x000D_
   filter: brightness(70%);_x000D_
}
_x000D_
<img src="http://dummyimage.com/300x150/ebebeb/000.jpg">
_x000D_
_x000D_
_x000D_

That will do it, Hope that helps

Viewing all defined variables

As RedBlueThing and analog said:

  • dir() gives a list of in scope variables
  • globals() gives a dictionary of global variables
  • locals() gives a dictionary of local variables

Using the interactive shell (version 2.6.9), after creating variables a = 1 and b = 2, running dir() gives

['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']

running locals() gives

{'a': 1, 'b': 2, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

Running globals() gives exactly the same answer as locals() in this case.

I haven't gotten into any modules, so all the variables are available as both local and global variables. locals() and globals() list the values of the variables as well as the names; dir() only lists the names.

If I import a module and run locals() or globals() inside the module, dir() still gives only a small number of variables; it adds __file__ to the variables listed above. locals() and globals() also list the same variables, but in the process of printing out the dictionary value for __builtin__, it lists a far larger number of variables: built-in functions, exceptions, and types such as "'type': <type 'type'>", rather than just the brief <module '__builtin__' (built-in)> as shown above.

For more about dir() see Python 2.7 quick reference at New Mexico Tech or the dir() function at ibiblio.org.

For more about locals() and globals() see locals and globals at Dive Into Python and a page about globals at New Mexico Tech.

[Comment: @Kurt: You gave a link to enumerate-or-list-all-variables-in-a-program-of-your-favorite-language-here but that answer has a mistake in it. The problem there is: type(name) in that example will always return <type 'str'>. You do get a list of the variables, which answers the question, but with incorrect types listed beside them. This was not obvious in your example because all the variables happened to be strings anyway; however, what it's returning is the type of the name of the variable instead of the type of the variable. To fix this: instead of print type(name) use print eval('type(' + name + ')'). I apologize for posting a comment in the answer section but I don't have comment posting privileges, and the other question is closed.]

How can I add a Google search box to my website?

This is one of the way to add google site search to websites:

_x000D_
_x000D_
<form action="https://www.google.com/search" class="searchform" method="get" name="searchform" target="_blank">_x000D_
<input name="sitesearch" type="hidden" value="example.com">_x000D_
<input autocomplete="on" class="form-control search" name="q" placeholder="Search in example.com" required="required"  type="text">_x000D_
<button class="button" type="submit">Search</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

how to change any data type into a string in python

Just use str - for example:

>>> str([])
'[]'

The Network Adapter could not establish the connection when connecting with Oracle DB

I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.

Reactjs - setting inline styles correctly

You could also try setting style inline without using a variable, like so:

style={{"height" : "100%"}} or,

for multiple attributes: style={{"height" : "100%", "width" : "50%"}}

iOS - UIImageView - how to handle UIImage image orientation

I converted the code from @Nicolas Miari answer to Swift 3 in case anybody needs it

func fixOrientation() -> UIImage
{

    if self.imageOrientation == UIImageOrientation.up {
        return self
    }

    var transform = CGAffineTransform.identity

    switch self.imageOrientation {
    case .down, .downMirrored:
        transform = transform.translatedBy(x: self.size.width, y: self.size.height)
        transform = transform.rotated(by: CGFloat(M_PI));

    case .left, .leftMirrored:
        transform = transform.translatedBy(x: self.size.width, y: 0);
        transform = transform.rotated(by: CGFloat(M_PI_2));

    case .right, .rightMirrored:
        transform = transform.translatedBy(x: 0, y: self.size.height);
        transform = transform.rotated(by: CGFloat(-M_PI_2));

    case .up, .upMirrored:
        break
    }


    switch self.imageOrientation {

    case .upMirrored, .downMirrored:
        transform = transform.translatedBy(x: self.size.width, y: 0)
        transform = transform.scaledBy(x: -1, y: 1)

    case .leftMirrored, .rightMirrored:
        transform = transform.translatedBy(x: self.size.height, y: 0)
        transform = transform.scaledBy(x: -1, y: 1);

    default:
        break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    let ctx = CGContext(
        data: nil,
        width: Int(self.size.width),
        height: Int(self.size.height),
        bitsPerComponent: self.cgImage!.bitsPerComponent,
        bytesPerRow: 0,
        space: self.cgImage!.colorSpace!,
        bitmapInfo: UInt32(self.cgImage!.bitmapInfo.rawValue)
    )



    ctx!.concatenate(transform);

    switch self.imageOrientation {

    case .left, .leftMirrored, .right, .rightMirrored:
        // Grr...
        ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.height ,height:self.size.width))

    default:
        ctx?.draw(self.cgImage!, in: CGRect(x:0 ,y: 0 ,width: self.size.width ,height:self.size.height))
        break;
    }

    // And now we just create a new UIImage from the drawing context
    let cgimg = ctx!.makeImage()

    let img = UIImage(cgImage: cgimg!)

    return img;

}

How do I force make/GCC to show me the commands?

To invoke a dry run:

make -n

This will show what make is attempting to do.

Display a tooltip over a button using Windows Forms

private void Form1_Load(object sender, System.EventArgs e)
{
    ToolTip toolTip1 = new ToolTip();
    toolTip1.AutoPopDelay = 5000;
    toolTip1.InitialDelay = 1000;
    toolTip1.ReshowDelay = 500;
    toolTip1.ShowAlways = true;
    toolTip1.SetToolTip(this.button1, "My button1");
    toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

How/When does Execute Shell mark a build as failure in Jenkins?

In my opinion, turning off the -e option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.

If you have a line in your script where failure is expected, like a grep or a find, then just add || true to the end of that line. That ensures that line will always return success.

If you need to use that exit code, you can either hoist the command into your if statement:

grep foo bar; if [ $? == 0 ]; then ...    -->   if grep foo bar; then ...

Or you can capture the return code in your || clause:

grep foo bar || ret=$?

How to create composite primary key in SQL Server 2008

For MSSQL Server 2012

CREATE TABLE usrgroup(
  usr_id int FOREIGN KEY REFERENCES users(id),
  grp_id int FOREIGN KEY REFERENCES groups(id),

  PRIMARY KEY (usr_id, grp_id)
)

UPDATE

I should add !

If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:

CREATE TABLE usrgroup(
  usr_id int,
  grp_id int,

  CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
  CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),

  CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)

Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.

I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.

How to run regasm.exe from command line other than Visual Studio command prompt?

For the 64-bit RegAsm.exe you will need to find it someplace like this:

c:\Windows\Microsoft.NET\Framework64\version_number_stuff\regasm.exe

Fixing the order of facets in ggplot

There are a couple of good solutions here.

Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:

# Change this code:
facet_grid(.~size) + 
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))

This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

In my case, the solution was to make every directory in the directory path readable and accessible by mysql (chmod a+rx). The directory was still specified by its relative path in the command line.

chmod a+rx /tmp
chmod a+rx /tmp/migration
etc.

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

This solution worked for me Android Studio 3.3.2.

  1. Delete the .iml file from the project directory.
  2. In android studio File->invalidate caches/restart.
  3. Clean and Rebuild project if the auto build throws error.

How do I add a bullet symbol in TextView?

Prolly a better solution out there somewhere, but this is what I did.

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <TableRow>    
            <TextView
                android:layout_column="1"
                android:text="•"></TextView>
            <TextView
                android:layout_column="2"
                android:layout_width="wrap_content"
                android:text="First line"></TextView>
        </TableRow>
        <TableRow>    
            <TextView
                android:layout_column="1"
                android:text="•"></TextView>
            <TextView
                android:layout_column="2"
                android:layout_width="wrap_content"
                android:text="Second line"></TextView>
        </TableRow>
  </TableLayout>

It works like you want, but a workaround really.

How to convert Integer to int?

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

What's the default password of mariadb on fedora?

If your DB is installed properly and typed the wrong password, the error thrown will be:

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

The following error indicates you DB hasn't been started/installed completely. Your command is not able to locate and talk with your DB instance.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2 "No such file or directory")

Good practice would be to change your password after a fresh install

$ sudo service mysql stop
$ mysqld_safe --skip-grant-tables &
$ sudo service mysql start
$ sudo mysql -u root

MariaDB [(none)]> use mysql;
MariaDB [mysql]> update user set password=PASSWORD("snafu8") where User='root';
MariaDB [mysql]> flush privileges;
MariaDB [mysql]> exit;

$ sudo service mysql restart

OR

mysqladmin -u root password 'enter password here'

Which characters need to be escaped when using Bash?

Characters that need escaping are different in Bourne or POSIX shell than Bash. Generally (very) Bash is a superset of those shells, so anything you escape in shell should be escaped in Bash.

A nice general rule would be "if in doubt, escape it". But escaping some characters gives them a special meaning, like \n. These are listed in the man bash pages under Quoting and echo.

Other than that, escape any character that is not alphanumeric, it is safer. I don't know of a single definitive list.

The man pages list them all somewhere, but not in one place. Learn the language, that is the way to be sure.

One that has caught me out is !. This is a special character (history expansion) in Bash (and csh) but not in Korn shell. Even echo "Hello world!" gives problems. Using single-quotes, as usual, removes the special meaning.

Check if an apt-get package is installed and then install it if it's not on Linux

For Ubuntu, apt provides a fairly decent way to do this. Below is an example for google chrome:

apt -qq list google-chrome-stable 2>/dev/null | grep -qE "(installed|upgradeable)" || apt-get install google-chrome-stable

I'm redirecting error output to null because apt warns against using its "unstable cli". I suspect list package is stable so I think it's ok to throw this warning away. The -qq makes apt super quiet.

What are examples of TCP and UDP in real life?

  • TCP: will get there in meaningful order
  • UDP: god knows (maybe)

Date constructor returns NaN in IE, but works in Firefox and Chrome

Here's a code snippet that fixes that behavior of IE (v['date'] is a comma separated date-string, e.g. "2010,4,1"):

if($.browser.msie){
    $.lst = v['date'].split(',');
    $.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2]));
} else {
    $.tmp = new Date(v['date']);
}

The previous approach didn't consider that JS Date month is ZERO based...

Sorry for not explaining too much, I'm at work and just thought this might help.

What is the difference between a field and a property?

Though fields and properties look to be similar to each other, they are 2 completely different language elements.

  1. Fields are the only mechanism how to store data on class level. Fields are conceptually variables at class scope. If you want to store some data to instances of your classes (objects) you need to use fields. There is no other choice. Properties can't store any data even though, it may look they are able to do so. See bellow.

  2. Properties on the other hand never store data. They are just the pairs of methods (get and set) that can be syntactically called in a similar way as fields and in most cases they access (for read or write) fields, which is the source of some confusion. But because property methods are (with some limitations like fixed prototype) regular C# methods they can do whatever regular methods can do. It means they can have 1000 lines of code, they can throw exceptions, call another methods, can be even virtual, abstract or overridden. What makes properties special, is the fact that C# compiler stores some extra metadata into assemblies that can be used to search for specific properties - widely used feature.

Get and set property methods has the following prototypes.

PROPERTY_TYPE get();

void set(PROPERTY_TYPE value);

So it means that properties can be 'emulated' by defining a field and 2 corresponding methods.

class PropertyEmulation
{
    private string MSomeValue;

    public string GetSomeValue()
    {
        return(MSomeValue);
    }

    public void SetSomeValue(string value)
    {
        MSomeValue=value;
    }
}

Such property emulation is typical for programming languages that don't support properties - like standard C++. In C# there you should always prefer properties as the way how to access to your fields.

Because only the fields can store a data, it means that more fields class contains, more memory objects of such class will consume. On the other hand, adding new properties into a class doesn't make objects of such class bigger. Here is the example.

class OneHundredFields
{
        public int Field1;
        public int Field2;
        ...
        public int Field100;
}

OneHundredFields Instance=new OneHundredFields() // Variable 'Instance' consumes 100*sizeof(int) bytes of memory.

class OneHundredProperties
{
    public int Property1
    {
        get
        {
            return(1000);
        }
        set
        {
            // Empty.
        }
    }

    public int Property2
    {
        get
        {
            return(1000);
        }
        set
        {
            // Empty.
        }
    }

    ...

    public int Property100
    {
        get
        {
            return(1000);
        }
        set
        {
            // Empty.
        }
    }
}

OneHundredProperties Instance=new OneHundredProperties() // !!!!! Variable 'Instance' consumes 0 bytes of memory. (In fact a some bytes are consumed becasue every object contais some auxiliarity data, but size doesn't depend on number of properties).

Though property methods can do anything, in most cases they serve as a way how to access objects' fields. If you want to make a field accessible to other classes you can do by 2 ways.

  1. Making fields as public - not advisable.
  2. Using properties.

Here is a class using public fields.

class Name
{
    public string FullName;
    public int YearOfBirth;
    public int Age;
}

Name name=new Name();

name.FullName="Tim Anderson";
name.YearOfBirth=1979;
name.Age=40;

While the code is perfectly valid, from design point of view, it has several drawbacks. Because fields can be both read and written, you can't prevent user from writing to fields. You can apply readonly keyword, but in this way, you have to initialize readonly fields only in constructor. What's more, nothing prevents you to store invalid values into your fields.

name.FullName=null;
name.YearOfBirth=2200;
name.Age=-140;

The code is valid, all assignments will be executed though they are illogical. Age has a negative value, YearOfBirth is far in future and doesn't correspond to Age and FullName is null. With fields you can't prevent users of class Name to make such mistakes.

Here is a code with properties that fixes these issues.

class Name
{
    private string MFullName="";
    private int MYearOfBirth;

    public string FullName
    {
        get
        {
            return(MFullName);
        }
        set
        {
            if (value==null)
            {
                throw(new InvalidOperationException("Error !"));
            }

            MFullName=value;
        }
    }

    public int YearOfBirth
    {
        get
        {
            return(MYearOfBirth);
        }
        set
        {
            if (MYearOfBirth<1900 || MYearOfBirth>DateTime.Now.Year)
            {
                throw(new InvalidOperationException("Error !"));
            }

            MYearOfBirth=value;
        }
    }

    public int Age
    {
        get
        {
            return(DateTime.Now.Year-MYearOfBirth);
        }
    }

    public string FullNameInUppercase
    {
        get
        {
            return(MFullName.ToUpper());
        }
    }
}

The updated version of class has the following advantages.

  1. FullName and YearOfBirth are checked for invalid values.
  2. Age is not writtable. It's callculated from YearOfBirth and current year.
  3. A new property FullNameInUppercase converts FullName to UPPER CASE. This is a little contrived example of property usage, where properties are commonly used to present field values in the format that is more appropriate for user - for instance using current locale on specific numeric of DateTime format.

Beside this, properties can be defined as virtual or overridden - simply because they are regular .NET methods. The same rules applies for such property methods as for regular methods.

C# also supports indexers which are the properties that have an index parameter in property methods. Here is the example.

class MyList
{
    private string[]                 MBuffer;

    public MyList()
    {
        MBuffer=new string[100];
    }

    public string this[int Index]
    {
        get
        {
            return(MBuffer[Index]);
        }
        set
        {
            MBuffer[Index]=value;
        }
    }
}

MyList   List=new MyList();

List[10]="ABC";
Console.WriteLine(List[10]);

Since C# 3.0 allows you to define automatic properties. Here is the example.

class AutoProps
{
    public int Value1
    {
        get;
        set;
    }

    public int Value2
    {
        get;
        set;
    }
}

Even though class AutoProps contains only properties (or it looks like), it can store 2 values and size of objects of this class is equal to sizeof(Value1)+sizeof(Value2)=4+4=8 bytes.

The reason for this is simple. When you define an automatic property, C# compiler generates automatic code that contains hidden field and a property with property methods accessing this hidden field. Here is the code compiler produces.

Here is a code generated by the ILSpy from compiled assembly. Class contains generated hidden fields and properties.

internal class AutoProps
{
    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int <Value1>k__BackingField;

    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int <Value2>k__BackingField;

    public int Value1
    {
        [CompilerGenerated]
        get
        {
            return <Value1>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            <Value1>k__BackingField = value;
        }
    }

    public int Value2
    {
        [CompilerGenerated]
        get
        {
            return <Value2>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            <Value2>k__BackingField = value;
        }
    }
}

So, as you can see, the compiler still uses the fields to store the values - since fields are the only way how to store values into objects.

So as you can see, though properties and fields have similar usage syntax they are very different concepts. Even if you use automatic properties or events - hidden fields are generated by compiler where the real data are stored.

If you need to make a field value accessible to the outside world (users of your class) don't use public or protected fields. Fields always should be marked as private. Properties allow you to make value checks, formatting, conversions etc. and generally make your code safer, more readable and more extensible for future modifications.

How to clear APC cache entries?

The stable of APC is having option to clear a cache in its interface itself. To clear those entries you must login to apc interface.

APC is having option to set username and password in apc.php file.

enter image description here

How to get key names from JSON using jq

You need to use jq 'keys[]'. For example:

echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'

Will output a line separated list:

"example1"
"example2"
"example3"

"Comparison method violates its general contract!"

Just because this is what I got when I Googled this error, my problem was that I had

if (value < other.value)
  return -1;
else if (value >= other.value)
  return 1;
else
  return 0;

the value >= other.value should (obviously) actually be value > other.value so that you can actually return 0 with equal objects.