Programs & Examples On #Qbasic

QBasic is a general-purpose interpreted programming language derived from QuickBasic 4.5. QBasic replaced GWBasic starting from MSDOS 5. It became popular, because it had a quite advanced IDE with a debugger and was delivered free with MSDOS, Windows 95 and 98. The well-known game 'Nibbles' was written in QBasic. QBasic was written by Paul Allen (Microsoft) in 1991. Also see [tag:quickbasic]

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Please try one of these solutions :

  1. Sometimes, if you add new object to data list in a thread (or doInBackground method), this error will occur. The solution is : create a temporary list and do adding data to this list in thread(or doInBackground), then do copying all data from temporary list to the list of adapter in UI thread (or onPostExcute)

  2. Make sure all UI updates are called in UI thread.

Can an AJAX response set a cookie?

For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).

How to display errors on laravel 4?

Just go to your app/storage/logs there logs of error available. Go to filename of today's date time and you will find latest error in your application.

OR

Open app/config/app.php and change setting

'debug' => false,

To

'debug' => true, 

OR

Go to .env file to your application and change the configuratuion

APP_LOG_LEVEL=debug

What's the difference between Invoke() and BeginInvoke()

Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.

Delegate.Invoke() synchronously calls the delegate in the same thread.

MSDN Article

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

How would I find the second largest salary from the employee table?

    select max(Salary) from Employee 
where Salary
 not in (Select Max(Salary) from Employee)

how to get text from textview

You have to do the following:

a=a.replace("\n"," ");
a=a.trim();
String b[]=a.split("+");
int k=Integer.ValueOf(b[0]);
int l=Integer.ValueOf(b[1]);
int sum=k+l;

How do I remove a key from a JavaScript object?

If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit

var thisIsObject= {
    'Cow' : 'Moo',
    'Cat' : 'Meow',
    'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object

=> {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result

If you want to modify the current object, assign the returning object to the current object.

thisIsObject = _.omit(thisIsObject,'Cow');

With pure JavaScript, use:

delete thisIsObject['Cow'];

Another option with pure JavaScript.

thisIsObject.cow = undefined;

thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));

How can I declare enums using java

public enum NewEnum {
   ONE("test"),
   TWO("test");

   private String s;

   private NewEnum(String s) {
      this.s = s);
   }

    public String getS() {
        return this.s;
    }
}

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

XML Schema minOccurs / maxOccurs default values

The default values for minOccurs and maxOccurs are 1. Thus:

<xsd:element minOccurs="1" name="asdf"/>

cardinality is [1-1] Note: if you specify only minOccurs attribute, it can't be greater than 1, because the default value for maxOccurs is 1.

<xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>

invalid

<xsd:element maxOccurs="2" name="asdf"/>

cardinality is [1-2] Note: if you specify only maxOccurs attribute, it can't be smaller than 1, because the default value for minOccurs is 1.

<xsd:element minOccurs="0" maxOccurs="0"/>

is a valid combination which makes the element prohibited.

For more info see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints

NTFS performance and large volumes of files and directories

When you create a folder with N entries, you create a list of N items at file-system level. This list is a system-wide shared data structure. If you then start modifying this list continuously by adding/removing entries, I expect at least some lock contention over shared data. This contention - theoretically - can negatively affect performance.

For read-only scenarios I can't imagine any reason for performance degradation of directories with large number of entries.

Hibernate Error executing DDL via JDBC Statement

in your CFG file please change the hibernate dialect

<!-- SQL dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

How to recover corrupted Eclipse workspace?

I haven't been able to avoid rebuilding workspace occasionally (one or twice over several years of using eclipse). Delete the .metedata and rebuild.

git reset --hard HEAD leaves untracked files behind

User interactive approach:

git clean -i -fd

Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y

-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)

Note: Add -n or --dry-run to just check what it will do.

Simplest way to form a union of two lists

Using LINQ's Union

Enumerable.Union(ListA,ListB);

or

ListA.Union(ListB);

What are the specific differences between .msi and setup.exe file?

An MSI is a Windows Installer database. Windows Installer (a service installed with Windows) uses this to install software on your system (i.e. copy files, set registry values, etc...).

A setup.exe may either be a bootstrapper or a non-msi installer. A non-msi installer will extract the installation resources from itself and manage their installation directly. A bootstrapper will contain an MSI instead of individual files. In this case, the setup.exe will call Windows Installer to install the MSI.

Some reasons you might want to use a setup.exe:

  • Windows Installer only allows one MSI to be installing at a time. This means that it is difficult to have an MSI install other MSIs (e.g. dependencies like the .NET framework or C++ runtime). Since a setup.exe is not an MSI, it can be used to install several MSIs in sequence.
  • You might want more precise control over how the installation is managed. An MSI has very specific rules about how it manages the installations, including installing, upgrading, and uninstalling. A setup.exe gives complete control over the software configuration process. This should only be done if you really need the extra control since it is a lot of work, and it can be tricky to get it right.

Insert Data Into Temp Table with Query

Fastest way to do this is using "SELECT INTO" command e.g.

SELECT * INTO #TempTableName
FROM....

This will create a new table, you don't have to create it in advance.

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

This worked for me :

EDITOR="/usr/bin/vim"
export EDITOR

Add this to ~/.bash_profile or ~/.bashrc to enable this for current user.

How to remove space from string?

Since you're using bash, the fastest way would be:

shopt -s extglob # Allow extended globbing
var=" lakdjsf   lkadsjf "
echo "${var//+([[:space:]])/}"

It's fastest because it uses built-in functions instead of firing up extra processes.

However, if you want to do it in a POSIX-compliant way, use sed:

var=" lakdjsf   lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'

Export to CSV via PHP

I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

_tkinter.TclError: no display name and no $DISPLAY environment variable

You can solve it by adding these two lines in the VERY beginning of your .py script.

import matplotlib
matplotlib.use('Agg')

PS: The error will still exists if these two lines are not added in the very beginning of the source code.

How to parseInt in Angular.js

Option 1 (via controller):

angular.controller('numCtrl', function($scope, $window) {
   $scope.num = parseInt(num , 10);
}

Option 2 (via custom filter):

app.filter('num', function() {
    return function(input) {
       return parseInt(input, 10);
    }
});

{{(num1 | num) + (num2 | num)}}

Option 3 (via expression):

Declare this first in your controller:

$scope.parseInt = parseInt;

Then:

{{parseInt(num1)+parseInt(num2)}}

Option 4 (from raina77ow)

{{(num1-0) + (num2-0)}}

How to define an enumerated type (enum) in C?

When you say

enum {RANDOM, IMMEDIATE, SEARCH} strategy;

you create a single instance variable, called 'strategy' of a nameless enum. This is not a very useful thing to do - you need a typedef:

typedef enum {RANDOM, IMMEDIATE, SEARCH} StrategyType; 
StrategyType strategy = IMMEDIATE;

Is it correct to use alt tag for an anchor link?

Such things are best answered by looking at the official specification:

  1. go to the specification: https://www.w3.org/TR/html5/

  2. search for "a element": https://www.w3.org/TR/html5/text-level-semantics.html#the-a-element

  3. check "Content attributes", which lists all allowed attributes for the a element:

    • Global attributes
    • href
    • target
    • download
    • rel
    • hreflang
    • type
  4. check the linked "Global attributes": https://www.w3.org/TR/html5/dom.html#global-attributes

As you will see, the alt attribute is not allowed on the a element.
Also you’d notice that the src attribute isn’t allowed either.

By validating your HTML, errors like these are reported to you.


Note that the above is for HTML5, which is W3C’s HTML standard from 2014. In 2016, HTML 5.1 became the next HTML standard. Finding the allowed attributes works in the same way. You’ll see that the a element can have another attribute in HTML 5.1: rev.

You can find all HTML specifications (including the latest standard) on W3C’s HTML Current Status.

How can I build multiple submit buttons django form?

one url to the same view! like so!

urls.py

url(r'^$', views.landing.as_view(), name = 'landing'),

views.py

class landing(View):
        template_name = '/home.html'
        form_class1 = forms.pynamehere1
        form_class2 = forms.pynamehere2
            def get(self, request):
                form1 = self.form_class1(None)
                form2 = self.form_class2(None)
                return render(request, self.template_name, { 'register':form1, 'login':form2,})

             def post(self, request):
                 if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
                        ## do what ever you want to do for first function ####
                 if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
                         ## do what ever you want to do for second function ####
                        ## return def post###  
                 return render(request, self.template_name, {'form':form,})
/home.html
    <!-- #### form 1 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ register.as_p }}
    <button type="submit" name="htmlsubmitbutton1">Login</button>
    </form>
    <!--#### form 2 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ login.as_p }}
    <button type="submit" name="htmlsubmitbutton2">Login</button>
    </form>

Extending an Object in Javascript

Function.prototype.extends=function(ParentClass) {
    this.prototype = new ParentClass();
    this.prototype.constructor = this;
}

Then:

function Person() {
    this.name = "anonym"
    this.skills = ["abc"];
}
Person.prototype.profile = function() {
    return this.skills.length // 1
};

function Student() {} //well extends fom Person Class
Student.extends(Person)

var s1 = new Student();
s1.skills.push("")
s1.profile() // 2

Update 01/2017:

Please, Ignore my answer of 2015 since Javascript is now supports extends keyword since ES6 (Ecmasctipt6 )

- ES6 :

class Person {
   constructor() {
     this.name = "anonym"
     this.skills = ["abc"];
   }

   profile() {
    return this.skills.length // 1
   }

}

Person.MAX_SKILLS = 10;
class Student extends Person {


} //well extends from Person Class

//-----------------
var s1 = new Student();
s1.skills.push("")
s1.profile() // 2

- ES7 :

class Person {
    static MAX_SKILLS = 10;
    name = "anonym"
    skills = ["abc"];

    profile() {
      return this.skills.length // 1
    }

}
class Student extends Person {


} //well extends from Person Class

//-----------------
var s1 = new Student();
s1.skills.push("")
s1.profile() // 2

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

No, CASE is a function, and can only return a single value. I think you are going to have to duplicate your CASE logic.

The other option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

What is "android.R.layout.simple_list_item_1"?

as answered above by: kcoppock and Joril

go here : https://github.com/android/platform_frameworks_base/tree/master/core/res/res/layout

just right click the layout file you want, then select 'Save As', save somewhere, then copy it in 'layout' folder in your android project(eclipse)...

you can see how the layout looks like :)

