Programs & Examples On #Mouse pointer

Questions related to the mouse pointer or cursor.

Is there a way to use two CSS3 box shadows on one element?

Box shadows can use commas to have multiple effects, just like with background images (in CSS3).

How to view instagram profile picture in full-size?

replace "150x150" with 720x720 and remove /vp/ from the link.it should work.

UITableViewCell Selected Background Color on Multiple Selection

Swift 4

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
    let selectedCell = tableView.cellForRow(at: indexPath)! as! LeftMenuCell
    selectedCell.contentView.backgroundColor = UIColor.blue
}

If you want to unselect the previous cell, also you can use the different logic for this

var tempcheck = 9999
var lastrow = IndexPath()
var lastcolor = UIColor()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if tempcheck == 9999
    {
        tempcheck = 0
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
    else
    {
        let selectedCelllasttime = tableView.cellForRow(at: lastrow)! as! HealthTipsCell
        selectedCelllasttime.contentView.backgroundColor = lastcolor
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
}

How to sum up elements of a C++ vector?

Nobody seems to address the case of summing elements of a vector that can have NaN values in it, e.g. numerical_limits<double>::quite_NaN()

I usually loop through the elements and bluntly check.

vector<double> x;

//...

size_t n = x.size();

double sum = 0;

for (size_t i = 0; i < n; i++){

  sum += (x[i] == x[i] ? x[i] : 0);

}

It's not fancy at all, i.e. no iterators or any other tricks but I this is how I do it. Some times if there are other things to do inside the loop and I want the code to be more readable I write

double val = x[i];

sum += (val == val ? val : 0);

//...

inside the loop and re-use val if needed.

Take n rows from a spark dataframe and pass to toPandas()

You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])

df_pandas = pd.DataFrame(df.head(3), columns=df.columns)

In [4]: df_pandas
Out[4]: 
     name  age
0   Alice    1
1     Jim    2
2  Sandra    3

How do I replace text in a selection?

You can use ctrl+F to find the text.
ctrl+h to enter the replacement text. Then ctrl+shift+h to replace the current selected text and move to next matched text.

This is for windows. But you can check in mac also for which you might want to check the key bindings under Preferences.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

I don't think so. I wanted this the other day. The closest I got was:

SELECT
  o.OrderId,
  CASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN o.NegotiatedPrice 
     ELSE o.SuggestedPrice
  END
FROM Order o

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Well, for a link, there must be a link tag around. what you can also do is that make a css class for the button and assign that class to the link tag. like,

_x000D_
_x000D_
#btn {_x000D_
  background: url(https://image.flaticon.com/icons/png/128/149/149668.png) no-repeat 0 0;_x000D_
  display: block;_x000D_
  width: 128px;_x000D_
  height: 128px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
}
_x000D_
<a href="btnlink.html" id="btn"></a>
_x000D_
_x000D_
_x000D_

Defining a percentage width for a LinearLayout?

Google introduced new API called PercentRelativeLayout

Add compile dependency like

compile 'com.android.support:percent:22.2.0'

in that PercentRelativeLayout is what we can do percentagewise layout

What is stability in sorting algorithms and why is it important?

A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.

Background: a "stable" sorting algorithm keeps the items with the same sorting key in order. Suppose we have a list of 5-letter words:

peach
straw
apple
spork

If we sort the list by just the first letter of each word then a stable-sort would produce:

apple
peach
straw
spork

In an unstable sort algorithm, straw or spork may be interchanged, but in a stable one, they stay in the same relative positions (that is, since straw appears before spork in the input, it also appears before spork in the output).

We could sort the list of words using this algorithm: stable sorting by column 5, then 4, then 3, then 2, then 1. In the end, it will be correctly sorted. Convince yourself of that. (by the way, that algorithm is called radix sort)

Now to answer your question, suppose we have a list of first and last names. We are asked to sort "by last name, then by first". We could first sort (stable or unstable) by the first name, then stable sort by the last name. After these sorts, the list is primarily sorted by the last name. However, where last names are the same, the first names are sorted.

You can't stack unstable sorts in the same fashion.

Is a Python dictionary an example of a hash table?

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

That's why you can't use something 'not hashable' as a dict key, like a list:

>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.

Error: class X is public should be declared in a file named X.java

The name of the public class within a file has to be the same as the name of that file.

So if your file declares class WeatherArray, it needs to be named WeatherArray.java

The system cannot find the file specified in java

Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.

What's your favorite "programmer" cartoon?

Terms and Conditions cartoon from brainstuck.com

https://brainstuck.com/2008/08/08/t-c/

I'm guessing that this would probably never happen, as agreeing to the terms and conditions is more important than actually reading them (from the software publisher perspective).

Convert Iterator to ArrayList

List result = new ArrayList();
while (i.hasNext()){
    result.add(i.next());
}

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

Setting up enviromental variables in Windows 10 to use java and javac

To find the env vars dialog in Windows 10:

Right Click Start
>>  Click Control Panel  (Or you may have System in the list)
>>  Click System
>>  Click Advanced system settings
>>  Go to the Advanced Tab
>>  Click the "Environment Variables..." button at the bottom of that dialog page.

TypeError : Unhashable type

You are creating a set via set(...) call, and set needs hashable items. You can't have set of lists. Because list's arent hashable.

[[(a,b) for a in range(3)] for b in range(3)] is a list. It's not a hashable type. The __hash__ you saw in dir(...) isn't a method, it's just None.

A list comprehension returns a list, you don't need to explicitly use list there, just use:

>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]

Try those:

>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Declaring and initializing arrays in C

The OP left out some crucial information from the question and only put it in a comment to an answer.

I need to initialize after declaring, because will be different depending on a condition, I mean something like this int myArray[SIZE]; if(condition1) { myArray{x1, x2, x3, ...} } else if(condition2) { myArray{y1, y2, y3, ...} } . . and so on...

With this in mind, all of the possible arrays will need to be stored into data somewhere anyhow, so no memcpy is needed (or desired), only a pointer and a 2d array are required.

//static global since some compilers build arrays from instruction data
//... notably not const though so they can later be modified if needed
#define SIZE 8
static int myArrays[2][SIZE] = {{0,1,2,3,4,5,6,7},{7,6,5,4,3,2,1,0}};

static inline int *init_myArray(_Bool conditional){
  return myArrays[conditional];
}

// now you can use:
//int *myArray = init_myArray(1 == htons(1)); //any boolean expression

The not-inlined version gives this resulting assembly on x86_64:

init_myArray(bool):
        movzx   eax, dil
        sal     rax, 5
        add     rax, OFFSET FLAT:myArrays
        ret
myArrays:
        .long   0
        .long   1
        .long   2
        .long   3
        .long   4
        .long   5
        .long   6
        .long   7
        .long   7
        .long   6
        .long   5
        .long   4
        .long   3
        .long   2
        .long   1
        .long   0

For additional conditionals/arrays, just change the 2 in myArrays to the desired number and use similar logic to get a pointer to the right array.

Can you put two conditions in an xslt test attribute?

Not quite, the AND has to be lower-case.

<xsl:when test="4 &lt; 5 and 1 &lt; 2">
<!-- do something -->
</xsl:when>

Convert double/float to string

See if the BSD C Standard Library has fcvt(). You could start with the source for it that rather than writing your code from scratch. The UNIX 98 standard fcvt() apparently does not output scientific notation so you would have to implement it yourself, but I don't think it would be hard.

How can I solve a connection pool problem between ASP.NET and SQL Server?

I also got this exact error log on my AWS EC2 instance.

There were no connection leaks since I was just deploying the alpha application (no real users), and I confirmed with Activity Monitor and sp_who that there are in fact no connections to the database.

My issue was AWS related - more specifically, with the Security Groups. See, only certain security groups had access to the RDS server where I hosted the database. I added an ingress rule with authorize-security-group-ingress command to allow access to the correct EC2 instance to the RDS server by using --source-group-name parameter. The ingress rule was added, I could see that on the AWS UI - but I got this error.

When I removed and then added the ingress rule manually on AWS UI - suddenly the exception was no more and the app was working.

How can I set the background color of <option> in a <select> element?

I assume you mean the <select> input element?

Support for that is pretty new, but FF 3.6, Chrome and IE 8 render this all right:

_x000D_
_x000D_
<select name="select">
  <option value="1" style="background-color: blue">Test</option>
  <option value="2" style="background-color: green">Test</option>
</select>
_x000D_
_x000D_
_x000D_

Java division by zero doesnt throw an ArithmeticException - why?

Java will not throw an exception if you divide by float zero. It will detect a run-time error only if you divide by integer zero not double zero.

If you divide by 0.0, the result will be INFINITY.

Filter dataframe rows if value in column is in a set list of values

You can use query, i.e.:

b = df.query('a > 1 & a < 5')

AngularJS - Attribute directive input value change

There's a great example in the AngularJS docs.

It's very well commented and should get you pointed in the right direction.

A simple example, maybe more so what you're looking for is below:

jsfiddle


HTML

<div ng-app="myDirective" ng-controller="x">
    <input type="text" ng-model="test" my-directive>
</div>

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('value changed, new value is: ' + v);
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}


