Programs & Examples On #Entity sql

Entity SQL is a storage-independent query language that is similar to SQL.

Use jQuery to hide a DIV when the user clicks outside of it

Instead of listening to every single click on the DOM to hide one specific element, you could set tabindex to the parent <div> and listen to the focusout events.

Setting tabindex will make sure that the blur event is fired on the <div> (normally it wouldn't).

So your HTML would look like:

<div class="form_wrapper" tabindex="0">
    <a class="agree" href="javascript:;">I Agree</a>
    <a class="disagree" href="javascript:;">Disagree</a>
</div>

And your JS:

$('.form_wrapper').on('focusout', function(event){
    $('.form_wrapper').hide();
});

Apache and IIS side by side (both listening to port 80) on windows2003

I see this is quite an old post, but came across this looking for an answer for this problem. After reading some of the answers they seem very long winded, so after about 5 mins I managed to solve the problem very simply as follows:

httpd.conf for Apache leave the listen port as 80 and 'Server Name' as FQDN/IP :80.

Now for IIS go to Administrative Services > IIS Manager > 'Sites' in the Left hand nav drop down > in the right window select the top line (default web site) then bindings on the right.

Now select http > edit and change to 81 and enter your local IP for the server/pc and in domain enter either your FQDN (www.domain.com) or external IP close.

Restart both servers ensure your ports are open on both router and firewall, done.

This sounds long winded but literally took 5 mins of playing about. works perfectly.

System: Windows 8, IIS 8, Apache 2.2

Pro JavaScript programmer interview questions (with answers)

Basic JS programmming

  • Scope of variable
  • What is Associative Array? How do we use it?

OOPS JS

  • Difference between Classic Inheritance and Prototypical Inheritance
  • What is difference between private variable, public variable and static variable? How we achieve this in JS?
  • How to add/remove properties to object in run time?
  • How to achieve inheritance ?
  • How to extend built-in objects?
  • Why extending array is bad idea?

DOM and JS

  • Difference between browser detection and feature detection
  • DOM Event Propagation
  • Event Delegation
  • Event bubbling V/s Event Capturing

Misc

  • Graceful Degradation V/s Progressive Enhancement

How to Convert datetime value to yyyymmddhhmmss in SQL server?

20090320093349

SELECT CONVERT(VARCHAR,@date,112) + 
LEFT(REPLACE(CONVERT(VARCHAR,@date,114),':',''),6)

How to add a RequiredFieldValidator to DropDownList control?

Suppose your drop down list is:

<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>

There are two ways:

<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />

the 2nd way is to use a compare validator:

<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

To use an identity column in v10,

ALTER TABLE test 
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;

For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.

For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.

For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

public static String getCurrentTimezoneOffset() {

    TimeZone tz = TimeZone.getDefault();  
    Calendar cal = GregorianCalendar.getInstance(tz);
    int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
    offset = (offsetInMillis >= 0 ? "+" : "-") + offset;

    return offset;
}

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

How to get the mysql table columns data type?

First select the Database using use testDB; then execute

desc `testDB`.`images`;
-- or
SHOW FIELDS FROM images;

Output:

Get Table Columns with DataTypes

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

This happened to me after upgrading from angular 1.6 -> 1.7 when using $sce.trustAsResourceUrl() as the return value of a function called from ng-src. You can see this issue mentioned here.

In my case I had to change the following.

<source ng-src="{{trustSrc(someUrl)}}" type='video/mp4' />
trustSrc = function(url){
    return $sce.trustAsResourceUrl(url);
};

to

<source ng-src='{{trustedUrl}} type='video/mp4' />
trustedUrl = $sce.trustAsResourceUrl(someUrl);

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

Can we pass parameters to a view in SQL?

You can bypass just to run the view, SQL will wine and cry but just do this and run it! You can't save.

create or replace view v_emp(eno number) as select * from emp where (emp_id = @Parameter1);

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

Node - how to run app.js?

you have a package.json file that shows the main configuration of your project, and a lockfile that contains the full details of your project configuration such as the urls that holds each of the package or libraries used in your project at the root folder of the project......

npm is the default package manager for Node.js.... All you need to do is call $ npm install from the terminal in the root directory where you have the package.json and lock file ...since you are not adding any particular package to be install ..... it will go through the lock file and download one after the other, the required packages from their urls written in the lock file if it isnt present in the project enviroment .....

you make sure you edit your package.json file .... to give an entry point to your app..... "name":"app.js" where app.js is the main script .. or index.js depending on the project naming convention...

then you can run..$ Node app.js or $ npm start if your package.json scripts has a start field config as such "scripts": { "start": "Node index.js", "test": "test" }..... which is indirectly still calling your $ Node app.js

How can I override Bootstrap CSS styles?

If you are planning to make any rather big changes, it might be a good idea to make them directly in bootstrap itself and rebuild it. Then, you could reduce the amount of data loaded.

Please refer to Bootstrap on GitHub for the build guide.

Update Top 1 record in table sql server

WITH UpdateList_view AS (
  SELECT TOP 1  * from TX_Master_PCBA 
  WHERE SERIAL_NO IN ('0500030309') 
  ORDER BY TIMESTAMP2 DESC 
)

update UpdateList_view 
set TIMESTAMP2 = '2013-12-12 15:40:31.593'

From Now() to Current_timestamp in Postgresql

Here is what the MySQL docs say about NOW():

Returns the current date and time as a value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

mysql> SELECT NOW();
        -> '2007-12-15 23:50:26'
mysql> SELECT NOW() + 0;
        -> 20071215235026.000000

Now, you can certainly reduce your smart date to something less...

SELECT (
 date_part('year', NOW())::text
 || date_part('month', NOW())::text
 || date_part('day', NOW())::text
 || date_part('hour', NOW())::text
 || date_part('minute', NOW())::text
 || date_part('second', NOW())::text
)::float8 + foo;

But, that would be a really bad idea, what you need to understand is that times and dates are not stupid unformated numbers, they are their own type with their own set of functions and operators

So the MySQL time essentially lets you treat NOW() as a dumber type, or it overrides + to make a presumption that I can't find in the MySQL docs. Eitherway, you probably want to look at the date and interval types in pg.

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

How to trigger a click on a link using jQuery

You should call the element's native .click() method or use the createEvent API.

For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/

How to find memory leak in a C++ code/project?

  1. Download Debugging Tools for Windows.
  2. Use the gflags utility to turn on user-mode stack traces.
  3. Use UMDH to take multiple snapshots of your program's memory. Take a snapshot before memory gets allocated, and take a second snapshot after a point at which you believe that your program has leaked memory. You might want to add pauses or prompts in your program to give you a chance to run UMDH and take the snapshots.
  4. Run UMDH again, this time in its mode that does a diff between the two snapshots. It will then generate a report containing the call stacks of suspected memory leaks.
  5. Restore your previous gflags settings when you're done.

UMDH will give you more information than the CRT debug heap because it is watching memory allocations across your entire process; it can even tell you if third-party components are leaking.

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

How to get the last char of a string in PHP?

Or by direct string access:

$string[strlen($string)-1];

Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.

As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];

CSS Selector for <input type="?"

You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.

Just refresh the port in your ajax url string to the appropriate one.

conn = new WebSocket('ws://localhost:3030'); //should solve the issue

Show/hide widgets in Flutter programmatically

As already highlighted by @CopsOnRoad, you can use the Visibility widget. But, if you want to keep its state, for example, if you want to build a viewpager and make a certain button appear and disappear based on the page, you can do it this way

void checkVisibilityButton() {
  setState(() {
  isVisibileNextBtn = indexPage + 1 < pages.length;
  });
}    

 Stack(children: <Widget>[
      PageView.builder(
        itemCount: pages.length,
        onPageChanged: (index) {
          indexPage = index;
          checkVisibilityButton();
        },
        itemBuilder: (context, index) {
          return pages[index];
        },
        controller: controller,
      ),
      Container(
        alignment: Alignment.bottomCenter,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            Visibility(
              visible: isVisibileNextBtn,
              child: "your widget"
            )
          ],
        ),
      )
    ]))

Why std::cout instead of simply cout?

Everything in the Standard Template/Iostream Library resides in namespace std. You've probably used:

using namespace std;

In your classes, and that's why it worked.

What is the best way to repeatedly execute a function every x seconds?

Here's an adapted version to the code from MestreLion. In addition to the original function, this code:

1) add first_interval used to fire the timer at a specific time(caller need to calculate the first_interval and pass in)