way to go...

What is the most efficient string concatenation method in python?

One Year later, let's test mkoistinen's answer with python 3.4.3:

  • plus 0.963564149000 (95.83% as fast)
  • join 0.923408469000 (100.00% as fast)
  • form 1.501130934000 (61.51% as fast)
  • intp 1.019677452000 (90.56% as fast)

Nothing changed. Join is still the fastest method. With intp being arguably the best choice in terms of readability you might want to use intp nevertheless.

Set UIButton title UILabel font size programmatically

To support the Accessibility feature in UIButton

extension UILabel
{
   func scaledFont(for font: UIFont) -> UIFont {
        if #available(iOS 11.0, *) {
            return UIFontMetrics.default.scaledFont(for: font)
        } else {
            return font.withSize(scaler * font.pointSize)
        }
    }
    func customFontScaleFactor(font : UIFont) {
        translatesAutoresizingMaskIntoConstraints = false

         self.adjustsFontForContentSizeCategory = true
         self.font = FontMetrics.scaledFont(for: font)
    }
}

You can can button font now.

UIButton().titleLabel?.customFontScaleFactor(font: UIFont.systemFont(ofSize: 12))

PHP cURL error code 60

php --ini

This will tell you exactly which php.ini file is being loaded, so you know which one to modify. I wasted a lot of time changing the wrong php.ini file because I had WAMP and XAMPP installed.

Also, don't forget to restart the WAMP server (or whatever you use) after changing php.ini.

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

Eliminating duplicate values based on only one column of the table

I solve such queries using this pattern:

SELECT *
FROM t
WHERE t.field=(
  SELECT MAX(t.field) 
  FROM t AS t0 
  WHERE t.group_column1=t0.group_column1
    AND t.group_column2=t0.group_column2 ...)

That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:

WITH site_history AS (
  SELECT sites.siteName, sites.siteIP, history.date
  FROM sites
  JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
  SELECT MAX(date) 
  FROM site_history h0 
  WHERE h.siteName=h0.siteName)
ORDER BY siteName

It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date field should be unique for each siteName, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history table has an unique index for (site, date), this query is also very fast, index range scan on the history table scanning just the first item can be used.

Calculate AUC in R?

I found some of the solutions here to be slow and/or confusing (and some of them don't handle ties correctly) so I wrote my own data.table based function auc_roc() in my R package mltools.

library(data.table)
library(mltools)

preds <- c(.1, .3, .3, .9)
actuals <- c(0, 0, 1, 1)

auc_roc(preds, actuals)  # 0.875

auc_roc(preds, actuals, returnDT=TRUE)
   Pred CountFalse CountTrue CumulativeFPR CumulativeTPR AdditionalArea CumulativeArea
1:  0.9          0         1           0.0           0.5          0.000          0.000
2:  0.3          1         1           0.5           1.0          0.375          0.375
3:  0.1          1         0           1.0           1.0          0.500          0.875

How do I find which process is leaking memory?

If you can't do it deductively, consider the Signal Flare debugging pattern: Increase the amount of memory allocated by one process by a factor of ten. Then run your program.

If the amount of the memory leaked is the same, that process was not the source of the leak; restore the process and make the same modification to the next process.

When you hit the process that is responsible, you'll see the size of your memory leak jump (the "signal flare"). You can narrow it down still further by selectively increasing the allocation size of separate statements within this process.

Simplest way to profile a PHP script

You want xdebug I think. Install it on the server, turn it on, pump the output through kcachegrind (for linux) or wincachegrind (for windows) and it'll show you a few pretty charts that detail the exact timings, counts and memory usage (but you'll need another extension for that).

It rocks, seriously :D

MySQL: Error dropping database (errno 13; errno 17; errno 39)

In my case it was due to 'lower_case_table_names' parameter.

The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.

This is fixed by reverting back the lower case parameter changes to the previous state.

Allowed memory size of 536870912 bytes exhausted in Laravel

You can also get this error if you fail to include .htaccess or have a problem in it. The file should be something like this

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

Get unique values from arraylist in java

ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique

Correct way to detach from a container without stopping it

Update: As mentioned in below answers Ctrl+p, Ctrl+q will now turn interactive mode into daemon mode.


Well Ctrl+C (or Ctrl+\) should detach you from the container but it will kill the container because your main process is a bash.

A little lesson about docker. The container is not a real full functional OS. When you run a container the process you launch take the PID 1 and assume init power. So when that process is terminated the daemon stop the container until a new process is launched (via docker start) (More explanation on the matter http://phusion.github.io/baseimage-docker/#intro)

If you want a container that run in detached mode all the time, i suggest you use

docker run -d foo

With an ssh server on the container. (easiest way is to follow the dockerizing openssh tutorial https://docs.docker.com/engine/examples/running_ssh_service/)

Or you can just relaunch your container via

docker start foo

(it will be detached by default)

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

Changing API level Android Studio

Gradle Scripts ->
build.gradle (Module: app) ->
minSdkVersion (Your min sdk version)

What is the pythonic way to detect the last element in a 'for' loop?

So, this is definitely not the "shorter" version - and one might digress if "shortest" and "Pythonic" are actually compatible.

But if one needs this pattern often, just put the logic in to a 10-liner generator - and get any meta-data related to an element's position directly on the for call. Another advantage here is that it will work wit an arbitrary iterable, not only Sequences.

_sentinel = object()

def iter_check_last(iterable):
    iterable = iter(iterable)
    current_element = next(iterable, _sentinel)
    while current_element is not _sentinel:
        next_element = next(iterable, _sentinel)
        yield (next_element is _sentinel, current_element)
        current_element = next_element
In [107]: for is_last, el in iter_check_last(range(3)):
     ...:     print(is_last, el)
     ...: 
     ...: 
False 0
False 1
True 2

Can gcc output C code after preprocessing?

cpp is the preprocessor.

Run cpp filename.c to output the preprocessed code, or better, redirect it to a file with cpp filename.c > filename.preprocessed.

relative path to CSS file

You have to move the css folder into your web folder. It seems that your web folder on the hard drive equals the /ServletApp folder as seen from the www. Other content than inside your web folder cannot be accessed from the browsers.

The url of the CSS link is then

 <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>

How to remove application from app listings on Android Developer Console

No, you cannot delete the application once you have published it in Google Play. Google will keep all the apk files. But you can unpublish the version, if you dont want that version to be availaible to user.

What is the difference between a strongly typed language and a statically typed language?

Data Coercion does not necessarily mean weakly typed because sometimes its syntacical sugar:

The example above of Java being weakly typed because of

String s = "abc" + 123;

Is not weakly typed example because its really doing:

String s = "abc" + new Integer(123).toString()

Data coercion is also not weakly typed if you are constructing a new object. Java is a very bad example of weakly typed (and any language that has good reflection will most likely not be weakly typed). Because the runtime of the language always knows what the type is (the exception might be native types).

This is unlike C. C is the one of the best examples of weakly typed. The runtime has no idea if 4 bytes is an integer, a struct, a pointer or a 4 characters.

The runtime of the language really defines whether or not its weakly typed otherwise its really just opinion.

EDIT: After further thought this is not necessarily true as the runtime does not have to have all the types reified in the runtime system to be a Strongly Typed system. Haskell and ML have such complete static analysis that they can potential ommit type information from the runtime.

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

How to add one day to a date?

you want after days find date this code try..

public Date getToDateAfterDays(Integer day) {
        Date nowdate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowdate);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }

Clicking at coordinates without identifying element

I first used the JavaScript code, it worked amazingly until a website did not click.

So I've found this solution:

First, import ActionChains for Python & active it:

from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)

To click on a specific point in your sessions use this:

actions.move_by_offset(X coordinates, Y coordinates).click().perform()

NOTE: The code above will only work if the mouse has not been touched, to reset the mouse coordinates use this:

actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0))

In Full:

actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0)
actions.move_by_offset(X coordinates, Y coordinates).click().perform()

find files by extension, *.html under a folder in nodejs

node.js, recursive simple function:

var path = require('path'), fs=require('fs');

function fromDir(startPath,filter){

    //console.log('Starting from dir '+startPath+'/');

    if (!fs.existsSync(startPath)){
        console.log("no dir ",startPath);
        return;
    }

    var files=fs.readdirSync(startPath);
    for(var i=0;i<files.length;i++){
        var filename=path.join(startPath,files[i]);
        var stat = fs.lstatSync(filename);
        if (stat.isDirectory()){
            fromDir(filename,filter); //recurse
        }
        else if (filename.indexOf(filter)>=0) {
            console.log('-- found: ',filename);
        };
    };
};

fromDir('../LiteScript','.html');

add RegExp if you want to get fancy, and a callback to make it generic.

var path = require('path'), fs=require('fs');

function fromDir(startPath,filter,callback){

    //console.log('Starting from dir '+startPath+'/');

    if (!fs.existsSync(startPath)){
        console.log("no dir ",startPath);
        return;
    }

    var files=fs.readdirSync(startPath);
    for(var i=0;i<files.length;i++){
        var filename=path.join(startPath,files[i]);
        var stat = fs.lstatSync(filename);
        if (stat.isDirectory()){
            fromDir(filename,filter,callback); //recurse
        }
        else if (filter.test(filename)) callback(filename);
    };
};

fromDir('../LiteScript',/\.html$/,function(filename){
    console.log('-- found: ',filename);
});

How can I initialize a MySQL database with schema in a Docker container?

The easiest solution is to use tutum/mysql

Step1

docker pull tutum/mysql:5.5

Step2

docker run -d -p 3306:3306 -v /tmp:/tmp  -e STARTUP_SQL="/tmp/to_be_imported.mysql" tutum/mysql:5.5

Step3

Get above CONTAINER_ID and then execute command docker logs to see the generated password information.

docker logs #<CONTAINER_ID>

How do I toggle an ng-show in AngularJS based on a boolean?

If based on click here it is:

ng-click="orderReverse = orderReverse ? false : true"

Assign width to half available screen width declaratively

<LinearLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
    android:id="@+id/textD_Author"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:text="Author : "
    android:textColor="#0404B4"
    android:textSize="20sp" />
 <TextView
    android:id="@+id/textD_Tag"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:text="Edition : "
    android:textColor="#0404B4"
    android:textSize="20sp" />
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:weightSum="1" >
    <Button
        android:id="@+id/btbEdit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="Edit" />
    <Button
        android:id="@+id/btnDelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="Delete" />