Edit: Same thing, doesn't require ngModel jsfiddle:

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: {
            myDirective: '='
        },
        link: function (scope, element, attrs) {
            // set the initial value of the textbox
            element.val(scope.myDirective);
            element.data('old-value', scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective', function (val) {
                element.val(scope.myDirective);
            });

            // on blur, update the value in scope
            element.bind('propertychange keyup paste', function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed, new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value', element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

Setting up a git remote origin

For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: https://help.github.com/articles/changing-a-remote-s-url/. Using git remote add to do this will result in "fatal: remote origin already exists."

Nutshell: git remote set-url origin https://github.com/username/repo

(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)

How to close jQuery Dialog within the dialog?

You need

$('selector').dialog('close');

Editing the git commit message in GitHub

For Android Studio / intellij users:

  • Select Version Control
  • Select Log
  • Right click the commit for which you want to rename
  • Click Edit Commit Message
  • Write your commit message
  • Done

Pip freeze vs. pip list

When you are using a virtualenv, you can specify a requirements.txt file to install all the dependencies.

A typical usage:

$ pip install -r requirements.txt

The packages need to be in a specific format for pip to understand, which is

feedparser==5.1.3
wsgiref==0.1.2
django==1.4.2
...

That is the "requirements format".

Here, django==1.4.2 implies install django version 1.4.2 (even though the latest is 1.6.x). If you do not specify ==1.4.2, the latest version available would be installed.

You can read more in "Virtualenv and pip Basics", and the official "Requirements File Format" documentation.

fatal: The current branch master has no upstream branch

Apparently you also get this error message when you forget the --all parameter when pushing for the first time. I wrote

git push -u origin

which gave this error, it should have been

git push -u origin --all

Oh how I love these copy-paste errors ...

What does it mean to inflate a view from an xml file?

Inflating is the process of adding a view (.xml) to activity on runtime. When we create a listView we inflate each of its items dynamically. If we want to create a ViewGroup with multiple views like buttons and textview, we can create it like so:

Button but = new Button();
but.setText ="button text";
but.background ...
but.leftDrawable.. and so on...

TextView txt = new TextView();
txt.setText ="button text";
txt.background ... and so on...

Then we have to create a layout where we can add above views:

RelativeLayout rel = new RelativeLayout();

rel.addView(but);

And now if we want to add a button in the right-corner and a textview on the bottom, we have to do a lot of work. First by instantiating the view properties and then applying multiple constraints. This is time consuming.

Android makes it easy for us to create a simple .xml and design its style and attributes in xml and then simply inflate it wherever we need it without the pain of setting constraints programatically.

LayoutInflater inflater = 
              (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View menuLayout = inflater.inflate(R.layout.your_menu_layout, mainLayout, true);
//now add menuLayout to wherever you want to add like

(RelativeLayout)findViewById(R.id.relative).addView(menuLayout);

What is the use of join() in Python threading?

This example demonstrate the .join() action:

import threading
import time

def threaded_worker():
    for r in range(10):
        print('Other: ', r)
        time.sleep(2)

thread_ = threading.Timer(1, threaded_worker)
thread_.daemon = True  # If the main thread kills, this thread will be killed too. 
thread_.start()

flag = True

for i in range(10):
    print('Main: ', i)
    time.sleep(2)
    if flag and i > 4:
        print(
            '''
            Threaded_worker() joined to the main thread. 
            Now we have a sequential behavior instead of concurrency.
            ''')
        thread_.join()
        flag = False

Out:

Main:  0
Other:  0
Main:  1
Other:  1
Main:  2
Other:  2
Main:  3
Other:  3
Main:  4
Other:  4
Main:  5
Other:  5

            Threaded_worker() joined to the main thread. 
            Now we have a sequential behavior instead of concurrency.

Other:  6
Other:  7
Other:  8
Other:  9
Main:  6
Main:  7
Main:  8
Main:  9

Lumen: get URL parameter in a Blade view

Laravel 5.8

{{ request()->a }}

Install python 2.6 in CentOS

# yum groupinstall "Development tools"
# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel

Download and install Python 3.3.0

# wget http://python.org/ftp/python/3.3.0/Python-3.3.0.tar.bz2
# tar xf Python-3.3.0.tar.bz2
# cd Python-3.3.0
# ./configure --prefix=/usr/local
# make && make altinstall

Download and install Distribute for Python 3.3

# wget http://pypi.python.org/packages/source/d/distribute/distribute-0.6.35.tar.gz
# tar xf distribute-0.6.35.tar.gz
# cd distribute-0.6.35
# python3.3 setup.py install

Install and use virtualenv for Python 3.3

# easy_install-3.3 virtualenv
# virtualenv-3.3 --distribute otherproject

New python executable in otherproject/bin/python3.3
Also creating executable in otherproject/bin/python
Installing distribute...................done.
Installing pip................done.

# source otherproject/bin/activate
# python --version
Python 3.3.0

Enabling CORS in Cloud Functions for Firebase

If You are not using Express or simply want to use CORS. The following code will help resolve

const cors = require('cors')({ origin: true, });   
exports.yourfunction = functions.https.onRequest((request, response) => {  
   return cors(request, response, () => {  
        // *Your code*
    });
});

Oracle PL/SQL : remove "space characters" from a string

Shorter version of:

REGEXP_REPLACE( my_value, '[[:space:]]', '' )

Would be:

REGEXP_REPLACE( my_value, '\s')

Neither of the above statements will remove "null" characters.

To remove "nulls" encase the statement with a replace

Like so:

REPLACE(REGEXP_REPLACE( my_value, '\s'), CHR(0))

Installing Bootstrap 3 on Rails App

I actually had an easy workaround on this one in which I nearly scratch my head on how to make it work. hahah!

Well, first I downloaded Bootstrap (the compiled css and js version).

Then I pasted all the bootstrap css files to the app/assets/stylesheets/.

And then I pasted all the bootstrap js files to the app/assets/javascripts/.

I reloaded the page and wallah! I just added bootstrap in my RoR!

Get Character value from KeyCode in JavaScript... then trim

Refer this link Get Keycode from key press and char value for any key code

$('input#inp').keyup(function(e){
   $(this).val(String.fromCharCode(e.keyCode)); 
   $('div#output').html('Keycode : ' + e.keyCode);  
});

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

How can I extract a number from a string in JavaScript?

This answer will cover most of the scenario. I can across this situation when user try to copy paste the phone number

  $('#help_number').keyup(function(){
    $(this).val().match(/\d+/g).join("")
  });

Explanation:

str= "34%^gd 5-67 6-6ds"

str.match(/\d+/g)

It will give a array of string as output >> ["34", "56766"]

str.match(/\d+/g).join("")

join will convert and concatenate that array data into single string

output >> "3456766"

In my example I need the output as 209-356-6788 so I used replace

  $('#help_number').keyup(function(){
    $(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
  });

How to select a radio button by default?

Use the checked attribute.

<input type="radio" name="imgsel"  value="" checked /> 

or

<input type="radio" name="imgsel"  value="" checked="checked" /> 

Label on the left side instead above an input field

You can see from the existing answers that Bootstrap's terminology is confusing. If you look at the bootstrap documentation, you see that the class form-horizontal is actually for a form with fields below each other, i.e. what most people would think of as a vertical form. The correct class for a form going across the page is form-inline. They probably introduced the term inline because they had already misused the term horizontal.

You see from some of the answers here that some people are using both of these classes in one form! Others think that they need form-horizontal when they actually want form-inline.

I suggest to do it exactly as described in the Bootstrap documentation:

<form class="form-inline">
  <div class="form-group">
    <label for="nameId">Name</label>
    <input type="text" class="form-control" id="nameId" placeholder="Jane Doe">
  </div>
</form>

Which produces:

enter image description here

How to save a base64 image to user's disk using JavaScript?

HTML5 download attribute

Just to allow user to download the image or other file you may use the HTML5 download attribute.

Static file download

<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg"> 

Dynamic file download

In cases requesting image dynamically it is possible to emulate such download.

If your image is already loaded and you have the base64 source then:

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");

    document.body.appendChild(link); // for Firefox

    link.setAttribute("href", base64);
    link.setAttribute("download", fileName);
    link.click();
}

Otherwise if image file is downloaded as Blob you can use FileReader to convert it to Base64:

function saveBlobAsFile(blob, fileName) {
    var reader = new FileReader();

    reader.onloadend = function () {    
        var base64 = reader.result ;
        var link = document.createElement("a");

        document.body.appendChild(link); // for Firefox

        link.setAttribute("href", base64);
        link.setAttribute("download", fileName);
        link.click();
    };

    reader.readAsDataURL(blob);
}

Firefox

The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).

IE is not supported: Caniuse link

Update ViewPager dynamically?

I have lived same problem and I have searched too much times. Any answer given in stackoverflow or via google was not solution for my problem. My problem was easy. I have a list, I show this list with viewpager. When I add a new element to head of the list and I refresh the viewpager nothings changed. My final solution was very easy anybody can use. When a new element added to list and want to refresh the list. Firstly set viewpager adapter to null then recreate the adapter and set i to it to viewpager.

myVPager.setAdapter(null);
myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),newList);
myVPager.setAdapter(myFragmentAdapter);

Be sure your adapter must extend FragmentStatePagerAdapter

Android: Pass data(extras) to a fragment

There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment

private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;


public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    fragment.init(music);
    return fragment;
}

public void init(List<Music> music){
    this.listMusic = music;
}

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

    View view = inflater.inflate(R.layout.musiclistview, container, false);
    listMusic = (ListView) view.findViewById(R.id.musicListView);
    listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));

    return view;
}
}

In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.

Getting "Cannot call a class as a function" in my React Project

Looks like there're no single case when this error appears.

Happened to me when I didn't declare constructor in statefull component.

class MyComponent extends Component {

    render() {
        return <div>Test</div>;
    }
}

instead of

class MyComponent extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return <div>Test</div>;
    }
}

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

How to insert programmatically a new line in an Excel cell in C#?