2) solve a race-condition in original code. In the original code, if control thread failed to cancel the running timer("Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage." quoted from https://docs.python.org/2/library/threading.html), the timer will run endlessly.

class RepeatedTimer(object):
def __init__(self, first_interval, interval, func, *args, **kwargs):
    self.timer      = None
    self.first_interval = first_interval
    self.interval   = interval
    self.func   = func
    self.args       = args
    self.kwargs     = kwargs
    self.running = False
    self.is_started = False

def first_start(self):
    try:
        # no race-condition here because only control thread will call this method
        # if already started will not start again
        if not self.is_started:
            self.is_started = True
            self.timer = Timer(self.first_interval, self.run)
            self.running = True
            self.timer.start()
    except Exception as e:
        log_print(syslog.LOG_ERR, "timer first_start failed %s %s"%(e.message, traceback.format_exc()))
        raise

def run(self):
    # if not stopped start again
    if self.running:
        self.timer = Timer(self.interval, self.run)
        self.timer.start()
    self.func(*self.args, **self.kwargs)

def stop(self):
    # cancel current timer in case failed it's still OK
    # if already stopped doesn't matter to stop again
    if self.timer:
        self.timer.cancel()
    self.running = False

How can I introduce multiple conditions in LIKE operator?

Oracle 10g has functions that allow the use of POSIX-compliant regular expressions in SQL:

  • REGEXP_LIKE
  • REGEXP_REPLACE
  • REGEXP_INSTR
  • REGEXP_SUBSTR

See the Oracle Database SQL Reference for syntax details on this functions.

Take a look at Regular expressions in Perl with examples.

Code :

    select * from tbl where regexp_like(col, '^(ABC|XYZ|PQR)');

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

I'm not sure, but I think the string stores its info as an array of Chars, which is inefficient with bytes. Specifically, the definition of a Char is "Represents a Unicode character".

take this example sample:

String str = "asdf éß";
String str2 = "asdf gh";
EncodingInfo[] info =  Encoding.GetEncodings();
foreach (EncodingInfo enc in info)
{
    System.Console.WriteLine(enc.Name + " - " 
      + enc.GetEncoding().GetByteCount(str)
      + enc.GetEncoding().GetByteCount(str2));
}

Take note that the Unicode answer is 14 bytes in both instances, whereas the UTF-8 answer is only 9 bytes for the first, and only 7 for the second.

So if you just want the bytes used by the string, simply use Encoding.Unicode, but it will be inefficient with storage space.

Restart container within pod

The whole reason for having kubernetes is so it manages the containers for you so you don't have to care so much about the lifecyle of the containers in the pod.

Since you have a deployment setup that uses replica set. You can delete the pod using kubectl delete pod test-1495806908-xn5jn and kubernetes will manage the creation of a new pod with the 2 containers without any downtime. Trying to manually restart single containers in pods negates the whole benefits of kubernetes.

Android Design Support Library expandable Floating Action Button(FAB) menu

Another option for the same result with ConstraintSet animation:

fab animation example

1) Put all the animated views in one ConstraintLayout

2) Animate it from code like this (if you want some more effects its up to you..this is only example)

menuItem1 and menuItem2 is the first and second FABs in menu, descriptionItem1 and descriptionItem2 is the description to the left of menu, parentConstraintLayout is the root ConstraintLayout wich contains all the animated views, isMenuOpened is some function to change open/closed flag in the state

I put animation code in extension file but its not necessary.

fun FloatingActionButton.expandMenu(
    menuItem1: View,
    menuItem2: View,
    descriptionItem1: TextView,
    descriptionItem2: TextView,
    parentConstraintLayout: ConstraintLayout,
    isMenuOpened: (Boolean)-> Unit
) {
    val constraintSet = ConstraintSet()
    constraintSet.clone(parentConstraintLayout)

    constraintSet.setVisibility(descriptionItem1.id, View.VISIBLE)
    constraintSet.clear(menuItem1.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem1.id, ConstraintSet.BOTTOM, this.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    constraintSet.setVisibility(descriptionItem2.id, View.VISIBLE)
    constraintSet.clear(menuItem2.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem2.id, ConstraintSet.BOTTOM, menuItem1.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    val transition = AutoTransition()
    transition.duration = 150
    transition.interpolator = AccelerateInterpolator()

    transition.addListener(object: Transition.TransitionListener {
        override fun onTransitionEnd(p0: Transition) {
            isMenuOpened(true)
        }
        override fun onTransitionResume(p0: Transition) {}
        override fun onTransitionPause(p0: Transition) {}
        override fun onTransitionCancel(p0: Transition) {}
        override fun onTransitionStart(p0: Transition) {}
    })

    TransitionManager.beginDelayedTransition(parentConstraintLayout, transition)
    constraintSet.applyTo(parentConstraintLayout)
}

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

I'm a Perl user, an a game we have is to find every different ways to increment a variable... that's not really different here. The answer to how many ways to find the sum of the elements of a vector in C++ is probably an infinity...

My 2 cents:

Using BOOST_FOREACH, to get free of the ugly iterator syntax:

sum = 0;
BOOST_FOREACH(int & x, myvector){
  sum += x;
}

iterating on indices (really easy to read).

int i, sum = 0;
for (i=0; i<myvector.size(); i++){
  sum += myvector[i];
}

This other one is destructive, accessing vector like a stack:

while (!myvector.empty()){
   sum+=myvector.back();
   myvector.pop_back();
}

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".

Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.

How can I force gradle to redownload dependencies?

delete this directory:

C:\Users\[username]\.gradle

Java: Unresolved compilation problem

I had this error when I used a launch configuration that had an invalid classpath. In my case, I had a project that initially used Maven and thus a launch configuration had a Maven classpath element in it. I had later changed the project to use Gradle and removed the Maven classpath from the project's classpath, but the launch configuration still used it. I got this error trying to run it. Cleaning and rebuilding the project did not resolve this error. Instead, edit the launch configuration, remove the project classpath element, then add the project back to the User Entries in the classpath.

iptables LOG and DROP in one rule

At work, I needed to log and block SSLv3 connections on ports 993 (IMAPS) and 995 (POP3S) using iptables. So, I combined Gert van Dijk's How to take down SSLv3 in your network using iptables firewall? (POODLE) with Prevok's answer and came up with this:

iptables -N SSLv3
iptables -A SSLv3 -j LOG --log-prefix "SSLv3 Client Hello detected: "
iptables -A SSLv3 -j DROP
iptables -A INPUT \
  -p tcp \! -f -m multiport --dports 993,995 \
  -m state --state ESTABLISHED -m u32 --u32 \
  "0>>22&0x3C@ 12>>26&0x3C@ 0 & 0xFFFFFF00=0x16030000 && \
   0>>22&0x3C@ 12>>26&0x3C@ 2 & 0xFF=0x01 && \
   0>>22&0x3C@ 12>>26&0x3C@ 7 & 0xFFFF=0x0300" \
  -j SSLv3

Explanation

  1. To LOG and DROP, create a custom chain (e.g. SSLv3):

    iptables -N SSLv3
    iptables -A SSLv3 -j LOG --log-prefix "SSLv3 Client Hello detected: "
    iptables -A SSLv3 -j DROP
    
  2. Then, redirect what you want to LOG and DROP to that chain (see -j SSLv3):

    iptables -A INPUT \
      -p tcp \! -f -m multiport --dports 993,995 \
      -m state --state ESTABLISHED -m u32 --u32 \
      "0>>22&0x3C@ 12>>26&0x3C@ 0 & 0xFFFFFF00=0x16030000 && \
       0>>22&0x3C@ 12>>26&0x3C@ 2 & 0xFF=0x01 && \
       0>>22&0x3C@ 12>>26&0x3C@ 7 & 0xFFFF=0x0300" \
      -j SSLv3
    

Note: mind the order of the rules. Those rules did not work for me until I put them above this one I had on my firewall script:

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Transform DateTime into simple Date in Ruby on Rails

DateTime#to_date does exist with ActiveSupport:

$ irb
>> DateTime.new.to_date
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
    from (irb):1

>> require 'active_support/core_ext'
=> true

>> DateTime.new.to_date
=> Mon, 01 Jan -4712

react-native: command not found

Install react-native-cli with npm install -g react-native-cli. You may need to use sudo like sudo npm install -g react-native-cli

Tower of Hanoi: Recursive Algorithm

In simple sense the idea is to fill another tower among the three defined towers in the same order of discs as present without a larger disc overlapping a small disc at any time during the procedure.

Let 'A' , 'B' and 'C' be three towers. 'A' will be the tower containing 'n' discs initially. 'B' can be used as intermediate tower and 'C' is the target tower.

The algo is as follows:

  1. Move n-1 discs from tower 'A' to 'B' using 'C'
  2. Move a disc from 'A' to 'C'
  3. Move n-1 discs from tower 'B' to 'C' using 'A'

The code is as follows in java:

public class TowerOfHanoi {

public void TOH(int n, int A , int B , int C){
    if (n>0){
        TOH(n-1,A,C,B);
        System.out.println("Move a disk from tower "+A +" to tower " + C);
        TOH(n-1,B,A,C);
    }
}

public static void main(String[] args) {
    new TowerOfHanoi().TOH(3, 1, 2, 3);
}   

}

How can one display images side by side in a GitHub README.md?

If, like me, you found that @wiggin answer didn't work and images still did not appear in-line, you can use the 'align' property of the html image tag and some breaks to achieve the desired effect, for example:

# Title

<img align="left" src="./documentation/images/A.jpg" alt="Made with Angular" title="Angular" hspace="20"/>
<img align="left" src="./documentation/images/B.png" alt="Made with Bootstrap" title="Bootstrap" hspace="20"/>
<img align="left" src="./documentation/images/C.png" alt="Developed using Browsersync" title="Browsersync" hspace="20"/>
<br/><br/><br/><br/><br/>

## Table of Contents...

Obviously, you have to use more breaks depending on how big the images are: awful yes, but it worked for me so I thought I'd share.

Connect Device to Mac localhost Server?

  1. Connect your iPhone to your Mac via USB.

  2. Go to Network Utility (cmd+space and type "network utility")

  3. Go to the "Info" tab

  4. Click on the drop down menu that says "Wi-Fi" and select "iPhone USB" as shown here:

    Photo for Step 4

  5. You'll find an IP address like "xxx.xxx.xx.xx" or similar. Open Safari browser on your iPhone and enter IP_address:port_number

    Example: 169.254.72.86:3000

[NOTE: If the IP address field is blank, make sure your iPhone is connected via USB, quit Network Utility, open it again and check for the IP address.]

How to remove leading zeros from alphanumeric text?

And what about just searching for the first non-zero character?

[1-9]\d+

This regex finds the first digit between 1 and 9 followed by any number of digits, so for "00012345" it returns "12345". It can be easily adapted for alphanumeric strings.

Google Maps API v3: How do I dynamically change the marker icon?

Call the marker.setIcon('newImage.png')... Look here for the docs.

Are you asking about the actual way to do it? You could just create each div, and a add a mouseover and mouseout listener that would change the icon and back for the markers.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Brew doctor says: "Warning: /usr/local/include isn't writable."

What worked for me was

$ sudo chown -R yourname:admin /usr/local/bin

PostgreSQL next value of the sequences?

I stumbled upon this question b/c I was trying to find the next sequence value by table. This didn't answer my question however this is how its done, and it may help those looking for the sequence value not by name but by table:

SELECT nextval(pg_get_serial_sequence('<your_table>', 'id')) AS new_id; 

Hope it helps :)

Limit the length of a string with AngularJS

Edit The latest version of AngularJSoffers limitTo filter.

You need a custom filter like this:

angular.module('ng').filter('cut', function () {
        return function (value, wordwise, max, tail) {
            if (!value) return '';

            max = parseInt(max, 10);
            if (!max) return value;
            if (value.length <= max) return value;

            value = value.substr(0, max);
            if (wordwise) {
                var lastspace = value.lastIndexOf(' ');
                if (lastspace !== -1) {
                  //Also remove . and , so its gives a cleaner result.
                  if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') {
                    lastspace = lastspace - 1;
                  }
                  value = value.substr(0, lastspace);
                }
            }

            return value + (tail || ' …');
        };
    });