</LinearLayout>
</LinearLayout>

Nested jQuery.each() - continue/break

Confirm in API documentation http://api.jquery.com/jQuery.each/ say:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

and this is my example http://jsfiddle.net/r6jqP/

(function($){
    $('#go').on('click',function(){
        var i=0,
            all=0;
        $('li').each(function(){
             all++;
             if($('#mytext').val()=='continue')return true;
             i++;
             if($('#mytext').val()==$(this).html()){
                 return false;
             }
        });
        alert('Iterazione : '+i+' to '+all);
    });
}(jQuery));

How to convert object to Dictionary<TKey, TValue> in C#?

You can create a generic extension method and then use it on the object like:

public static class Extensions
{
    public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this Object obj)
    {
        // if obj is null throws exception
        Contract.Requires(obj != null);

        // gets the type of the obj parameter
        var type = obj.GetType();
        // checks if obj is of type KeyValuePair
        if (type.IsGenericType && type == typeof(KeyValuePair<TKey, TValue>))
        {

            return new KeyValuePair<TKey, TValue>(
                                                    (TKey)type.GetProperty("Key").GetValue(obj, null), 
                                                    (TValue)type.GetProperty("Value").GetValue(obj, null)
                                                 );

        }
        // if obj type does not match KeyValuePair throw exception
        throw new ArgumentException($"obj argument must be of type KeyValuePair<{typeof(TKey).FullName},{typeof(TValue).FullName}>");   
 }

and usage would be like:

KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();

Android Studio - Failed to notify project evaluation listener error

For me I had to specifically stop the gradlew and clear caches and this fixed my issues:

./gradlew --stop
// Delete all cache files in your project. With git: `git -xfd clean` 
// Delete global cache dir. On Mac it is located in `~/.gradle/caches

Found here: https://github.com/realm/realm-java/issues/5650#issuecomment-355011135

"Could not load type [Namespace].Global" causing me grief

I experienced this problem when I accidentally set "Chrome" to be the default browser for debugging. When I set it back to "IE" the problem disappeared. I am not sure why...


EDIT: I was about to delete this answer, because I wasn't sure about it, but then I had the problem again. I switched to browsing with Chrome, then back again to IE and it stopped! What gives!?

How can I extract embedded fonts from a PDF as valid font files?

This is a followup to the font-forge section of @Kurt Pfeifle's answer, specific to Red Hat (and possibly other Linux distros).

  1. After opening the PDF and selecting the font you want, you will want to select "File -> Generate Fonts..." option.
  2. If there are errors in the file, you can choose to ignore them or save the file and edit them. Most of the errors can be fixed automatically if you click "Fix" enough times.
  3. Click "Element -> Font Info...", and "Fontname", "Family Name" and "Name for Humans" are all set to values you like. If not, modify them and save the file somewhere. These names will determine how your font appears on the system.
  4. Select your file name and click "Save..."

Once you have your TTF file, you can install it on your system by

  1. Copying it to folder /usr/share/fonts (as root)
  2. Running fc-cache -f /usr/share/fonts/ (as root)

Get a list of checked checkboxes in a div using jQuery

If you need to get quantity of selected checkboxes:

var selected = []; // initialize array
    $('div#checkboxes input[type=checkbox]').each(function() {
       if ($(this).is(":checked")) {
           selected.push($(this));
       }
    });
var selectedQuantity = selected.length;

What svn command would list all the files modified on a branch?

svn log -q -v shows paths and hides comments. All the paths are indented so you can search for lines starting with whitespace. Then pipe to cut and sort to tidy up:

svn log --stop-on-copy -q -v | grep '^[[:space:]]'| cut -c6- | sort -u

This gets all the paths mentioned on the branch since its branch point. Note it will list deleted and added, as well as modified files. I just used this to get the stuff I should worry about reviewing on a slightly messy branch from a new dev.

Passing multiple parameters to pool.map() function in Python

In case you don't have access to functools.partial, you could use a wrapper function for this, as well.

def target(lock):
    def wrapped_func(items):
        for item in items:
            # Do cool stuff
            if (... some condition here ...):
                lock.acquire()
                # Write to stdout or logfile, etc.
                lock.release()
    return wrapped_func

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    lck = multiprocessing.Lock()
    pool.map(target(lck), iterable)
    pool.close()
    pool.join()

This makes target() into a function that accepts a lock (or whatever parameters you want to give), and it will return a function that only takes in an iterable as input, but can still use all your other parameters. That's what is ultimately passed in to pool.map(), which then should execute with no problems.

Override devise registrations controller

I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).

If you set properly your nested form, at model and view level, everything works like a charm.

My User model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id

  has_many :organization_memberships
  has_many :organizations, :through => :organization_memberships

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes

  accepts_nested_attributes_for :owned_organizations
  ...
end

My Organization Model:

class Organization < ActiveRecord::Base
  belongs_to :owner, :class_name => 'User'
  has_many :organization_memberships
  has_many :users, :through => :organization_memberships
  has_many :contracts

  attr_accessor :plan_name

  after_create :set_owner_membership, :set_contract
  ...
end

My view : 'devise/registrations/new.html.erb'

<h2>Sign up</h2>

<% resource.owned_organizations.build if resource.owned_organizations.empty? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :name %><br />
    <%= f.text_field :name %></p>

  <p><%= f.label :email %><br />
    <%= f.text_field :email %></p>

  <p><%= f.label :username %><br />
    <%= f.text_field :username %></p>

  <p><%= f.label :password %><br />
    <%= f.password_field :password %></p>

  <p><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %></p>

  <%= f.fields_for :owned_organizations do |organization_form| %>

    <p><%= organization_form.label :name %><br />
      <%= organization_form.text_field :name %></p>

    <p><%= organization_form.label :subdomain %><br />
      <%= organization_form.text_field :subdomain %></p>

    <%= organization_form.hidden_field :plan_name, :value => params[:plan] %>

  <% end %>

  <p><%= f.submit "Sign up" %></p>
<% end %>

<%= render :partial => "devise/shared/links" %>

jQuery Keypress Arrow Keys

$(document).on( "keydown",  keyPressed);

function keyPressed (e){
    e = e || window.e;
    var newchar = e.which || e.keyCode;
    alert(newchar)
}

What are the differences between Visual Studio Code and Visual Studio?

For Unity3D users ...

  • VSCode is incredibly faster than VS. Files open instantly from Unity. VS is very slow. VSCode launches instantly. VS takes forever to launch.

  • VS can literally compile code, build apps and so on, it's a huge IDE like Unity itself or XCode. VSCode is indeed "just" a full-featured text editor. VSCode is NOT a compiler (far less a huge, build-everything system that can literally create apps and software of all types): VSCode is literally "just a text editor".

  • With VSCode, you DO need to install the "Visual Studio Code" package. (Not to be confused with the "Visual Studio" package.) (It seems to me that VS works fine without the VS package, but, with VS Code, you must install Unity's VSCode package.)

enter image description here

  • When you first download and install VSCode, simply open any C# file on your machine. It will instantly prompt you to install the needed C# package. This is harmless and easy.

  • Unfortunately VSCode generally has only one window! You cannot, really, easily drag files to separate windows. If this is important to you, you may need to go with VS.

  • The biggest problem with VS is that the overall concept of settings and preferences are absolutely horrible. In VS, it is all-but impossible to change the font, etc. In contrast, VSCode has FANTASTIC preferences - dead simple, never a problem.

  • As far as I can see, every single feature in VS which you use in Unity is present in VSCode. (So, code coloring, jump to definitions, it understands/autocompletes every single thing in Unity, it opens from Unity, double clicking something in the Unity console opens the file to that line, etc etc)

  • If you are used to VS. And you want to change to VSCode. It's always hard changing editors, they are so intimate, but it's pretty similar; you won't have a big heartache.

In short if you're a VS for Unity3D user,

and you're going to try VSCode...

  1. VSCode is on the order of 19 trillion times faster in every way. It will blow your mind.

  2. It does seem to have every feature.

  3. Basically VS is the world's biggest IDE and application building system: VSCode is just an editor. (Indeed, that's exactly what you want with Unity, since Unity itself is the IDE.)

  4. Don't forget to just click to install the relevant Unity package.

If I'm not mistaken, there is no reason whatsoever to use VS with Unity.

Unity is an IDE so you just need a text editor, and that is what VSCode is. VSCode is hugely better in both speed and preferences. The only possible problem - multiple-windows are a bit clunky in VSCode!

That horrible "double copy" problem in VS ... solved!

If you are using VS with Unity. There is an infuriating problem where often VS will try to open twice, that is you will end up with two or more copies of VS running. Nobody has ever been able to fix this or figure out what the hell causes it. Fortunately, this problem never happens with VSCode.

Installing VSCode on a Mac - unbelievably easy.

There are no installers, etc etc etc. On the download page, you download a zipped Mac app. Put it in the Applications folder and you're done.

Folding! (Mac/Windows keystrokes are different)

Bizarrely there's no menu entry / docu whatsoever for folding, but here are the keys:

https://stackoverflow.com/a/30077543/294884

Setting colors and so on in VSCode - the critical tips

Particularly for Mac users who may find the colors strange:

Priceless post #1:

https://stackoverflow.com/a/45640244/294884

Priceless post #2:

https://stackoverflow.com/a/63303503/294884

Meta files ...

To keep the "Explorer" list of files on the left tidy, in the Unity case:

enter image description here

How to calculate time difference in java?

TO get pretty timing differences, then

// d1, d2 are dates
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

How do I convert datetime to ISO 8601 in PHP

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601

Procedural

For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));

Convert bytes to a string

I think this way is easy:

>>> bytes_data = [112, 52, 52]
>>> "".join(map(chr, bytes_data))
'p44'

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

After all the Jquery script tag's add

<script>jQuery.noConflict();</script>

to avoid the conflict between Prototype and Jquery.

-didSelectRowAtIndexPath: not being called

Another possible cause seems to be that the UITableView is embed in a UIScrollView. I had this problem today because I inadvertently had a scroll view instead of a normal view as the root view of my controller.

What is causing this error - "Fatal error: Unable to find local grunt"

I had the same issue in Vagrant.

I have used sudo to run the command to install.

sudo npm install -g grunt-cli

It worked for me.

Get size of folder or file

The File object has a length method:

f = new File("your/file/name");
f.length();