You need to insert the character code that Excel uses, which IIRC is 10 (ten).


EDIT: OK, here's some code. Note that I was able to confirm that the character-code used is indeed 10, by creating a cell containing:

A

B

...and then selecting it and executing this in the VBA immediate window:

?Asc(Mid(Activecell.Value,2,1))

So, the code you need to insert that value into another cell in VBA would be:

ActiveCell.Value = "A" & vbLf & "B"

(since vbLf is character code 10).

I know you're using C# but I find it's much easier to figure out what to do if you first do it in VBA, since you can try it out "interactively" without having to compile anything. Whatever you do in C# is just replicating what you do in VBA so there's rarely any difference. (Remember that the C# interop stuff is just using the same underlying COM libraries as VBA).

Anyway, the C# for this would be:

oCell.Value = "A\nB";

Spot the difference :-)


EDIT 2: Aaaargh! I just re-read the post and saw that you're using the Aspose library. Sorry, in that case I've no idea.

How to handle invalid SSL certificates with Apache HttpClient?

For a way to easily add hosts you trust at runtime without throwing out all checks, try the code here: http://code.google.com/p/self-signed-cert-trust-manager/.

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

HttpURLConnection timeout settings

You can set timeout like this,

con.setConnectTimeout(connectTimeout);
con.setReadTimeout(socketTimeout);

Returning a value even if no result

Do search with LEFT OUTER JOIN. I don't know if MySQL allows inline VALUES in join clauses but you can have predefined table for this purposes.

Definitive way to trigger keypress events with jQuery

If you're using jQuery UI too, you can do like this:

var e = jQuery.Event("keypress");
e.keyCode = $.ui.keyCode.ENTER;
$("input").trigger(e);

Delete all documents from index/type without deleting type

Torsten Engelbrecht's comment in John Petrones answer expanded:

curl -XDELETE 'http://localhost:9200/twitter/tweet/_query' -d 
  '{
      "query": 
      {
          "match_all": {}
      }
   }'

(I did not want to edit John's reply, since it got upvotes and is set as answer, and I might have introduced an error)

jQuery onclick event for <li> tags

You can get the ID, or any other attribute, using jQuery's attrib function.

$('ul.art-vmenu li').attrib('id');

To get the menu text, which is in the t span, you can do this:

$('ul.art-vmenu li').children('span.t').html();

To change the HTML is just as easy:

$('ul.art-vmenu li').children('span.t').html("I'm different");

Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:

$('ul.art-vemnu li span.t').html();

But I'm assuming you've already got the li's, and want to use child() to find something within that element.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

simple solution will be change spring.datasource.url=jdbc:h2:file:~/dasboot in application.properties to new file name like : spring.datasource.url=jdbc:h2:file:~/dasboots

Command to get nth line of STDOUT

Another poster suggested

ls -l | head -2 | tail -1

but if you pipe head into tail, it looks like everything up to line N is processed twice.

Piping tail into head

ls -l | tail -n +2 | head -n1

would be more efficient?

Remove all special characters except space from a string using JavaScript

You can do it specifying the characters you want to remove:

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g, '');

Make a number a percentage

A percentage is just:

(number_one / number_two) * 100

No need for anything fancy:

var number1 = 4.954848;
var number2 = 5.9797;

alert(Math.floor((number1 / number2) * 100)); //w00t!

How to run .jar file by double click on Windows 7 64-bit?

I had the same issue: if I doubleclick on a jar executable file, and my Java application does not start.

So tried to change manually also registry key, but it didn't help me. Tried to reinstall JDK newer/older without any result. (I have several versions of Java)

And I've solved it only using jarfix program. Jarfix automatically fixed .jar association problem on Windows system. (check regedit: PC\HKEY_CLASSES_ROOT\jarfile\shell\open\command)

What says Johann Nepomuk Löfflmann:

The root cause for the problem above is, that a program has stolen the .jar association. If you have installed the Java Runtime Environment the first time, the file type called "jar" is assigned to javaw.exe correctly. "jar" is an abbreviation for "java archive" and javaw.exe is the correct program to execute a .jar. However, on Windows any program can steal a file type at any time even if it is already associated with a program. Many zip/unzip programs prefer to do this, because a jar is stored in the .zip format. If you doubleclick on a .jar, your pack program opens the file, rather than javaw runs the program, because your pack program ignores the meta information which are also stored in a .jar. In the Oracle bug database there is the low-priority report 4912211 "add mechanism to restore hijacked .jar and .jnlp file extensions", but it has been closed as "Closed, Will Not Fix".

You may also miss the file connection with .jar if you are using a free OpenJDK without an installer.

Notice: my OS is Windows 10, but logic is the same for 7, 8 and so on.

Helpful links:
https://windowsreport.com/jar-files-not-opening-windows-10/ https://johann.loefflmann.net/en/software/jarfix/index.html

Lightweight workflow engine for Java

I'd recommend you yo use an out-of-the-box solution. Given that the development of a workflow engine requires a vast amount of resources and time, a ready-made engine is a better option. Have a look at Workflow Engine. It's a lightweight component that enables you to add custom executable workflows of any complexity to any Java solutions.

Returning JSON response from Servlet to Javascript/JSP page

I used JSONObject as shown below in Servlet.

    JSONObject jsonReturn = new JSONObject();

    NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);

    map = new HashMap<String, String>();
    map.put("Status", "Success");
    map.put("FailureReason", "None");
    map.put("DataElements", "2");

    jsonReturn = new JSONObject();
    jsonReturn.accumulate("Header", map);

    List<String> list = new ArrayList<String>();
    list.add(NhAdminTree);
    list.add(userName);

    jsonReturn.accumulate("Elements", list);

The Servlet returns this JSON object as shown below:

    response.setContentType("application/json");
    response.getWriter().write(jsonReturn.toString());

This Servlet is called from Browser using AngularJs as below

$scope.GetNeighborhoodTreeUsingPost = function(){
    alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );

    $http({

        method: 'POST',
        url : 'http://localhost:8080/EPortal/xlEPortalService',
        headers: {
           'Content-Type': 'application/json'
         },
        data : {
            'action': 64,
            'userName' : $scope.userName
        }
    }).success(function(data, status, headers, config){
        alert("DATA.header.status : " + data.Header.Status);
        alert("DATA.header.FailureReason : " + data.Header.FailureReason);
        alert("DATA.header.DataElements : " + data.Header.DataElements);
        alert("DATA.elements : " + data.Elements);

    }).error(function(data, status, headers, config) {
        alert(data + " : " + status + " : " + headers + " : " + config);
    });

};

This code worked and it is showing correct data in alert dialog box:

Data.header.status : Success

Data.header.FailureReason : None

Data.header.DetailElements : 2

Data.Elements : Coma seperated string values i.e. NhAdminTree, userName

How can I check that JButton is pressed? If the isEnable() is not work?

JButton has a model which answers these question:

  • isArmed(),
  • isPressed(),
  • isRollOVer()

etc. Hence you can ask the model for the answer you are seeking:

     if(jButton1.getModel().isPressed())
        System.out.println("the button is pressed");

ASP.NET MVC Ajax Error handling

In agreement with aleho's response here's a complete example. It works like a charm and is super simple.

Controller code

[HttpGet]
public async Task<ActionResult> ChildItems()
{
    var client = TranslationDataHttpClient.GetClient();
    HttpResponseMessage response = await client.GetAsync("childItems);

    if (response.IsSuccessStatusCode)
        {
            string content = response.Content.ReadAsStringAsync().Result;
            List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
            return Json(content, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
        }
    }
}

Javascript code in the view

var url = '@Html.Raw(@Url.Action("ChildItems", "WorkflowItemModal")';

$.ajax({
    type: "GET",
    dataType: "json",
    url: url,
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        // Do something with the returned data
    },
    error: function (xhr, status, error) {
        // Handle the error.
    }
});

Hope this helps someone else!

How to update cursor limit for ORA-01000: maximum open cursors exceed

you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts

How to clear the canvas for redrawing

the shortest way:

canvas.width += 0

GitHub Error Message - Permission denied (publickey)

Issue solved if you change the ssh access to https access to the remote repository:

git remote set-url origin https_link_to_repository

git push -u origin master

How to make a select with array contains value clause in psql

Note that this may also work:

SELECT * FROM table WHERE s=ANY(array)

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).

How to convert from java.sql.Timestamp to java.util.Date?

You should use a Calendar instead:

Calendar start = Calendar.getInstance();
start.setTimeInMillis( timeStampValue.getTime() );

.htaccess: where is located when not in www base dir

The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.

Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

Type or namespace name does not exist

Check to see that your target framework has the same .NET versions. I had the same problem and my class .NET was 3.5 and web solution had 4.5. I synchronised those, and then it worked :)

Correct way to synchronize ArrayList in java

You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with synchronized (in_queue_list) Using Collections.synchronizedList() is superfluous in that case (it creates a wrapper that synchronizes individual operations).

However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.

Instead, simply call clear() - no iteration needed.

Edit: If you need the single-method synchronization of Collections.synchronizedList() later on, then this is the correct way:

List<Record> in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); // synchronized implicitly, 

But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so Collections.synchronizedList() is just useless additional overhead.

python: after installing anaconda, how to import pandas

even after installing anaconda i got the same error and entering python3 showed this:

$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

enter this command: source ~/.bashrc (it is kind of restarting the terminal) after running the command enter python3 again:

$ python3
Python 3.7.4 (default, Aug 13 2019, 20:35:49) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

this means anaconda is added. now import pandas will work.

In Objective-C, how do I test the object type?