Usage:

{{some_text | cut:true:100:' ...'}}

Options:

  • wordwise (boolean) - if true, cut only by words bounds,
  • max (integer) - max length of the text, cut to this number of chars,
  • tail (string, default: ' …') - add this string to the input string if the string was cut.

Another solution: http://ngmodules.org/modules/angularjs-truncate (by @Ehvince)

Is there a Google Keep API?

No there's not and developers still don't know why google doesn't pay attention to this request!

As you can see in this link it's one of the most popular issues with many stars in google code but still no response from google! You can also add stars to this issue, maybe google hears that!

How can I use MS Visual Studio for Android Development?

Yes you can:

http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/

enter image description here

In case you get "Unable to locate tools.jar. Expected to find it in C:\Program Files (x86)\Java\jre6\lib\tools.jar" you can add an environment variable JAVA_HOME that points to your Java JDK path, for example c:\sdks\glassfish3\jdk (restart MSVC afterwards)

An even better solution is using WinGDB Mobile Edition in Visual Studio: it lets you create and debug Android projects all inside Visual Studio:

http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html

Download WinGDC for Android from http://www.wingdb.com/wgMobileEdition.htm

Cross compile Go on OSX?

Thanks to kind and patient help from golang-nuts, recipe is the following:

1) One needs to compile Go compiler for different target platforms and architectures. This is done from src folder in go installation. In my case Go installation is located in /usr/local/go thus to compile a compiler you need to issue make utility. Before doing this you need to know some caveats.

There is an issue about CGO library when cross compiling so it is needed to disable CGO library.

Compiling is done by changing location to source dir, since compiling has to be done in that folder

cd /usr/local/go/src

then compile the Go compiler:

sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean

You need to repeat this step for each OS and Architecture you wish to cross compile by changing the GOOS and GOARCH parameters.

If you are working in user mode as I do, sudo is needed because Go compiler is in the system dir. Otherwise you need to be logged in as super user. On Mac you may need to enable/configure SU access (it is not available by default), but if you have managed to install Go you possibly already have root access.

2) Once you have all cross compilers built, you can happily cross compile your application by using the following settings for example:

GOOS=windows GOARCH=386 go build -o appname.exe appname.go

GOOS=linux GOARCH=386 CGO_ENABLED=0 go build -o appname.linux appname.go

Change the GOOS and GOARCH to targets you wish to build.

If you encounter problems with CGO include CGO_ENABLED=0 in the command line. Also note that binaries for linux and mac have no extension so you may add extension for the sake of having different files. -o switch instructs Go to make output file similar to old compilers for c/c++ thus above used appname.linux can be any other extension.

Can I give the col-md-1.5 in bootstrap?

You cloud also simply override the width of the Column...

<div class="col-md-1" style="width: 12.499999995%"></div>

Since col-md-1 is of width 8.33333333%; simply multiply 8.33333333 * 1.5 and set it as your width.

in bootstrap 4, you will have to override flex and max-width property too:

<div class="col-md-1" style="width: 12.499999995%;
    flex: 0 0 12.499%;max-width: 12.499%;"></div>

How to Lock/Unlock screen programmatically?

Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:

Swift's guard keyword

Simply put, it provides a way to validate fields prior to execution. This is a good programming style as it enhances readability. In other languages, it may look like this:

func doSomething() {
    if something == nil {
        // return, break, throw error, etc.
    }
    ...
}

But because Swift provides you with optionals, we can't check if it's nil and assign its value to a variable. In contrast, if let checks that it's not nil and assigns a variable to hold the actual value. This is where guard comes into play. It gives you a more concise way of exiting early using optionals.

How to position two divs horizontally within another div

This should do what you are looking for:

<html>
    <head>
        <style type="text/css">
            #header {
                text-align: center;
            }
            #wrapper {
                margin:0 auto;
                width:600px;
            }
            #submain {
                margin:0 auto;
                width:600px;
            }
            #sub-left {
                float:left;
                width:300px;
            }
            #sub-right {
                float:right;
                width:240px;
                text-align: right;
            }
        </style>

    </head>
    <body>
        <div id="wrapper">
            <div id="header"><h1>Head</h1></div>
            <div id="sub-main">
                <div id="sub-left">
                    Right
                </div>
                <div id="sub-right">
                    Left
                </div>
            </div>
        </div>
    </body>
</html>

And you can control the entire document with the wrapper class, or just the two columns with the sub-main class.

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

What is the difference between Normalize.css and Reset CSS?

Normalize.css is mainly a set of styles, based on what its author thought would look good, and make it look consistent across browsers. Reset basically strips styling from elements so you have more control over the styling of everything.

I use both.

Some styles from Reset, some from Normalize.css. For example, from Normalize.css, there's a style to make sure all input elements have the same font, which doesn't occur (between text inputs and textareas). Reset has no such style, so inputs have different fonts, which is not normally wanted.

So bascially, using the two CSS files does a better job 'Equalizing' everything ;)

regards!

Bridged networking not working in Virtualbox under Windows 10

I solved it with similar way to @Khalil's but I attched to 'Bridged Adapter' instead of 'Host-only Adapter'. Here is more detail with screenshots.

How do I parse command line arguments in Bash?

getopts works great if #1 you have it installed and #2 you intend to run it on the same platform. OSX and Linux (for example) behave differently in this respect.

Here is a (non getopts) solution that supports equals, non-equals, and boolean flags. For example you could run your script in this way:

./script --arg1=value1 --arg2 value2 --shouldClean

# parse the arguments.
COUNTER=0
ARGS=("$@")
while [ $COUNTER -lt $# ]
do
    arg=${ARGS[$COUNTER]}
    let COUNTER=COUNTER+1
    nextArg=${ARGS[$COUNTER]}

    if [[ $skipNext -eq 1 ]]; then
        echo "Skipping"
        skipNext=0
        continue
    fi

    argKey=""
    argVal=""
    if [[ "$arg" =~ ^\- ]]; then
        # if the format is: -key=value
        if [[ "$arg" =~ \= ]]; then
            argVal=$(echo "$arg" | cut -d'=' -f2)
            argKey=$(echo "$arg" | cut -d'=' -f1)
            skipNext=0

        # if the format is: -key value
        elif [[ ! "$nextArg" =~ ^\- ]]; then
            argKey="$arg"
            argVal="$nextArg"
            skipNext=1

        # if the format is: -key (a boolean flag)
        elif [[ "$nextArg" =~ ^\- ]] || [[ -z "$nextArg" ]]; then
            argKey="$arg"
            argVal=""
            skipNext=0
        fi
    # if the format has not flag, just a value.
    else
        argKey=""
        argVal="$arg"
        skipNext=0
    fi

    case "$argKey" in 
        --source-scmurl)
            SOURCE_URL="$argVal"
        ;;
        --dest-scmurl)
            DEST_URL="$argVal"
        ;;
        --version-num)
            VERSION_NUM="$argVal"
        ;;
        -c|--clean)
            CLEAN_BEFORE_START="1"
        ;;
        -h|--help|-help|--h)
            showUsage
            exit
        ;;
    esac
done

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Replace Into seems like an option. Or you can check with

IF NOT EXISTS(QUERY) Then INSERT

This will insert or delete then insert. I tend to go for a IF NOT EXISTS check first.

com.jcraft.jsch.JSchException: UnknownHostKey

Depending on what program you use for ssh, the way to get the proper key could vary. Putty (popular with Windows) uses their own format for ssh keys. With most variants of Linux and BSD that I've seen, you just have to look in ~/.ssh/known_hosts. I usually ssh from a Linux machine and then copy this file to a Windows machine. Then I use something similar to

jsch.setKnownHosts("C:\\Users\\cabbott\\known_hosts");

Assuming I have placed the file in C:\Users\cabbott on my Windows machine. If you don't have access to a Linux machine, try http://www.cygwin.com/

Maybe someone else can suggest another Windows alternative. I find putty's way of handling SSH keys by storing them in the registry in a non-standard format bothersome to extract.

How to update (append to) an href in jquery?

var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');

To loop with each()