If/else else if in Jquery for a condition

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <form name="myform">
    Enter your name
    <input type="text" name="inputbox" id='textBox' value="" />
    <input type="button" name="button" class="member" value="Click1" />
    <input type="button" name="button" value="Click2" onClick="testResults()" />
  </form>
  <script>
    function testResults(n) {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    }
    $(document).on('click', '.member', function () {
      var answer = $("#textBox").val();
      if (answer == 2) {
        alert("Good !");
      } else if (answer == 3) {
        alert("very Good !");
      } else if (answer == 4) {
        alert("better !");
      } else if (answer == 5) {
        alert("best !");
      } else {
        alert('wrong');
      }
    });
  </script>

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"

Apparently the differences between these date formats are as follow:

DT_DATE A date structure that consists of year, month, day, and hour.

DT_DBDATE A date structure that consists of year, month, and day.

DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction

By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.

z-index not working with fixed positioning

z-index only works within a particular context i.e. relative, fixed or absolute position.

z-index for a relative div has nothing to do with the z-index of an absolutely or fixed div.

EDIT This is an incomplete answer. This answer provides false information. Please review @Dansingerman's comment and example below.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For me it was important to delete the "php.executablePath" path from the VS code settings and leave only the path to PHP in the Path variable.

When I had the Path variable together with php.executablePath, an irritating error still occurred (despite the fact that the path to php was correct).

How to remove a key from HashMap while iterating over it?

To remove specific key and element from hashmap use

hashmap.remove(key)

full source code is like

import java.util.HashMap;
public class RemoveMapping {
     public static void main(String a[]){
        HashMap hashMap = new HashMap();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : "+hashMap);
        hashMap.remove(3);   
        System.out.println("Changed HashMap : "+hashMap);        
    }
}

Source : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified--key-from-hashmap

Convert datetime object to a String of date only in Python

Another option:

import datetime
now=datetime.datetime.now()
now.isoformat()
# ouptut --> '2016-03-09T08:18:20.860968'

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

How to select records from last 24 hours using SQL?

SELECT * 
FROM tableName 
WHERE datecolumn >= dateadd(hour,-24,getdate())

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

Codeigniter : calling a method of one controller from other

test.php Controller File :

Class Test {
 function demo() {
  echo "Hello";
 }
}

test1.php Controller File :

Class Test1 {
 function demo2() {
  require('test.php');
  $test = new Test();
  $test->demo();
 }
}

Automatically open Chrome developer tools when new tab/new window is opened

You can open Dev Tools (F12 in Chrome) in new window by clicking three, vertical dots on the right bottom corner, and choose Open as Separate Window.

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

shared global variables in C

In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

If a reboot does not correct the problem (as suggested by Greg Hegwill's answer) then check your PATH for conflicting installation(s) of the msys-1.0.dll (and possibly other related DLLs).

In my particular situation MinGW's installation of msys has a copy of that DLL in its bin directory (<MinGW_Install_Path>\msys\1.0\bin), and it was listed in the PATH. Git's cmd directory was listed in the PATH, but its bin was not. (Git's version of msys-1.0.dll is in the bin directory. Apparently the default installation of MSys-Git does not add its bin to the PATH.)

A temporary fix was to add Git's bin directory to the PATH so that it appears before MinGW's paths. (A more permanent fix will likely involve sorting out the path conflicts between MinGW's msys and Git's and/or removing the duplicate msys installations.)

Which Architecture patterns are used on Android?

I would like to add a design pattern that has been applied in Android Framework. This is Half Sync Half Async pattern used in the Asynctask implementation. See my discussion at

https://docs.google.com/document/d/1_zihWXAwgTAdJc013-bOLUHPMrjeUBZnDuPkzMxEEj0/edit?usp=sharing

numpy: most efficient frequency counts for unique values in an array

Most of simple problems get complicated because simple functionality like order() in R that gives a statistical result in both and descending order is missing in various python libraries. But if we devise our thinking that all such statistical ordering and parameters in python are easily found in pandas, we can can result sooner than looking in 100 different places. Also, development of R and pandas go hand-in-hand because they were created for same purpose. To solve this problem I use following code that gets me by anywhere:

unique, counts = np.unique(x, return_counts=True)
d = {'unique':unique, 'counts':count}  # pass the list to a dictionary
df = pd.DataFrame(d) #dictionary object can be easily passed to make a dataframe
df.sort_values(by = 'count', ascending=False, inplace = True)
df = df.reset_index(drop=True) #optional only if you want to use it further

wait() or sleep() function in jquery?

That'd be .delay().

http://api.jquery.com/delay/

If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.

Read response headers from API response - Angular 5 + TypeScript

Try this simple code.

1. Components side code: to get both body and header property. Here there's a token in body and Authorization in the header.

loginUser() {
    this.userService.loginTest(this.loginCred).
    subscribe(res => {
        let output1 = res;
        console.log(output1.body.token);
        console.log(output1.headers.get('Authorization'));
    })
}

2. Service side code: sending login data in the body and observe the response in Observable any which be subscribed in the component side.

loginTest(loginCred: LoginParams): Observable<any> {
    const header1= {'Content-Type':'application/json',};
    const body =  JSON.stringify(loginCred);
    return this.http.post<any>(this.baseURL+'signin',body,{
        headers: header1,
        observe: 'response',
        responseType: 'json'
    });
}

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

How to generate a random alpha-numeric string

I found this solution that generates a random hex encoded string. The provided unit test seems to hold up to my primary use case. Although, it is slightly more complex than some of the other answers provided.

/**
 * Generate a random hex encoded string token of the specified length
 *  
 * @param length
 * @return random hex string
 */
public static synchronized String generateUniqueToken(Integer length){ 
    byte random[] = new byte[length];
    Random randomGenerator = new Random();
    StringBuffer buffer = new StringBuffer();

    randomGenerator.nextBytes(random);

    for (int j = 0; j < random.length; j++) {
        byte b1 = (byte) ((random[j] & 0xf0) >> 4);
        byte b2 = (byte) (random[j] & 0x0f);
        if (b1 < 10)
            buffer.append((char) ('0' + b1));
        else
            buffer.append((char) ('A' + (b1 - 10)));
        if (b2 < 10)
            buffer.append((char) ('0' + b2));
        else
            buffer.append((char) ('A' + (b2 - 10)));
    }
    return (buffer.toString());
}

@Test
public void testGenerateUniqueToken(){
    Set set = new HashSet();
    String token = null;
    int size = 16;

    /* Seems like we should be able to generate 500K tokens 
     * without a duplicate 
     */
    for (int i=0; i<500000; i++){
        token = Utility.generateUniqueToken(size);

        if (token.length() != size * 2){
            fail("Incorrect length");
        } else if (set.contains(token)) {
            fail("Duplicate token generated");
        } else{
            set.add(token);
        }
    }
}

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

_x000D_
_x000D_
console.log(String(5).padStart(2, '0'));
_x000D_
_x000D_
_x000D_

How to fix 'android.os.NetworkOnMainThreadException'?

Network-based operations cannot be run on the main thread. You need to run all network-based tasks on a child thread or implement AsyncTask.

This is how you run a task in a child thread:

new Thread(new Runnable(){
    @Override
    public void run() {
        try {
            // Your implementation goes here
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}).start();

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

LinkButton Send Value to Code Behind OnClick

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'

How to embed small icon in UILabel

you have to make a custom object where you used a UIView and inside you put a UIImageView and a UILabel

Determine which MySQL configuration file is being used

I found this really useful:

  1. Find the MySQL process in Services under Control Panel -> Administration Tools
  2. Right mouse click and choose Properties
  3. Click and select the Path to executable and see if it contains the path to the my.ini/my.cfg

Oracle JDBC intermittent Connection Issue

I was facing exactly the same problem. With Windows Vista I could not reproduce the problem but on Ubuntu I reproduced the 'connection reset'-Error constantly.

I found http://forums.oracle.com/forums/thread.jspa?threadID=941911&tstart=0&messageID=3793101

According to a user on that forum:

I opened a ticket with Oracle and this is what they told me.

java.security.SecureRandom is a standard API provided by sun. Among various methods offered by this class void nextBytes(byte[]) is one. This method is used for generating random bytes. Oracle 11g JDBC drivers use this API to generate random number during login. Users using Linux have been encountering SQLException("Io exception: Connection reset").

The problem is two fold

  1. The JVM tries to list all the files in the /tmp (or alternate tmp directory set by -Djava.io.tmpdir) when SecureRandom.nextBytes(byte[]) is invoked. If the number of files is large the method takes a long time to respond and hence cause the server to timeout

  2. The method void nextBytes(byte[]) uses /dev/random on Linux and on some machines which lack the random number generating hardware the operation slows down to the extent of bringing the whole login process to a halt. Ultimately the the user encounters SQLException("Io exception: Connection reset")

Users upgrading to 11g can encounter this issue if the underlying OS is Linux which is running on a faulty hardware.

Cause The cause of this has not yet been determined exactly. It could either be a problem in your hardware or the fact that for some reason the software cannot read from dev/random

Solution Change the setup for your application, so you add the next parameter to the java command:

-Djava.security.egd=file:/dev/../dev/urandom

We made this change in our java.security file and it has gotten rid of the error.

which solved my problem.

How do you cast a List of supertypes to a List of subtypes?

class MyClass {
  String field;

  MyClass(String field) {
    this.field = field;
  }
}

@Test
public void testTypeCast() {
  List<Object> objectList = Arrays.asList(new MyClass("1"), new MyClass("2"));

  Class<MyClass> clazz = MyClass.class;
  List<MyClass> myClassList = objectList.stream()
      .map(clazz::cast)
      .collect(Collectors.toList());

  assertEquals(objectList.size(), myClassList.size());
  assertEquals(objectList, myClassList);
}

This test shows how to cast List<Object> to List<MyClass>. But you need to take an attention to that objectList must contain instances of the same type as MyClass. And this example can be considered when List<T> is used. For this purpose get field Class<T> clazz in constructor and use it instead of MyClass.class.

Take a full page screenshot with Firefox on the command-line

Update 2018-07-23

As was just pointed out in the comments, this question was about getting a screenshot from the command line. Sorry, I just read over that. So here is the correct answer:

As of Firefox 57 you can create a screenshot in headless mode like this:

firefox -screenshot https://developer.mozilla.com

Read more in the documentation.

Update 2017-06-15

As of Firefox 55 there is Firefox Screenshots as a more flexible alternative. As of Firefox 57 Screenshots can capture a full page, too.

Original answer

Since Firefox 32 there is also a full page screenshot button in the developer tools (F12). If it is not enabled go to the developer tools settings (gear button) and choose "Take a fullpage screenshot" at the "Available Toolbox Buttons" section.

developer tools toolbar source: developer.mozilla.org

By default the screenshots are saved in the download directory. This works similar to screenshot --fullpage in the toolbar.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

In our case it turned out that the error happened because we have a custom filter in our application which does HttpServletResponse sendRedirect() to other url.

For some reason, the redirection is not closing the keep-alive status of the connection, hence the timeout exception.

We checked with Tomcat Docs and when we disabled the maxKeepAliveRequests by setting it's value to 1 and the error stopped showing up.

For now we do not have the actual solution to the error.

C pass int array pointer as parameter into a function

Maybe you were trying to do this?

#include <stdio.h>

int func(int * B){

    /* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
    *(B + 2) = 5;
}

int main(void) {

    int B[10];

    func(B);

    /* Let's say you edited only 2 and you want to show it. */
    printf("b[0] = %d\n\n", B[2]);

    return 0;
}

jQuery DIV click, with anchors

If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
    return false;
});

See event.preventDefault() vs. return false for details on return false vs. preventDefault.

How to install Java SDK on CentOS?

I have written a shell script to install/uninstall java on centos. You can get it done by just run the shell. The core of this shell is :

1.download the jdk rpm(RedHat Package Manager) package.
2.install java using rpm.

You can see more detail here: https://github.com/daikaixian/WaterShell/tree/master/program_installer

Hope it works for you.

How to scroll to bottom in react?

This is modified from an answer above to support 'children' instead of a data array.

Note: The use of styled-components is of no importance to the solution.

import {useEffect, useRef} from "react";
import React from "react";
import styled from "styled-components";

export interface Props {
    children: Array<any> | any,
}

export function AutoScrollList(props: Props) {
    const bottomRef: any = useRef();

    const scrollToBottom = () => {
        bottomRef.current.scrollIntoView({
            behavior: "smooth",
            block: "start",
        });
    };

    useEffect(() => {
        scrollToBottom()
    }, [props.children])

    return (
        <Container {...props}>
            <div key={'child'}>{props.children}</div>
            <div key={'dummy'} ref={bottomRef}/>
        </Container>
    );
}

const Container = styled.div``;

How to generate auto increment field in select query

In the case you have no natural partition value and just want an ordered number regardless of the partition you can just do a row_number over a constant, in the following example i've just used 'X'. Hope this helps someone

select 
    ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1, 
    period_next_id, period_name_long
from 
(
  select distinct col1, period_name_long, 'X' as num
  from {TABLE} 
) as x

android.os.NetworkOnMainThreadException with android 4.2

This is the correct way:

public class JSONParser extends AsyncTask <String, Void, String>{

    static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}
@Override
protected String doInBackground(String... params) {


    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();

        //HttpResponse httpResponse = httpClient.execute(httpPost);
        //HttpEntity httpEntity = httpResponse.getEntity();
        is = getResponseEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IO", e.getMessage().toString());
        e.printStackTrace();

    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;


}
protected void onPostExecute(String page)
{   
    //onPostExecute
}   
}

To call it (from main):

mJSONParser = new JSONParser();
mJSONParser.execute();

Chain-calling parent initialisers in python

The way you are doing it is indeed the recommended one (for Python 2.x).

The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".

How can I get a user's media from Instagram without authenticating as a user?

Just want to add to @350D answer, since it was hard for me to understand.

My logic in code is next:

When calling API first time, i'm calling only https://www.instagram.com/_vull_ /media/. When I receive response, I check boolean value of more_available. If its true, I get the last photo from the array, get its id and then call Instagram API again but this time https://www.instagram.com/_vull_/media/?max_id=1400286183132701451_1642962433.

Important thing to know here, this Id is the Id of the last picture in the array. So when asking for maxId with the last id of the picture in the array, you will get next 20 pictures, and so on.

Hope this clarify things.

How to use sudo inside a docker container?

When neither sudo nor apt-get is available in container, you can also jump into running container as root user using command

docker exec -u root -t -i container_id /bin/bash

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Reason for me is 2 of following code in one xml

<?xml version="1.0" encoding="utf-8"?>

UIButton title text color

In Swift:

Changing the label text color is quite different than changing it for a UIButton. To change the text color for a UIButton use this method:

self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)