Simple, [yourobject class] it will return the class name of yourobject.

Android Canvas: drawing too large bitmap

In my case I had to remove the android platform and add it again. Something got stuck and copying all my code into another app worked like a charm - hence my idea of cleaning up the build for android by removing the platform.

cordova platform remove android
cordova platform add android

I guess it's some kind of cleanup that you have to do from time to time :-(

Making a Windows shortcut start relative to where the folder is?

I tried %~dp0 in the Start in field and it is working fine in Windows 10 x64

What's alternative to angular.copy in Angular

The simplest solution I've found is:

let yourDeepCopiedObject = _.cloneDeep(yourOriginalObject);

*IMPORTANT STEPS: You must install lodash to use this (which was unclear from other answers):

$ npm install --save lodash

$ npm install --save @types/lodash

and then import it in your ts file:

import * as _ from "lodash";

How do I get the RootViewController from a pushed controller?

I encounter a strange condition.

self.viewControllers.first is not root viewController always.

Generally, self.viewControllers.first is root viewController indeed. But sometimes it's not.

class MyCustomMainNavigationController: UINavigationController {

    function configureForView(_ v: UIViewController, animated: Bool) {
        let root = self.viewControllers.first
        let isRoot = (v == root)
    
        // Update UI based on isRoot
        // ....
    }
}

extension MyCustomMainNavigationController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, 
        willShow viewController: UIViewController, 
        animated: Bool) {

        self.configureForView(viewController, animated: animated)
    }
}

My issue:

Generally, self.viewControllers.first is root viewController. But, when I call popToRootViewController(animated:), and then it triggers navigationController(_:willShow:animated:). At this moment, self.viewControllers.first is NOT root viewController, it's the last viewController which will disappear.

Summary

  • self.viewControllers.first is not always root viewController. Sometime, it will be the last viewController.

So, I suggest to keep rootViewController by property when self.viewControllers have ONLY one viewController. I get root viewController in viewDidLoad() of custom UINavigationController.

class MyCustomMainNavigationController: UINavigationController {
    fileprivate var myRoot: UIViewController!
    override func viewDidLoad() {

        super.viewDidLoad()

        // My UINavigationController is defined in storyboard. 
        // So at this moment, 
        // I can get root viewController by `self.topViewController!`
        let v = self.topViewController!
        self.myRoot = v
    }

}

Enviroments:

  • iPhone 7 with iOS 14.0.1
  • Xcode 12.0.1 (12A7300)

How to handle iframe in Selenium WebDriver using java

To get back to the parent frame, use:

driver.switchTo().parentFrame();

To get back to the first/main frame, use:

driver.switchTo().defaultContent();

How to make a TextBox accept only alphabetic characters?

private void textbox1_KeyDown_1(object sender, KeyEventArgs e)
{
    if (e.Key >= Key.A && e.Key <= Key.Z)
    {
    }
    else
    {
       e.Handled = true;
    }
}

How to delete history of last 10 commands in shell?

With Bash 5 you can now do a range...Hooray!:

history -d 511-520

or counting backwards 10:

history -d -10--1

Excerpt from Bash 5 Man Page:

'history'

Options, if supplied, have the following meanings:

'-d OFFSET' Delete the history entry at position OFFSET. If OFFSET is positive, it should be specified as it appears when the history is displayed. If OFFSET is negative, it is interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of '-1' refers to the current 'history -d' command.

'-d START-END' Delete the history entries between positions START and END, inclusive. Positive and negative values for START and END are interpreted as described above.

Here is my solution for Bash 4. It iteratively deletes a single entry or a range of history starting with lowest index.

delHistory () {
    count=$(( ${2:-$1} - $1 ))
    while [[ $count -ge 0 ]]; do
        history -d "$1"
        ((count--))
    done
}

delHistory 511 520

How to move columns in a MySQL table?

I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';

SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS c2 
    WHERE c2.TABLE_NAME = t.TABLE_NAME);

How do I find out if first character of a string is a number?

To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true

For character Character.isLetter(str.charAt(0)) --return true

Extreme wait-time when taking a SQL Server database offline

In my case i stopped Tomcat server . then immediately the DB went offline .

Convert blob to base64

this worked for me:

var blobToBase64 = function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function() {
        var dataUrl = reader.result;
        var base64 = dataUrl.split(',')[1];
        callback(base64);
    };
    reader.readAsDataURL(blob);
};

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You haven't provided any of your code from LightFactoryRemote, so this is only a presumption, but it looks like the kind of problem you'd be seeing if you were using the bindService method on it's own.

To ensure a service is kept running, even after the activity that started it has had its onDestroy method called, you should first use startService.

The android docs for startService state:

Using startService() overrides the default service lifetime that is managed by bindService(Intent, ServiceConnection, int): it requires the service to remain running until stopService(Intent) is called, regardless of whether any clients are connected to it.

Whereas for bindService:

The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.


So what's happened is the activity that bound (and therefore started) the service, has been stopped and thus the system thinks the service is no longer required and causes that error (and then probably stops the service).


Example

In this example the service should be kept running regardless of whether the calling activity is running.

ComponentName myService = startService(new Intent(this, myClass.class));
bindService(new Intent(this, myClass.class), myServiceConn, BIND_AUTO_CREATE);

The first line starts the service, and the second binds it to the activity.

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Whilst you certainly can use MySQL's IF() control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE expression instead:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
         ELSE A
       END
WHERE  A IS NOT NULL

Of course, in this specific example it's a little wasteful to set A to itself in the ELSE clause—better entirely to filter such conditions from the UPDATE, via the WHERE clause:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
       END
WHERE  (A > 0 AND A < 1) OR (A > 1 AND A < 2)

(The inequalities entail A IS NOT NULL).

Or, if you want the intervals to be closed rather than open (note that this would set values of 0 to 1—if that is undesirable, one could explicitly filter such cases in the WHERE clause, or else add a higher precedence WHEN condition):

UPDATE Table
SET    A = CASE
         WHEN A BETWEEN 0 AND 1 THEN 1
         WHEN A BETWEEN 1 AND 2 THEN 2
       END
WHERE  A BETWEEN 0 AND 2

Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL() instead:

UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2

How to force deletion of a python object?

  1. Add an exit handler that closes all the bars.
  2. __del__() gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.
  3. If __init__() raises an exception then the object is assumed to be incomplete and __del__() won't be invoked.

Threads vs Processes in Linux

Threads -- > Threads shares a memory space,it is an abstraction of the CPU,it is lightweight. Processes --> Processes have their own memory space,it is an abstraction of a computer. To parallelise task you need to abstract a CPU. However the advantages of using a process over a thread is security,stability while a thread uses lesser memory than process and offers lesser latency. An example in terms of web would be chrome and firefox. In case of Chrome each tab is a new process hence memory usage of chrome is higher than firefox ,while the security and stability provided is better than firefox. The security here provided by chrome is better,since each tab is a new process different tab cannot snoop into the memory space of a given process.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Running Facebook application on localhost

I wrote a tutorial about this a while ago.

The most important point is the "Site URL":

Site URL: http://localhost/app_name/

Where the folder structure is something like:

app_name
¦   index.php
¦
+---canvas
¦   ¦   index.php
¦   ¦
¦   +---css
¦           main.css
¦           reset.css
¦
+---src
        facebook.php
        fb_ca_chain_bundle.crt

EDIT:
Kavya: how does the FB server recognize my localhost even without an IP or port??

I don't think this has anything to do with Facebook, I guess since the iframe src parameter is loaded from client-side it'll treat your local URL as if you put it directly on your browser.

For example have a file on your online server with content (e.g. online.php):

<iframe src="http://localhost/test.php" width="100%" height="100%">
    <p>Not supported!</p>
</iframe>

And on your localhost root directory, have the file test.php:

<?php echo "Hello from Localhost!"; ?>

Now visit http://your_domain.com/online.php you will see your localhost file's content!

This is why realtime subscriptions and deauthorize callbacks (just to mention) won't work with localhost URLs! because Facebook will ping (send http requests) to these URLs but obviously Facebook server won't translate those URLs to yours!

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Case insensitive comparison NSString

 NSString *stringA;
 NSString *stringB;

 if (stringA && [stringA caseInsensitiveCompare:stringB] == NSOrderedSame) {
     // match
 }

Note: stringA && is required because when stringA is nil:

 stringA = nil;
 [stringA caseInsensitiveCompare:stringB] // return 0

and so happens NSOrderedSame is also defined as 0.

The following example is a typical pitfall:

 NSString *rank = [[NSUserDefaults standardUserDefaults] stringForKey:@"Rank"];
 if ([rank caseInsensitiveCompare:@"MANAGER"] == NSOrderedSame) {
     // what happens if "Rank" is not found in standardUserDefaults
 }

Difference between $(document.body) and $('body')

They refer to the same element, the difference is that when you say document.body you are passing the element directly to jQuery. Alternatively, when you pass the string 'body', the jQuery selector engine has to interpret the string to figure out what element(s) it refers to.

In practice either will get the job done.

If you are interested, there is more information in the documentation for the jQuery function.

How to execute a Python script from the Django shell?

I'm late for the party but I hope that my response will help someone: You can do this in your Python script:

import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings

the rest of your stuff goes here ....

Rails and PostgreSQL: Role postgres does not exist

Could you have multiple local databases? Check your database.yml and make sure you are hitting the pg db that you want. Use rails console to confirm.

decompiling DEX into Java sourcecode