$("a.directions-link").each(function() {
   var $this = $(this);       
   var _href = $this.attr("href"); 
   $this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

If any of the answers mentioned here doesn't work then go to File > Invalidate Catches/Restart

How to convert a string to utf-8 in Python

city = 'Ribeir\xc3\xa3o Preto'
print city.decode('cp1252').encode('utf-8')

How to find where gem files are installed

gem env works just like gem environment. Saves some typing.

# gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.0.14
  - RUBY VERSION: 2.0.0 (2014-02-24 patchlevel 451) [i686-linux]
  - INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/2.0.0
  - RUBY EXECUTABLE: /usr/local/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
  - GEM PATHS:
     - /usr/local/lib/ruby/gems/2.0.0
     - /root/.gem/ruby/2.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/

How can you test if an object has a specific property?

Like this?

 [bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")

How do I convert strings in a Pandas data frame to a 'date' data type?

 #   Column          Non-Null Count   Dtype         
---  ------          --------------   -----         
 0   startDay        110526 non-null  object
 1   endDay          110526 non-null  object

import pandas as pd

df['startDay'] = pd.to_datetime(df.startDay)

df['endDay'] = pd.to_datetime(df.endDay)

 #   Column          Non-Null Count   Dtype         
---  ------          --------------   -----         
 0   startDay        110526 non-null  datetime64[ns]
 1   endDay          110526 non-null  datetime64[ns]

How to change the decimal separator of DecimalFormat from comma to dot/point?

public String getGermanCurrencyFormat(double value) {
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
    nf.setGroupingUsed(true);
    return "€ " + nf.format(value);
}

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

Conditionally hide CommandField or ButtonField in Gridview

Convert the CommandField to a TemplateField and set the visible property of the button based on the value of the field (true/false)

<asp:Button ID="btnSelect" 
runat="server" Text="Select" 
Visible='<%# DataBinder.Eval(Container.DataItem,"IsLeaf") %>'/>

It says that TypeError: document.getElementById(...) is null

It means that element with id passed to getElementById() does not exist.

Laravel 5 – Remove Public from URL

Easy way to remove public from laravel 5 url. You just need to cut index.php and .htaccess from public directory and paste it in the root directory,thats all and replace two lines in index.php as

require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';

Note: The above method is just for the beginners as they might be facing problem in setting up virtual host and The best solution is to setup virtual host on local machine and point it to the public directory of the project.

Can Mockito stub a method without regard to the argument?

http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Matchers.html

anyObject() should fit your needs.

Also, you can always consider implementing hashCode() and equals() for the Bazoo class. This would make your code example work the way you want.

Find and replace specific text characters across a document with JS

In javascript without using jquery:

document.body.innerText = document.body.innerText.replace('actualword', 'replacementword');

Microsoft Excel mangles Diacritics in .csv files?

Note that including the UTF-8 BOM is not necessarily a good idea - Mac versions of Excel ignore it and will actually display the BOM as ASCII… three nasty characters at the start of the first field in your spreadsheet…

How to use the 'og' (Open Graph) meta tag for Facebook share

I built a tool for meta generation. It pre-configures entries for Facebook, Google+ and Twitter, and you can use it free here: http://www.groovymeta.com

To answer the question a bit more, OG tags (Open Graph) tags work similarly to meta tags, and should be placed in the HEAD section of your HTML file. See Facebook's best practises for more information on how to use OG tags effectively.

javascript functions to show and hide divs

You need the link inside to be clickable, meaning it needs a href with some content, and also, close() is a built-in function of window, so you need to change the name of the function to avoid a conflict.

<div id="upbutton"><a href="#" onclick="close2()">click to close</a></div>

Also if you want a real "button" instead of a link, you should use <input type="button"/> or <button/>.

startsWith() and endsWith() functions in PHP

The substr function can return false in many special cases, so here is my version, which deals with these issues:

function startsWith( $haystack, $needle ){
  return $needle === ''.substr( $haystack, 0, strlen( $needle )); // substr's false => empty string
}

function endsWith( $haystack, $needle ){
  $len = strlen( $needle );
  return $needle === ''.substr( $haystack, -$len, $len ); // ! len=0
}

Tests (true means good):

var_dump( startsWith('',''));
var_dump( startsWith('1',''));
var_dump(!startsWith('','1'));
var_dump( startsWith('1','1'));
var_dump( startsWith('1234','12'));
var_dump(!startsWith('1234','34'));
var_dump(!startsWith('12','1234'));
var_dump(!startsWith('34','1234'));
var_dump('---');
var_dump( endsWith('',''));
var_dump( endsWith('1',''));
var_dump(!endsWith('','1'));
var_dump( endsWith('1','1'));
var_dump(!endsWith('1234','12'));
var_dump( endsWith('1234','34'));
var_dump(!endsWith('12','1234'));
var_dump(!endsWith('34','1234'));

Also, the substr_compare function also worth looking. http://www.php.net/manual/en/function.substr-compare.php

Check whether an input string contains a number in javascript

It's not bulletproof by any means, but it worked for my purposes and maybe it will help someone.

var value = $('input').val();
 if(parseInt(value)) {
  console.log(value+" is a number.");
 }
 else {
  console.log(value+" is NaN.");
 }

Convert HashBytes to VarChar

With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:

@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)

WPF button click in C# code

The following should do the trick:

btn.Click += btn1_Click;

MySQL SELECT only not null values

I use the \! command within MySQL to grep out NULL values from the shell:

\! mysql -e "SELECT * FROM table WHERE column = 123456\G" | grep -v NULL

It works best with a proper .my.cnf where your database/username/password are specified. That way you just have to surround your select with \! mysql e and | grep -v NULL.

Show two digits after decimal point in c++

cout << fixed << setprecision(2) << total;

setprecision specifies the minimum precision. So

cout << setprecision (2) << 1.2; 

will print 1.2

fixed says that there will be a fixed number of decimal digits after the decimal point

cout << setprecision (2) << fixed << 1.2;

will print 1.20

What's the best way to check if a String represents an integer in Java?

Integer.valueOf(string); 

works for me most of the time!

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

As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
enter image description here

Is there a difference between x++ and ++x in java?

Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression. Take an example:

public static void main(String args[])
{
    int i , j , k = 0;
    j = k++; // Value of j is 0
    i = ++j; // Value of i becomes 1
    k = i++; // Value of k is 1
    System.out.println(k);  
}

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

Easy way to build Android UI?

http://www.appinventor.mit.edu/

Creating an App Inventor app begins in your browser, where you design how the app will look. Then, like fitting together puzzle pieces, you set your app's behavior. All the while, through a live connection between your computer and your phone, your app appears on your phone.

How to detect a textbox's content has changed

Something like this should work, mainly because focus and focusout would end up with two separate values. I'm using data here because it stores values in the element but doesn't touch the DOM. It is also an easy way to store the value connected to its element. You could just as easily use a higher-scoped variable.

var changed = false;

$('textbox').on('focus', function(e) {
    $(this).data('current-val', $(this).text();
});

$('textbox').on('focusout', function(e) {
    if ($(this).data('current-val') != $(this).text())
        changed = true;
    }
    console.log('Changed Result', changed);
}

How to save image in database using C#

//Arrange the Picture Of Path.***

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

                    string[] PicPathArray;
                    string ArrangePathOfPic;

                    PicPathArray = openFileDialog1.FileName.Split('\\');

                    ArrangePathOfPic = PicPathArray[0] + "\\\\" + PicPathArray[1];
                    for (int a = 2; a < PicPathArray.Length; a++)
                    {
                        ArrangePathOfPic = ArrangePathOfPic + "\\\\" + PicPathArray[a];
                    }
               }

// Save the path Of Pic in database

                    SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                    con.Open();

                    SqlCommand cmd = new SqlCommand("insert into PictureTable (Pic_Path) values (@Pic_Path)", con);
                    cmd.Parameters.Add("@Pic_Path", SqlDbType.VarChar).Value = ArrangePathOfPic;

                    cmd.ExecuteNonQuery();

***// Get the Picture Path in Database.***

SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                con.Open();

                SqlCommand cmd = new SqlCommand("Select * from Pic_Path where ID = @ID", con);

                SqlDataAdapter adp = new SqlDataAdapter();
                cmd.Parameters.Add("@ID",SqlDbType.VarChar).Value = "1";
                adp.SelectCommand = cmd;

                DataTable DT = new DataTable();

                adp.Fill(DT);

                DataRow DR = DT.Rows[0];
                pictureBox1.Image = Image.FromFile(DR["Pic_Path"].ToString());

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

Git fast forward VS no fast forward merge

I can give an example commonly seen in project.

Here, option --no-ff (i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff (i.e. fast-forward merge) is by default.

$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature'         // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk                           // => see details with graph

$ git checkout -b anotherFeature        // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature       // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk                           // => see details with graph

(*) Note that here if the newFeature branch is re-used, instead of creating a new branch, git will have to do a --no-ff merge anyway. This means fast forward merge is not always eligible.

What does it mean to "call" a function in Python?

when you invoke a function , it is termed 'calling' a function . For eg , suppose you've defined a function that finds the average of two numbers like this-

def avgg(a,b) :
        return (a+b)/2;

now, to call the function , you do like this .

x=avgg(4,6)
print x

value of x will be 5 .

How to access session variables from any class in ASP.NET?

(Updated for completeness)
You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...


I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

How to initialize all members of an array to the same value?

Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.

Don't overlook the obvious solution, though:

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

Elements with missing values will be initialized to 0:

int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...

So this will initialize all elements to 0:

int myArray[10] = { 0 }; // all elements 0

In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:

int myArray[10] = {}; // all elements 0 in C++

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:

static int myArray[10]; // all elements 0

And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)

How do I print the content of a .txt file in Python?

to input a file:

fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'

to output this file you can do:

for element in fin:
    print element 

if the elements are a string you'd better add this before print:

element = element.strip()

strip() remove notations like this: /n

How to delete files/subfolders in a specific directory at the command prompt in Windows

The simplest solution I can think of is removing the whole directory with

RD /S /Q folderPath

Then creating this directory again:

MD folderPath

How to make Bitmap compress without change the bitmap size?

If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.

Quality Accepts 0 - 100

0 = MAX Compression (Least Quality which is suitable for Small images)

100 = Least Compression (MAX Quality which is suitable for Big images)

Iterating over Typescript Map

Per the TypeScript 2.3 release notes on "New --downlevelIteration":

for..of statements, Array Destructuring, and Spread elements in Array, Call, and New expressions support Symbol.iterator in ES5/E3 if available when using --downlevelIteration

This is not enabled by default! Add "downlevelIteration": true to your tsconfig.json, or pass --downlevelIteration flag to tsc, to get full iterator support.

With this in place, you can write for (let keyval of myMap) {...} and keyval's type will be automatically inferred.


Why is this turned off by default? According to TypeScript contributor @aluanhaddad,

It is optional because it has a very significant impact on the size of generated code, and potentially on performance, for all uses of iterables (including arrays).

If you can target ES2015 ("target": "es2015" in tsconfig.json or tsc --target ES2015) or later, enabling downlevelIteration is a no-brainer, but if you're targeting ES5/ES3, you might benchmark to ensure iterator support doesn't impact performance (if it does, you might be better off with Array.from conversion or forEach or some other workaround).

Send array with Ajax to PHP script

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:

dataString = {key: 'val', key2: 'val2'};
$.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

You may also write POST/GET query on your own, like key=val&key2=val2, but you'd have to handle escaping yourself which is impractical.

'App not Installed' Error on Android

I had a similar situation.I was able to install app in debug mode using USB but not a signed version. I was able to install signed version on other phone, but not on my device. Numerous reasons and solutions did not help me. But one direction I got from a solution "uninstall for all users". What I did is to again install app in debug mode using USB connection, go to app details and "uninstall for all users" from right top 3 dots - to remove debug version. This looks like cleared all kinds of references. I usually do a normal uninstall.

Now I am able to get signed APK on the device and install and its success.

Populating a razor dropdownlist from a List<object> in MVC

Instead of a List<UserRole>, you can let your Model contain a SelectList<UserRole>. Also add a property SelectedUserRoleId to store... well... the selected UserRole's Id value.

Fill up the SelectList, then in your View use:

@Html.DropDownListFor(x => x.SelectedUserRoleId, x.UserRole)

and you should be fine.

See also http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx.

What do raw.githubusercontent.com URLs represent?

There are two ways of looking at github content, the "raw" way and the "Web page" way.

raw.githubusercontent.com returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.

If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com.

To see the content of raw.githubusercontent.com/${repo}/${branch}/${path} in the usual github interface:

  1. you replace raw.githubusercontent.com with plain github.com
  2. AND you insert "blob" between the repo name and the branch name.

In this case, the branch name is "master" (which is a very common branch name), so you replace /master/ with /blob/master/, and so

https://raw.githubusercontent.com/Homebrew/install/master/install

becomes

https://github.com/Homebrew/install/blob/master/install

This is the reverse of finding a file on Github and clicking the Raw link.

How do I truncate a .NET string?

public static string Truncate( this string value, int maxLength )
    {
        if (string.IsNullOrEmpty(value)) { return value; }

        return new string(value.Take(maxLength).ToArray());// use LINQ and be happy
    }

printing a two dimensional array in python

A combination of list comprehensions and str joins can do the job:

inf = float('inf')
A = [[0,1,4,inf,3],
     [1,0,2,inf,4],
     [4,2,0,1,5],
     [inf,inf,1,0,3],
     [3,4,5,3,0]]

print('\n'.join([''.join(['{:4}'.format(item) for item in row]) 
      for row in A]))

yields

   0   1   4 inf   3
   1   0   2 inf   4
   4   2   0   1   5
 inf inf   1   0   3
   3   4   5   3   0

Using for-loops with indices is usually avoidable in Python, and is not considered "Pythonic" because it is less readable than its Pythonic cousin (see below). However, you could do this:

for i in range(n):
    for j in range(n):
        print '{:4}'.format(A[i][j]),
    print

The more Pythonic cousin would be:

for row in A:
    for val in row:
        print '{:4}'.format(val),
    print

However, this uses 30 print statements, whereas my original answer uses just one.

How do I calculate someone's age in Java?

It's perhaps surprising to note that you don't need to know how many days or months there are in a year or how many days are in those months, likewise, you don't need to know about leap years, leap seconds, or any of that stuff using this simple, 100% accurate method:

public static int age(Date birthday, Date date) {
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    int d1 = Integer.parseInt(formatter.format(birthday));
    int d2 = Integer.parseInt(formatter.format(date));
    int age = (d2-d1)/10000;
    return age;
}

Is a Python dictionary an example of a hash table?

There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:

>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438

Yet it doesn't break the dictionary:

>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'

Sanity check:

>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438

Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.

(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8).)

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I'm using Eclipse Kepler SR2 on Ubuntu 12.04LTS and was trying to access an internal GitHub using HTTPS. Unfortunately, my underlying JVM with which Eclipse was started experienced problems with the self-signed certificate of the server. Switching to a different JVM for Eclipse got the HTTPS connection to our GitHub working.

Create a simple Eclipse starter that uses a different JDK, e.g. with OpenJDK: /Eclipse_Kepler_4.4.2/eclipse -vm /usr/lib/jvm/java-6-openjdk-i386/jre/bin

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

Is it ok to run docker from inside docker?

Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".

And also it would require to run the docker in privileged mode, so the commands would be:

sudo chmod 757 /var/run/docker.sock

docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...

How do I write a backslash (\) in a string?

txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";

Put a double backslash instead of a single backslash...

SLF4J: Class path contains multiple SLF4J bindings

Gradle version;

configurations.all {
    exclude module: 'slf4j-log4j12'
}

Best practice to look up Java Enum

Guava also provides such function which will return an Optional if an enum cannot be found.

Enums.getIfPresent(MyEnum.class, id).toJavaUtil()
            .orElseThrow(()-> new RuntimeException("Invalid enum blah blah blah.....")))