Java Ordered Map

The SortedMap interface (with the implementation TreeMap) should be your friend.

The interface has the methods:

  • keySet() which returns a set of the keys in ascending order
  • values() which returns a collection of all values in the ascending order of the corresponding keys

So this interface fulfills exactly your requirements. However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

onCreateOptionsMenu inside Fragments

try this,

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_sample, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

Finally, in onCreateView method, add this line to make the options appear in your Toolbar

setHasOptionsMenu(true);

jQuery find and replace string

You could do something like this:

HTML

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>


jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});

Initializing data.frames()

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

How can I change the default Mysql connection timeout when connecting through python?

Do:

con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')

Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")

  • connect_timeout: Number of seconds the mysqld server waits for a connect packet before responding with 'Bad handshake'
  • interactive_timeout Number of seconds the server waits for activity on an interactive connection before closing it
  • wait_timeout Number of seconds the server waits for activity on a connection before closing it

BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.

Get content of a cell given the row and column numbers

You don't need the CELL() part of your formulas:

=INDIRECT(ADDRESS(B1,B2))

or

=OFFSET($A$1, B1-1,B2-1)

will both work. Note that both INDIRECT and OFFSET are volatile functions. Volatile functions can slow down calculation because they are calculated at every single recalculation.

How to format a numeric column as phone number in SQL

I'd generally recommend you leave the formatting up to your front-end code and just return the data as-is from SQL. However, to do it in SQL, I'd recommend you create a user-defined function to format it. Something like this:

CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
RETURNS VARCHAR(25)
AS
BEGIN
DECLARE @Formatted VARCHAR(25)

IF (LEN(@PhoneNo) <> 10)
    SET @Formatted = @PhoneNo
ELSE
    SET @Formatted = LEFT(@PhoneNo, 3) + '-' + SUBSTRING(@PhoneNo, 4, 3) + '-' + SUBSTRING(@PhoneNo, 7, 4)

RETURN @Formatted
END
GO

Which you can then use like this:

SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber
FROM SomeTable

It has a safeguard in, in case the phone number stored isn't the expected number of digits long, is blank, null etc - it won't error.

EDIT: Just clocked on you want to update your existing data. The main bit that's relevant from my answer then is that you need to protect against "dodgy"/incomplete data (i.e. what if some existing values are only 5 characters long)

Generate random number between two numbers in JavaScript

function randomIntFromInterval(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min);
}

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

Secure hash and salt for PHP passwords

SHA1 and a salt should suffice (depending, naturally, on whether you are coding something for Fort Knox or a login system for your shopping list) for the foreseeable future. If SHA1 isn't good enough for you, use SHA256.

The idea of a salt is to throw the hashing results off balance, so to say. It is known, for example, that the MD5-hash of an empty string is d41d8cd98f00b204e9800998ecf8427e. So, if someone with good enough a memory would see that hash and know that it's the hash of an empty string. But if the string is salted (say, with the string "MY_PERSONAL_SALT"), the hash for the 'empty string' (i.e. "MY_PERSONAL_SALT") becomes aeac2612626724592271634fb14d3ea6, hence non-obvious to backtrace. What I'm trying to say, that it's better to use any salt, than not to. Therefore, it's not too much of an importance to know which salt to use.

There are actually websites that do just this - you can feed it a (md5) hash, and it spits out a known plaintext that generates that particular hash. If you would get access to a database that stores plain md5-hashes, it would be trivial for you to enter the hash for the admin to such a service, and log in. But, if the passwords were salted, such a service would become ineffective.

Also, double-hashing is generally regarded as bad method, because it diminishes the result space. All popular hashes are fixed-length. Thus, you can have only a finite values of this fixed length, and the results become less varied. This could be regarded as another form of salting, but I wouldn't recommend it.

How to improve a case statement that uses two columns

You could do it this way:

-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     ELSE '"DECLINED"'
END

The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

The key part here is that the STATE condition is a part of the WHEN.

Hiding and Showing TabPages in tabControl

There are at least two ways to code a solution in software... Thanks for posting answers. Just wanted to update this with another version. A TabPage array is used to shadow the Tab Control. During the Load event, the TabPages in the TabControl are copied to the shadow array. Later, this shadow array is used as the source to copy the TabPages into the TabControl...and in the desired presentation order.

    Private tabControl1tabPageShadow() As TabPage = Nothing

    Private Sub Form2_DailyReportPackageViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
        LoadTabPageShadow()
    End Sub


    Private Sub LoadTabPageShadow()
        ReDim tabControl1tabPageShadow(TabControl1.TabPages.Count - 1)
        For Each tabPage In TabControl1.TabPages
            tabControl1tabPageShadow(tabPage.TabIndex) = tabPage
        Next
    End Sub

    Private Sub ViewAllReports(sender As Object, e As EventArgs) Handles Button8.Click
        TabControl1.TabPages.Clear()
        For Each tabPage In tabControl1tabPageShadow
            TabControl1.TabPages.Add(tabPage)
        Next
    End Sub


    Private Sub ViewOperationsReports(sender As Object, e As EventArgs) Handles Button10.Click
        TabControl1.TabPages.Clear()

        For tabCount As Integer = 0 To 9
            For Each tabPage In tabControl1tabPageShadow
                Select Case tabPage.Text
                    Case "Overview"
                        If tabCount = 0 Then TabControl1.TabPages.Add(tabPage)
                    Case "Production Days Under 110%"
                        If tabCount = 1 Then TabControl1.TabPages.Add(tabPage)
                    Case "Screening Status"
                        If tabCount = 2 Then TabControl1.TabPages.Add(tabPage)
                    Case "Rework Status"
                        If tabCount = 3 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary by Machine"
                        If tabCount = 4 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Set Ups"
                        If tabCount = 5 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Run Times"
                        If tabCount = 6 Then TabControl1.TabPages.Add(tabPage)
                    Case "Primary Set Ups"
                        If tabCount = 7 Then TabControl1.TabPages.Add(tabPage)
                    Case "Variance"
                        If tabCount = 8 Then TabControl1.TabPages.Add(tabPage)
                    Case "Schedule Changes"
                        If tabCount = 9 Then TabControl1.TabPages.Add(tabPage)
                End Select
            Next
        Next


