Programs & Examples On #Source filter

Darken background image on hover

How about this, using an overlay?

.image:hover > .overlay {
    width:100%;
    height:100%;
    position:absolute;
    background-color:#000;
    opacity:0.5;
    border-radius:30px;
}

Demo

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Somewhat hilariously, Google has made a font that works correctly in Safari but not in Chrome. Here's the https://codepen.io/anon/pen/zbavza

<i class="material-icons-round red">warning</i>

red round warning material icon in safari

In reference to https://stackoverflow.com/a/54902967/4740291 and not being able to change the color using css.

matrix multiplication algorithm time complexity

Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.

The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

I hope the above answer works for elastic search <7.0 but in 7.0 we cannot specify doc type and it is no longer supported. And in that case if we specify doc type we get similar error.

I you are making use of Elastic search 7.0 and Nest C# lastest version(6.6). There are some breaking changes with ES 7.0 which is causing this issue. This is because we cannot specify doc type and in the version 6.6 of NEST they are using doctype. So in order to solve that untill NEST 7.0 is released, we need to download their beta package

Please go through this link for fixing it

https://xyzcoder.github.io/elasticsearch/nest/2019/04/12/es-70-and-nest-mapping-error.html

EDIT: NEST 7.0 is now released. NEST 7.0 works with Elastic 7.0. See the release notes here for details.

Can I start the iPhone simulator without "Build and Run"?

The easiest way is start the simulator from the Xcode, and then on the dock, Ctrl + Click on the icon and select Keep in Dockenter image description here

java.net.MalformedURLException: no protocol

The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. ... Welcome to the Java standard levels of indirections !

Basically :

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));

Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

Javascript to check whether a checkbox is being checked or unchecked

function enter_comment(super_id) {
    if (!(document.getElementById(super_id).checked)) {
        alert('selected checkbox is unchecked now')
    } else {
        alert('selected checkbox is checked now');
    }
}

<input type="checkbox" name="a" id="1" value="1" onclick="enter_comment(this.value)" />

<input type="checkbox" name="b" id="2" value="2" onclick="enter_comment(this.value)" />

JavaScript split String with white space

For split string by space like in Python lang, can be used:

   var w = "hello    my brothers    ;";
   w.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );

output:

   ["hello", "my", "brothers", ";"]

or similar:

   w.split(/(\s+)/).filter( e => e.trim().length > 0)

(output some)

Call Python function from JavaScript code

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).

  1. Install python and create a sample file test.py

    import sys
    # print sys.argv[0] prints test.py
    # print sys.argv[1] prints your_var_1
    
    def hello():
        print "Hi" + " " + sys.argv[1]
    
    if __name__ == "__main__":
        hello()
    
  2. Create a method in your Web API Server

    [HttpGet]
    public string SayHi(string id)
    {
        string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";          
    
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        p.Start();
    
        return p.StandardOutput.ReadToEnd();                  
    }
    
  3. And now for your JavaScript:

    function processSayingHi() {          
       var your_param = 'abc';
       $.ajax({
           url: '/api/your_controller_name/SayHi/' + your_param,
           type: 'GET',
           success: function (response) {
               console.log(response);
           },
           error: function (error) {
               console.log(error);
           }
        });
    }
    

Remember that your .py file won't run on your user's computer, but instead on the server.

Adding n hours to a date in Java?

If you use Apache Commons / Lang, you can do it in one step using DateUtils.addHours():

Date newDate = DateUtils.addHours(oldDate, 3);

(The original object is unchanged)

Should Jquery code go in header or footer?

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

EDIT: Firefox does support the DEFER attribute since version 3.6.

Sources:

Convert data.frame column format from character to factor

# To do it for all names
df[] <- lapply( df, factor) # the "[]" keeps the dataframe structure
 col_names <- names(df)
# to do it for some names in a vector named 'col_names'
df[col_names] <- lapply(df[col_names] , factor)

Explanation. All dataframes are lists and the results of [ used with multiple valued arguments are likewise lists, so looping over lists is the task of lapply. The above assignment will create a set of lists that the function data.frame.[<- should successfully stick back into into the dataframe, df

Another strategy would be to convert only those columns where the number of unique items is less than some criterion, let's say fewer than the log of the number of rows as an example:

cols.to.factor <- sapply( df, function(col) length(unique(col)) < log10(length(col)) )
df[ cols.to.factor] <- lapply(df[ cols.to.factor] , factor)

How to write :hover condition for a:before and a:after?

BoltClock's answer is correct. The only thing I want to append is that if you want to only select the pseudo element, put in a span.

For example:

<li><span data-icon='u'></span> List Element </li>

instead of:

<li> data-icon='u' List Element</li>

This way you can simply say

ul [data-icon]:hover::before {color: #f7f7f7;}

which will only highlight the pseudo element, not the entire li element

How to test valid UUID/GUID?

If you are using Node.js for development, it is recommended to use a package called Validator. It includes all the regexes required to validate different versions of UUID's plus you get various other functions for validation.

Here is the npm link: Validator

var a = 'd3aa88e2-c754-41e0-8ba6-4198a34aa0a2'
v.isUUID(a)
true
v.isUUID('abc')
false
v.isNull(a)
false

How do I clone a subdirectory only of a Git repository?

What you are trying to do is called a sparse checkout, and that feature was added in git 1.7.0 (Feb. 2012). The steps to do a sparse clone are as follows:

mkdir <repo>
cd <repo>
git init
git remote add -f origin <url>

This creates an empty repository with your remote, and fetches all objects but doesn't check them out. Then do:

git config core.sparseCheckout true

Now you need to define which files/folders you want to actually check out. This is done by listing them in .git/info/sparse-checkout, eg:

echo "some/dir/" >> .git/info/sparse-checkout
echo "another/sub/tree" >> .git/info/sparse-checkout

Last but not least, update your empty repo with the state from the remote:

git pull origin master

You will now have files "checked out" for some/dir and another/sub/tree on your file system (with those paths still), and no other paths present.

You might want to have a look at the extended tutorial and you should probably read the official documentation for sparse checkout.

As a function:

function git_sparse_clone() (
  rurl="$1" localdir="$2" && shift 2

  mkdir -p "$localdir"
  cd "$localdir"

  git init
  git remote add -f origin "$rurl"

  git config core.sparseCheckout true

  # Loops over remaining args
  for i; do
    echo "$i" >> .git/info/sparse-checkout
  done

  git pull origin master
)

Usage:

git_sparse_clone "http://github.com/tj/n" "./local/location" "/bin"

Note that this will still download the whole repository from the server – only the checkout is reduced in size. At the moment it is not possible to clone only a single directory. But if you don't need the history of the repository, you can at least save on bandwidth by creating a shallow clone. See udondan's answer below for information on how to combine shallow clone and sparse checkout.


As of git 2.25.0 (Jan 2020) an experimental sparse-checkout command is added in git:

git sparse-checkout init
# same as: 
# git config core.sparseCheckout true

git sparse-checkout set "A/B"
# same as:
# echo "A/B" >> .git/info/sparse-checkout

git sparse-checkout list
# same as:
# cat .git/info/sparse-checkout

How do you serialize a model instance in Django?

It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset with one object. If, on the other hand, what you need is a way to re-inflate the model instance somewhere else without touching the database or without using Django, then you have a little bit of work to do.

Here's what I do:

First, I use demjson for the conversion. It happened to be what I found first, but it might not be the best. My implementation depends on one of its features, but there should be similar ways with other converters.

Second, implement a json_equivalent method on all models that you might need serialized. This is a magic method for demjson, but it's probably something you're going to want to think about no matter what implementation you choose. The idea is that you return an object that is directly convertible to json (i.e. an array or dictionary). If you really want to do this automatically:

def json_equivalent(self):
    dictionary = {}
    for field in self._meta.get_all_field_names()
        dictionary[field] = self.__getattribute__(field)
    return dictionary

This will not be helpful to you unless you have a completely flat data structure (no ForeignKeys, only numbers and strings in the database, etc.). Otherwise, you should seriously think about the right way to implement this method.

Third, call demjson.JSON.encode(instance) and you have what you want.

Escape double quotes in a string

No.

Either use verbatim string literals as you have, or escape the " using backslash.

string test = "He said to me, \"Hello World\" . How are you?";

The string has not changed in either case - there is a single escaped " in it. This is just a way to tell C# that the character is part of the string and not a string terminator.

ActiveXObject creation error " Automation server can't create object"

I have the same problem , it solved by registering the dll

at project properties => build => register for COM interop => check it

Convert spark DataFrame column to python list

Let's create the dataframe in question

df_test = spark.createDataFrame(
    [
        (1, 5),
        (2, 9),
        (3, 3),
        (4, 1),
    ],
    ['mvv', 'count']
)
df_test.show()

Which gives

+---+-----+
|mvv|count|
+---+-----+
|  1|    5|
|  2|    9|
|  3|    3|
|  4|    1|
+---+-----+

and then apply rdd.flatMap(f).collect() to get the list

test_list = df_test.select("mvv").rdd.flatMap(list).collect()
print(type(test_list))
print(test_list)

which gives

<type 'list'>
[1, 2, 3, 4]

Why are my PowerShell scripts not running?

Use:

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

Always use the above command to enable to executing PowerShell in the current session.

How to solve error: "Clock skew detected"?

One of the reason may be improper date/time of your PC.

In Ubuntu PC to check the date and time using:

date

Example, One of the ways to update date and time is:

date -s "23 MAR 2017 17:06:00"

How to create a property for a List<T>

Simple and effective alternative:

public class ClassName
{
    public List<dynamic> MyProperty { get; set; }
}

or

public class ClassName
{
    public List<object> MyProperty { get; set; }
}

For differences see this post: List<Object> vs List<dynamic>

Multiple conditions in WHILE loop

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')

What should be the package name of android app?

As stated here: Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:

enter image description here

How to find my realm file?

I found most simplest way for iOS/macOS (for swift 3 Xcode 8.3)

override func viewDidLoad() {

   // for swift 2.0 Xcode 7
   print(Realm.Configuration.defaultConfiguration.fileURL!)
}

Then x code will log the correct path, check the screen below.

enter image description here

Now open your Finder and press ? + ? + G (command+shift+G) and paste the path that logs on your Xcode

How to detect when an @Input() value changes in Angular?

You could also just pass an EventEmitter as Input. Not quite sure if this is best practice tho...

CategoryComponent.ts:

categoryIdEvent: EventEmitter<string> = new EventEmitter<>();

- OTHER CODE -

setCategoryId(id) {
 this.category.id = id;
 this.categoryIdEvent.emit(this.category.id);
}

CategoryComponent.html:

<video-list *ngIf="category" [categoryId]="categoryIdEvent"></video-list>

And in VideoListComponent.ts:

@Input() categoryIdEvent: EventEmitter<string>
....
ngOnInit() {
 this.categoryIdEvent.subscribe(newID => {
  this.categoryId = newID;
 }
}

What is the difference between function and procedure in PL/SQL?

Both stored procedures and functions are named blocks that reside in the database and can be executed as and when required.

The major differences are:

  1. A stored procedure can optionally return values using out parameters, but can also be written in a manner without returning a value. But, a function must return a value.

  2. A stored procedure cannot be used in a SELECT statement whereas a function can be used in a SELECT statement.

Practically speaking, I would go for a stored procedure for a specific group of requirements and a function for a common requirement that could be shared across multiple scenarios. For example: comparing between two strings, or trimming them or taking the last portion, if we have a function for that, we could globally use it for any application that we have.

WPF: ItemsControl with scrollbar (ScrollViewer)

You have to modify the control template instead of ItemsPanelTemplate:

<ItemsControl >
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.

Setting the MySQL root user password on OS X

To reference MySQL 8.0.15 + , the password() function is not available. Use the command below.

Kindly use

UPDATE mysql.user SET authentication_string='password' WHERE User='root';

Forking / Multi-Threaded Processes | Bash

I don't know of any explicit fork call in bash. What you probably want to do is append & to a command that you want to run in the background. You can also use & on functions that you define within a bash script:

do_something_with_line()
{
  line=$1
  foo
  foo2
  foo3
}

for line in file
do
  do_something_with_line $line &
done

EDIT: to put a limit on the number of simultaneous background processes, you could try something like this:

for line in file
do
  while [`jobs | wc -l` -ge 50 ]
  do
    sleep 5
  done
  do_something_with_line $line &
done

What is the difference between DBMS and RDBMS?

DBMS : Data Base Management System ..... for storage of data and efficient retrieval of data. Eg: Foxpro

1)A DBMS has to be persistent (it should be accessible when the program created the data donot exist or even the application that created the data restarted).

2) DBMS has to provide some uniform methods independent of a specific application for accessing the information that is stored.

3)DBMS does not impose any constraints or security with regard to data manipulation. It is user or the programmer responsibility to ensure the ACID PROPERTY of the database

4)In DBMS Normalization process will not be present