Google Play Services Missing in Emulator (Android 4.4.2)

google play service is just a library to create application but in order to use application that use google play service library , you need to install google play in your emulator.and for that it need the unique device id. and device id is only on the real device not have on emulator. so for testing it , you need real android device.

How can I disable a specific LI element inside a UL?

Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp

If that's not an option for any reason, you could try giving the list items classes:

<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>

Then in your css:

li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/

Grep characters before and after match?

3 characters before and 4 characters after

$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and

Convert SQL Server result set into string

or a single select statement...

DECLARE @results VarChar(1000)
SELECT @results = CASE
     WHEN @results IS NULL THEN CONVERT( VarChar(20), [StudentId])
     ELSE ', ' + CONVERT( VarChar(20), [StudentId])
   END
FROM Student WHERE condition = abc;

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

Find value in an array

I know this question has already been answered, but I came here looking for a way to filter elements in an Array based on some criteria. So here is my solution example: using select, I find all constants in Class that start with "RUBY_"

Class.constants.select {|c| c.to_s =~ /^RUBY_/ }

UPDATE: In the meantime I have discovered that Array#grep works much better. For the above example,

Class.constants.grep /^RUBY_/

did the trick.

How do I execute a Shell built-in command with a C function?

You can use the excecl command

int execl(const char *path, const char *arg, ...);

Like shown here

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>

int main (void) {

   return execl ("/bin/pwd", "pwd", NULL);

}

The second argument will be the name of the process as it will appear in the process table.

Alternatively, you can use the getcwd() function to get the current working directory:

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255

int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';

if(getcwd(wd, MAX-1) == NULL) {
  printf ("Can not get current working directory\n");
}
else {
  printf("%s\n", wd);
}
  return 0;
}

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

Ansible: create a user with sudo privileges

To create a user with sudo privileges is to put the user into /etc/sudoers, or make the user a member of a group specified in /etc/sudoers. And to make it password-less is to additionally specify NOPASSWD in /etc/sudoers.

Example of /etc/sudoers:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

And instead of fiddling with /etc/sudoers file, we can create a new file in /etc/sudoers.d/ directory since this directory is included by /etc/sudoers by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers.

To achieve above in Ansible, refer to the following:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

You may replace %wheel with other group names like %sudoers or other user names like deployer.

jQuery adding 2 numbers from input fields

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnadd').on('click', function () {
            var n1 = parseInt($('#txtn1').val());
            var n2 = parseInt($('#txtn2').val());
            var r = n1 + n2;
            alert("sum of 2 No= " + r);
            return false;
        });
        $('#btnclear').on('click', function () {
            $('#txtn1').val('');
            $('#txtn2').val('');
            $('#txtn1').focus();
            return false;
        });
    });
</script>

Regular expression to match URLs in Java

Here is a proposal of an URL parser regex that recognizes :

  • Protocol
  • Host
  • Port
  • Path (Document/folder)
  • Get parameters
^(?>(?<protocol>[[:alpha:]]+(?>\:[[:alpha:]]+)*)\:\/\/)?(?<host>(?>[[:alnum:]]|[-_.])+)(?>\:(?<port>[[:digit:]]+))?(?<path>\/(?>[[:alnum:]]|[-_.\/])*)?(?>\?(?<request>(?>[[:alnum:]]+=[[:alnum:]]+)(?>\&(?>[[:alnum:]]+=[[:alnum:]]+))*))?$

This regex is able to parse an URL such :

jdbc:hsqldb:hsql://localhost:91/index.

There can be many way to engineer a URL regex, thus the one I propose can be lightly adapted to match more accurate URL grammars.

It can be tested on the following page : https://regex101.com/r/Dy7HE0/5

Be aware that langages native API for regex (such as java.util.regex) don't support smart character classes such as [[:alnum:]] and [[:alpha:]].

Use instead \w and \d.