onclick="javascript:history.go(-1)" not working in Chrome

Why not get rid of the inline javascript and do something like this instead?

Inline javascript is considered bad practice as it is outdated.

Notes

Why use addEventListener?

addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling) It works on any DOM element, not just HTML elements.

<a id="back" href="www.mypage.com"> Link </a>

document.getElementById("back").addEventListener("click", window.history.back, false);

On jsfiddle

What is the best way to call a script from another script?

I prefer runpy:

#!/usr/bin/env python
# coding: utf-8

import runpy

runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')

How to style the UL list to a single line

in bootstrap use .list-inline css class

<ul class="list-inline">
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>

Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I put this for future visitors:

if you are receiving the error on creating an Exception object, then the cause of it probably is a lack of definition for what() virtual function.

How to add hours to current time in python

from datetime import datetime, timedelta

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

And then use string formatting to get the relevant pieces:

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

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

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

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

How to find nth occurrence of character in a string?

public class Sam_Stringnth {

    public static void main(String[] args) {
        String str="abcabcabc";
        int n = nthsearch(str, 'c', 3);
        if(n<=0)
            System.out.println("Character not found");
        else
            System.out.println("Position is:"+n);
    }
    public static int nthsearch(String str, char ch, int n){
        int pos=0;
        if(n!=0){
            for(int i=1; i<=n;i++){
                pos = str.indexOf(ch, pos)+1;
            }
            return pos;
        }
        else{
            return 0;
        }
    }
}

Tree implementation in Java (root, parents and children)

Here is my implementation in java for your requirement. In the treeNode class i used generic array to store the tree data. we can also use arraylist or dynamic array to store the tree value.

public class TreeNode<T> {
   private T value = null;
   private TreeNode[] childrens = new TreeNode[100];
   private int childCount = 0;

    TreeNode(T value) {
        this.value = value;
    }

    public TreeNode addChild(T value) {
        TreeNode newChild = new TreeNode(value, this);
        childrens[childCount++] = newChild;
        return newChild;
    }

    static void traverse(TreeNode obj) {
        if (obj != null) {
            for (int i = 0; i < obj.childCount; i++) {
                System.out.println(obj.childrens[i].value);
                traverse(obj.childrens[i]);
            }
        }
        return;
    }

    void printTree(TreeNode obj) {
        System.out.println(obj.value);
        traverse(obj);
    }
}

And the client class for the above implementation.

public class Client {
    public static void main(String[] args) {
        TreeNode menu = new TreeNode("Menu");
        TreeNode item = menu.addChild("Starter");
            item = item.addChild("Veg");
                item.addChild("Paneer Tikka");
                item.addChild("Malai Paneer Tikka");
            item = item.addChild("Non-veg");
                item.addChild("Chicken Tikka");
                item.addChild("Malai Chicken Tikka");
        item = menu.addChild("Main Course");
            item = item.addChild("Veg");
                item.addChild("Mili Juli Sabzi");
                item.addChild("Aloo Shimla Mirch");
            item = item.addChild("Non-veg");
                item.addChild("Chicken Do Pyaaza");
                item.addChild("Chicken Chettinad");
        item = menu.addChild("Desserts");
                item = item.addChild("Cakes");
                        item.addChild("Black Forest");
                        item.addChild("Black Current");
                item = item.addChild("Ice Creams");
                        item.addChild("chocolate");
                        item.addChild("Vanilla");
        menu.printTree(menu);
    }
}

OUTPUT

Menu                                                                     
Starter                                                                 
Veg                                                                
Paneer Tikka                                                        
Malai Paneer Tikka                                                    
Non-veg                                                              
Chicken Tikka                                                      
Malai Chicken Tikka                                                 
Main Course                                                      
Veg                                                             
Mili Juli Sabzi                                                   
Aloo Shimla Mirch                                                  
Non-veg                                                               
Chicken Do Pyaaza                                                   
Chicken Chettinad                                                    
Desserts                                                         
Cakes                                                            
Black Forest                                                     
Black Current                                                   
Ice Creams                                                      
chocolate                                                       
Vanilla           

Mean per group in a data.frame

Here are a variety of ways to do this in base R including an alternative aggregate approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:

Using ave:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))

my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data

Using by:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)

my.data <- merge(my.data, by.month, by = 'Month')
my.data

Using lapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)

my.data <- merge(my.data, ly.mean, by = 'Month')
my.data

Using sapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data

sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data

Using aggregate:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month), 
                   FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))

my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary

my.data <- merge(my.data, my.summary, by = 'Month')
my.data

EDIT: June 28, 2020

Here I use aggregate to obtain the column means of an entire matrix by group where group is defined in an external vector:

my.group <- c(1,2,1,2,2,3,1,2,3,3)