5)In dbms no relationship concept

6)It supports Single User only

7)It treats Data as Files internally

8)It supports 3 rules of E.F.CODD out off 12 rules

9)It requires low Software and Hardware Requirements.

FoxPro, IMS are Examples

RDBMS: Relational Data Base Management System

.....the database which is used by relations(tables) to acquire information retrieval Eg: oracle, SQL..,

1)RDBMS is based on relational model, in which data is represented in the form of relations, with enforced relationships between the tables.

2)RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY.

3)In RDBMS, normalization process will be present to check the database table cosistency

4)RDBMS helps in recovery of the database in case of loss of data

5)It is used to establish the relationship concept between two database objects, i.e, tables

6)It supports multiple users

7)It treats data as Tables internally

8)It supports minimum 6 rules of E.F.CODD

9)It requires High software and hardware

Add class to an element in Angular 4

Use [ngClass] and conditionally apply class based on the id.

In your HTML file:

<li>
    <img [ngClass]="{'this-is-a-class': id === 1 }" id="1"  
         src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
    <img [ngClass]="{'this-is-a-class': id === 2 }" id="2"  
         src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>

In your TypeScript file:

addClass(id: any) {
    this.id = id;
}

How to Remove Array Element and Then Re-Index Array?

unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array

Split string in Lua?

Because there are more than one way to skin a cat, here's my approach:

Code:

#!/usr/bin/env lua

local content = [=[
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna 
aliqua. Ut enim ad minim veniam, quis nostrud exercitation 
ullamco laboris nisi ut aliquip ex ea commodo consequat.
]=]

local function split(str, sep)
   local result = {}
   local regex = ("([^%s]+)"):format(sep)
   for each in str:gmatch(regex) do
      table.insert(result, each)
   end
   return result
end

local lines = split(content, "\n")
for _,line in ipairs(lines) do
   print(line)
end

Output: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Explanation:

The gmatch function works as an iterator, it fetches all the strings that match regex. The regex takes all characters until it finds a separator.

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Which is a better way to check if an array has more than one element?

Obviously using count($arr) > 1 (sizeof is just an alias for count) is the best solution. Depending on the structure of your array, there might be tons of elements but no $array['1'] element.

Throw away local commits in Git

Remove untracked files (uncommitted local changes)

git clean -df

Permanently deleting all local commits and get latest remote commit

git reset --hard origin/<branch_name>

Maximum concurrent connections to MySQL

You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.

For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.

While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:

You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.

That means, you are really only establishing about 10-20 concurrent requests.

As others mentioned, you have nothing to worry about in that department.

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

Declaring variable workbook / Worksheet vba

Use Sheets rather than Sheet and activate them sequentially:

Sub kl()
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = Sheets("Sheet1")
    wb.Activate
    ws.Select
End Sub

How to document Python code using Doxygen

This is documented on the doxygen website, but to summarize here:

You can use doxygen to document your Python code. You can either use the Python documentation string syntax:

"""@package docstring
Documentation for this module.

More details.
"""

def func():
    """Documentation for a function.

    More details.
    """
    pass

In which case the comments will be extracted by doxygen, but you won't be able to use any of the special doxygen commands.

Or you can (similar to C-style languages under doxygen) double up the comment marker (#) on the first line before the member:

## @package pyexample
#  Documentation for this module.
#
#  More details.

## Documentation for a function.
#
#  More details.
def func():
    pass

In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting OPTMIZE_OUTPUT_JAVA to YES.

Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?

Git merge error "commit is not possible because you have unmerged files"

You need to do two things. First add the changes with

git add .
git stash  

git checkout <some branch>

It should solve your issue as it solved to me.

SQL: How to perform string does not equal

NULL-safe condition would looks like:

select * from table
where NOT (tester <=> 'username')

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

Adding :default => true to boolean in existing Rails column

As a variation on the accepted answer you could also use the change_column_default method in your migrations:

def up
  change_column_default :profiles, :show_attribute, true
end

def down
  change_column_default :profiles, :show_attribute, nil
end

Rails API-docs

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Run a Command Prompt command from Desktop Shortcut

Create A Shortcut That Opens The Command Prompt & Runs A Command:

Yes! You can create a shortcut to cmd.exe with a command specified after it. Alternatively you could create a batch script, if your goal is just to have a clickable way to run commands.

Steps:

  1. Right click on some empty space in Explorer, and in the context menu go to "New/Shortcut".

  2. When prompted to enter a location put either:

"C:\Windows\System32\cmd.exe /k your-command" This will run the command and keep (/k) the command prompt open after.

or

"C:\Windows\System32\cmd.exe /c your-command" This will run the command and the close (/c) the command prompt.

Notes:

  • Tested, and working on Windows 8 - Core X86-64 September 12 2014

  • If you want to have more than one command, place an "&" symbol in between them. For example: "C:\Windows\System32\cmd.exe /k command1 & command2".

How to convert HH:mm:ss.SSS to milliseconds?

If you want to use SimpleDateFormat, you could write:

private final SimpleDateFormat sdf =
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    { sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }

private long parseTimeToMillis(final String time) throws ParseException
    { return sdf.parse("1970-01-01 " + time).getTime(); }

But a custom method would be much more efficient. SimpleDateFormat, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)

Also, SimpleDateFormat is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)

Personally, I'd probably write a custom method.

New self vs. new static

will I get the same results?

Not really. I don't know of a workaround for PHP 5.2, though.

What is the difference between new self and new static?

self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

In the following example, B inherits both methods from A. The self invocation is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class()).

class A {
    public static function get_self() {
        return new self();
    }