Powershell 2 copy-item which creates a folder if doesn't exist

I modified @FrinkTheBrave 's answer to also create sub-directories, and resolve relative paths:

$src_root = Resolve-Path("./source/path/")
$target_root = Resolve-Path("./target/path/")
$glob_filter = "*.*"
Get-ChildItem -path $src_root -filter $glob_filter -recurse | 
  ForEach-Object {
        $target_filename=($_.FullName -replace [regex]::escape($src_root),$target_root) 
        $target_path=Split-Path $target_filename
        if (!(Test-Path -Path $target_path)) {
            New-Item $target_path -ItemType Directory
        }
        Copy-Item $_.FullName -destination $target_filename
    }

How to use the priority queue STL for objects?

You would write a comparator class, for example:

struct CompareAge {
    bool operator()(Person const & p1, Person const & p2) {
        // return "true" if "p1" is ordered before "p2", for example:
        return p1.age < p2.age;
    }
};

and use that as the comparator argument:

priority_queue<Person, vector<Person>, CompareAge>

Using greater gives the opposite ordering to the default less, meaning that the queue will give you the lowest value rather than the highest.

Property '...' has no initializer and is not definitely assigned in the constructor

I think you are using the latest version of TypeScript. Please see the section "Strict Class Initialization" in the link.

There are two ways to fix this:

A. If you are using VSCode you need to change the TS version that the editor use.

B. Just initialize the array when you declare it inside the constructor,

makes: any[] = [];

constructor(private makeService: MakeService) { 
   // Initialization inside the constructor
   this.makes = [];
}

How to take character input in java

You can simply use (char) System.in.read(); casting to char is necessary to convert int to char

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

Timer function to provide time in nano seconds using C++

You can use Embedded Profiler (free for Windows and Linux) which has an interface to a multiplatform timer (in a processor cycle count) and can give you a number of cycles per seconds:

EProfilerTimer timer;
timer.Start();

... // Your code here

const uint64_t number_of_elapsed_cycles = timer.Stop();
const uint64_t nano_seconds_elapsed =
    mumber_of_elapsed_cycles / (double) timer.GetCyclesPerSecond() * 1000000000;

Recalculation of cycle count to time is possibly a dangerous operation with modern processors where CPU frequency can be changed dynamically. Therefore to be sure that converted times are correct, it is necessary to fix processor frequency before profiling.

Can Json.NET serialize / deserialize to / from a stream?

public static void Serialize(object value, Stream s)
{
    using (StreamWriter writer = new StreamWriter(s))
    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
    {
        JsonSerializer ser = new JsonSerializer();
        ser.Serialize(jsonWriter, value);
        jsonWriter.Flush();
    }
}

public static T Deserialize<T>(Stream s)
{
    using (StreamReader reader = new StreamReader(s))
    using (JsonTextReader jsonReader = new JsonTextReader(reader))
    {
        JsonSerializer ser = new JsonSerializer();
        return ser.Deserialize<T>(jsonReader);
    }
}

Mobile Redirect using htaccess

I tested bits and pieces of the following, but not the complete rule set in its entirety, so if you run into trouble with it let me know and I'll dig around a bit more. However, assuming I got everything correct, you could try something like the following:

RewriteEngine On

# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)noredirect=true(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]

# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
#  had to check, but I believe most mobile devices should send at
#  least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile}       !^$
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie}        !\smredir=0(;|$)
# Now redirect to the mobile site
RewriteRule ^ http://m.example.org%{REQUEST_URI} [R,L]

PostgreSQL IF statement

You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

_x000D_
_x000D_
.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
  background:_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
_x000D_
_x000D_

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

Connecting to MySQL from Android with JDBC

You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver

See

http://www.helloandroid.com/tutorials/connecting-mysql-database

http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html

Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html

For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.

New Line Issue when copying data from SQL Server 2012 to Excel

  • If your table contains an nvarchar(max) field move that field to the bottom of your table.
  • In the event the field type is different to nvarchar(max), then identify the offending field or fields and use this same technique.
  • Save It.
  • Reselect the Table in SQL.
  • If you cant save without an alter you can temporarily turn of relevant warnings in TOOLS | OPTIONS. This method carries no risk.
  • Copy and Paste the SQL GRID display with Headers to Excel.
  • The data may still exhibit a carriage return but at least your data is all on the same row.
  • Then select all row records and do a custom sort on the ID column.
  • All of your records should now be intact and consecutive.

How exactly does the python any() function work?

>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True

>>> all(n in 'King and Queen' for n in names)
False

It just reduce several line of code into one. You don't have to write lengthy code like:

for n in names:
    if n in 'King and john':
       print True
    else:
       print False

Passing arguments to AsyncTask, and returning results

Change your method to look like this:

String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list

And change your async task implementation

public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(baraj_mapa.this);
        dialog.setTitle("Calculating...");
        dialog.setMessage("Please wait...");
        dialog.setIndeterminate(true);
        dialog.show();
    }

    protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
        ArrayList<String> result = new ArrayList<String>();
        ArrayList<String> passed = passing[0]; //get passed arraylist

        //Some calculations...

        return result; //return result
    }

    protected void onPostExecute(ArrayList<String> result) {
        dialog.dismiss();
        String minim = result.get(0);
        int min = Integer.parseInt(minim);
        String glons = result.get(1);
        String glats = result.get(2);
        double glon = Double.parseDouble(glons);
        double glat = Double.parseDouble(glats);
        GeoPoint g = new GeoPoint(glon, glat);
        String korisni_linii = result.get(3);
    }

UPD:

If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:

new calc_stanica() {
    protected void onPostExecute(ArrayList<String> result) {
      // here you have access to the context in which execute was called in first place. 
      // You'll have to mark all the local variables final though..
     }
}.execute(passing);

is the + operator less performant than StringBuffer.append()

It is pretty easy to set up a quick benchmark and check out Javascript performance variations using jspref.com. Which probably wasn't around when this question was asked. But for people stumbling on this question they should take alook at the site.

I did a quick test of various methods of concatenation at http://jsperf.com/string-concat-methods-test.

Method List in Visual Studio Code

It is an extra part to the answer to this question here but I thought it might be useful. As many people mentioned, Visual Studio Code has the OUTLINE part which provides the ability to browse to different function and show them on the side.

I also wanted to add that if you check the follow cursor mark, it highlights that function name in the OUTLINE view, which is very helpful in browsing and seeing which function you are in.

enter image description here

Http 415 Unsupported Media type error with JSON

If you are making jquery ajax request, dont forget to add

contentType:'application/json'

Using {% url ??? %} in django templates

Instead of importing the logout_view function, you should provide a string in your urls.py file:

So not (r'^login/', login_view),

but (r'^login/', 'login.views.login_view'),

That is the standard way of doing things. Then you can access the URL in your templates using:

{% url login.views.login_view %}

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

Mask for an Input to allow phone numbers?

I Think the simplest solutions is to add ngx-mask

npm i --save ngx-mask

then you can do

<input type='text' mask='(000) 000-0000' >

OR

<p>{{ phoneVar | mask: '(000) 000-0000' }} </p>

I'm getting Key error in python

I received this error when I was parsing dict with nested for:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cat:
        print(cats[cat][attr])

Traceback:

Traceback (most recent call last):
      File "<input>", line 3, in <module>
    KeyError: 'K'

Because in second loop should be cats[cat] instead just cat (what is just a key)

So:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cats[cat]:
        print(cats[cat][attr])

Gives

black
10
white
8

How to create EditText with cross(x) button at end of it?

If you don't want to use custom views or special layouts, you can use 9-patch to make the (X) button .

Example: http://postimg.org/image/tssjmt97p/ (I don't have enough points to post images on StackOverflow)

The intersection of the right and bottom black pixels represent the content area. Anything outside of that area is padding. So to detect that the user clicked on the x you can set a OnTouchListener like so:

editText.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_UP){
            if (motionEvent.getX()>(view.getWidth()-view.getPaddingRight())){
                ((EditText)view).setText("");
            }
        }
        return false;
    }
});

According to your needs this solution can work better in some cases. I prefer to keep my xml less complicated. This also helps if you want to have an icon on the left, as you can simply include it in the 9 patch.

Differences between Ant and Maven

I can take a person that has never seen Ant - its build.xmls are reasonably well-written - and they can understand what is going on. I can take that same person and show them a Maven POM and they will not have any idea what is going on.

In an engineering organization that is huge, people write about Ant files becoming large and unmanageable. I've written those types and clean Ant scripts. It's really understanding upfront what you need to do going forward and designing a set of templates that can respond to change and scale over a 3+ year period.

Unless you have a simple project, learning the Maven conventions and the Maven way about getting things done is quite a bit of work.

At the end of the day you cannot consider project startup with Ant or Maven a factor: it's really the total cost of ownership. What it takes for the organization to maintain and extend its build system over a few years is one of the main factors that must be considered.

The most important aspects of a build system are dependency management and flexibility in expressing the build recipe. It must be somewhat intuitive when done well.

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

How do you switch pages in Xamarin.Forms?

In Xamarin we have page called NavigationPage. It holds stack of ContentPages. NavigationPage has method like PushAsync()and PopAsync(). PushAsync add a page at the top of the stack, at that time that page page will become the currently active page. PopAsync() method remove the page from the top of the stack.

In App.Xaml.Cs we can set like.

MainPage = new NavigationPage( new YourPage());

await Navigation.PushAsync(new newPage()); this method will add newPage at the top of the stack. At this time nePage will be currently active page.

How to change Angular CLI favicon

we can change angular CLI favicon icon. we have to put icon file in "assets" folder and give that path in index.html.

<link rel="icon" type="image/x-icon" href="./assets/images/favicon.png"> It's work for me.