my.data <- matrix(c(   1,    2,    3,    4,    5,
                      10,   20,   30,   40,   50,
                       2,    4,    6,    8,   10,
                      20,   30,   40,   50,   60,
                      20,   18,   16,   14,   12,
                    1000, 1100, 1200, 1300, 1400,
                       2,    3,    4,    3,    2,
                      50,   40,   30,   20,   10,
                    1001, 2001, 3001, 4001, 5001,
                    1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data

my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
#  Group.1          X1       X2          X3       X4          X5
#1       1    1.666667    3.000    4.333333    5.000    5.666667
#2       2   25.000000   27.000   29.000000   31.000   33.000000
#3       3 1000.333333 1700.333 2400.333333 3100.333 3800.333333

What is a word boundary in regex, does \b match hyphen '-'?

In the course of learning regular expression, I was really stuck in the metacharacter which is \b. I indeed didn't comprehend its meaning while I was asking myself "what it is, what it is" repetitively. After some attempts by using the website, I watch out the pink vertical dashes at the every beginning of words and at the end of words. I got it its meaning well at that time. It's now exactly word(\w)-boundary.

My view is merely to immensely understanding-oriented. Logic behind of it should be examined from another answers.

enter image description here

php implode (101) with quotes

If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....

$output = '';
foreach ($list as $row) {
  $output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}

Or from a list of objects...

foreach ($list as $obj) {
  $output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}

Then you can output the string as desired.

Run javascript function when user finishes typing instead of on key up?

agree with the @going 's answer. Another similar solution that worked for me is the one below. The only difference is that I am using .on("input"...) instead of keyup. This only captures changes in the input. other keys like Ctrl, Shift etc. are ignored

var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on input change, start the countdown

$('#myInput').on("input", function() {    
    clearTimeout(typingTimer);
    typingTimer = setTimeout(function(){
        // doSomething...
    }, doneTypingInterval);
});

How do you know a variable type in java?

I would like to expand on Martin's answer there...

His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.

Martins Solution:

a.getClass().getName()

However, If you want it to work with anything you can do this:

((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()

In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.

I myself used it like this:

private static String nameOf(Object o) {
    return o.getClass().getSimpleName();
}

Using Generics:

public static <T> String nameOf(T o) {
    return o.getClass().getSimpleName();
}

Creating an array of objects in Java

This is correct.

A[] a = new A[4];

...creates 4 A references, similar to doing this:

A a1;
A a2;
A a3;
A a4;

Now you couldn't do a1.someMethod() without allocating a1 like this:

a1 = new A();

Similarly, with the array you need to do this:

a[0] = new A();

...before using it.

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Why do we use $rootScope.$broadcast in AngularJS?

  1. What does $rootScope.$broadcast do?

    $rootScope.$broadcast is sending an event through the application scope. Any children scope of that app can catch it using a simple: $scope.$on().

    It is especially useful to send events when you want to reach a scope that is not a direct parent (A branch of a parent for example)

    !!! One thing to not do however is to use $rootScope.$on from a controller. $rootScope is the application, when your controller is destroyed that event listener will still exist, and when your controller will be created again, it will just pile up more event listeners. (So one broadcast will be caught multiple times). Use $scope.$on() instead, and the listeners will also get destroyed.

  2. What is the difference between $rootScope.$broadcast & $rootScope.$broadcast.apply?

    Sometimes you have to use apply(), especially when working with directives and other JS libraries. However since I don't know that code base, I wouldn't be able to tell if that's the case here.

What is Activity.finish() method doing exactly?

When calling finish() on an activity, the method onDestroy() is executed. This method can do things like:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog

Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed

How do I make a column unique and index it in a Ruby on Rails migration?

The short answer for old versions of Rails (see other answers for Rails 4+):

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

If you get "index name... is too long", you can add name: "whatever" to the add_index method to make the name shorter.

For fine-grained control, there's a "execute" method that executes straight SQL.

That's it!

If you are doing this as a replacement for regular old model validations, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.

How to do case insensitive string comparison?

If you know you're dealing with ascii text then you can just use a uppercase/lowercase character offset comparison.

Just make sure the string your "perfect" string (the one you want to match against) is lowercase:

const CHARS_IN_BETWEEN = 32;
const LAST_UPPERCASE_CHAR = 90; // Z
function strMatchesIgnoreCase(lowercaseMatch, value) {
    let i = 0, matches = lowercaseMatch.length === value.length;
    while (matches && i < lowercaseMatch.length) {
        const a = lowercaseMatch.charCodeAt(i);
        const A = a - CHARS_IN_BETWEEN;
        const b = value.charCodeAt(i);
        const B = b + ((b > LAST_UPPERCASE_CHAR) ? -CHARS_IN_BETWEEN : CHARS_IN_BETWEEN);
        matches = a === b // lowerA === b
            || A === b // upperA == b
            || a === B // lowerA == ~b
            || A === B; // upperA == ~b
        i++;
    }
    return matches;
}

How do I debug a stand-alone VBScript script?

Click the mse7.exe installed along with Office typically at \Program Files\Microsoft Office\OFFICE11.

This will open up the debugger, open the file and then run the debugger in the GUI mode.

Multiple returns from a function

Add all variables in an array and then finally return the array.

function test($testvar)
{
  // do something
  return array("var1" => $var1, "var2" => @var2);
}

And then

$myTest = test($myTestVar);
//$myTest["var1"] and $myTest["var2"] will be usable

How to apply color in Markdown?

In Jekyll I was able to add some color or other styles to a bold element (should work with all other elements as well).

I started the "styling" with {: and end it }. There is no space allowed between element and curly bracket!

**My Bold Text, in red color.**{: style="color: red; opacity: 0.80;" }

Will be translated to html:

<strong style="color: red; opacity: 0.80;">My Bold Text, in red color.</strong>

CSS Animation and Display None

The following will get you to animate an element when

  1. Giving it a Display - None
  2. Giving it a Display - Block

CSS

.MyClass {
       opacity: 0;
       display:none;
       transition: opacity 0.5s linear;
       -webkit-transition: opacity 0.5s linear;
       -moz-transition: opacity 0.5s linear;
       -o-transition: opacity 0.5s linear;
       -ms-transition: opacity 0.5s linear;
 }

JavaScript

function GetThisHidden(){
    $(".MyClass").css("opacity", "0").on('transitionend webkitTransitionEnd oTransitionEnd otransitionend', HideTheElementAfterAnimation);
}

function GetThisDisplayed(){
    $(".MyClass").css("display", "block").css("opacity", "1").unbind("transitionend webkitTransitionEnd oTransitionEnd otransitionend");
}

function HideTheElementAfterAnimation(){
    $(".MyClass").css("display", "none");
}

How to configure Eclipse build path to use Maven dependencies?

I did like this..

Right click on the project--> configure-->convert to maven project. Right click on the project-->maven-->add dependencies.

How to open a second activity on click of button in android app

Replace your MainActivity.class with these code

public class MainActivity extends Activity {

Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 b1=(Button)findViewById(R.id.button1);
 b1.setOnClickListener(new View.onClickListener()
 {
  public void onClick(View v)
   {
       Intent i=new Intent(getApplicationContext(),SendPhotos.class);
       startActivity(i);
    }
 }
 )
}

Add these Code in your AndroidManifest.xml after the </activity> and Before </application>

<activity android:name=".SendPhotos"></activity>

jQuery multiselect drop down menu

<select id="mycontrolId" multiple="multiple">
   <option value="1" >one</option>
   <option value="2" >two</option>
   <option value="3">three</option>
   <option value="4">four</option>
</select>

var data = "1,3,4"; var dataarray = data.split(",");

$("#mycontrolId").val(dataarray);

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I encountered this error when running my Android app on my home WiFi, then trying to run it on different WiFi without closing my simulator.

Simply closing the simulator and re-launching the app worked for me!

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

Do AJAX requests retain PHP Session info?

If the PHP file the AJAX requests has a session_start() the session info will be retained. (baring the requests are within the same domain)

Serial Port (RS -232) Connection in C++

For the answer above, the default serial port is

        serialParams.BaudRate = 9600;
        serialParams.ByteSize = 8;
        serialParams.StopBits = TWOSTOPBITS;
        serialParams.Parity = NOPARITY;

What is Turing Complete?

Here is the simplest explanation

Alan Turing created a machine that can take a program, run that program, and show some result. But then he had to create different machines for different programs. So he created "Universal Turing Machine" that can take ANY program and run it.

Programming languages are similar to those machines (although virtual). They take programs and run them. Now, a programing language is called "Turing complete", if it can run any program (irrespective of the language) that a Turing machine can run given enough time and memory.

For example: Let's say there is a program that takes 10 numbers and adds them. A Turing machine can easily run this program. But now imagine that for some reason your programming language can't perform the same addition. This would make it "Turing incomplete" (so to speak). On the other hand, if it can run any program that the universal Turing machine can run, then it's Turing complete.

Most modern programming languages (e.g. Java, JavaScript, Perl, etc.) are all Turing complete because they each implement all the features required to run programs like addition, multiplication, if-else condition, return statements, ways to store/retrieve/erase data and so on.

Update: You can learn more on my blog post: "JavaScript Is Turing Complete" — Explained

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

How can I see if a Perl hash already has a certain key?

Well, your whole code can be limited to:

foreach $line (@lines){
        $strings{$1}++ if $line =~ m|my regex|;
}

If the value is not there, ++ operator will assume it to be 0 (and then increment to 1). If it is already there - it will simply be incremented.

How to have Ellipsis effect on Text

_x000D_
_x000D_
const styles = theme => ({_x000D_
 contentClass:{_x000D_
    overflow: 'hidden',_x000D_
    textOverflow: 'ellipsis',_x000D_
    display: '-webkit-box',_x000D_
    WebkitLineClamp:1,_x000D_
    WebkitBoxOrient:'vertical'_x000D_
 }   _x000D_
})
_x000D_
render () {_x000D_
  return(_x000D_
    <div className={classes.contentClass}>_x000D_
      {'content'}_x000D_
    </div>_x000D_
  )_x000D_
}
_x000D_
_x000D_
_x000D_

How do I remove diacritics (accents) from a string in .NET?

you can use string extension from MMLib.Extensions nuget package:

using MMLib.RapidPrototyping.Generators;
public void ExtensionsExample()
{
  string target = "aácceéií";
  Assert.AreEqual("aacceeii", target.RemoveDiacritics());
} 

Nuget page: https://www.nuget.org/packages/MMLib.Extensions/ Codeplex project site https://mmlib.codeplex.com/

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

Implementing Singleton with an Enum (in Java)

An enum type is a special type of class.

Your enum will actually be compiled to something like

public final class MySingleton {
    public final static MySingleton INSTANCE = new MySingleton();
    private MySingleton(){} 
}

When your code first accesses INSTANCE, the class MySingleton will be loaded and initialized by the JVM. This process initializes the static field above once (lazily).

node.js require() cache - possible to invalidate?

I'd add to luff's answer one more line and change the parameter name:

function requireCached(_module){
    var l = module.children.length;
    for (var i = 0; i < l; i++)
    {
        if (module.children[i].id === require.resolve(_module))
        {
            module.children.splice(i, 1);
            break;
        }
    }
    delete require.cache[require.resolve(_module)];
    return require(_module)
}

How to add a TextView to a LinearLayout dynamically in Android?

I customized more @Suragch code. My output looks

enter image description here

I wrote a method to stop code redundancy.

public TextView createATextView(int layout_widh, int layout_height, int align,
        String text, int fontSize, int margin, int padding) {

    TextView textView_item_name = new TextView(this);

    // LayoutParams layoutParams = new LayoutParams(
    // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    // layoutParams.gravity = Gravity.LEFT;
    RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
            layout_widh, layout_height);

    _params.setMargins(margin, margin, margin, margin);
    _params.addRule(align);
    textView_item_name.setLayoutParams(_params);

    textView_item_name.setText(text);
    textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
    textView_item_name.setTextColor(Color.parseColor("#000000"));
    // textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView_item_name.setPadding(padding, padding, padding, padding);

    return textView_item_name;

}

It can be called like

createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20);

Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.

    RelativeLayout primary_layout = new RelativeLayout(this);

    LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);

    primary_layout.setLayoutParams(layoutParam);

    // FOR LINEAR LAYOUT SET ORIENTATION
    // primary_layout.setOrientation(LinearLayout.HORIZONTAL);

    // FOR BACKGROUND COLOR 
    primary_layout.setBackgroundColor(0xff99ccff);

    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
            20, 10, 20));
    primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
            subTotal.toString(), 20, 10, 20));

How can I remove file extension from a website address?

Actually, the simplest way to manipulate this is to

  1. Open a new folder on your server, e.g. "Data"
  2. Put index.php (or index.html) in it

And then the URL www.yoursite.com/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.com/data/list run that PHP file.

This way you can have full control over this, very useful for SEO.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

What is sharding and why is it important?

In my opinion the application tier should have no business determining where data should be stored

This is a good rule but like most things not always correct.

When you do your architecture you start with responsibilities and collaborations. Once you determine your functional architecture, you have to balance the non-functional forces.

If one of these non-functional forces is massive scalability, you have to adapt your architecture to cater for this force even if it means that your data storage abstraction now leaks into your application tier.

How can I echo the whole content of a .html file in PHP?

Just use:

<?php
    include("/path/to/file.html");
?>

That will echo it as well. This also has the benefit of executing any PHP in the file.

If you need to do anything with the contents, use file_get_contents(),

For example,

<?php
    $pagecontents = file_get_contents("/path/to/file.html");

    echo str_replace("Banana", "Pineapple", $pagecontents);

?>

This doesn't execute code in that file, so be careful if you expect that to work.

I usually use:

include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");

as then I can move files without breaking the includes.

How to silence output in a Bash script?

Note: This answer is related to the question "How to turn off echo while executing a shell script Linux" which was in turn marked as duplicated to this one.

To actually turn off the echo the command is:

stty -echo

(this is, for instance; when you want to enter a password and you don't want it to be readable. Remember to turn echo on at the end of your script, otherwise the person that runs your script won't see what he/she types in from then on. To turn echo on run:

stty echo

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

throws error, but I added name attribute to input:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

and it started to work.

Excel VBA: Copying multiple sheets into new workbook

Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):

Sub NewWBandPasteSpecialALLSheets()
   MyBook = ActiveWorkbook.Name ' Get name of this book
   Workbooks.Add ' Open a new workbook
   NewBook = ActiveWorkbook.Name ' Save name of new book

   Workbooks(MyBook).Activate ' Back to original book

   Set WB = ActiveWorkbook

   Dim SH As Worksheet

   For Each SH In WB.Worksheets

       SH.Range("WholePrintArea").Copy

       Workbooks(NewBook).Activate

       With SH.Range("A1")
        .PasteSpecial (xlPasteColumnWidths)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlValues)

       End With

     Next

End Sub

But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:

Sub NewWBandPasteSpecialALLSheets()
   Dim wb As Workbook
   Dim wbNew As Workbook
   Dim sh As Worksheet
   Dim shNew As Worksheet

   Set wb = ThisWorkbook
   Workbooks.Add ' Open a new workbook
   Set wbNew = ActiveWorkbook

   On Error Resume Next

   For Each sh In wb.Worksheets
      sh.Range("WholePrintArea").Copy

      'add new sheet into new workbook with the same name
      With wbNew.Worksheets

          Set shNew = Nothing
          Set shNew = .Item(sh.Name)

          If shNew Is Nothing Then
              .Add After:=.Item(.Count)
              .Item(.Count).Name = sh.Name
              Set shNew = .Item(.Count)
          End If
      End With

      With shNew.Range("A1")
          .PasteSpecial (xlPasteColumnWidths)
          .PasteSpecial (xlFormats)
          .PasteSpecial (xlValues)
      End With
   Next
End Sub