Once you downloaded your APK file , You need to do the following steps to get a editable java code/document.

  1. Convert your apk file to zip (while start your download don't go with "save" option , just go with "save as" and mention your extension as .zip) by doing like this you may avoid APKTOOL...
  2. Extract the zip file , there you can find somefilename.dex. so now we need to convert dex -> .class
  3. To do that, you need "dex2jar"(you can download it from http://code.google.com/p/dex2jar/ , after extracted, in command prompt you have to mention like, [D:\dex2jar-0.09>dex2jar somefilename.dex] (Keep in mind that your somefilename.dex must be inside the same folder where you have keep your dex2jar.)
  4. Download jad from http://www.viralpatel.net/blogs/download/jad/jad.zip and extract it. Once extracted you can see two files like "jad.exe" and "Readme.txt" (sometimes "jad.txt" may there instead of "jad.exe", so just rename its extension as.exe to run)
  5. Finally, in command prompt you have to mention like [D:\jad>jad -sjava yourfilename.class] it will parse your class file into editable java document.

phpMyAdmin mbstring error

Strangely, I noticed that the php.ini file that WAMP was using wasn't the one in the php directory, but rather was referencing a php.ini file in the bin directory... I copied my php.ini file to wamp\bin\apache\apache2.4.17\bin directory, restarted the wamp services and PHPMyadmin was off and running...

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

CSS - Syntax to select a class within an id

This will also work and you don't need the extra class:

#navigation li li {}

If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:

#navigation li li li {}

How to extract year and month from date in PostgreSQL without using to_char() function?

It is working for "greater than" functions not for less than.

For example:

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) > '2000' limit 10;

is working fine.

but for

select date_part('year',txndt)
from "table_name"
where date_part('year',txndt) < '2000' limit 10;

I am getting error.

How to remove all subviews of a view in Swift?

The code can be written simpler as following.

view.subviews.forEach { $0.removeFromSuperview() }

How to get screen dimensions as pixels in Android

Kotlin

fun getScreenHeight(activity: Activity): Int {
    val metrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.heightPixels
}

fun getScreenWidth(activity: Activity): Int {
    val metrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.widthPixels
}

Bulk Insertion in Laravel using eloquent ORM

You can just use Eloquent::insert().

For example:

$data = array(
    array('name'=>'Coder 1', 'rep'=>'4096'),
    array('name'=>'Coder 2', 'rep'=>'2048'),
    //...
);

Coder::insert($data);

SQL Case Expression Syntax?

Considering you tagged multiple products, I'd say the full correct syntax would be the one found in the ISO/ANSI SQL-92 standard:

<case expression> ::=
       <case abbreviation>
     | <case specification>

<case abbreviation> ::=
       NULLIF <left paren> <value expression> <comma>
              <value expression> <right paren>
     | COALESCE <left paren> <value expression>
                { <comma> <value expression> }... <right paren>

<case specification> ::=
       <simple case>
     | <searched case>

<simple case> ::=
     CASE <case operand>
          <simple when clause>...
        [ <else clause> ]
     END

<searched case> ::=
     CASE
       <searched when clause>...
     [ <else clause> ]
     END

<simple when clause> ::= WHEN <when operand> THEN <result>

<searched when clause> ::= WHEN <search condition> THEN <result>

<else clause> ::= ELSE <result>

<case operand> ::= <value expression>

<when operand> ::= <value expression>

<result> ::= <result expression> | NULL

<result expression> ::= <value expression>

Syntax Rules

1) NULLIF (V1, V2) is equivalent to the following <case specification>:

     CASE WHEN V1=V2 THEN NULL ELSE V1 END

2) COALESCE (V1, V2) is equivalent to the following <case specification>:

     CASE WHEN V1 IS NOT NULL THEN V1 ELSE V2 END

3) COALESCE (V1, V2, . . . ,n ), for n >= 3, is equivalent to the
   following <case specification>:

     CASE WHEN V1 IS NOT NULL THEN V1 ELSE COALESCE (V2, . . . ,n )
     END

4) If a <case specification> specifies a <simple case>, then let CO
   be the <case operand>:

   a) The data type of each <when operand> WO shall be comparable
      with the data type of the <case operand>.

   b) The <case specification> is equivalent to a <searched case>
      in which each <searched when clause> specifies a <search
      condition> of the form "CO=WO".

5) At least one <result> in a <case specification> shall specify a
   <result expression>.

6) If an <else clause> is not specified, then ELSE NULL is im-
   plicit.

7) The data type of a <case specification> is determined by ap-
   plying Subclause 9.3, "Set operation result data types", to the
   data types of all <result expression>s in the <case specifica-
   tion>.

Access Rules

   None.

General Rules

1) Case:

   a) If a <result> specifies NULL, then its value is the null
      value.

   b) If a <result> specifies a <value expression>, then its value
      is the value of that <value expression>.

2) Case:

   a) If the <search condition> of some <searched when clause> in
      a <case specification> is true, then the value of the <case
      specification> is the value of the <result> of the first
      (leftmost) <searched when clause> whose <search condition> is
      true, cast as the data type of the <case specification>.

   b) If no <search condition> in a <case specification> is true,
      then the value of the <case expression> is the value of the
      <result> of the explicit or implicit <else clause>, cast as
      the data type of the <case specification>.

How to iterate over associative arrays in Bash

declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )

echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"

echo -e " \n Total elements in arr are : ${arr[*]} \n"

echo -e " \n Total lenght of arr is : ${#arr[@]} \n"

for (( i=0; i<10; i++ ))
do      echo "The value in position $i for arr is [ ${arr[i]} ]"
done

for (( j=0; j<10; j++ ))
do      echo "The length in element $j is ${#arr[j]}"
done

for z in "${!arr[@]}"
do      echo "The key ID is $z"
done
~

Alter MySQL table to add comments on columns

Script for all fields on database:

SELECT 
table_name,
column_name,
CONCAT('ALTER TABLE `',
        TABLE_SCHEMA,
        '`.`',
        table_name,
        '` CHANGE `',
        column_name,
        '` `',
        column_name,
        '` ',
        column_type,
        ' ',
        IF(is_nullable = 'YES', '' , 'NOT NULL '),
        IF(column_default IS NOT NULL, concat('DEFAULT ', IF(column_default IN ('CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP()', 'NULL', 'b\'0\'', 'b\'1\''), column_default, CONCAT('\'',column_default,'\'') ), ' '), ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '' AND column_type = 'timestamp','NULL ', ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '','DEFAULT NULL ', ''),
        extra,
        ' COMMENT \'',
        column_comment,
        '\' ;') as script
FROM
    information_schema.columns
WHERE
    table_schema = 'my_database_name'
ORDER BY table_name , column_name
  1. Export all to a CSV
  2. Open it on your favorite csv editor

Note: You can improve to only one table if you prefer

The solution given by @Rufinus is great but if you have auto increments it will break it.

How do I negate a test with regular expressions in a bash script?

I like to simplify the code without using conditional operators in such cases:

TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP

How to make --no-ri --no-rdoc the default for gem install?

On Linux (and probably Mac):

echo 'gem: --no-document' >> ~/.gemrc

This one-liner used to be in comments here, but somehow disappeared.

What is Cache-Control: private?

The Expires entity-header field gives the date/time after which the response is considered stale.The Cache-control:maxage field gives the age value (in seconds) bigger than which response is consider stale.

Althought above header field give a mechanism to client to decide whether to send request to the server. In some condition, the client send a request to sever and the age value of response is bigger then the maxage value ,dose it means server needs to send the resource to client? Maybe the resource never changed.

In order to resolve this problem, HTTP1.1 gives last-modifided head. The server gives the last modified date of the response to client. When the client need this resource, it will send If-Modified-Since head field to server. If this date is before the modified date of the resouce, the server will sends the resource to client and gives 200 code.Otherwise,it will returns 304 code to client and this means client can use the resource it cached.

How to change UINavigationBar background color from the AppDelegate

The colour code is the issue here. Instead of using 195/255, use 0.7647 or 195.f/255.f The problem is converting the float is not working properly. Try using exact float value.

JavaScript object: access variable property by name as string

ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

Where your string reference to a given property ressembles property1.property2

Code and comments in JsFiddle.

JPQL SELECT between date statement

Try this query (replace t.eventsDate with e.eventsDate):

SELECT e FROM Events e WHERE e.eventsDate BETWEEN :startDate AND :endDate

How do I format a number with commas in T-SQL?

For SQL Server 2012+ implementations, you will have the ability to use the FORMAT to apply string formatting to non-string data types.