    public static function get_static() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

Ruby: What is the easiest way to remove the first element from an array?

[0, 132, 432, 342, 234][1..-1]
=> [132, 432, 342, 234]

So unlike shift or slice this returns the modified array (useful for one liners).

How to install pandas from pip on windows cmd?

pip install pandas make sure, this is 'pandas' not 'panda'

If you are not able to access pip, then got to C:\Python37\Scripts and run pip.exe install pandas.

Alternatively, you can add C:\Python37\Scripts in the env variables for windows machines. Hope this helps.

PostgreSQL query to list all table names?

SELECT table_name
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='public';

For MySQL you would need table_schema='dbName' and for MSSQL remove that condition.

Notice that "only those tables and views are shown that the current user has access to". Also, if you have access to many databases and want to limit the result to a certain database, you can achieve that by adding condition AND table_catalog='yourDatabase' (in PostgreSQL).

If you'd also like to get rid of the header showing row names and footer showing row count, you could either start the psql with command line option -t (short for --tuples-only) or you can toggle the setting in psql's command line by \t (short for \pset tuples_only). This could be useful for example when piping output to another command with \g [ |command ].

How do I register a DLL file on Windows 7 64-bit?

And while doing this, if you get error code 0x80040201, try the solution in DllRegisterServer failed with the error code 0x80040201, but make sure, you open command prompt as Run as Administrator.

nodejs - first argument must be a string or Buffer - when using response.write with http.request

response.statusCode is a number, e.g. response.statusCode === 200, not '200'. As the error message says, write expects a string or Buffer object, so you must convert it.

res.write(response.statusCode.toString());

You are also correct about your callback comment though. res.end(); should be inside the callback, just below your write calls.

Android Studio Stuck at Gradle Download on create new project

If you're using OS X, and it continues to hang indefinitely, I'd recommend shutting down Android Studio (may have to force kill), then going to your ~/.gradle directory on the console. You'll see a wrapper/dists directory there and whatever version of gradle AS is trying to download. Check the timestamp of the download underneath the randomly named subdirectory. If you see that it is never changing, most likely your download was interrupted and AS wasn't able to restart it properly and will not unless you delete everything below the dists directory and start over.

So, with AS shutdown delete everything below ~/.gradle/wrapper/dists and then try again with a new project in AS. You can check the progress of the gradle download file (it will end in .part) to make sure that it's growing. Give it plenty of time as it IS a large file.

That's what finally worked for me.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

java.lang.ClassNotFoundException is indicate that class is not found in class path. it could be the version of log4j is not compatible. check for different log4j version.

querySelectorAll with multiple conditions

According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

This example returns a list of all div elements within the document with a class of either "note" or "alert":

var matches = document.querySelectorAll("div.note, div.alert");

source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

https://api.jquery.com/multiple-attribute-selector/

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

CSS3 Spin Animation

For the guys who still search some cool and easy spinner, we have multiple exemples of spinner on fontawesome site : https://fontawesome.com/v4.7.0/examples/

You just have to inspect the spinner you want with your debugger and copy the css styles.

MySQL dump by query

not mysqldump, but mysql cli...

mysql -e "select * from myTable" -u myuser -pxxxxxxxxx mydatabase

you can redirect it out to a file if you want :

mysql -e "select * from myTable" -u myuser -pxxxxxxxx mydatabase > mydumpfile.txt

Update: Original post asked if he could dump from the database by query. What he asked and what he meant were different. He really wanted to just mysqldump all tables.

mysqldump --tables myTable --where="id < 1000"

did you register the component correctly? For recursive components, make sure to provide the "name" option

In my case, i was calling twice the import...

@click="$router.push({ path: 'searcherresult' })"

import SearcherResult from "../views/SearcherResult"; --- ERROR

Cause i call in other component...

How to include a child object's child object in Entity Framework 5

If you include the library System.Data.Entity you can use an overload of the Include() method which takes a lambda expression instead of a string. You can then Select() over children with Linq expressions rather than string paths.

return DatabaseContext.Applications
     .Include(a => a.Children.Select(c => c.ChildRelationshipType));

How do I format a number in Java?

As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

Use Spring's Numberformatter instead, which is thread safe.

Slack URL to open a channel from browser

You can use

slack://

in order to open the Slack desktop application. For example, on mac, I've run:

open slack://

from the terminal and it opens the Mac desktop Slack application. Still, I didn't figure out the URL that should be used for opening a certain team, channel or message.

Create timestamp variable in bash script

You can use

timestamp=`date --rfc-3339=seconds`

This delivers in the format 2014-02-01 15:12:35-05:00

The back-tick (`) characters will cause what is between them to be evaluated and have the result included in the line. date --help has other options.

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Pycharm and sys.argv arguments

On PyCharm Community or Professional Edition 2019.1+ :

  1. From the menu bar click Run -> Edit Configurations
  2. Add your arguments in the Parameters textbox (for example file2.txt file3.txt, or --myFlag myArg --anotherFlag mySecondArg)
  3. Click Apply
  4. Click OK

When is a CDATA section necessary within a script tag?

When you are going for strict XHTML compliance, you need the CDATA so less than and ampersands are not flagged as invalid characters.

C# How do I click a button by hitting Enter whilst textbox has focus?

Simply set form "Accept Button" Property to button that you want to hit by Enter key. Or in load event write this.acceptbutton = btnName;

Is there a decorator to simply cache function return values?

I coded this simple decorator class to cache function responses. I find it VERY useful for my projects:

from datetime import datetime, timedelta 

class cached(object):
    def __init__(self, *args, **kwargs):
        self.cached_function_responses = {}
        self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=0))

    def __call__(self, func):
        def inner(*args, **kwargs):
            max_age = kwargs.get('max_age', self.default_max_age)
            if not max_age or func not in self.cached_function_responses or (datetime.now() - self.cached_function_responses[func]['fetch_time'] > max_age):
                if 'max_age' in kwargs: del kwargs['max_age']
                res = func(*args, **kwargs)
                self.cached_function_responses[func] = {'data': res, 'fetch_time': datetime.now()}
            return self.cached_function_responses[func]['data']
        return inner

The usage is straightforward:

import time

@cached
def myfunc(a):
    print "in func"
    return (a, datetime.now())

@cached(default_max_age = timedelta(seconds=6))
def cacheable_test(a):
    print "in cacheable test: "
    return (a, datetime.now())


print cacheable_test(1,max_age=timedelta(seconds=5))
print cacheable_test(2,max_age=timedelta(seconds=5))
time.sleep(7)
print cacheable_test(3,max_age=timedelta(seconds=5))

dll missing in JDBC

Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

java -Djava.library.path=C:\Java\native\libs YourProgram

C:\Java\native\libs should contain sqljdbc_auth.dll

Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

Put this on routes.php file:

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    echo'<pre>';
    var_dump($query->sql);
    var_dump($query->bindings);
    var_dump($query->time);
    echo'</pre>';
});

Submitted by msurguy, source code in this page. You will find this fix-code for laravel 5.2 in comments.

Node.js quick file server (static files over HTTP)

You also asked why requests are dropping - not sure what's the specific reason on your case, but in overall you better server static content using dedicated middleware (nginx, S3, CDN) because Node is really not optimized for this networking pattern. See further explanation here (bullet 13): http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/

Remove duplicates in the list using linq

If there is something that is throwing off your Distinct query, you might want to look at MoreLinq and use the DistinctBy operator and select distinct objects by id.

var distinct = items.DistinctBy( i => i.Id );

Any way to Invoke a private method?

Use getDeclaredMethod() to get a private Method object and then use method.setAccessible() to allow to actually call it.

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

How to workaround 'FB is not defined'?

For people who still got this FB bug, I use this cheeky fix to this problem.

Instead of http://connect.facebook.net/en_US/all.js, I used HTTPS and changed it into https://connect.facebook.net/en_US/all.js and it fixed my problem.

ignoring any 'bin' directory on a git project

[Bb]in will solve the problem, but... Here a more extensive list of things you should ignore (sample list by GitExtension):

#ignore thumbnails created by windows
Thumbs.db
#Ignore files build by Visual Studio
*.user
*.aps
*.pch
*.vspscc
*_i.c
*_p.c
*.ncb
*.suo
*.bak
*.cache
*.ilk
*.log
[Bb]in
[Dd]ebug*/
*.sbr
obj/
[Rr]elease*/
_ReSharper*/

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

How do I split a string into an array of characters?

To support emojis use this

('Dragon ').split(/(?!$)/u);

=> ['D', 'r', 'a', 'g', 'o', 'n', ' ', '']

Ordering by the order of values in a SQL IN() clause

I just tried to do this is MS SQL Server where we do not have FIELD():

SELECT table1.id
... 
INNER JOIN
    (VALUES (10,1),(3,2),(4,3),(5,4),(7,5),(8,6),(9,7),(2,8),(6,9),(5,10)
    ) AS X(id,sortorder)
        ON X.id = table1.id
    ORDER BY X.sortorder

Note that I am allowing duplication too.

Any way to limit border length?

Hope this helps:

_x000D_
_x000D_
#mainDiv {_x000D_
  height: 100px;_x000D_
  width: 80px;_x000D_
  position: relative;_x000D_
  border-bottom: 2px solid #f51c40;_x000D_
  background: #3beadc;_x000D_
}_x000D_
_x000D_
#borderLeft {_x000D_
  border-left: 2px solid #f51c40;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  bottom: 0;_x000D_
}
_x000D_
<div id="mainDiv">_x000D_
  <div id="borderLeft"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Start HTML5 video at a particular position when loading?

You can link directly with Media Fragments URI, just change the filename to file.webm#t=50

Here's an example

This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.

Maven: Command to update repository after adding dependency to POM

I know it is an old question now, but for users who are using Maven plugin with Eclipse under Windows, you have two options:

  1. If you got Maven installed as a standalone application:

    You can use the following command in the CMD under your project path:

    mvn eclipse:eclipse
    

    It will update your repository with all the missing jars, according to your dependencies in your pom.xml file.

  2. If you haven't got Maven installed as a standalone application you can follow these steps on your eclipse:

    Right click on the project ->Run As -- >Run configurations.

    Then select mavenBuild.

    Then click new button to create a configuration of the selected type .Click on Browse workspace then select your project and in goals specify eclipse:eclipse

You can refer to how to run the command mvn eclipse:eclipse for further details.

Angular 2 - innerHTML styling

The simple solution you need to follow is

import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer){}

transformYourHtml(htmlTextWithStyle) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}

Python function overloading

Either use multiple keyword arguments in the definition, or create a Bullet hierarchy whose instances are passed to the function.

php REQUEST_URI

Since vars passed through url are $_GET vars, you can use filter_input() function:

$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$othervar = filter_input(INPUT_GET, 'othervar', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

It would store the values of each var and sanitize/validate them too.

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Using GCC to produce readable assembly?

You can use gdb for this like objdump.

This excerpt is taken from http://sources.redhat.com/gdb/current/onlinedocs/gdb_9.html#SEC64


Here is an example showing mixed source+assembly for Intel x86:

  (gdb) disas /m main
Dump of assembler code for function main:
5       {
0x08048330 :    push   %ebp
0x08048331 :    mov    %esp,%ebp
0x08048333 :    sub    $0x8,%esp
0x08048336 :    and    $0xfffffff0,%esp
0x08048339 :    sub    $0x10,%esp

6         printf ("Hello.\n");
0x0804833c :   movl   $0x8048440,(%esp)
0x08048343 :   call   0x8048284 

7         return 0;
8       }
0x08048348 :   mov    $0x0,%eax
0x0804834d :   leave
0x0804834e :   ret

End of assembler dump.

Checking letter case (Upper/Lower) within a string in Java

I have streamlined the answer of @Quirliom above into functions that can be used:

private static boolean hasLength(CharSequence data) {
    if (String.valueOf(data).length() >= 8) return true;
    else return false;
}

private static boolean hasSymbol(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
    return hasSpecial;
}

private static boolean hasUpperCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasUppercase = !password.equals(password.toLowerCase());
    return hasUppercase;
}

private static boolean hasLowerCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasLowercase = !password.equals(password.toUpperCase());
    return hasLowercase;
}

Reset textbox value in javascript

this is might be a possible solution

void 0 != document.getElementById("ad") &&       (document.getElementById("ad").onclick =function(){
 var a = $("#client_id").val();
 var b = $("#contact").val();
 var c = $("#message").val();
 var Qdata = { client_id: a, contact:b, message:c }
 var respo='';
     $("#message").html('');

return $.ajax({

    url: applicationPath ,
    type: "POST",
    data: Qdata,
    success: function(e) {
         $("#mcg").html("msg send successfully");

    }

})

});

Extract data from log file in specified range of time

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

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

href around input type submit

I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.

IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.

If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.

How to Resize image in Swift?

UIImage Extension Swift 5

extension UIImage {
    func resize(_ width: CGFloat, _ height:CGFloat) -> UIImage? {
        let widthRatio  = width / size.width
        let heightRatio = height / size.height
        let ratio = widthRatio > heightRatio ? heightRatio : widthRatio
        let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}


Use : UIImage().resize(200, 300)

Is it possible to change javascript variable values while debugging in Google Chrome?

This is now possible in chrome 35 (today as of July 11, 2014). I don't know which version allowed it first though.

Just tested @gilly3 example on my machine and it works.

  • Open the console, in Sources and the tab Snippets, add a new snippet, paste the following code into it:

    var g_n = 0; function go() { var n = 0; var o = { n: 0 }; return g_n + n + o.n; // breakpoint here }

  • Right-click the snippet name, click 'Run' (this does not fire the function though)

  • Add the breakpoint at the return statement.
  • In the console below, type go()
  • and change the variable values as demonstrated below

function with local modification allowed.

and the returned result g_n + n + o.n is 30.

Parsing JSON Array within JSON Object

Your code is fine, just replace the following line:

JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));

with this line:

JSONArray jsonMainArr = mainJSON.getJSONArray("source");

Bootstrap 3 2-column form layout

You could use the bootstrap grid system :

<div class="col-md-6 form-group">
    <label for="textbox1">Label1</label>
    <input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
    <label for="textbox2">Label2</label>
    <input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">

http://getbootstrap.com/css/#grid

Is that what you want to achieve?

How can I reuse a navigation bar on multiple pages?

You can use php for making multi-page website.

  • Create a header.php in which you should put all your html code for menu's and social media etc
  • Insert header.php in your index.php using following code

<? php include 'header.php'; ?>

(Above code will dump all html code before this)Your site body content.

  • Similarly you can create footer and other elements with ease. PHP built-in support html code in their extensions. So, better learn this easy fix.

What is a magic number, and why is it bad?

A problem that has not been mentioned with using magic numbers...

If you have very many of them, the odds are reasonably good that you have two different purposes that you're using magic numbers for, where the values happen to be the same.

And then, sure enough, you need to change the value... for only one purpose.

How to detect if numpy is installed

You can try importing them and then handle the ImportError if the module doesn't exist.

try:
    import numpy
except ImportError:
    print "numpy is not installed"

How can you get the Manifest Version number from the App's (Layout) XML variables?

I believe that was already answered here.

String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

OR

int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

Counting DISTINCT over multiple columns

Many (most?) SQL databases can work with tuples like values so you can just do: SELECT COUNT(DISTINCT (DocumentId, DocumentSessionId)) FROM DocumentOutputItems; If your database doesn't support this, it can be simulated as per @oncel-umut-turer's suggestion of CHECKSUM or other scalar function providing good uniqueness e.g. COUNT(DISTINCT CONCAT(DocumentId, ':', DocumentSessionId)).

A related use of tuples is performing IN queries such as: SELECT * FROM DocumentOutputItems WHERE (DocumentId, DocumentSessionId) in (('a', '1'), ('b', '2'));

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

This is a problem with space consumption or choosing the wrong camera. My suggestion in to restart kernel and clear output and run it again. It works then.

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

GIT serves it's purpose well for version control and team projects if commits and branches are maintained properly.
Step 1: Clone your local repo using cli as mentioned by above answers

$ cd [path_to_repo]
$ git remote add origin ssh://[email protected]//.git
$ git push -u origin --all

Step 2: You can follow any of the above steps to push/pull your works. Easy way is to use git gui. It provides Graphical Interface so that it's easy to stage(add)/unstage, commit/uncommit and push/pull. Beginners can easily understand the git process.

$ git gui

(OR)
Step 2: As mentioned above. Cli codes will do the work.

$ git status
$ git add [file_name]
$ git commit _m "[Comit message"]"
$ git push origin master/branch_name

CSS-moving text from left to right

You could simply use CSS animated text generator. There are pre-created templates already

Batch file include external file for variables

So you just have to do this right?:

@echo off
echo text shizzle
echo.
echo pause^>nul (press enter)
pause>nul

REM writing to file
(
echo XD
echo LOL
)>settings.cdb
cls

REM setting the variables out of the file
(
set /p input=
set /p input2=
)<settings.cdb
cls

REM echo'ing the variables
echo variables:
echo %input%
echo %input2%
pause>nul

if %input%==XD goto newecho
DEL settings.cdb
exit

:newecho
cls
echo If you can see this, good job!
DEL settings.cdb
pause>nul
exit

How to find sitemap.xml path on websites?

There is no standard, so there is no guarantee. With that said, its common for the sitemap to be self labeled and on the root, like this:

example.com/sitemap.xml

Case is sensitive on some servers, so keep that in mind. If its not there, look in the robots file on the root:

example.com/robots.txt

If you don't see it listed in the robots file head to Google and search this:

site:example.com filetype:xml

This will limit the results to XML files on your target domain. At this point its trial-and-error and based on the specifics of the website you are working with. If you get several pages of results from the Google search phrase above then try to limit the results further:

filetype:xml site:example.com inurl:sitemap

or

filetype:xml site:example.com inurl:products

If you still can't find it you can right-click > "View Source" and do a search (aka: "control find" or Ctrl + F) for .xml to see if there is a reference to it in the code.

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

If it is on a Linux box, I would suggest you add the database IP name and IP resolution to the /etc/hosts.

I have the same error and when we do the above, it works fine.

Printing Batch file results to a text file

For showing result of batch file in text file, you can use

this command

chdir > test.txt

This command will redirect result to test.txt.

When you open test.txt you will found current path of directory in test.txt

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

You have to set classpath for mysql-connector.jar

In eclipse, use the build path

If you are developing any web app, you have to put mysql-connector to the lib folder of WEB-INF Directory of your web-app

Should image size be defined in the img tag height/width attributes or in CSS?

Definitely not both. Other than that I'd have to say it's a personal preference. I'd use css if I had many images the same size to reduce code.

.my_images img {width: 20px; height:20px}

In the long term CSS may win out due to HTML attribute deprecation and more likely due to the growth of vector image formats like SVG where it can actually make sense to scale images using non-pixel based units like % or em.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:

Bar diagram plot in Excel

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.

How to get substring from string in c#?

Riya,

Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurences:

// add @ to the string to allow split over multiple lines 
// (display purposes to save scroll bar appearing on SO question :))
string strBig = @"Retrieves a substring from this instance. 
            The substring starts at a specified character position. great";

// split the string on the fullstop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
    .Where(x => x.Length > 0).Select(x => x.Trim());

// iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
    Console.WriteLine(subword);
}

enjoy...

What is the strict aliasing rule?

Type punning via pointer casts (as opposed to using a union) is a major example of breaking strict aliasing.

Open text file and program shortcut in a Windows batch file

In some cases, when opening a LNK file it is expecting the end of the application run.

In such cases it is better to use the following syntax (so you do not have to wait the end of the application):

START /B /I "MyTitleApp" "myshortcut.lnk"

To open a TXT file can be in the way already indicated (because notepad.exxe not interrupt the execution of the start command)

START notepad "myfile.txt"

Given two directory trees, how can I find out which files differ by content?

To report differences between dirA and dirB, while also updating/syncing.

rsync -auv <dirA> <dirB>

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

arranging div one below the other

The default behaviour of divs is to take the full width available in their parent container.
This is the same as if you'd give the inner divs a width of 100%.

By floating the divs, they ignore their default and size their width to fit the content. Everything behind it (in the HTML), is placed under the div (on the rendered page).
This is the reason that they align theirselves next to each other.

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/float

Get rid of the float, and the divs will be aligned under each other.
If this does not happen, you'll have some other css on divs or children of wrapper defining a floating behaviour or an inline display.

If you want to keep the float, for whatever reason, you can use clear on the 2nd div to reset the floating properties of elements before that element.
clear has 5 valid values: none | left | right | both | inherit. Clearing no floats (used to override inherited properties), left or right floats or both floats. Inherit means it'll inherit the behaviour of the parent element

Also, because of the default behaviour, you don't need to set the width and height on auto.
You only need this is you want to set a hardcoded height/width. E.g. 80% / 800px / 500em / ...

<div id="wrapper">
    <div id="inner1"></div>
    <div id="inner2"></div>
</div>

CSS is

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; // this is not needed, as parent container, this div will size automaticly
    width:auto; // this is not needed, as parent container, this div will size automaticly
}

/*
You can get rid of the inner divs in the css, unless you want to style them.
If you want to style them identicly, you can use concatenation
*/
#inner1, #inner2 {
    border: 1px solid black;
}

How to find the index of an element in an array in Java?

Simplest solution:

Convert array to list and you can get position of an element.

List<String> abcd  = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");

Other solution, you can iterator array:

int position = 0;
for (String obj : yourArray) {
    if (obj.equals("abcd") {
    return position;
    }
    position += 1;
} 

//OR
for (int i = 0; i < yourArray.length; i++) {
    if (obj.equals("abcd") {
       return i;
    }
}

regular expression for Indian mobile numbers

^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$

Hi, This is regex for indian local mobile number validation and for Indian international .

starting with 9,8,7 you can add more as well.

you can test it using https://regex101.com/

Valid number are.

9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344

Android - Center TextView Horizontally in LinearLayout

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

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:padding="10dp"
    android:text="HELLO WORLD" />

</LinearLayout>

Is there a 'box-shadow-color' property?

Actually… there is! Sort of. box-shadow defaults to color, just like border does.

According to http://dev.w3.org/.../#the-box-shadow

The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.

In practice, you have to change the color property and leave box-shadow without a color:

box-shadow: 1px 2px 3px;
color: #a00;

Support

  • Safari 6+
  • Chrome 20+ (at least)
  • Firefox 13+ (at least)
  • IE9+ (IE8 doesn't support box-shadow at all)

Demo

_x000D_
_x000D_
div {_x000D_
    box-shadow: 0 0 50px;_x000D_
    transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
    color: green;_x000D_
}_x000D_
.red {_x000D_
    color: red;_x000D_
}_x000D_
div:hover {_x000D_
    color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
div {_x000D_
    display: inline-block;_x000D_
    background: white;_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    margin: 30px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
_x000D_
_x000D_

The bug mentioned in the comment below has since been fixed :)

How to find duplicate records in PostgreSQL

In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.

In order to find duplicate values you should run,

SELECT year, COUNT(id)
FROM YOUR_TABLE
GROUP BY year
HAVING COUNT(id) > 1
ORDER BY COUNT(id);

Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.

DELETE
FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
WHERE A.year=B.year AND A.id<B.id;

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

it turns out that I got this error because my requested module is not bundled in the minification prosses due to path misspelling

so make sure that your module exists in minified js file (do search for a word within it to be sure)

Android. WebView and loadData

the answers above doesn't work in my case. You need to specify utf-8 in meta tag

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <!-- you content goes here -->
    </body>
</html>

How to run C program on Mac OS X using Terminal?

To do this:

  1. open terminal

  2. type in the terminal: nano ; which is a text editor available for the terminal. when you do this. something like this would appear.

  3. here you can type in your C program

  4. type in control(^) + x -> which means to exit.

  5. save the file by typing in y to save the file

  6. write the file name; e.g. helloStack.c (don't forget to add .c)

  7. when this appears, type in gcc helloStack.c

  8. then ./a.out: this should give you your result!!

How to run an external program, e.g. notepad, using hyperlink?

I've wrote a small extension to do so.

Since you are creating the page using C# you may want to implement this:

https://github.com/felix-d-git/DesktopAppLink

Basically u are creating some registry entries to parse the links you click in your html page.

The browser will then ask to open the specified app.

C#:

DesktopAppLink.CreateLink("applink.sample", "\"<path to exe>\"", "");

HTML:

<a href="applink.sample:">Run Desktop App</a>

Result:

enter image description here

How do I declare an array variable in VBA?

David, Error comes Microsoft Office Excel has stopped working. Two options check online for a solution and close the programme and other option Close the program I am sure error is in my array but I am reading everything and seem this is way to define arrays.

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

Using multidex support should be the last resort. By default gradle build will collect a ton of transitive dependencies for your APK. As recommended in Google Developers Docs, first attempt to remove unnecessary dependencies from your project.

Using command line navigate to Android Projects Root. You can get the compile dependency tree as follows.

gradlew app:dependencies --configuration debugCompileClasspath

You can get full list of dependency tree

gradlew app:dependencies

enter image description here

Then remove the unnecessary or transitive dependencies from your app build.gradle. As an example if your app uses dependency called 'com.google.api-client' you can exclude the libraries/modules you do not need.

implementation ('com.google.api-client:google-api-client-android:1.28.0'){
   exclude group: 'org.apache.httpcomponents'
   exclude group: 'com.google.guava'
   exclude group: 'com.fasterxml.jackson.core'
   }

Then in Android Studio Select Build > Analyze APK... Select the release/debug APK file to see the contents. This will give you the methods and references count as follows.

Analyze APK

Converting String array to java.util.List

On Java 14 you can do this

List<String> strings = Arrays.asList("one", "two", "three");

nodejs mongodb object id to string

If you're using Mongoose, the only way to be sure to have the id as an hex String seems to be:

object._id ? object._id.toHexString():object.toHexString();

This is because object._id exists only if the object is populated, if not the object is an ObjectId

How do I execute a file in Cygwin?

To execute a file in the current directory, the syntax to use is: ./foo

As mentioned by allain, ./a.exe is the correct way to execute a.exe in the working directory using Cygwin.

Note: You may wish to use the -o parameter to cc to specify your own output filename. An example of this would be: cc helloworld.c -o helloworld.exe.

mysql stored-procedure: out parameter

You must have use correct signature for input parameter *IN is missing in the below code.

CREATE PROCEDURE my_sqrt(IN input_number INT, OUT out_number FLOAT)

How to for each the hashmap?

You can iterate over a HashMap (and many other collections) using an iterator, e.g.:

HashMap<T,U> map = new HashMap<T,U>();

...

Iterator it = map.values().iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}

Using Mysql WHERE IN clause in codeigniter

$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query =  $this->db->get();
return $query->result_array();

Where to place JavaScript in an HTML file?

The Yahoo! Exceptional Performance team recommend placing scripts at the bottom of your page because of the way browsers download components.

Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Make sure to import component in declarations array

@NgModule({
  declarations: [ExampleComponent],
  imports: [
      CommonModule,
      ExampleRoutingModule,
      ReactiveFormsModule
  ]
})

Convert a CERT/PEM certificate to a PFX certificate

I created .pfx file from .key and .pem files.

Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx

That's not the direct answer but still maybe it helps out someone else.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How do you round UP a number in Python?

My share

I have tested print(-(-101 // 5)) = 21 given example above.

Now for rounding up:

101 * 19% = 19.19

I can not use ** so I spread the multiply to division:

(-(-101 //(1/0.19))) = 20

How to find the users list in oracle 11g db?

select * from all_users

This will work for sure

How to deserialize a JObject to .NET object

From the documentation I found this

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

The class definition for Person should be compatible to the following:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

Autoincrement VersionCode with gradle extra properties

To increment versionCode only in release version do it:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    def versionPropsFile = file('version.properties')
    def code = 1;
    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropsFile))
        List<String> runTasks = gradle.startParameter.getTaskNames();
        def value = 0
        for (String item : runTasks)
        if ( item.contains("assembleRelease")) {
            value = 1;
        }
        code = Integer.parseInt(versionProps['VERSION_CODE']).intValue() + value
        versionProps['VERSION_CODE']=code.toString()
        versionProps.store(versionPropsFile.newWriter(), null)
    }
    else {
        throw new GradleException("Could not read version.properties!")
    }

    defaultConfig {
        applicationId "com.pack"
        minSdkVersion 14
        targetSdkVersion 21
        versionName "1.0."+ code
        versionCode code
    }

expects an existing c://YourProject/app/version.properties file, which you would create by hand before the first build to have VERSION_CODE=8

File version.properties:

VERSION_CODE=8

Running sites on "localhost" is extremely slow

Disable the antivirus on the folders where is the code of the web application. In my case I have observed a big improvement with Avast antivirus.

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

How can I change image tintColor in iOS and WatchKit

This is my UIImage extension and you can directly use changeTintColor function for an image.

extension UIImage {

    func changeTintColor(color: UIColor) -> UIImage {
        var newImage = self.withRenderingMode(.alwaysTemplate)
        UIGraphicsBeginImageContextWithOptions(self.size, false, newImage.scale)
        color.set()
        newImage.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
        newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }

    func changeColor(color: UIColor) -> UIImage {
        let backgroundSize = self.size
        UIGraphicsBeginImageContext(backgroundSize)
        guard let context = UIGraphicsGetCurrentContext() else {
            return self
        }
        var backgroundRect = CGRect()
        backgroundRect.size = backgroundSize
        backgroundRect.origin.x = 0
        backgroundRect.origin.y = 0

        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        context.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
        context.translateBy(x: 0, y: backgroundSize.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.clip(to: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height),
                 mask: self.cgImage!)
        context.fill(backgroundRect)

        var imageRect = CGRect()
        imageRect.size = self.size
        imageRect.origin.x = (backgroundSize.width - self.size.width) / 2
        imageRect.origin.y = (backgroundSize.height - self.size.height) / 2

        context.setBlendMode(.multiply)
        context.draw(self.cgImage!, in: imageRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }

}

Example usage like this

let image = UIImage(named: "sample_image")
imageView.image = image.changeTintColor(color: UIColor.red)

And you can use change changeColor function to change the image color

When to use references vs. pointers

Just putting my dime in. I just performed a test. A sneeky one at that. I just let g++ create the assembly files of the same mini-program using pointers compared to using references. When looking at the output they are exactly the same. Other than the symbolnaming. So looking at performance (in a simple example) there is no issue.

Now on the topic of pointers vs references. IMHO I think clearity stands above all. As soon as I read implicit behaviour my toes start to curl. I agree that it is nice implicit behaviour that a reference cannot be NULL.

Dereferencing a NULL pointer is not the problem. it will crash your application and will be easy to debug. A bigger problem is uninitialized pointers containing invalid values. This will most likely result in memory corruption causing undefined behaviour without a clear origin.

This is where I think references are much safer than pointers. And I agree with a previous statement, that the interface (which should be clearly documented, see design by contract, Bertrand Meyer) defines the result of the parameters to a function. Now taking this all into consideration my preferences go to using references wherever/whenever possible.

@selector() in Swift?

you create the Selector like below.
1.

UIBarButtonItem(
    title: "Some Title",
    style: UIBarButtonItemStyle.Done,
    target: self,
    action: "flatButtonPressed"
)

2.

flatButton.addTarget(self, action: "flatButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

Take note that the @selector syntax is gone and replaced with a simple String naming the method to call. There’s one area where we can all agree the verbosity got in the way. Of course, if we declared that there is a target method called flatButtonPressed: we better write one:

func flatButtonPressed(sender: AnyObject) {
  NSLog("flatButtonPressed")
}

set the timer:

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                    target: self, 
                    selector: Selector("flatButtonPressed"), 
                    userInfo: userInfo, 
                    repeats: true)
    let mainLoop = NSRunLoop.mainRunLoop()  //1
    mainLoop.addTimer(timer, forMode: NSDefaultRunLoopMode) //2 this two line is optinal

In order to be complete, here’s the flatButtonPressed

func flatButtonPressed(timer: NSTimer) {
}

Are arrays passed by value or passed by reference in Java?

No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.

How to develop a soft keyboard for Android?

Create Custom Key Board for Own EditText

Download Entire Code

In this post i Created Simple Keyboard which contains Some special keys like ( France keys ) and it's supported Capital letters and small letters and Number keys and some Symbols .

package sra.keyboard;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class Main extends Activity implements OnTouchListener, OnClickListener,
  OnFocusChangeListener {
 private EditText mEt, mEt1; // Edit Text boxes
 private Button mBSpace, mBdone, mBack, mBChange, mNum;
 private RelativeLayout mLayout, mKLayout;
 private boolean isEdit = false, isEdit1 = false;
 private String mUpper = "upper", mLower = "lower";
 private int w, mWindowWidth;
 private String sL[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
   "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
   "x", "y", "z", "ç", "à", "é", "è", "û", "î" };
 private String cL[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
   "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
   "X", "Y", "Z", "ç", "à", "é", "è", "û", "î" };
 private String nS[] = { "!", ")", "'", "#", "3", "$", "%", "&", "8", "*",
   "?", "/", "+", "-", "9", "0", "1", "4", "@", "5", "7", "(", "2",
   "\"", "6", "_", "=", "]", "[", "<", ">", "|" };
 private Button mB[] = new Button[32];

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
   setContentView(R.layout.main);
   // adjusting key regarding window sizes
   setKeys();
   setFrow();
   setSrow();
   setTrow();
   setForow();
   mEt = (EditText) findViewById(R.id.xEt);
   mEt.setOnTouchListener(this);
   mEt.setOnFocusChangeListener(this);
   mEt1 = (EditText) findViewById(R.id.et1);

   mEt1.setOnTouchListener(this);
   mEt1.setOnFocusChangeListener(this);
   mEt.setOnClickListener(this);
   mEt1.setOnClickListener(this);
   mLayout = (RelativeLayout) findViewById(R.id.xK1);
   mKLayout = (RelativeLayout) findViewById(R.id.xKeyBoard);

  } catch (Exception e) {
   Log.w(getClass().getName(), e.toString());
  }

 }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  if (v == mEt) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  if (v == mEt1) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  return true;
 }

 @Override
 public void onClick(View v) {

  if (v == mBChange) {

   if (mBChange.getTag().equals(mUpper)) {
    changeSmallLetters();
    changeSmallTags();
   } else if (mBChange.getTag().equals(mLower)) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  } else if (v != mBdone && v != mBack && v != mBChange && v != mNum) {
   addText(v);

  } else if (v == mBdone) {

   disableKeyboard();

  } else if (v == mBack) {
   isBack(v);
  } else if (v == mNum) {
   String nTag = (String) mNum.getTag();
   if (nTag.equals("num")) {
    changeSyNuLetters();
    changeSyNuTags();
    mBChange.setVisibility(Button.INVISIBLE);

   }
   if (nTag.equals("ABC")) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  }

 }

 @Override
 public void onFocusChange(View v, boolean hasFocus) {
  if (v == mEt && hasFocus == true) {
   isEdit = true;
   isEdit1 = false;

  } else if (v == mEt1 && hasFocus == true) {
   isEdit = false;
   isEdit1 = true;

  }

 }

 private void addText(View v) {
  if (isEdit == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt.append(b);

   }
  }

  if (isEdit1 == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt1.append(b);

   }

  }

 }

 private void isBack(View v) {
  if (isEdit == true) {
   CharSequence cc = mEt.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt.setText("");
     mEt.append(cc.subSequence(0, cc.length() - 1));
    }

   }
  }

  if (isEdit1 == true) {
   CharSequence cc = mEt1.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt1.setText("");
     mEt1.append(cc.subSequence(0, cc.length() - 1));
    }
   }
  }
 }
 private void changeSmallLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < sL.length; i++)
   mB[i].setText(sL[i]);
  mNum.setTag("12#");
 }
 private void changeSmallTags() {
  for (int i = 0; i < sL.length; i++)
   mB[i].setTag(sL[i]);
  mBChange.setTag("lower");
  mNum.setTag("num");
 }
 private void changeCapitalLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < cL.length; i++)
   mB[i].setText(cL[i]);
  mBChange.setTag("upper");
  mNum.setText("12#");

 }

 private void changeCapitalTags() {
  for (int i = 0; i < cL.length; i++)
   mB[i].setTag(cL[i]);
  mNum.setTag("num");

 }

 private void changeSyNuLetters() {

  for (int i = 0; i < nS.length; i++)
   mB[i].setText(nS[i]);
  mNum.setText("ABC");
 }

 private void changeSyNuTags() {
  for (int i = 0; i < nS.length; i++)
   mB[i].setTag(nS[i]);
  mNum.setTag("ABC");
 }

 // enabling customized keyboard
 private void enableKeyboard() {

  mLayout.setVisibility(RelativeLayout.VISIBLE);
  mKLayout.setVisibility(RelativeLayout.VISIBLE);

 }

 // Disable customized keyboard
 private void disableKeyboard() {
  mLayout.setVisibility(RelativeLayout.INVISIBLE);
  mKLayout.setVisibility(RelativeLayout.INVISIBLE);

 }

 private void hideDefaultKeyboard() {
  getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

 }

 private void setFrow() {
  w = (mWindowWidth / 13);
  w = w - 15;
  mB[16].setWidth(w);
  mB[22].setWidth(w + 3);
  mB[4].setWidth(w);
  mB[17].setWidth(w);
  mB[19].setWidth(w);
  mB[24].setWidth(w);
  mB[20].setWidth(w);
  mB[8].setWidth(w);
  mB[14].setWidth(w);
  mB[15].setWidth(w);
  mB[16].setHeight(50);
  mB[22].setHeight(50);
  mB[4].setHeight(50);
  mB[17].setHeight(50);
  mB[19].setHeight(50);
  mB[24].setHeight(50);
  mB[20].setHeight(50);
  mB[8].setHeight(50);
  mB[14].setHeight(50);
  mB[15].setHeight(50);

 }

 private void setSrow() {
  w = (mWindowWidth / 10);
  mB[0].setWidth(w);
  mB[18].setWidth(w);
  mB[3].setWidth(w);
  mB[5].setWidth(w);
  mB[6].setWidth(w);
  mB[7].setWidth(w);
  mB[26].setWidth(w);
  mB[9].setWidth(w);
  mB[10].setWidth(w);
  mB[11].setWidth(w);
  mB[26].setWidth(w);

  mB[0].setHeight(50);
  mB[18].setHeight(50);
  mB[3].setHeight(50);
  mB[5].setHeight(50);
  mB[6].setHeight(50);
  mB[7].setHeight(50);
  mB[9].setHeight(50);
  mB[10].setHeight(50);
  mB[11].setHeight(50);
  mB[26].setHeight(50);
 }

 private void setTrow() {
  w = (mWindowWidth / 12);
  mB[25].setWidth(w);
  mB[23].setWidth(w);
  mB[2].setWidth(w);
  mB[21].setWidth(w);
  mB[1].setWidth(w);
  mB[13].setWidth(w);
  mB[12].setWidth(w);
  mB[27].setWidth(w);
  mB[28].setWidth(w);
  mBack.setWidth(w);

  mB[25].setHeight(50);
  mB[23].setHeight(50);
  mB[2].setHeight(50);
  mB[21].setHeight(50);
  mB[1].setHeight(50);
  mB[13].setHeight(50);
  mB[12].setHeight(50);
  mB[27].setHeight(50);
  mB[28].setHeight(50);
  mBack.setHeight(50);

 }

 private void setForow() {
  w = (mWindowWidth / 10);
  mBSpace.setWidth(w * 4);
  mBSpace.setHeight(50);
  mB[29].setWidth(w);
  mB[29].setHeight(50);

  mB[30].setWidth(w);
  mB[30].setHeight(50);

  mB[31].setHeight(50);
  mB[31].setWidth(w);
  mBdone.setWidth(w + (w / 1));
  mBdone.setHeight(50);

 }

 private void setKeys() {
  mWindowWidth = getWindowManager().getDefaultDisplay().getWidth(); // getting
  // window
  // height
  // getting ids from xml files
  mB[0] = (Button) findViewById(R.id.xA);
  mB[1] = (Button) findViewById(R.id.xB);
  mB[2] = (Button) findViewById(R.id.xC);
  mB[3] = (Button) findViewById(R.id.xD);
  mB[4] = (Button) findViewById(R.id.xE);
  mB[5] = (Button) findViewById(R.id.xF);
  mB[6] = (Button) findViewById(R.id.xG);
  mB[7] = (Button) findViewById(R.id.xH);
  mB[8] = (Button) findViewById(R.id.xI);
  mB[9] = (Button) findViewById(R.id.xJ);
  mB[10] = (Button) findViewById(R.id.xK);
  mB[11] = (Button) findViewById(R.id.xL);
  mB[12] = (Button) findViewById(R.id.xM);
  mB[13] = (Button) findViewById(R.id.xN);
  mB[14] = (Button) findViewById(R.id.xO);
  mB[15] = (Button) findViewById(R.id.xP);
  mB[16] = (Button) findViewById(R.id.xQ);
  mB[17] = (Button) findViewById(R.id.xR);
  mB[18] = (Button) findViewById(R.id.xS);
  mB[19] = (Button) findViewById(R.id.xT);
  mB[20] = (Button) findViewById(R.id.xU);
  mB[21] = (Button) findViewById(R.id.xV);
  mB[22] = (Button) findViewById(R.id.xW);
  mB[23] = (Button) findViewById(R.id.xX);
  mB[24] = (Button) findViewById(R.id.xY);
  mB[25] = (Button) findViewById(R.id.xZ);
  mB[26] = (Button) findViewById(R.id.xS1);
  mB[27] = (Button) findViewById(R.id.xS2);
  mB[28] = (Button) findViewById(R.id.xS3);
  mB[29] = (Button) findViewById(R.id.xS4);
  mB[30] = (Button) findViewById(R.id.xS5);
  mB[31] = (Button) findViewById(R.id.xS6);
  mBSpace = (Button) findViewById(R.id.xSpace);
  mBdone = (Button) findViewById(R.id.xDone);
  mBChange = (Button) findViewById(R.id.xChange);
  mBack = (Button) findViewById(R.id.xBack);
  mNum = (Button) findViewById(R.id.xNum);
  for (int i = 0; i < mB.length; i++)
   mB[i].setOnClickListener(this);
  mBSpace.setOnClickListener(this);
  mBdone.setOnClickListener(this);
  mBack.setOnClickListener(this);
  mBChange.setOnClickListener(this);
  mNum.setOnClickListener(this);

 }

}

Programmatically get own phone number in iOS

Update: capability appears to have been removed by Apple on or around iOS 4


Just to expand on an earlier answer, something like this does it for me:

NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];

Note: This retrieves the "Phone number" that was entered during the iPhone's iTunes activation and can be null or an incorrect value. It's NOT read from the SIM card.

At least that does in 2.1. There are a couple of other interesting keys in NSUserDefaults that may also not last. (This is in my app which uses a UIWebView)

WebKitJavaScriptCanOpenWindowsAutomatically
NSInterfaceStyle
TVOutStatus
WebKitDeveloperExtrasEnabledPreferenceKey

and so on.

Not sure what, if anything, the others do.

Rank function in MySQL

While the most upvoted answer ranks, it doesn't partition, You can do a self Join to get the whole thing partitioned also:

SELECT    a.first_name,
      a.age,
      a.gender,
        count(b.age)+1 as rank
FROM  person a left join person b on a.age>b.age and a.gender=b.gender 
group by  a.first_name,
      a.age,
      a.gender

Use Case

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');

Answer:

Bill    32  M   4
Bob     25  M   2
Jack    30  M   3
Nick    22  M   1
Steve   36  M   5
Anne    25  F   3
Jane    20  F   2
Kathy   18  F   1

How to create EditText accepts Alphabets only in android?

For spaces, you can add single space in the digits. If you need any special characters like the dot, a comma also you can add to this list

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "

What is the { get; set; } syntax in C#?

Basically, it's a shortcut of:

class Genre{
    private string genre;
    public string getGenre() {
        return this.genre;
    }
    public void setGenre(string theGenre) {
        this.genre = theGenre;
    }
}
//In Main method
genre g1 = new Genre();
g1.setGenre("Female");
g1.getGenre(); //Female

What do all of Scala's symbolic operators mean?

You can group those first according to some criteria. In this post I will just explain the underscore character and the right-arrow.

_._ contains a period. A period in Scala always indicates a method call. So left of the period you have the receiver, and right of it the message (method name). Now _ is a special symbol in Scala. There are several posts about it, for example this blog entry all use cases. Here it is an anonymous function short cut, that is it a shortcut for a function that takes one argument and invokes the method _ on it. Now _ is not a valid method, so most certainly you were seeing _._1 or something similar, that is, invoking method _._1 on the function argument. _1 to _22 are the methods of tuples which extract a particular element of a tuple. Example:

val tup = ("Hallo", 33)
tup._1 // extracts "Hallo"
tup._2 // extracts 33

Now lets assume a use case for the function application shortcut. Given a map which maps integers to strings:

val coll = Map(1 -> "Eins", 2 -> "Zwei", 3 -> "Drei")

Wooop, there is already another occurrence of a strange punctuation. The hyphen and greater-than characters, which resemble a right-hand arrow, is an operator which produces a Tuple2. So there is no difference in the outcome of writing either (1, "Eins") or 1 -> "Eins", only that the latter is easier to read, especially in a list of tuples like the map example. The -> is no magic, it is, like a few other operators, available because you have all implicit conversions in object scala.Predef in scope. The conversion which takes place here is

implicit def any2ArrowAssoc [A] (x: A): ArrowAssoc[A] 

Where ArrowAssoc has the -> method which creates the Tuple2. Thus 1 -> "Eins" is actual the call Predef.any2ArrowAssoc(1).->("Eins"). Ok. Now back to the original question with the underscore character:

// lets create a sequence from the map by returning the
// values in reverse.
coll.map(_._2.reverse) // yields List(sniE, iewZ, ierD)

The underscore here shortens the following equivalent code:

coll.map(tup => tup._2.reverse)

Note that the map method of a Map passes in the tuple of key and value to the function argument. Since we are only interested in the values (the strings), we extract them with the _2 method on the tuple.

Angular 2: How to access an HTTP response body?

Here is an example to access response body using angular2 built in Response

import { Injectable } from '@angular/core';
import {Http,Response} from '@angular/http';

@Injectable()
export class SampleService {
  constructor(private http:Http) { }

  getData(){

    this.http.get(url)
   .map((res:Response) => (
       res.json() //Convert response to JSON
       //OR
       res.text() //Convert response to a string
   ))
   .subscribe(data => {console.log(data)})

  }
}

How to make child divs always fit inside parent div?

In your example, you can't: the 5px margin is added to the bounding box of div#two and div#three effectively making their width and height 100% of parent + 5px, which will overflow.

You can use padding on the parent Element to ensure there's 5px of space inside its border:

<style>
    html, body {width:100%;height:100%;margin:0;padding:0;}
    .border {border:1px solid black;}
    #one {padding:5px;width:500px;height:300px;}
    #two {width:100%;height:50px;}
    #three {width:100px;height:100%;}
</style>

EDIT: In testing, removing the width:100% from div#two will actually let it work properly as divs are block-level and will always fill their parents' widths by default. That should clear your first case if you'd like to use margin.

Rename multiple files in a folder, add a prefix (Windows)

The problem with the two Powershell answers here is that the prefix can end up being duplicated since the script will potentially run over the file both before and after it has been renamed, depending on the directory being resorted as the renaming process runs. To get around this, simply use the -Exclude option:

Get-ChildItem -Exclude "house chores-*" | rename-item -NewName { "house chores-" + $_.Name }

This will prevent the process from renaming any one file more than once.

How to get the values of a ConfigurationSection of type NameValueSectionHandler

This is an old question, but I use the following class to do the job. It's based on Scott Dorman's blog:

public class NameValueCollectionConfigurationSection : ConfigurationSection
{
    private const string COLLECTION_PROP_NAME = "";

    public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
    {
        foreach ( string key in this.ConfigurationCollection.AllKeys )
        {
            NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
            yield return new KeyValuePair<string, string>
                (confElement.Name, confElement.Value);
        }
    }

    [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
    protected NameValueConfigurationCollection ConfCollection
    {
        get
        {
            return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];
        }
    }

The usage is straightforward:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config = 
    (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");

NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));

Unit testing private methods in C#

Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)

It seem that you need extract to the private method to another class; in this should be public. Instead of trying to test on the private method, you should test public method of this another class.

We has the following scenario:

Class A
+ outputFile: Stream
- _someLogic(arg1, arg2) 

We need to test the logic of _someLogic; but it seem that Class A take more role than it need(violate the SRP principle); just refactor into two classes

Class A1
    + A1(logicHandler: A2) # take A2 for handle logic
    + outputFile: Stream
Class A2
    + someLogic(arg1, arg2) 

In this way someLogic could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic.

Check if an element is present in a Bash array

As bash does not have a built-in value in array operator and the =~ operator or the [[ "${array[@]" == *"${item}"* ]] notation keep confusing me, I usually combine grep with a here-string:

colors=('black' 'blue' 'light green')
if grep -q 'black' <<< "${colors[@]}"
then
    echo 'match'
fi

Beware however that this suffers from the same false positives issue as many of the other answers that occurs when the item to search for is fully contained, but is not equal to another item:

if grep -q 'green' <<< "${colors[@]}"
then
    echo 'should not match, but does'
fi

If that is an issue for your use case, you probably won't get around looping over the array:

for color in "${colors[@]}"
do
    if [ "${color}" = 'green' ]
    then
        echo "should not match and won't"
        break
    fi
done

for color in "${colors[@]}"
do
    if [ "${color}" = 'light green' ]
    then
        echo 'match'
        break
    fi
done

Is PowerShell ready to replace my Cygwin shell on Windows?

I am not a very experienced PowerShell user by any means, but the little bit of it that I was exposed to impressed me a great deal. You can chain the built-in cmdlets together to do just about anything that you could do at a Unix prompt, and there's some additional goodness for doing things like exporting to CSV, HTML tables, and for more in-depth system administration types of jobs.

And if you really needed something like sed, there's always UnixUtils or GnuWin32, which you could integrate with PowerShell fairly easily.

As a longtime Unix user, I did however have a bit of trouble getting used to the command naming scheme, and I certainly would have benefitted more from it if I knew more .NET.

So essentially, I say it's well worth learning it if the Windows-only-ness of it doesn't pose a problem.

How can I check if the array of objects have duplicate property values?

You can use map to return just the name, and then use this forEach trick to check if it exists at least twice:

var areAnyDuplicates = false;

values.map(function(obj) {
    return obj.name;
}).forEach(function (element, index, arr) {
    if (arr.indexOf(element) !== index) {
        areAnyDuplicates = true;
    }
});

Fiddle

What does the percentage sign mean in Python

x % n == 0
which means the x/n and the value of reminder will taken as a result and compare with zero....

example: 4/5==0

4/5 reminder is 4

4==0 (False)

how to access parent window object using jquery?

Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:

window.parent.$("#serverMsg")

Why can't I inherit static classes?

Hmmm... would it be much different if you just had non-static classes filled with static methods..?

Attaching click event to a JQuery object not yet added to the DOM

Maybe bind() would help:

button.bind('click', function() {
  alert('User clicked');
});

How do I change the default application icon in Java?

You can try this one, it works just fine :

`   ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
    this.setIconImage(icon.getImage());`

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EmailComposer } from '@ionic-native/email-composer';

@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})
export class AboutPage {
  sendObj = {
    to: '',
    cc: '',
    bcc: '',
    attachments:'',
    subject:'',
    body:''
  }

  constructor(public navCtrl: NavController,private emailComposer: EmailComposer) {}

  sendEmail(){
  let email = {
    to: this.sendObj.to,
    cc: this.sendObj.cc,
    bcc: this.sendObj.bcc,
    attachments: [this.sendObj.attachments],
    subject: this.sendObj.subject,
    body: this.sendObj.body,
    isHtml: true
  }; 
  this.emailComposer.open(email);
  }  
 }

starts here html about

<ion-header>
  <ion-navbar>
    <ion-title>
      Send Invoice
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label stacked>To</ion-label>
    <ion-input [(ngModel)]="sendObj.to"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>CC</ion-label>
    <ion-input [(ngModel)]="sendObj.cc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>BCC</ion-label>
    <ion-input [(ngModel)]="sendObj.bcc"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Add pdf</ion-label>
    <ion-input [(ngModel)]="sendObj.attachments" type="file"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Subject</ion-label>
    <ion-input [(ngModel)]="sendObj.subject"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label stacked>Text message</ion-label>
    <ion-input [(ngModel)]="sendObj.body"></ion-input>
  </ion-item>

  <button ion-button full (click)="sendEmail()">Send Email</button>

</ion-content>


other stuff here

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { EmailComposer } from '@ionic-native/email-composer';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    EmailComposer,
    {provide: ErrorHandler, useClass: IonicErrorHandler},  
    File,
    FileOpener
  ]
})
export class AppModule {}

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

The MDN Documentation is very eloquent and features examples.

Get names of all keys in the collection

I know this question is 10 years old but there is no C# solution and this took me hours to figure out. I'm using the .NET driver and System.Linq to return a list of the keys.

var map = new BsonJavaScript("function() { for (var key in this) { emit(key, null); } }");
var reduce = new BsonJavaScript("function(key, stuff) { return null; }");
var options = new MapReduceOptions<BsonDocument, BsonDocument>();
var result = await collection.MapReduceAsync(map, reduce, options);
var list = result.ToEnumerable().Select(item => item["_id"].ToString());

Escaping ampersand character in SQL string

You can use

set define off

Using this it won't prompt for the input

For loop example in MySQL

Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below

CREATE TABLE `table1` (
    `col1` VARCHAR(50) NULL DEFAULT NULL
)

Now if you want to insert number from 1 to 50 in that table then use following stored procedure

DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      DECLARE a INT Default 1 ;
      simple_loop: LOOP         
         insert into table1 values(a);
         SET a=a+1;
         IF a=51 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

To call that stored procedure use

CALL `ABC`()

No provider for HttpClient

Go to app.module.ts

import import { HttpClientModule } from '@angular/common/http';

AND

Add HttpClientModule under imports

should look like this

imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule]

Dead simple example of using Multiprocessing Queue, Pool and Locking

For everyone using editors like Komodo Edit (win10) add sys.stdout.flush() to:

def mp_worker((inputs, the_time)):
    print " Process %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs
    sys.stdout.flush()

or as first line to:

    if __name__ == '__main__':
       sys.stdout.flush()

This helps to see what goes on during the run of the script; in stead of having to look at the black command line box.

Reading a JSP variable from JavaScript

   <% String s="Hi"; %>
   var v ="<%=s%>"; 

How I can get and use the header file <graphics.h> in my C++ program?

There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.

I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).

When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.

MySQL Query GROUP BY day / month / year

I wanted to get similar data per day, after experimenting a bit, this is the fastest I could find for my scenario

SELECT COUNT(id)
FROM stats
GROUP BY record_date DIV 1000000;

If you want to have it per month, add additional zeroes (00) I would not recommend this since it is not clear why or how this works, it might also break in different versions. But in our case this took less then half the time compared to some other more clearer queries that I tested.

Incrementing a variable inside a Bash loop

while read -r country _; do
  if [[ $country = 'US' ]]; then
    ((USCOUNTER++))
    echo "US counter $USCOUNTER"
  fi
done < "$FILE"

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

How to return part of string before a certain character?

You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:

str.substring(0, str.indexOf(":"));

Where 'str' represents the variable with your string inside.

Click here for JSFiddle Example

Javascript

var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');

var left_text = input_string.substring(0, input_string.indexOf(":"));

output_element.innerText = left_text;

Html

<p>
  <h5>Input:</h5>
  <strong id="my-input">Left Text:Right Text</strong>
  <h5>Output:</h5>
  <strong id="my-output">XXX</strong>
</p>

CSS

body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
  width:90%;
  padding: 0.5em 1em;
  background-color: cyan;
}
#my-output { background-color: gold; }

jQuery events .load(), .ready(), .unload()

NOTE: .load() & .unload() have been deprecated


$(window).load();

Will execute after the page along with all its contents are done loading. This means that all images, CSS (and content defined by CSS like custom fonts and images), scripts, etc. are all loaded. This happens event fires when your browser's "Stop" -icon becomes gray, so to speak. This is very useful to detect when the document along with all its contents are loaded.

$(document).ready();

This on the other hand will fire as soon as the web browser is capable of running your JavaScript, which happens after the parser is done with the DOM. This is useful if you want to execute JavaScript as soon as possible.

$(window).unload();

This event will be fired when you are navigating off the page. That could be Refresh/F5, pressing the previous page button, navigating to another website or closing the entire tab/window.

To sum up, ready() will be fired before load(), and unload() will be the last to be fired.

How does the compilation/linking process work?

The skinny is that a CPU loads data from memory addresses, stores data to memory addresses, and execute instructions sequentially out of memory addresses, with some conditional jumps in the sequence of instructions processed. Each of these three categories of instructions involves computing an address to a memory cell to be used in the machine instruction. Because machine instructions are of a variable length depending on the particular instruction involved, and because we string a variable length of them together as we build our machine code, there is a two step process involved in calculating and building any addresses.

First we laying out the allocation of memory as best we can before we can know what exactly goes in each cell. We figure out the bytes, or words, or whatever that form the instructions and literals and any data. We just start allocating memory and building the values that will create the program as we go, and note down anyplace we need to go back and fix an address. In that place we put a dummy to just pad the location so we can continue to calculate memory size. For example our first machine code might take one cell. The next machine code might take 3 cells, involving one machine code cell and two address cells. Now our address pointer is 4. We know what goes in the machine cell, which is the op code, but we have to wait to calculate what goes in the address cells till we know where that data will be located, i.e. what will be the machine address of that data.

If there were just one source file a compiler could theoretically produce fully executable machine code without a linker. In a two pass process it could calculate all of the actual addresses to all of the data cells referenced by any machine load or store instructions. And it could calculate all of the absolute addresses referenced by any absolute jump instructions. This is how simpler compilers, like the one in Forth work, with no linker.

A linker is something that allows blocks of code to be compiled separately. This can speed up the overall process of building code, and allows some flexibility with how the blocks are later used, in other words they can be relocated in memory, for example adding 1000 to every address to scoot the block up by 1000 address cells.

So what the compiler outputs is rough machine code that is not yet fully built, but is laid out so we know the size of everything, in other words so we can start to calculate where all of the absolute addresses will be located. the compiler also outputs a list of symbols which are name/address pairs. The symbols relate a memory offset in the machine code in the module with a name. The offset being the absolute distance to the memory location of the symbol in the module.

That's where we get to the linker. The linker first slaps all of these blocks of machine code together end to end and notes down where each one starts. Then it calculates the addresses to be fixed by adding together the relative offset within a module and the absolute position of the module in the bigger layout.

Obviously I've oversimplified this so you can try to grasp it, and I have deliberately not used the jargon of object files, symbol tables, etc. which to me is part of the confusion.

What is a CSRF token? What is its importance and how does it work?

The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.

How to compare types

You can compare for exactly the same type using:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof returns the Type object from a given class.

But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

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

From Save MySQL query results into a text or CSV file:

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders

which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

Syntax

   SELECT Your_Column_Name
    FROM Your_Table_Name
    INTO OUTFILE 'Filename.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Or you could try to grab the output via the client:

You could try executing the query from the your local client and redirect the output to a local file destination:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

How to "inverse match" with regex?

In perl you can do

process($line) if ($line =~ !/Andrea/);

How do I query between two dates using MySQL?

Is date_field of type datetime? Also you need to put the eariler date first.

It should be:

SELECT * FROM `objects` 
WHERE  (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')

Modulo operator in Python

When you have the expression:

a % b = c

It really means there exists an integer n that makes c as small as possible, but non-negative.

a - n*b = c

By hand, you can just subtract 2 (or add 2 if your number is negative) over and over until the end result is the smallest positive number possible:

  3.14 % 2
= 3.14 - 1 * 2
= 1.14

Also, 3.14 % 2 * pi is interpreted as (3.14 % 2) * pi. I'm not sure if you meant to write 3.14 % (2 * pi) (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).

How to use lodash to find and return an object from Array?

You don't need Lodash or Ramda or any other extra dependency.

Just use the ES6 find() function in a functional way:

savedViews.find(el => el.description === view)

Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:

  • bloat your bundled code size,
  • you will have to keep them up to date,
  • and they can introduce bugs or security risks

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Converting java date to Sql timestamp

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This gives me the following output:

 utilDate:Fri Apr 04 12:07:37 MSK 2014
 sqlDate:2014-04-04

HTML Canvas Full Screen

You could just capture window resize events and set the size of your canvas to be the browser's viewport.

web.xml is missing and <failOnMissingWebXml> is set to true

You can also do this which is less verbose

<properties>
    <failOnMissingWebXml>false</failOnMissingWebXml>
</properties>

What is the canonical way to trim a string in Ruby without creating a new string?

My way:

> (@title = " abc ").strip!
 => "abc" 
> @title
 => "abc"