How to add local .jar file dependency to build.gradle file?

I couldn't get the suggestion above at https://stackoverflow.com/a/20956456/1019307 to work. This worked for me though. For a file secondstring-20030401.jar that I stored in a libs/ directory in the root of the project:

repositories {
    mavenCentral()
    // Not everything is available in a Maven/Gradle repository.  Use a local 'libs/' directory for these.
    flatDir {
       dirs 'libs'
   }
}

...

compile name: 'secondstring-20030401'

MySQL with Node.js

Since this is an old thread just adding an update:

To install the MySQL node.js driver:

If you run just npm install mysql, you need to be in the same directory that your run your server. I would advise to do it as in one of the following examples:

For global installation:

npm install -g mysql

For local installation:

1- Add it to your package.json in the dependencies:

"dependencies": {
    "mysql": "~2.3.2",
     ...

2- run npm install


Note that for connections to happen you will also need to be running the mysql server (which is node independent)

To install MySQL server:

There are a bunch of tutorials out there that explain this, and it is a bit dependent on operative system. Just go to google and search for how to install mysql server [Ubuntu|MacOSX|Windows]. But in a sentence: you have to go to http://www.mysql.com/downloads/ and install it.

Class has no member named

Did you remember to include the closing brace in main?

#include <iostream>
#include "Attack.h"

using namespace std;

int main()
{
  Attack attackObj;
  attackObj.printShiz();
}

Java: Reading integers from a file into an array

You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I have tried your code and it works just fine. The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):

    public ActionResult ExportToExcel()
    {
        var products = new System.Data.DataTable("teste");
        products.Columns.Add("col1", typeof(int));
        products.Columns.Add("col2", typeof(string));

        products.Rows.Add(1, "product 1");
        products.Rows.Add(2, "product 2");
        products.Rows.Add(3, "product 3");
        products.Rows.Add(4, "product 4");
        products.Rows.Add(5, "product 5");
        products.Rows.Add(6, "product 6");
        products.Rows.Add(7, "product 7");


        var grid = new GridView();
        grid.DataSource = products;
        grid.DataBind();

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
        Response.ContentType = "application/ms-excel";

        Response.Charset = "";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);

        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

        return View("MyView");
    }

how to check if string value is in the Enum list?

To parse the age:

Age age;
if (Enum.TryParse(typeof(Age), "New_Born", out age))
  MessageBox.Show("Defined");  // Defined for "New_Born, 1, 4 , 8, 12"

To see if it is defined:

if (Enum.IsDefined(typeof(Age), "New_Born"))
   MessageBox.Show("Defined");

Depending on how you plan to use the Age enum, flags may not be the right thing. As you probably know, [Flags] indicates you want to allow multiple values (as in a bit mask). IsDefined will return false for Age.Toddler | Age.Preschool because it has multiple values.

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

public static void main(String arg[])
{
    HashMap<String, ArrayList<String>> hashmap = 
        new HashMap<String, ArrayList<String>>();
    ArrayList<String> arraylist = new ArrayList<String>();
    arraylist.add("Hello");
    arraylist.add("World.");
    hashmap.put("my key", arraylist);
    arraylist = hashmap.get("not inserted");
    System.out.println(arraylist);
    arraylist = hashmap.get("my key");
    System.out.println(arraylist);
}

null
[Hello, World.]

Works fine... maybe you find your mistake in my code.

How to overload __init__ method based on argument type?

OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.

class MyData:
    def __init__(self, data):
        self.myList = []
        if isinstance(data, tuple):
            for i in data:
                self.myList.append(i)
        else:
            self.myList = data

    def GetData(self):
        print self.myList

a = [1,2]

b = (2,3)

c = MyData(a)

d = MyData(b)

c.GetData()

d.GetData()

[1, 2]

[2, 3]

Script to Change Row Color when a cell changes text

user2532030's answer is the correct and most simple answer.

I just want to add, that in the case, where the value of the determining cell is not suitable for a RegEx-match, I found the following syntax to work the same, only with numerical values, relations et.c.:

[Custom formula is]
=$B$2:$B = "Complete"
Range: A2:Z1000

If column 2 of any row (row 2 in script, but the leading $ means, this could be any row) textually equals "Complete", do X for the Range of the entire sheet (excluding header row (i.e. starting from A2 instead of A1)).

But obviously, this method allows also for numerical operations (even though this does not apply for op's question), like:

=$B$2:$B > $C$2:$C

So, do stuff, if the value of col B in any row is higher than col C value.

One last thing: Most likely, this applies only to me, but I was stupid enough to repeatedly forget to choose Custom formula is in the drop-down, leaving it at Text contains. Obviously, this won't float...

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

How to center text vertically with a large font-awesome icon?

Another option to fine-tune the line height of an icon is by using a percentage of the vertical-align property. Usually, 0% is a the bottom, and 100% at the top, but one could use negative values or more than a hundred to create interesting effects.

.my-element i.fa {
    vertical-align: 100%; // top
    vertical-align: 50%; // middle
    vertical-align: 0%; // bottom
}

How to work with string fields in a C struct?

While Richard's is what you want if you do want to go with a typedef, I'd suggest that it's probably not a particularly good idea in this instance, as you lose sight of it being a pointer, while not gaining anything.

If you were treating it a a counted string, or something with additional functionality, that might be different, but I'd really recommend that in this instance, you just get familiar with the 'standard' C string implementation being a 'char *'...

How do I import modules or install extensions in PostgreSQL 9.1+?

Into psql terminal put:

\i <path to contrib files>

in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql

How do I look inside a Python object?

Python has a strong set of introspection features.

Take a look at the following built-in functions:

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

How to disable a input in angular2

can use simply like

     <input [(ngModel)]="model.name" disabled="disabled"

I got it like this way. so i prefer.

SQL Server converting varbinary to string

Try:

DECLARE @varbinaryField varbinary(max);
SET @varbinaryField = 0x21232F297A57A5A743894A0E4A801FC3;

SELECT CONVERT(varchar(max),@varbinaryField,2), 
@varbinaryField

UPDATED: For SQL Server 2008

angular.element vs document.getElementById or jQuery selector with spin (busy) control

Maybe I am too late here but this will work :

var target = angular.element(appBusyIndicator);

Notice, there is no appBusyIndicator, it is plain ID value.

What is happening behind the scenes: (assuming it's applied on a div) (taken from angular.js line no : 2769 onwards...)

/////////////////////////////////////////////
function JQLite(element) {     //element = div#appBusyIndicator
  if (element instanceof JQLite) {
    return element;
  }

  var argIsString;

  if (isString(element)) {
    element = trim(element);
    argIsString = true;
  }
  if (!(this instanceof JQLite)) {
    if (argIsString && element.charAt(0) != '<') {
      throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
    }
    return new JQLite(element);
  }

By default if there is no jQuery on the page, jqLite will be used. The argument is internally understood as an id and corresponding jQuery object is returned.

How to remove specific value from array using jQuery

I had a similar task where I needed to delete multiple objects at once based on a property of the objects in the array.

So after a few iterations I end up with:

list = $.grep(list, function (o) { return !o.IsDeleted });

How to extract img src, title and alt from html using php?

$url="http://example.com";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
       echo $tag->getAttribute('src');
}

How to get year and month from a date - PHP

$dateValue = strtotime($q);

$yr = date("Y", $dateValue) ." "; 
$mon = date("m", $dateValue)." "; 
$date = date("d", $dateValue); 

Eclipse : Maven search dependencies doesn't work

Use https://search.maven.org/ manually with the prefix fc: to search for class names. Both Netbeans and Eclipse seem to be too stupid to use that search interface and the gigabytes of downloaded repository indexes seem to not contain any class information. Total waste of disk space. Those IDE projects are so badly maintained lately, I wish they would move development to GitHub.

Regex to match alphanumeric and spaces

There appear to be two problems.

  1. You're using the ^ outside a [] which matches the start of the line
  2. You're not using a * or + which means you will only match a single character.

I think you want the following regex @"([^a-zA-Z0-9\s])+"

Passing headers with axios POST request

Interceptors

I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

How do I call a JavaScript function on page load?

You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.

Try the code below:

<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        yourFunction();
    });
    function yourFunction(){
      //some code
    }
</script>

Why does CSS not support negative padding?

You asked WHY, not how to cheat it:

Usually because of laziness of programmers of the initial implementation, because they HAVE already put way more effort in other features, delivering more odd side-effects like floats, because they were more requested by designers back then and yet they haven't taken the time to allow this so we can use the FOUR properties to push/pull an element against its neighbors (now we only have four to push, and only 2 to pull).

When html was designed, magazines loved text reflown around images back then, now hated because today we have touch trends, and love squary things with lots of space and nothing to read. That's why they put more pressure on floats than on centering, or they could have designed something like margin-top: fill; or margin: average 0; to simply align the content to the bottom, or distribute its extra space around.

In this case I think it hasn't been implemented because of the same reason that makes CSS to lack of a :parent pseudo-selector: To prevent looping evaluations.

Without being an engineer, I can see that CSS right now is made to paint elements once, remember some properties for future elements to be painted, but NEVER going back to already-painted elements.

That's why (I guess) padding is calculated on the width, because that's the value that was available at the time of starting to paint it.

If you had a negative value for padding, it would affect the outer limits, which has ALREADY been defined when the margin has already been set. I know, nothing has been painted yet, but when you read how the painting process goes, created by geniuses with 90's technology, I feel like I am asking dumb questions and just say "thanks" hehe.

One of the requirements of web pages is that they are quickly available, unlike an app that can take its time and eat the computer resources to get everything correct before displaying it, web pages need to use little resources (so they are fit in every device possible) and be scrolled in a breeze.