How to view DLL functions?

You may try the Object Browser in Visual Studio.

Select Edit Custom Component Set. From there, you can choose from a variety of .NET, COM or project libraries or just import external dlls via Browse.

How to get data from Magento System Configuration

Magento 1.x

(magento 2 example provided below)

sectionName, groupName and fieldName are present in etc/system.xml file of the module.

PHP Syntax:

Mage::getStoreConfig('sectionName/groupName/fieldName');

From within an editor in the admin, such as the content of a CMS Page or Static Block; the description/short description of a Catalog Category, Catalog Product, etc.

{{config path="sectionName/groupName/fieldName"}}

For the "Within an editor" approach to work, the field value must be passed through a filter for the {{ ... }} contents to be parsed out. Out of the box, Magento will do this for Category and Product descriptions, as well as CMS Pages and Static Blocks. However, if you are outputting the content within your own custom view script and want these variables to be parsed out, you can do so like this:

<?php
    $example = Mage::getModel('identifier/name')->load(1);
    $filter  = Mage::getModel('cms/template_filter');
    echo $filter->filter($example->getData('field'));
?>

Replacing identifier/name with the a appropriate values for the model you are loading, and field with the name of the attribute you want to output, which may contain {{ ... }} occurrences that need to be parsed out.

Magento 2.x

From any Block class that extends \Magento\Framework\View\Element\AbstractBlock

$this->_scopeConfig->getValue('sectionName/groupName/fieldName');

Any other PHP class:

If the class (and none of it's parent's) does not inject \Magento\Framework\App\Config\ScopeConfigInterface via the constructor, you'll have to add it to your class.

// ... Remaining class definition above...

/**
 * @var \Magento\Framework\App\Config\ScopeConfigInterface
 */
protected $_scopeConfig;

/**
 * Constructor
 */
public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    // ...any other injected classes the class depends on...
) {
  $this->_scopeConfig = $scopeConfig;
  // Remaining constructor logic...
}

// ...remaining class definition below...

Once you have injected it into your class, you can now fetch store configuration values with the same syntax example given above for block classes.

Note that after modifying any class's __construct() parameter list, you may have to clear your generated classes as well as dependency injection directory: var/generation & var/di

Counting the number of elements with the values of x in a vector

This can be done with outer to get a metrix of equalities followed by rowSums, with an obvious meaning.
In order to have the counts and numbers in the same dataset, a data.frame is first created. This step is not needed if you want separate input and output.

df <- data.frame(No = numbers)
df$count <- rowSums(outer(df$No, df$No, FUN = `==`))

require_once :failed to open stream: no such file or directory

You will need to link to the file relative to the file that includes eventManager.php (Page A)

Change your code from
require_once('../includes/dbconn.inc');

To
require_once('../mysite/php/includes/dbconn.inc');

How can I create an editable dropdownlist in HTML?

Simple HTML + Javascript approach without CSS

_x000D_
_x000D_
function editDropBox() {_x000D_
    var cSelect = document.getElementById('changingList');_x000D_
_x000D_
    var optionsSavehouse = [];_x000D_
    if(cSelect != null) {_x000D_
        var optionsArray = Array.from(cSelect.options);_x000D_
_x000D_
        var arrayLength = optionsArray.length;_x000D_
        for (var o = 0; o < arrayLength; o++) {_x000D_
            var option = optionsArray[o];_x000D_
            var oVal = option.value;_x000D_
_x000D_
            if(oVal > 0) {_x000D_
                var localParams = [];_x000D_
                localParams.push(option.text);_x000D_
                localParams.push(option.value);_x000D_
                //localParams.push(option.selected); // if needed_x000D_
                optionsSavehouse.push(localParams);_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
_x000D_
    var hidden = ("<input id='hidden_select_options' type='hidden' value='" + JSON.stringify(optionsSavehouse) + "' />");_x000D_
_x000D_
    var cSpan = document.getElementById('changingSpan');_x000D_
    if(cSpan != null) {_x000D_
        cSpan.innerHTML = (hidden + "<input size='2' type='text' id='tempInput' name='fname' onchange='restoreDropBox()'>");_x000D_
    }_x000D_
}_x000D_
_x000D_
function restoreDropBox() {_x000D_
    var cSpan = document.getElementById('changingSpan');_x000D_
    var cInput = document.getElementById('tempInput');_x000D_
    var hOptions = document.getElementById('hidden_select_options');_x000D_
_x000D_
    if(cSpan != null) {_x000D_
_x000D_
        var optionsArray = [];_x000D_
_x000D_
        if(hOptions != null) {_x000D_
            optionsArray = JSON.parse(hOptions.value);_x000D_
        }_x000D_
_x000D_
        var selectList = "<select id='changingList'>\n";_x000D_
_x000D_
        var arrayLength = optionsArray.length;_x000D_
        for (var o = 0; o < arrayLength; o++) {_x000D_
            var option = optionsArray[o];_x000D_
            selectList += ("<option value='" + option[1] + "'>" + option[0] + "</option>\n");_x000D_
        }_x000D_
_x000D_
        if(cInput != null) {_x000D_
            selectList += ("<option value='-1' selected>" + cInput.value + "</option>\n");_x000D_
        }_x000D_
_x000D_
        selectList += ("<option value='-2' onclick='editDropBox()'>- Edit -</option>\n</select>");_x000D_
        cSpan.innerHTML = selectList;_x000D_
    }_x000D_
}
_x000D_
<span id="changingSpan">_x000D_
    <select id="changingList">_x000D_
        <option value="1">Apple</option>_x000D_
        <option value="2">Banana</option>_x000D_
        <option value="3">Cherry</option>_x000D_
        <option value="4">Dewberry</option>_x000D_
        <option onclick="editDropBox()" value="-2">- Edit -</option>_x000D_
    </select>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Call to undefined function App\Http\Controllers\ [ function name ]

say you define the static getFactorial function inside a CodeController

then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.

CodeController::getFactorial($index);

----------------UPDATE----------------

To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.

to do that

create a folder inside app directory and name it as lib (you can put a name you like).

this folder to needs to be autoload to do that add app/lib to composer.json as below. and run the composer dumpautoload command.

"autoload": {
    "classmap": [
                "app/commands",
                "app/controllers",
                ............
                "app/lib"
    ]
},

then files inside lib will autoloaded.

then create a file inside lib, i name it helperFunctions.php

inside that define the function.

if ( ! function_exists('getFactorial'))
{

    /**
     * return the factorial of a number
     *
     * @param $number
     * @return string
     */
    function getFactorial($date)
    {
        $fact = 1;

        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;

        return $fact;

     }
}

and call it anywhere within the app as

$fatorial_value = getFactorial(225);

Sending an HTTP POST request on iOS

I am not really sure why, but as soon as I comment out the following method it works:

connectionDidFinishDownloading:destinationURL:

Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.

Comments in Android Layout xml

As other said, the comment in XML are like this

<!-- this is a comment -->

Notice that they can span on multiple lines

<!--
    This is a comment
    on multiple lines
-->

But they cannot be nested

<!-- This <!-- is a comment --> This is not -->

Also you cannot use them inside tags

<EditText <!--This is not valid--> android:layout_width="fill_parent" />

How do I check two or more conditions in one <c:if>?

Just in case somebody needs to check the condition from session.Usage of or

<c:if test="${sessionScope['roleid'] == 1 || sessionScope['roleid'] == 4}">

Curl not recognized as an internal or external command, operable program or batch file

Steps to install curl in windows

Install cURL on Windows

There are 4 steps to follow to get cURL installed on Windows.

Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate

Step One: Install Visual C++ 2008 Redistributables

From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)

Step Two: Install Win(32/64) OpenSSL v1.0.0k Light

From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light

Step Three: Install cURL

Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html

Copy curl.exe to C:\Windows\System32

Step Four: Install Recent Certificates

Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt

If you have already installed curl or after doing the above steps, add the directory where it's installed to the windows path:

1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt

How to set Spring profile from system variable?

You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by System.getProperty("spring.profiles.active")

For java files in test directory you can supply

  • SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}

How do you list the primary key of a SQL Server table?

Is using MS SQL Server you can do the following:

--List all tables primary keys
select * from information_schema.table_constraints
where constraint_type = 'Primary Key'

You can also filter on the table_name column if you want a specific table.

Why em instead of px?

The top voted answer here from thomasrutter is right in his response about the em. But is very very wrong about the size of a pixel. So even though it is old, I cannot let it be undebated.

A computer screen is normally NOT 96dpi! (Or ppi, if you want to be pedantic.)


A pixel does NOT have a fixed physical size.
(Yes, it is fixed within one screen only, but in the next screen a pixel is most likely bigger, or smaller, and certainly NOT 1/96 of an inch.)


Proof
Draw a line, 960 pixels long. Measure it with a physical ruler. Is it 10 inches? No..?
Connect your laptop to your TV. Is the line 10 inches now? Still not?
Show the line on your iPhone. Still same size? Why not?

Who the heck invented the 96dpi computer screen myth?
(Some religions operate with a 72dpi myth. But equally wrong.)

Can't perform a React state update on an unmounted component

Depending on how you open your webpage, you may not be causing a mounting. Such as using a <Link/> back to a page that was already mounted in the virtual DOM, so requiring data from a componentDidMount lifecycle is caught.

Spring Boot Configure and Use Two DataSources

Refer the official documentation


Creating more than one data source works same as creating the first one. You might want to mark one of them as @Primary if you are using the default auto-configuration for JDBC or JPA (then that one will be picked up by any @Autowired injections).

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.primary")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}

How to delete last item in list?

you should use this

del record[-1]

The problem with

record = record[:-1]

Is that it makes a copy of the list every time you remove an item, so isn't very efficient

My httpd.conf is empty

It's empty by default. You'll find a bunch of settings in /etc/apache2/apache2.conf.

In there it does this:

# Include all the user configurations:
Include httpd.conf

How to get label of select option with jQuery?

Created working Plunker for this. https://plnkr.co/edit/vR9aGoCwoOUL9tevIEen $('#console').append("<br/>"+$('#test_s :selected').text())

What is and how to fix System.TypeInitializationException error?

i. Please check the InnerException property of the TypeInitializationException

ii. Also, this may occur due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly

Android Eclipse - Could not find *.apk

On my machine (Windows7, 64bit) I could fix this by setting my execution environment to a 32bit variant of the jdk (I used 1.6.0_23). And I tried a lot of things before...