In the original question, the user had requested the ability to use commas as thousands separators. In a closed as duplicate question, the user had asked how they could apply currency formatting. The following query shows how to perform both tasks. It also demonstrates the application of culture to make this a more generic solution (addressing Tsiridis Dimitris's function to apply Greek special formatting)

-- FORMAT
-- http://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx
-- FORMAT does not do conversion, that's the domain of cast/convert/parse etc
-- Only accepts numeric and date/time data types for formatting. 
--
-- Formatting Types
-- http://msdn.microsoft.com/en-us/library/26etazsy.aspx

-- Standard numeric format strings
-- http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
SELECT
    -- c => currency
    -- n => numeric
    FORMAT(987654321, N'N', C.culture) AS some_number
,   FORMAT(987654321, N'c', C.culture) AS some_currency
,   C.culture
FROM
    (
        -- Language culture names
        -- http://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx
        VALUES
            ('en-US')
        ,   ('en-GB')
        ,   ('ja-JP')
        ,   ('Ro-RO')
        ,   ('el-GR')
    ) C (culture);

SQLFiddle for the above

How add "or" in switch statements?

By stacking each switch case, you achieve the OR condition.

switch(myvar)
{
    case 2:
    case 5:
    ...
    break;

    case 7:
    case 12:
    ...
    break;
    ...
}

How do I POST JSON data with cURL?

HTTPie is a recommended alternative to curl because you can do just

$ http POST http://example.com/some/endpoint name=value name1=value1

It speaks JSON by default and will handle both setting the necessary header for you as well encoding data as valid JSON. There is also:

Some-Header:value

for headers, and

name==value

for query string parameters. If you have a large chunk of data, you can also read it from a file have it be JSON encoded:

 [email protected]

How to get data from database in javascript based on the value passed to the function

Try the following:

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

You don't have access to javascript variable names in SQL, you must pass the values to the Database.

PHP - iterate on string characters

Iterate string:

for ($i = 0; $i < strlen($str); $i++){
    echo $str[$i];
}

VARCHAR to DECIMAL

Implemented using Custom Function. This will check whether the string value can be converted to Decimal safely

CREATE FUNCTION [dbo].[TryParseAsDecimal]
(
    @Value      NVARCHAR(4000)
    ,@Precision INT
    ,@Scale     INT
)

RETURNS BIT
AS
BEGIN

    IF(ISNUMERIC(@Value) =0) BEGIN
        RETURN CAST(0 AS BIT)
    END
    SELECT @Value = REPLACE(@Value,',','') --Removes the comma

    --This function validates only the first part eg '1234567.8901111111'
    --It validates only the values before the '.' ie '1234567.'
    DECLARE @Index          INT
    DECLARE @Part1Length    INT 
    DECLARE @Part1          VARCHAR(4000)   

    SELECT @Index = CHARINDEX('.', @Value, 0)
    IF (@Index>0) BEGIN
        --If decimal places, extract the left part only and cast it to avoid leading zeros (eg.'0000000001' => '1')
        SELECT @Part1 =LEFT(@Value, @Index-1);
        SELECT @Part1=SUBSTRING(@Part1, PATINDEX('%[^0]%', @Part1+'.'), LEN(@Part1));
        SELECT @Part1Length = LEN(@Part1);
    END
    ELSE BEGIN
        SELECT @Part1 =CAST(@Value AS DECIMAL);
        SELECT @Part1Length= LEN(@Part1)
    END 

    IF (@Part1Length > (@Precision-@Scale)) BEGIN
        RETURN CAST(0 AS BIT)
    END

    RETURN CAST(1 AS BIT)

END

PDO error message?

Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:

$field1 = 'foo';
$field2 = 'bar';

$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);

$insert_QUERY->execute();

$databaseErrors = $insert_QUERY->errorInfo();

if( !empty($databaseErrors) ){  
    $errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
    $errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...         

/* 
 $errorLogMsg will return something like: 
 error info:  
 Array(
  [0] => 42000
  [1] => 1064
  [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table bogus(field1, field2) VALUES                                                  ('bar', NULL)' at line 1
 )
*/
} else {
    # no SQL errors.
}

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

hope this may help you:

SELECT  CAST(LoginTime AS DATE)
         FROM    AuditTrail 

If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month

How to recognize swipe in all 4 directions

Easy. Just follow the code below and enjoy.

//SwipeGestureMethodUsing
func SwipeGestureMethodUsing ()
{
    //AddSwipeGesture
    [UISwipeGestureRecognizerDirection.right,
     UISwipeGestureRecognizerDirection.left,
     UISwipeGestureRecognizerDirection.up,
     UISwipeGestureRecognizerDirection.down].forEach({ direction in
        let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
        swipe.direction = direction
        window?.addGestureRecognizer(swipe)
     })
}

//respondToSwipeGesture
func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer
    {
        switch swipeGesture.direction
        {
        case UISwipeGestureRecognizerDirection.right:
            print("Swiped right")
        case UISwipeGestureRecognizerDirection.down:
            print("Swiped down")
        case UISwipeGestureRecognizerDirection.left:
            print("Swiped left")
        case UISwipeGestureRecognizerDirection.up:
            print("Swiped up")
        default:
            break
        }
    }
}

"%%" and "%/%" for the remainder and the quotient

Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
> 
> # Integer Division:
> 5%/%2
[1] 2
> 
> # Remainder:
> 5%%2
[1] 1

What is the Angular equivalent to an AngularJS $watch?

If you want to make it 2 way binding, you can use [(yourVar)], but you have to implement yourVarChange event and call it everytime your variable change.

Something like this to track the hero change

@Output() heroChange = new EventEmitter();

and then when your hero get changed, call this.heroChange.emit(this.hero);

the [(hero)] binding will do the rest for you

see example here:

http://plnkr.co/edit/efOGIJ0POh1XQeRZctSx?p=preview

jquery data selector

You can set a data-* attribute on an elm using attr(), and then select using that attribute:

var elm = $('a').attr('data-test',123); //assign 123 using attr()
elm = $("a[data-test=123]"); //select elm using attribute

and now for that elm, both attr() and data() will yield 123:

console.log(elm.attr('data-test')); //123
console.log(elm.data('test')); //123

However, if you modify the value to be 456 using attr(), data() will still be 123:

elm.attr('data-test',456); //modify to 456
elm = $("a[data-test=456]"); //reselect elm using new 456 attribute

console.log(elm.attr('data-test')); //456
console.log(elm.data('test')); //123

So as I understand it, seems like you probably should steer clear of intermingling attr() and data() commands in your code if you don't have to. Because attr() seems to correspond directly with the DOM whereas data() interacts with the 'memory', though its initial value can be from the DOM. But the key point is that the two are not necessarily in sync at all.

So just be careful.

At any rate, if you aren't changing the data-* attribute in the DOM or in the memory, then you won't have a problem. Soon as you start modifying values is when potential problems can arise.

Thanks to @Clarence Liu to @Ash's answer, as well as this post.

Draw text in OpenGL ES

Take a look at CBFG and the Android port of the loading/rendering code. You should be able to drop the code into your project and use it straight away.

  1. CBFG

  2. Android loader

I have problems with this implementation. It displays only one character, when I try do change size of the font's bitmap (I need special letters) whole draw fails :(

What is parsing in terms that a new programmer would understand?

I'd explain parsing as the process of turning some kind of data into another kind of data.

In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.

For example, turning

":Nick!User@Host PRIVMSG #channel :Hello!"

into (C)

struct irc_line {
    char *nick;
    char *user;
    char *host;
    char *command;
    char **arguments;
    char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }

Adding Table rows Dynamically in Android

public Boolean addArtist(String artistName){

        SQLiteDatabase db= getWritableDatabase();

        ContentValues data=new ContentValues();
        data.put(ArtistMaster.ArtistDetails.COLUMN_ARTIST_NAME,artistName);
        long id = db.insert(ArtistMaster.ArtistDetails.TABLE_NAME,null,data);

        if(id>0){
            return true;
        }else{
            return false;
        }
    }

How do I get the resource id of an image if I know its name?

With something like this:

String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

Export tables to an excel spreadsheet in same directory

You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.

To obtain the path of the Access database, use the CurrentProject.Path property.

To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd") method.

Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet method.

Example:

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This will output both Table1 and Table2 into the same Workbook.

HTH

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

How to check if a file is empty in Bash?

Many of the answers are correct but I feel like they could be more complete / simplistic etc. for example :

Example 1 : Basic if statement

# BASH4+ example on Linux :

typeset read_file="/tmp/some-file.txt"
if [ ! -s "${read_file}" ]  || [ ! -f "${read_file}" ] ;then
    echo "Error: file (${read_file}) not found.. "
    exit 7
fi

if $read_file is empty or not there stop the show with exit. More than once I have had misread the top answer here to mean the opposite.

Example 2 : As a function

# -- Check if file is missing /or empty --
# Globals: None
# Arguments: file name
# Returns: Bool
# --
is_file_empty_or_missing() {
    [[ ! -f "${1}" || ! -s "${1}" ]] && return 0 || return 1
}

How to Identify port number of SQL server

You can also use this query

USE MASTER GO xp_readerrorlog 0, 1, N'Server is listening on' GO

Source : sqlauthority blog

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

sql server convert date to string MM/DD/YYYY

As of SQL Server 2012+, you can use FORMAT(value, format [, culture ])

Where the format param takes any valid standard format string or custom formatting string

Example:

SELECT FORMAT(GETDATE(), 'MM/dd/yyyy')

Further Reading:

How do I validate a date string format in python?

From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:

dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059

And here's the code I used (Python 3.6)


from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit


def is_date_parsing(date_str):
    try:
        return bool(date_parser.parse(date_str))
    except ValueError:
        return False


def is_date_matching(date_str):
    try:
        return bool(datetime.strptime(date_str, '%Y-%m-%d'))
    except ValueError:
        return False