If you see applications with complex reflowing and positioning, like InDesign, you can't scroll that fast! It takes a big effort both from processors and graphic card to jump to next pages!

So painting and calculating forward and forgetting about an element once drawn, for now it seems to be a MUST.

Pygame mouse clicking detection

I was looking for the same answer to this question and after much head scratching this is the answer I came up with:

#Python 3.4.3 with Pygame
import pygame

pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))


# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
    # Mouse position and button clicking.
    pos = pygame.mouse.get_pos()
    pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
    # Check if the rect collided with the mouse pos
    # and if the left mouse button was pressed.
    if Rectplace.collidepoint(pos) and pressed1:
        print("You have opened a chest!")
    # Quit pygame.
            for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit(1)

Comment out HTML and PHP together

You can only accomplish this with PHP comments.

 <!-- <tr>
      <td><?php //echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php //echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php //echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php //echo $sort_order; ?>" size="1" /></td>
    </tr> -->

The way that PHP and HTML works, it is not able to comment in one swoop unless you do:

<?php

/*

echo <<<ENDHTML
 <tr>
          <td>{$entry_keyword}</td>
          <td><input type="text" name="keyword" value="{echo $keyword}" /></td>
        </tr>
        <tr>
          <td>{$entry_sort_order}</td>
          <td><input name="sort_order" value="{$sort_order}" size="1" /></td>
        </tr>
ENDHTML;

*/
?>

How to define a preprocessor symbol in Xcode

You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png

If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

Visual Studio : short cut Key : Duplicate Line

It's simple Ctrl + C ; Ctrl + V , check this link. As long as you don't select any text, this will duplicate the line the cursor is over when you press Ctrl+C.

FileSystemWatcher Changed event is raised twice

This code worked for me.

        private void OnChanged(object source, FileSystemEventArgs e)
    {

        string fullFilePath = e.FullPath.ToString();
        string fullURL = buildTheUrlFromStudyXML(fullFilePath);

        System.Diagnostics.Process.Start("iexplore", fullURL);

        Timer timer = new Timer();
        ((FileSystemWatcher)source).Changed -= new FileSystemEventHandler(OnChanged);
        timer.Interval = 1000;
        timer.Elapsed += new ElapsedEventHandler(t_Elapsed);
        timer.Start();
    }

    private void t_Elapsed(object sender, ElapsedEventArgs e)
    {
        ((Timer)sender).Stop();
        theWatcher.Changed += new FileSystemEventHandler(OnChanged);
    }

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

I'm surprised to see all answers stating the use of alt attribute in a tag is not valid. This is absolutely wrong.

Html does not block you using any attributes:

<a your-custom-attribute="value">Any attribute can be used</a>

If you ask if it is semantically correct to use alt attribute in a then I will say:

NO. It is used to set image description <img alt="image description" />.

It is a matter of what you'd do with the attributes. Here's an example:

_x000D_
_x000D_
a::after {_x000D_
  content: attr(color); /* attr can be used as content */_x000D_
  display: block;_x000D_
  color: white;_x000D_
  background-color: blue;_x000D_
  background-color: attr(color); /* This won't work */_x000D_
  display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
  display: block;_x000D_
}_x000D_
[hidden] {_x000D_
  display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
_x000D_
_x000D_

Again, if you ask if it is semantically correct to use custom attribute then I will say:

No. Use data-* attributes for its semantic use.


Oops, question was asked in 2013.

Using Laravel Homestead: 'no input file specified'

Same issue for me.

Neither vagrant provision or homestead up --provision worked for me, but the below did - probably as homestead was already running when I modified the yml file

vagrant reload --provision

Checking length of dictionary object

Count and show keys in a dictionary (run in console):

o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")

Sample output:

"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"

Simple count function:

function size_dict(d){c=0; for (i in d) ++c; return c}

Difference between Visibility.Collapsed and Visibility.Hidden

The difference is that Visibility.Hidden hides the control, but reserves the space it occupies in the layout. So it renders whitespace instead of the control. Visibilty.Collapsed does not render the control and does not reserve the whitespace. The space the control would take is 'collapsed', hence the name.

The exact text from the MSDN:

Collapsed: Do not display the element, and do not reserve space for it in layout.

Hidden: Do not display the element, but reserve space for the element in layout.

Visible: Display the element.

See: http://msdn.microsoft.com/en-us/library/system.windows.visibility.aspx

Colorized grep -- viewing the entire file with highlighted matches

Use colout program: http://nojhan.github.io/colout/

It is designed to add color highlights to a text stream. Given a regex and a color (e.g. "red"), it reproduces a text stream with matches highlighted. e.g:

# cat logfile but highlight instances of 'ERROR' in red
colout ERROR red <logfile

You can chain multiple invocations to add multiple different color highlights:

tail -f /var/log/nginx/access.log | \
    colout ' 5\d\d ' red | \
    colout ' 4\d\d ' yellow | \
    colout ' 3\d\d ' cyan | \
    colout ' 2\d\d ' green

Or you can achieve the same thing by using a regex with N groups (parenthesised parts of the regex), followed by a comma separated list of N colors.

vagrant status | \
    colout \
        '\''(^.+  running)|(^.+suspended)|(^.+not running)'\'' \
        green,yellow,red

A Generic error occurred in GDI+ in Bitmap.Save method

For me it was a permission problem. Somebody removed write permissions on the folder for the user account under which the application was running.

jQuery Show-Hide DIV based on Checkbox Value

`Display

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

How to make a vertical line in HTML

To make the vertical line to center in the middle use:

position: absolute; 
left: 50%;

Check file uploaded is in csv format

You can't always rely on MIME type..

According to: http://filext.com/file-extension/CSV

text/comma-separated-values, text/csv, application/csv, application/excel, application/vnd.ms-excel, application/vnd.msexcel, text/anytext

There are various MIME types for CSV.

Your probably best of checking extension, again not very reliable, but for your application it may be fine.

$info = pathinfo($_FILES['uploadedfile']['tmp_name']);

if($info['extension'] == 'csv'){
 // Good to go
}

Code untested.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

Some of the solutions here are overly complex. Here's one with 4 lines of code, no batch files, no external apps and all self-contained in the SQL server.

In this example, my table is named "MyTable" and it has two columns named Column1 and Column2. Column2 is an integer, so we need to CAST it to varchar for the export:

DECLARE @FileName varchar(100)
DECLARE @BCPCommand varchar(8000)
DECLARE @ColumnHeader varchar(8000)

    SET @FileName = 'C:\Temp\OutputFile.csv'
 SELECT @ColumnHeader = COALESCE(@ColumnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='MyTable'
    SET @BCPCommand = 'bcp "SELECT '+ @ColumnHeader +' UNION ALL SELECT Column1, CAST(Column2 AS varchar(100)) AS Column2 FROM MyTable" queryout "' + @FileName + '" -c -t , -r \n  -S . -T'
   EXEC master..xp_cmdshell @BCPCommand

You could add this to a stored procedure to fully automate your .CSV file (with header row) creation.

Network usage top/htop on Linux

Also iftop:

display bandwidth usage on an interface

iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...

What should I do if the current ASP.NET session is null?

The following statement is not entirely accurate:

"So if you are calling other functionality, including static classes, from your page, you should be fine"

I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.

As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:

There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:

[WebMethod(EnableSession = true)]

By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.

Thanks to Matthew Cosier for the solution.

Just thought I'd add my two cents.

Ed

Border color on default input style

whats actually wrong with:

input { border: 1px solid #f00; }

do you only want it on inputs with errors? in that case give the input a class of error...

input.error { border: 1px solid #f00; }

Import Excel Data into PostgreSQL 9.3

As explained here http://www.postgresonline.com/journal/categories/journal/archives/339-OGR-foreign-data-wrapper-on-Windows-first-taste.html

With ogr_fdw module, its possible to open the excel sheet as foreign table in pgsql and query it directly like any other regular tables in pgsql. This is useful for reading data from the same regularly updated table

To do this, the table header in your spreadsheet must be clean, the current ogr_fdw driver can't deal with wide-width character or new lines etc. with these characters, you will probably not be able to reference the column in pgsql due to encoding issue. (Major reason I can't use this wonderful extension.)

The ogr_fdw pre-build binaries for windows are located here http://winnie.postgis.net/download/windows/pg96/buildbot/extras/ change the version number in link to download corresponding builds. extract the file to pgsql folder to overwrite the same name sub-folders. restart pgsql. Before the test drive, the module needs to be installed by executing:

CREATE EXTENSION ogr_fdw;

Usage in brief:

  1. use ogr_fdw_info.exe to prob the excel file for sheet name list

    ogr_fdw_info -s "C:/excel.xlsx"
    
  2. use "ogr_fdw_info.exe -l" to prob a individual sheet and generate a table definition code.

    ogr_fdw_info -s "C:/excel.xlsx" -l "sheetname"
    

Execute the generated definition code in pgsql, a foreign table is created and mapped to your excel file. it can be queried like regular tables.

This is especially useful, if you have many small files with the same table structure. Just change the path and name in definition, and update the definition will be enough.

This plugin supports both XLSX and XLS file. According to the document it also possible to write data back into the spreadsheet file, but all the fancy formatting in your excel will be lost, the file is recreated on write.

If the excel file is huge. This will not work. which is another reason I didn't use this extension. It load data in one time. But this extension also support ODBC interface, it should be possible to use windows' ODBC excel file driver to create a ODBC source for the excel file and use ogr_fdw or any other pgsql's ODBC foreign data wrapper to query this intermediate ODBC source. This should be fairly stable.

The downside is that you can't change file location or name easily within pgsql like in the previous approach.

A friendly reminder. The permission issue applies to this fdw extensions. since its loaded into pgsql service. pgsql must have access privileged to the excel files.