if __name__ == '__main__':
    print("dateutil.parser (valid date):", end=' ')
    print(timeit("is_date_parsing('2021-01-26')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("dateutil.parser (invalid date):", end=' ')
    print(timeit("is_date_parsing('meh')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("datetime.strptime (valid date):", end=' ')
    print(timeit("is_date_matching('2021-01-26')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

    print("datetime.strptime (invalid date):", end=' ')
    print(timeit("is_date_matching('meh')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

makedirs creates multiple levels of directories, if needed.

Printing with sed or awk a line following a matching pattern

Never use the word "pattern" as is it highly ambiguous. Always use "string" or "regexp" (or in shell "globbing pattern"), whichever it is you really mean.

The specific answer you want is:

awk 'f{print;f=0} /regexp/{f=1}' file

or specializing the more general solution of the Nth record after a regexp (idiom "c" below):

awk 'c&&!--c; /regexp/{c=1}' file

The following idioms describe how to select a range of records given a specific regexp to match:

a) Print all records from some regexp:

awk '/regexp/{f=1}f' file

b) Print all records after some regexp:

awk 'f;/regexp/{f=1}' file

c) Print the Nth record after some regexp:

awk 'c&&!--c;/regexp/{c=N}' file

d) Print every record except the Nth record after some regexp:

awk 'c&&!--c{next}/regexp/{c=N}1' file

e) Print the N records after some regexp:

awk 'c&&c--;/regexp/{c=N}' file

f) Print every record except the N records after some regexp:

awk 'c&&c--{next}/regexp/{c=N}1' file

g) Print the N records from some regexp:

awk '/regexp/{c=N}c&&c--' file

I changed the variable name from "f" for "found" to "c" for "count" where appropriate as that's more expressive of what the variable actually IS.

AngularJs .$setPristine to reset form

Just for those who want to get $setPristine without having to upgrade to v1.1.x, here is the function I used to simulate the $setPristine function. I was reluctant to use the v1.1.5 because one of the AngularUI components I used is no compatible.

var setPristine = function(form) {
    if (form.$setPristine) {//only supported from v1.1.x
        form.$setPristine();
    } else {
        /*
         *Underscore looping form properties, you can use for loop too like:
         *for(var i in form){ 
         *  var input = form[i]; ...
         */
        _.each(form, function (input) {
            if (input.$dirty) {
                input.$dirty = false;
            }
        });
    }
};

Note that it ONLY makes $dirty fields clean and help changing the 'show error' condition like $scope.myForm.myField.$dirty && $scope.myForm.myField.$invalid.

Other parts of the form object (like the css classes) still need to consider, but this solve my problem: hide error messages.

How do I disable log messages from the Requests library?

simple: just add requests.packages.urllib3.disable_warnings() after import requests

Change table header color using bootstrap

Here is another way to separate your table header and table body:

thead th {
    background-color: #006DCC;
    color: white;
}

tbody td {
    background-color: #EEEEEE;
}

Have a look at this example for separation of head and body of table. JsFiddleLink

How do I properly escape quotes inside HTML attributes?

If you are using Javascript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.

See here: https://lodash.com/docs/#escape

What is the meaning of curly braces?

In languages like C curly braces ({}) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

How can I make a div not larger than its contents?

<table cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td>
            <div id="content_lalala">
                this content inside the div being inside a table, needs no inline properties and the table is the one expanding to the content of this div =)
            </div>
        </td>
    </tr>
</table>

I know people don't like tables sometimes, but I gotta tell you, I tried the css inline hacks, and they kinda worked in some divs but in others didn't, so, it was really just easier to enclose the expanding div in a table...and...it can have or not the inline property and still the table is the one that's gonna hold the total width of the content. =)

Reactjs - setting inline styles correctly

Correct and more clear way is :

<div style={{"font-size" : "10px", "height" : "100px", "width" : "100%"}}> My inline Style </div>

It is made more simple by following approach :

// JS
const styleObject = {
      "font-size" : "10px",
      "height" : "100px",
      "width" : "100%"
}

// HTML    
<div style={styleObject}> My inline Style </div>

Inline style attribute expects object. Hence its written in {}, and it becomes double {{}} as one is for default react standards.

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

How to display multiple notifications in android

Below is the code for pass unique notification id:

//"CommonUtilities.getValudeFromOreference" is the method created by me to get value from savedPreferences.
String notificationId = CommonUtilities.getValueFromPreference(context, Global.NOTIFICATION_ID, "0");
int notificationIdinInt = Integer.parseInt(notificationId);

notificationManager.notify(notificationIdinInt, notification);

// will increment notification id for uniqueness
notificationIdinInt = notificationIdinInt + 1;
CommonUtilities.saveValueToPreference(context, Global.NOTIFICATION_ID, notificationIdinInt + "");
//Above "CommonUtilities.saveValueToPreference" is the method created by me to save new value in savePreferences.

Reset notificationId in savedPreferences at specific range like I have did it at 1000. So it will not create any issues in future. Let me know if you need more detail information or any query. :)

How to resolve Nodejs: Error: ENOENT: no such file or directory

In my case the issue was caused by using a file path starting at the directory where the script was executing rather than at the root of the project.

My directory stucture was like this: projectfolder/ +-- package.json +-- scriptFolder/ ¦ +-- myScript.js

And I was calling fs.createReadStream('users.csv') instead of the correct fs.createReadStream('scriptFolder/users.csv')

kubectl apply vs kubectl create?

+----------------------------------------------------------+
¦ command ¦ object does not exist ¦ object already exists  ¦
+---------+-----------------------+------------------------¦
¦ create  ¦ create new object     ¦          ERROR         ¦ 
¦         ¦                       ¦                        ¦
¦ apply   ¦ create new object     ¦ configure object       ¦
¦         ¦ (needs complete spec) ¦ (accepts partial spec) ¦
¦         ¦                       ¦                        ¦
¦ replace ¦         ERROR         ¦ delete object          ¦
¦         ¦                       ¦ create new object      ¦
+----------------------------------------------------------+

remote: repository not found fatal: not found

In my case, it was different! But I think sharing my experience might help someone!

In MAC, the 'keychain access' has saved my previous 'Github' password. I was trying with a new GitHub repository, and it never worked. When I removed the old GitHub password from 'keychain access' from my MAC machine it worked! I hope it helps someone.

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};

Launch a shell command with in a python script, wait for the termination and return to the script

You can use subprocess.Popen. There's a few ways to do it:

import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
    print line
p.wait()
print p.returncode

Or, if you don't care what the external program actually does:

cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()

Setting Windows PowerShell environment variables

I tried to optimise SBF's and Michael's code a bit to make it more compact.

I am relying on PowerShell's type coercion where it automatically converts strings to enum values, so I didn't define the lookup dictionary.

I also pulled out the block that adds the new path to the list based on a condition, so that work is done once and stored in a variable for re-use.

It is then applied permanently or just to the Session depending on the $PathContainer parameter.

We can put the block of code in a function or a ps1 file that we call directly from the command prompt. I went with DevEnvAddPath.ps1.

param(
    [Parameter(Position=0,Mandatory=$true)][String]$PathChange,

    [ValidateSet('Machine', 'User', 'Session')]
    [Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session',
    [Parameter(Position=2,Mandatory=$false)][Boolean]$PathPrepend=$false
)

[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';

if ($PathPersisted -notcontains $PathChange) {
    $PathPersisted = $(switch ($PathPrepend) { $true{,$PathChange + $PathPersisted;} default{$PathPersisted + $PathChange;} }) | Where-Object { $_ };

    $ConstructedEnvPath = $PathPersisted -join ";";
}

if ($PathContainer -ne 'Session') 
{
    # Save permanently to Machine, User
    [Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}

# Update the current session
${env:Path} = $ConstructedEnvPath;

I do something similar for a DevEnvRemovePath.ps1.

param(
    [Parameter(Position=0,Mandatory=$true)][String]$PathChange,

    [ValidateSet('Machine', 'User', 'Session')]
    [Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session'
)

[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';

if ($PathPersisted -contains $PathChange) {
    $PathPersisted = $PathPersisted | Where-Object { $_ -ne $PathChange };

    $ConstructedEnvPath = $PathPersisted -join ";";
}

if ($PathContainer -ne 'Session') 
{
    # Save permanently to Machine, User
    [Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}

# Update the current session
${env:Path} = $ConstructedEnvPath;

So far, they seem to work.

C++: Where to initialize variables in constructor

In short, always prefer initialization lists when possible. 2 reasons:

  • If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.

  • Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.

Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.

Print directly from browser without print popup window

AttendStar created a free add-on that suppresses the print dialog box and removes all headers and footers for most versions of Firefox.

https://addons.mozilla.org/en-US/firefox/addon/attendprint/

With that feature on you can use $('img').jqprint(); and jqprint for jquery will only print that image automatically called from your web application.

Disabling Strict Standards in PHP 5.4

.htaccess php_value is working only if you use PHP Server API as module of Web server Apache. Use IfModule syntax:

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
    php_value error_reporting 30711
</IfModule>

If you use PHP Server API CGI/FastCGI use

ini_set('error_reporting', 30711);

or

error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);

in your PHP code, or PHP configuration files .user.ini | php.ini modification:

error_reporting = E_ALL & ~E_STRICT & ~E_NOTICE

on your virtual host, server level.

Validate that a string is a positive integer

The modern solution that works in node and across over 90% of all browsers (except IE and Opera Mini) is to use Number.isInteger followed by a simple positive check.

Number.isInteger(x) && x > 0

This was finalized in ECMAScript 2015.

function isPositiveInteger(x) {
    return Number.isInteger(x) && x > 0
}

The Polyfil is:

Number.isInteger = Number.isInteger || function(value) {
  return typeof value === 'number' && 
    isFinite(value) && 
    Math.floor(value) === value;
};

If you need to support input that might be in string or number form then you can use this function I wrote a large test suite against after all the existing answers (2/1/2018) failed on some form of input.

function isPositiveInteger(v) {
  var i;
  return v && (i = parseInt(v)) && i > 0 && (i === v || ''+i === v);
}

Pipe to/from the clipboard in Bash script

Copy and paste to clipboard in Windows (Cygwin):

See:

$ clip.exe -?

CLIP
Description:
    Redirects output of command line tools to the Windows clipboard.
    This text output can then be pasted into other programs.
Parameter List:
/?                  Displays this help message.
Examples:
DIR | CLIP          Places a copy of the current directory
                        listing into the Windows clipboard.
CLIP < README.TXT   Places a copy of the text from readme.txt
                        on to the Windows clipboard.

Also getclip (it can be used instead of Shift + Ins!) and putclip (echo oaeuoa | putclip.exe to put it into clip) exist.

How Do I Take a Screen Shot of a UIView?

iOS 7 has a new method that allows you to draw a view hierarchy into the current graphics context. This can be used to get an UIImage very fast.

I implemented a category method on UIView to get the view as an UIImage:

- (UIImage *)pb_takeSnapshot {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);

    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];

    // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

It is considerably faster then the existing renderInContext: method.

Reference: https://developer.apple.com/library/content/qa/qa1817/_index.html

UPDATE FOR SWIFT: An extension that does the same:

extension UIView {

    func pb_takeSnapshot() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

        // old style: layer.renderInContext(UIGraphicsGetCurrentContext())

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

UPDATE FOR SWIFT 3

    UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)

    drawHierarchy(in: self.bounds, afterScreenUpdates: true)

    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image

How do I retrieve my MySQL username and password?

Login MySql from windows cmd using existing user:

mysql -u username -p
Enter password:****

Then run the following command:

mysql> SELECT * FROM mysql.user;

After that copy encrypted md5 password for corresponding user and there are several online password decrypted application available in web. Using this decrypt password and use this for login in next time. or update user password using flowing command:

mysql> UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';

Then login using the new password and user.

How to create json by JavaScript for loop?

Your question is pretty hard to decode, but I'll try taking a stab at it.

You say:

I want to create a json object having two fields uniqueIDofSelect and optionValue in javascript.

And then you say:

I need output like

[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Well, this example output doesn't have the field named uniqueIDofSelect, it only has optionValue.

Anyway, you are asking for array of objects...

Then in the comment to michaels answer you say:

It creates json object array. but I need only one json object.

So you don't want an array of objects?

What do you want then?

Please make up your mind.

How to add url parameters to Django template url tag?

Simply add Templates URL:

<a href="{% url 'service_data' d.id %}">
 ...XYZ
</a>

Used in django 2.0

Get JavaScript object from array of objects by value of property

You can use it with the arrow function as well like as below :

var demoArray = [
   {name: 'apples', quantity: 2},
   {name: 'bananas', quantity: 0},
   {name: 'cherries', quantity: 5}
];

var result = demoArray.filter( obj => obj.name === 'apples')[0];
console.log(result);
// {name: 'apples', quantity: 2}

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

height style property doesn't work in div elements

use the min-height property. min-height:20px;

Printing with "\t" (tabs) does not result in aligned columns

In continuation of the comments by Péter and duncan, I normally use a quick padding method, something like -

public String rpad(String inStr, int finalLength)
{
    return (inStr + "                          " // typically a sufficient length spaces string.
        ).substring(0, finalLength);
}

similarly you can have a lpad() as well

How to delete a stash created with git stash create?

The Document is here (in Chinese)please click.

you can use

git stash list

git stash drop stash@{0}

enter image description here

How to get package name from anywhere?

Create a java module to be initially run when starting your app. This module would be extending the android Application class and would initialize any global app variables and also contain app-wide utility routines -

public class MyApplicationName extends Application {

    private final String PACKAGE_NAME = "com.mysite.myAppPackageName";

    public String getPackageName() { return PACKAGE_NAME; }
}

Of course, this could include logic to obtain the package name from the android system; however, the above is smaller, faster and cleaner code than obtaining it from android.

Be sure to place an entry in your AndroidManifest.xml file to tell android to run your application module before running any activities -

<application 
    android:name=".MyApplicationName" 
    ...
>

Then, to obtain the package name from any other module, enter

MyApp myApp = (MyApp) getApplicationContext();
String myPackage = myApp.getPackageName();

Using an application module also gives you a context for modules that need but don't have a context.

Center a button in a Linear layout

You can also set the width of the LinearLayout to wrap_content and use android:layout_centerInParent, android:layout_centerVertical="true":

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
>

<ImageButton android:id="@+id/btnFindMe" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"       
    android:background="@drawable/findme"/>

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How to prevent long words from breaking my div?

Re the regex in this comment, it's good, but it adds the shy hyphen only between groups of 5 non-whitespace-or-hyphen chars. That allows the last group be much longer than intended, since there's no matching group after it.

For instance, this:

'abcde12345678901234'.replace(/([^\s-]{5})([^\s-]{5})/g, '$1&shy;$2')

...results in this:

abcde&shy;12345678901234

Here's a version using positive lookahead to avoid that problem:

.replace(/([^\s-]{5})(?=[^\s-])/g, '$1&shy;')

...with this result:

abcde&shy;12345&shy;67890&shy;1234

Url.Action parameters?

you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :

var qs = HttpUtility.ParseQueryString(""); 
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")

<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
    <span>People</span>
</a>

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

It's as simple as that:

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1
}

function isWindows() {
  return navigator.platform.indexOf('Win') > -1
}

You can do funny things then like:

var isMac = isMacintosh();
var isPC = !isMacintosh();

How do I shut down a python simpleHTTPserver?

Hitting ctrl + c once(wait for traceback), then hitting ctrl+c again did the trick for me :)

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

file_get_contents() Breaks Up UTF-8 Characters

I think you simply have a double conversion of the character type there :D

It may be, because you opened an html document within a html document. So you have something that looks like this in the end

<!DOCTYPE html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<!DOCTYPE html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>.......

The use of mb_detect_encoding therefore may lead you to other issues.

Why is the use of alloca() not considered good practice?

If you accidentally write beyond the block allocated with alloca (due to a buffer overflow for example), then you will overwrite the return address of your function, because that one is located "above" on the stack, i.e. after your allocated block.

_alloca block on the stack

The consequence of this is two-fold:

  1. The program will crash spectacularly and it will be impossible to tell why or where it crashed (stack will most likely unwind to a random address due to the overwritten frame pointer).

  2. It makes buffer overflow many times more dangerous, since a malicious user can craft a special payload which would be put on the stack and can therefore end up executed.

In contrast, if you write beyond a block on the heap you "just" get heap corruption. The program will probably terminate unexpectedly but will unwind the stack properly, thereby reducing the chance of malicious code execution.

How do I connect to an MDF database file?

Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

How to make a jquery function call after "X" seconds

try This

setTimeout( function(){ 
    // call after 5 second 
  }  , 5000 );

How to return only the Date from a SQL Server DateTime datatype

On SQL Server 2000

CAST(
(
    STR( YEAR( GETDATE() ) ) + '/' +
    STR( MONTH( GETDATE() ) ) + '/' +
    STR( DAY( GETDATE() ) )
)
AS DATETIME)

JQuery $.ajax() post - data in a java servlet

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

What is the difference between class and instance methods?

I think the best way to understand this is to look at alloc and init. It was this explanation that allowed me to understand the differences.

Class Method

A class method is applied to the class as a whole. If you check the alloc method, that's a class method denoted by the + before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.

Instance Method

You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. init for example (denoted with a - before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc.

Example

NSString *myString = [NSString alloc];

You are calling the class method alloc in order to generate an instance of that class. Notice how the receiver of the message is a class.

[myString initWithFormat:@"Hope this answer helps someone"];

You are modifying the instance of NSString called myString by setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString).

Media Queries - In between two widths

You need to switch your values:

/* No greater than 900px, no less than 400px */
@media (max-width:900px) and (min-width:400px) {
    .foo {
        display:none;
    }
}?

Demo: http://jsfiddle.net/xf6gA/ (using background color, so it's easier to confirm)

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

What is the apply function in Scala?

Mathematicians have their own little funny ways, so instead of saying "then we call function f passing it x as a parameter" as we programmers would say, they talk about "applying function f to its argument x".

In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia

apply serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int parameter and returns an Int will have OO type of Function1[Int,Int].

 // define a function in scala
 (x:Int) => x + 1

 // assign an object representing the function to a variable
 val f = (x:Int) => x + 1

Since everything is an object in Scala f can now be treated as a reference to Function1[Int,Int] object. For example, we can call toString method inherited from Any, that would have been impossible for a pure function, because functions don't have methods:

  f.toString

Or we could define another Function1[Int,Int] object by calling compose method on f and chaining two different functions together:

 val f2 = f.compose((x:Int) => x - 1)

Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply method on the Function1[Int,Int] object:

 f2.apply(2)

Writing f.apply(args) every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args). That's where Scala compiler steps in and whenever we have a reference f to a function object and write f (args) to apply arguments to the represented function the compiler silently expands f (args) to the object method call f.apply (args).

Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply method. Such objects can be used in the function notation:

// we will be able to use this object as a function, as well as an object
object Foo {
  var y = 5
  def apply (x: Int) = x + y
}


Foo (1) // using Foo object in function notation 

There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply object to a set of arguments to create a new instance of an associated class:

List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation

// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3) 

So apply method is just a handy way of closing the gap between functions and objects in Scala.

Is the sizeof(some pointer) always equal to four?

No, the size of a pointer may vary depending on the architecture. There are numerous exceptions.

how to end ng serve or firebase serve

With Windows 10 / Powershell ctrl + c did not work; Powershell tried to gracefully stop the app.

Used normal cmd and had no issues stopping the ng serve with ctrl + c.

JavaScript single line 'if' statement - best syntax, this alternative?

can use this,

lemons ? alert("please give me a lemonade") : alert("then give me a beer");

explanation: if lemons is true then alert("please give me a lemonade"), if not, alert("then give me a beer")

Difference between modes a, a+, w, w+, and r+ in built-in open function?

I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.