Programs & Examples On #Flashlite

Adobe Flash Lite is a lightweight version of Adobe Flash Player intended for mobile phones.

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

Alter column in SQL Server

Try this one.

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

Reading an Excel file in python using pandas

import pandas as pd

data = pd.read_excel (r'**YourPath**.xlsx')

print (data)

How to do a background for a label will be without color?

Generally, labels and textboxes that appear in front of an image is best organized in a panel. When rendering, if labels need to be transparent to an image within the panel, you can switch to image as parent of labels in Form initiation like this:

var oldParent = panel1;
var newParent = pictureBox1;

foreach (var label in oldParent.Controls.OfType<Label>())
{
    label.Location = newParent.PointToClient(label.Parent.PointToScreen(label.Location));
    label.Parent = newParent;
    label.BackColor = Color.Transparent;
}

How do you know if Tomcat Server is installed on your PC

In case of Windows(in my case XP):-

  1. Check the directory where tomcat is installed.
  2. Open the directory called \conf in it.
  3. Then search file server.xml
  4. Open that file and check what is the connector port for HTTP,whre you will found something like 8009,8080 etc.
  5. Suppose it found 8009,use that port as "/localhost:8009/" in your web-browser with HTTP protocol. Hope this will work !

LDAP root query syntax to search more than one specific OU

It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL

Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.

Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.

Single quotes vs. double quotes in Python

"If you're going to use apostrophes, 
       ^

you'll definitely want to use double quotes".
   ^

For that simple reason, I always use double quotes on the outside. Always

Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!

C# password TextBox in a ASP.net website

I think this is what you are looking for

 <asp:TextBox ID="txbPass" runat="server" TextMode="Password"></asp:TextBox>

Why doesn't Dijkstra's algorithm work for negative weight edges?

Recall that in Dijkstra's algorithm, once a vertex is marked as "closed" (and out of the open set) - the algorithm found the shortest path to it, and will never have to develop this node again - it assumes the path developed to this path is the shortest.

But with negative weights - it might not be true. For example:

       A
      / \
     /   \
    /     \
   5       2
  /         \
  B--(-10)-->C

V={A,B,C} ; E = {(A,C,2), (A,B,5), (B,C,-10)}

Dijkstra from A will first develop C, and will later fail to find A->B->C


EDIT a bit deeper explanation:

Note that this is important, because in each relaxation step, the algorithm assumes the "cost" to the "closed" nodes is indeed minimal, and thus the node that will next be selected is also minimal.

The idea of it is: If we have a vertex in open such that its cost is minimal - by adding any positive number to any vertex - the minimality will never change.
Without the constraint on positive numbers - the above assumption is not true.

Since we do "know" each vertex which was "closed" is minimal - we can safely do the relaxation step - without "looking back". If we do need to "look back" - Bellman-Ford offers a recursive-like (DP) solution of doing so.

cmake error 'the source does not appear to contain CMakeLists.txt'

You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there.

How to check if a file exists in a shell script

If you're using a NFS, "test" is a better solution, because you can add a timeout to it, in case your NFS is down:

time timeout 3 test -f 
/nfs/my_nfs_is_currently_down
real    0m3.004s <<== timeout is taken into account
user    0m0.001s
sys     0m0.004s
echo $?
124   <= 124 means the timeout has been reached

A "[ -e my_file ]" construct will freeze until the NFS is functional again:

if [ -e /nfs/my_nfs_is_currently_down ]; then echo "ok" else echo "ko" ; fi

<no answer from the system, my session is "frozen">

How to calculate the IP range when the IP address and the netmask is given?

You might already know this, but to check that you're getting this stuff right have a look at http://www.subnet-calculator.com/ - you can see there how the bits represent the network and host portions of the address.

Deleting specific rows from DataTable

You try this for getting and removing id column from data table

if (dt1.Columns.Contains("ID"))
{
    for (int i = dt1.Rows.Count - 1; i >= 0; i--)
    {
        DataRow dr = dt1.Rows[i];

        if (dr["ID"].ToString() != "" && dr["ID"].ToString() != null)
        {
            dr.Delete();
        }
    }

    dt1.Columns.Remove("ID");
}

What's the difference setting Embed Interop Types true and false in Visual Studio?

I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.

How can I delete all Git branches which have been merged?

Below query works for me

for branch in  `git branch -r --merged | grep -v '\*\|master\|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin\//, "")}1'`;do git push origin --delete $branch; done

and this will filter any given branch in the grep pipe.

Works well over http clone, but not so well for the ssh connection.

set gvim font in .vimrc file

For Windows do the following:

  1. Note down the font name and font size from the "Edit-Select Font..." menu of "gvim.exec".
  2. Then do :e $MYGVIMRC
  3. Search for "guifont" string and change it to set guifont=<font name as noted>:h<font size>
  4. Save the file and quit.
  5. Next time when you execute gvim.exec, you will see the effect.

Update and left outer join statements

The Left join in this query is pointless:

UPDATE md SET md.status = '3' 
FROM pd_mounting_details AS md 
LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id

It would update all rows of pd_mounting_details, whether or not a matching row exists in pd_order_ecolid. If you wanted to only update matching rows, it should be an inner join.

If you want to apply some condition based on the join occurring or not, you need to add a WHERE clause and/or a CASE expression in your SET clause.

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

Get city name using geolocation

You can get the name of the city, country, street name and other geodata using the Google Maps Geocoding API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {
            console.log(position.coords.latitude)
            console.log(position.coords.longitude)

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                console.log(location)
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

and to display this data on the page using jQuery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>

    <p>Country: <span id="country"></span></p>
    <p>State: <span id="state"></span></p>
    <p>City: <span id="city"></span></p>
    <p>Address: <span id="address"></span></p>

    <p>Latitude: <span id="latitude"></span></p>
    <p>Longitude: <span id="longitude"></span></p>

    <script type="text/javascript">
        navigator.geolocation.getCurrentPosition(success, error);

        function success(position) {

            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                $('#country').html(location.results[0].address_components[5].long_name);
                $('#state').html(location.results[0].address_components[4].long_name);
                $('#city').html(location.results[0].address_components[2].long_name);
                $('#address').html(location.results[0].formatted_address);
                $('#latitude').html(position.coords.latitude);
                $('#longitude').html(position.coords.longitude);
            })

        }

        function error(err) {
            console.log(err)
        }
    </script>
</body>
</html>

What is Gradle in Android Studio?

Short Answer

Gradle is a build system.

Long Answer

Before Android Studio you were using Eclipse for your development purposes, and, chances are, you didn't know how to build your Android APK without Eclipse.

You can do this on the command line, but you have to learn what each tool (dx, aapt) does in the SDK. Eclipse saved us all from these low level but important, fundamental details by giving us their own build system.

Now, have you ever wondered why the res folder is in the same directory as your src folder?

This is where the build system enters the picture. The build system automatically takes all the source files (.java or .xml), then applies the appropriate tool (e.g. takes java class files and converts them to dex files), and groups all of them into one compressed file, our beloved APK.

This build system uses some conventions: an example of one is to specify the directory containing the source files (in Eclipse it is \src folder) or resources files (in Eclipse it is \res folder).

Now, in order to automate all these tasks, there has to be a script; you can write your own build system using shell scripting in linux or batch files syntax in windows. Got it?

Gradle is another build system that takes the best features from other build systems and combines them into one. It is improved based off of their shortcomings. It is a JVM based build system, what that means is that you can write your own script in Java, which Android Studio makes use of.

One cool thing about gradle is that it is a plugin based system. This means if you have your own programming language and you want to automate the task of building some package (output like a JAR for Java) from sources then you can write a complete plugin in Java or Groovy(or Kotlin, see here), and distribute it to rest of world.

Why did Google use it?

Google saw one of the most advanced build systems on the market and realized that you could write scripts of your own with little to no learning curve, and without learning Groovy or any other new language. So they wrote the Android plugin for Gradle.

You must have seen build.gradle file(s) in your project. That is where you can write scripts to automate your tasks. The code you saw in these files is Groovy code. If you write System.out.println("Hello Gradle!"); then it will print on your console.

What can you do in a build script?

A simple example is that you have to copy some files from one directory to another before the actual build process happens. A Gradle build script can do this.

If/else else if in Jquery for a condition

See this answer. val() is comparing a string, not a numeric value.

Java code for getting current time

try this to get the current date.You can also get current hour, minutes and seconds by using getters :

new Date(System.currentTimeMillis()).get....()

Append values to a set in Python

keep.update((0,1,2,3,4,5,6,7,8,9,10))

Or

keep.update(np.arange(11))

SQL Server Management Studio missing

Try restarting your computer if you just installed SQL Server and there's no choice in the SQL Server Installation Center to install SQL Server Management Studio.

This choice (see image below) only appeared for me after I installed SQL Server, then restarted my computer:

enter image description here

'Framework not found' in Xcode

I realised that I hadn't run/built my framework with the Generic Device, which strangely lead to these issues. I just put the framework back in and it worked.

How to avoid 'undefined index' errors?

If you are maintaining old code, you probably cannot aim for "the best possible code ever"... That's one case when, in my opinion, you could lower the error_reporting level.

These "undefined index" should only be Notices ; so, you could set the error_reporting level to exclude notices.

One solution is with the error_reporting function, like this :

// Report all errors except E_NOTICE
error_reporting(E_ALL ^ E_NOTICE);

The good thing with this solution is you can set it to exclude notices only when it's necessary (say, for instance, if there is only one or two files with that kind of code)

One other solution would be to set this in php.ini (might not be such a good idea if you are working on several applications, though, as it could mask useful notices ) ; see error_reporting in php.ini.

But I insist : this is acceptable only because you are maintaining an old application -- you should not do that when developping new code !

Timeout jQuery effects

This can be done with only a few lines of jQuery:

$(function(){
    // make sure img is hidden - fade in
    $('img').hide().fadeIn(2000);

    // after 5 second timeout - fade out
    setTimeout(function(){$('img').fadeOut(2000);}, 5000);
});?

see the fiddle below for a working example...

http://jsfiddle.net/eNxuJ/78/

How to hide Table Row Overflow?

Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53

Just define width of the table and width for each table cell

something like

table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}

It works like a charm :o)

How to use AND in IF Statement

If you are simply looking for the occurrence of "Miami" or "Florida" inside a string (since you put * at both ends), it's probably better to use the InStr function instead of Like. Not only are the results more predictable, but I believe you'll get better performance.

Also, VBA is not short-circuited so when you use the AND keyword, it will test both sides of the AND, regardless if the first test failed or not. In VBA, it is more optimal to use 2 if-statements in these cases, that way you aren't checking for "Florida" if you don't find "Miami".

The other advice I have is that a for-each loop is faster than a for-loop. Using .offset, you can achieve the same thing, but with better effeciency. Of course there are even better ways (like variant arrays), but those will add a layer of complexity not needed in this example.

Here is some sample code:

Sub test()

Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row

For Each cell In Range("A1:A" & lastRow)
    If InStr(1, cell.Value, "Miami") <> 0 Then
        If InStr(1, cell.Offset(, 3).Value, "Florida") <> 0 Then
            cell.Offset(, 2).Value = "BA"
        End If
    End If
Next

Application.ScreenUpdating = True
End Sub

I hope you find some of this helpful, and keep at it with VBA! ^^

Handling a Menu Item Click Event - Android

Menu items file looks like

res/menu/menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/settings"
        android:title="Setting"
        app:showAsAction="never" />
    <item
        android:id="@+id/my_activity"
        android:title="My Activity"
        app:showAsAction="always"
        android:icon="@android:drawable/btn_radio"/>
</menu>

Java code looks like

src/MainActivity.java

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

      if (id == R.id.my_activity) {
            Intent intent1 = new Intent(this,MyActivity.class);
            this.startActivity(intent1);
            return true;
        }

        if (id == R.id.settings) {
            Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

And add following code to your AndroidManifest.xml file

<activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
        </activity>

I hope it will help you.

Close Bootstrap Modal

to close bootstrap modal you can pass 'hide' as option to modal method as follow

$('#modal').modal('hide');

Please take a look at working fiddle here

bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation

If none of the above method work, give a id to your close button and trigger click on close button.

Laravel Eloquent get results grouped by days

I had same problem, I'm currently using Laravel 5.3.

I use DATE_FORMAT()

->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))

Hopefully this will help you.

Should I return EXIT_SUCCESS or 0 from main()?

This is a never ending story that reflect the limits (an myth) of "interoperability and portability over all".

What the program should return to indicate "success" should be defined by who is receiving the value (the Operating system, or the process that invoked the program) not by a language specification.

But programmers likes to write code in "portable way" and hence they invent their own model for the concept of "operating system" defining symbolic values to return.

Now, in a many-to-many scenario (where many languages serve to write programs to many system) the correspondence between the language convention for "success" and the operating system one (that no one can grant to be always the same) should be handled by the specific implementation of a library for a specific target platform.

But - unfortunatly - these concept where not that clear at the time the C language was deployed (mainly to write the UNIX kernel), and Gigagrams of books where written by saying "return 0 means success", since that was true on the OS at that time having a C compiler.

From then on, no clear standardization was ever made on how such a correspondence should be handled. C and C++ has their own definition of "return values" but no-one grant a proper OS translation (or better: no compiler documentation say anything about it). 0 means success if true for UNIX - LINUX and -for independent reasons- for Windows as well, and this cover 90% of the existing "consumer computers", that - in the most of the cases - disregard the return value (so we can discuss for decades, bu no-one will ever notice!)

Inside this scenario, before taking a decision, ask these questions: - Am I interested to communicate something to my caller about my existing? (If I just always return 0 ... there is no clue behind the all thing) - Is my caller having conventions about this communication ? (Note that a single value is not a convention: that doesn't allow any information representation)

If both of this answer are no, probably the good solution is don't write the main return statement at all. (And let the compiler to decide, in respect to the target is working to).

If no convention are in place 0=success meet the most of the situations (and using symbols may be problematic, if they introduce a convention).

If conventions are in place, ensure to use symbolic constants that are coherent with them (and ensure convention coherence, not value coherence, between platforms).

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

How do I pass JavaScript variables to PHP?

We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

So it's better to use the AJAX to parse the JavaScript value into the php Code.

Or alternatively we can make this done with the help of COOKIES in our code.

Thanks & Cheers.

How do I calculate power-of in C#?

You are looking for the static method Math.Pow().

Warning: push.default is unset; its implicit value is changing in Git 2.0

I was wondering why I was getting that big warning message on Ubuntu 16.04 (which comes with Git 2.7.4), but not on Arch Linux. The reason is that the warning was removed in Git 2.8 (March 2016):

Across the transition at around Git version 2.0, the user used to get a pretty loud warning when running "git push" without setting push.default configuration variable. We no longer warn because the transition was completed a long time ago.

So you won't see the warning if you have Git 2.8 and later and don't need to set push.default unless you want to change the default 'simple' behavior.

Creating an Array from a Range in VBA

If we do it just like this:

Dim myArr as Variant
myArr = Range("A1:A10")

the new array will be with two dimensions. Which is not always somehow comfortable to work with:

enter image description here

To get away of the two dimensions, when getting a single column to array, we may use the built-in Excel function “Transpose”. With it, the data becomes in one dimension:

enter image description here

If we have the data in a row, a single transpose will not do the job. We need to use the Transpose function twice:

enter image description here

Note: As you see from the screenshots, when generated this way, arrays start with 1, not with 0. Just be a bit careful.

How do I clear this setInterval inside a function?

the_int=window.clearInterval(the_int);

After installation of Gulp: “no command 'gulp' found”

I solved the issue removing gulp and installing gulp-cli again:

rm /usr/local/bin/gulp
npm install -g gulp-cli

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

This seems much simpler than accepted solution - does it have shortcomings I'm not considering? Came here looking for some dead-simple copy pasta.

import threading, time

def print_every_n_seconds(n=2):
    while True:
        print(time.ctime())
        time.sleep(n)
    
thread = threading.Thread(target=print_every_n_seconds, daemon=True)
thread.start()

Which asynchronously outputs.

#Tue Oct 16 17:29:40 2018
#Tue Oct 16 17:29:42 2018
#Tue Oct 16 17:29:44 2018

This does have drift. If the task being run takes appreciable amount of time, then the interval becomes 2 seconds + task time, so if you need precise scheduling then this is not for you.**

Note the daemon=True flag means this thread won't block the app from shutting down. For example, had issue where pytest would hang indefinitely after running tests waiting for this thead to cease.

Generate your own Error code in swift 3

protocol CustomError : Error {

    var localizedTitle: String
    var localizedDescription: String

}

enum RequestError : Int, CustomError {

    case badRequest         = 400
    case loginFailed        = 401
    case userDisabled       = 403
    case notFound           = 404
    case methodNotAllowed   = 405
    case serverError        = 500
    case noConnection       = -1009
    case timeOutError       = -1001

}

func anything(errorCode: Int) -> CustomError? {

      return RequestError(rawValue: errorCode)
}

Can't use SURF, SIFT in OpenCV

IN opencv3.x SIFT() & SURF() are no longer exist .for this

uninstall all the opencv versions

python -m pip uninstall opencv-python

python -m pip uninstall opencv-contrib-python

after that install opencv-contrib to include sift() and surf() using below given command with python(3.x)

python -m pip install opencv-contrib-python==3.4.2.16

then you can use

sift = cv2.xfeatures2d.SIFT_create()

How to resolve symbolic links in a shell script

Another way:

# Gets the real path of a link, following all links
myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link" | sed "s|^\([^/].*\)\$|$(dirname $1)/\1|"); }

# Returns the absolute path to a command, maybe in $PATH (which) or not. If not found, returns the same
whereis() { echo $1 | sed "s|^\([^/].*/.*\)|$(pwd)/\1|;s|^\([^/]*\)$|$(which -- $1)|;s|^$|$1|"; } 

# Returns the realpath of a called command.
whereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed "s|^\([^/].*\)\$|$(dirname ${SCRIPT_PATH})/\1|"; } 

jQuery event to trigger action when a div is made visible

I changed the hide/show event trigger from Catalint based on Glenns idea. My problem was that I have a modular application. I change between modules showing and hiding divs parents. Then when I hide a module and show another one, with his method I have a visible delay when I change between modules. I only need sometimes to liten this event, and in some special childs. So I decided to notify only the childs with the class "displayObserver"

$.each(["show", "hide", "toggleClass", "addClass", "removeClass"], function () {
    var _oldFn = $.fn[this];
    $.fn[this] = function () {
        var hidden = this.find(".displayObserver:hidden").add(this.filter(":hidden"));
        var visible = this.find(".displayObserver:visible").add(this.filter(":visible"));
        var result = _oldFn.apply(this, arguments);
        hidden.filter(":visible").each(function () {
            $(this).triggerHandler("show");
        }); 
        visible.filter(":hidden").each(function () {
            $(this).triggerHandler("hide");
        });
        return result;
    }
});

Then when a child wants to listen for "show" or "hide" event I have to add him the class "displayObserver", and when It does not want to continue listen it, I remove him the class

bindDisplayEvent: function () {
   $("#child1").addClass("displayObserver");
   $("#child1").off("show", this.onParentShow);
   $("#child1").on("show", this.onParentShow);
},

bindDisplayEvent: function () {
   $("#child1").removeClass("displayObserver");
   $("#child1").off("show", this.onParentShow);
},

I wish help

What is the difference between window, screen, and document in Javascript?

Briefly, with more detail below,

  • window is the execution context and global object for that context's JavaScript
  • document contains the DOM, initialized by parsing HTML
  • screen describes the physical display's full screen

See W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window, and a window has window.document and window.screen properties. The browser tab's window is the global context, so document and screen refer to window.document and window.screen. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.

window

Each browser tab has its own top-level window object. Each <iframe> (and deprecated <frame>) element has its own window object too, nested within a parent window. Each of these windows gets its own separate global object. window.window always refers to window, but window.parent and window.top might refer to enclosing windows, giving access to other execution contexts. In addition to document and screen described below, window properties include

  • setTimeout() and setInterval() binding event handlers to a timer
  • location giving the current URL
  • history with methods back() and forward() giving the tab's mutable history
  • navigator describing the browser software

document

Each window object has a document object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet

<body>
  <p id="holyCow"> This is the first paragraph.</p>
</body>

the paragraph element can be referenced by any of the following:

  • window.holyCow or window["holyCow"]
  • document.getElementById("holyCow")
  • document.querySelector("#holyCow")
  • document.body.firstChild
  • document.body.children[0]

screen

The window object also has a screen object with properties describing the physical display:

  • screen properties width and height are the full screen

  • screen properties availWidth and availHeight omit the toolbar

The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect() method of any document element will return an object with top, left, bottom, and right properties describing the location of the element in the viewport.

Accessing a value in a tuple that is in a list

a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))

how to use the Box-Cox power transformation in R

Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().

How to customize the background/border colors of a grouped table view cell?

To change the table view border color:

In.h:

#import <QuartzCore/QuartzCore.h>

In .m:

tableView.layer.masksToBounds=YES;
tableView.layer.borderWidth = 1.0f;
tableView.layer.borderColor = [UIColor whiteColor].CGColor;

Regular Expression to get all characters before "-"

I dont think you need regex to achieve this. I would look at the SubString method along with the indexOf method. If you need more help, add a comment showing what you have attempted and I will offer more help.

Aborting a stash pop in Git

If DavidG is correct that it didn't pop the stash because of the merge conflict, then you merely need to clean up your working directory. Quickly git commit everything you care about. (You can reset or squash the commit later if you're not done.) Then with everything you care about safe, git reset everything else that git stash pop dumped into your working directory.

How to dynamically change the color of the selected menu item of a web page?

Set the styles for class active and hover:


Than you need to make the li active, on the server side. So when you are drawing the menu, you should know which page is loaded and set it to:

 <li class="active">Question</li>
 <li>Tags</li>
 <li>Users</li>

But if you are changing the content without reloading, you cannot change set the active li element on the server, you need to use javascript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
  .menu{width: 300px; height: 25; font-size: 18px;}
  .menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
  .menu li:hover, .menu li.active {
        background-color: #f90;
    }
</style>
</head>
<body>

<ul class="menu">
<li>Item 1</li>
<li class="active">Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>

<script type="text/javascript">

var make_button_active = function()
{
  //Get item siblings
  var siblings =($(this).siblings());

  //Remove active class on all buttons
  siblings.each(function (index)
    {
      $(this).removeClass('active');
    }
  )


  //Add the clicked button class
  $(this).addClass('active');
}

//Attach events to menu
$(document).ready(
  function()
  {
    $(".menu li").click(make_button_active);
  }  
)

</script>
</body>

</html>

Angular 2 Cannot find control with unspecified name attribute on formArrays

For me, I was trying to add [formGroupName]="i" and/or formControlName and forgetting to specify the parent formArrayName. Pay attention to your form group tree.

vue.js 'document.getElementById' shorthand

Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

_x000D_
_x000D_
 var app = new Vue({_x000D_
    el:'#app',_x000D_
    methods: {    _x000D_
        showMyDiv() {_x000D_
           console.log(this.$refs.myDiv);_x000D_
        }_x000D_
    }_x000D_
    _x000D_
   });
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
   <div id="myDiv" ref="myDiv"></div>_x000D_
   <button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Download a file from HTTPS using download.file()

Had exactly the same problem as UseR (original question), I'm also using windows 7. I tried all proposed solutions and they didn't work.

I resolved the problem doing as follows:

  1. Using RStudio instead of R console.

  2. Actualising the version of R (from 3.1.0 to 3.1.1) so that the library RCurl runs OK on it. (I'm using now R3.1.1 32bit although my system is 64bit).

  3. I typed the URL address as https (secure connection) and with / instead of backslashes \\.

  4. Setting method = "auto".

It works for me now. You should see the message:

Content type 'text/csv; charset=utf-8' length 9294 bytes
opened URL
downloaded 9294 by

Python, Pandas : write content of DataFrame into text File

@AHegde - To get the tab delimited output use separator sep='\t'.

For df.to_csv:

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')

For np.savetxt:

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')

How do you check that a number is NaN in JavaScript?

As far as a value of type Number is to be tested whether it is a NaN or not, the global function isNaN will do the work

isNaN(any-Number);

For a generic approach which works for all the types in JS, we can use any of the following:

For ECMAScript-5 Users:

#1
if(x !== x) {
    console.info('x is NaN.');
}
else {
    console.info('x is NOT a NaN.');
}

For people using ECMAScript-6:

#2
Number.isNaN(x);

And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan

#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
    return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {     
    return value !== value;
}

please check This Answer for more details.

How to make div follow scrolling smoothly with jQuery?

That code doesn't work very well i fixed it a little bit

var el = $('.caja-pago');
var elpos_original = el.offset().top;

 $(window).scroll(function(){
     var elpos = el.offset().top;
     var windowpos = $(window).scrollTop();
     var finaldestination = windowpos;
     if(windowpos<elpos_original) {
         finaldestination = elpos_original;
         el.stop().animate({'top':400},500);
     } else {
         el.stop().animate({'top':windowpos+10},500);
     }
 });

How to view table contents in Mysql Workbench GUI?

After displaying the first 1000 records, you can page through them by clicking on the icon beside "Fetch rows:" in the header of the result grid.

Why does git status show branch is up-to-date when changes exist upstream?

Let look into a sample git repo to verify if your branch (master) is up to date with origin/master.

Verify that local master is tracking origin/master:

$ git branch -vv
* master a357df1eb [origin/master] This is a commit message

More info about local master branch:

$ git show --summary
commit a357df1eb941beb5cac3601153f063dae7faf5a8 (HEAD -> master, tag: 2.8.0, origin/master, origin/HEAD)
Author: ...
Date:   Tue Dec 11 14:25:52 2018 +0100

    Another commit message

Verify if origin/master is on the same commit:

$ cat .git/packed-refs | grep origin/master
a357df1eb941beb5cac3601153f063dae7faf5a8 refs/remotes/origin/master

We can see the same hash around, and safe to say the branch is in consistency with the remote one, at least in the current git repo.

How do I define and use an ENUM in Objective-C?

This is how Apple does it for classes like NSString:

In the header file:

enum {
    PlayerStateOff,
    PlayerStatePlaying,
    PlayerStatePaused
};

typedef NSInteger PlayerState;

Refer to Coding Guidelines at http://developer.apple.com/

Convert XML String to Object

If you have the xsd of the xml message then you can generate c# classes using the .Net xsd.exe tool.

This .Net classes can then be used to generate the xml.

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

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

Just want to share my experience here. I came across the same issue while cross compiling for MTK platform on a Windows 64 bit machine. MinGW and MSYS are involved in the building process and this issue popped up. I solved it by changing the msys-1.0.dll file. Neither rebase.exe nor system reboot worked for me.

Since there is no rebase.exe installed on my computer. I installed cygwin64 and used the rebase.exe inside:

C:\cygwin64\bin\rebase.exe -b 0x50000000 msys-1.0.dll

Though rebasing looked successful, the error remained. Then I ran rebase command inside Cygwin64 terminal and got an error:

$ rebase -b 0x50000000 msys-1.0.dll
rebase: Invalid Baseaddress 0x50000000, must be > 0x200000000

I later tried a couple address but neither of them worked. So I ended up changing the msys-1.0.dll file and it solved the problem.

Send a SMS via intent

Uri uri = Uri.parse("smsto:YOUR_SMS_NUMBER");   
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);   
intent.putExtra("sms_body", "The SMS text");   
startActivity(intent);  

WPF Add a Border to a TextBlock

A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label

See this link for more on the differences between a TextBlock and other Controls

Multiple SQL joins

It will be something like this:

SELECT b.Title, b.Edition, b.Year, b.Pages, b.Rating, c.Category, p.Publisher, w.LastName
FROM
    Books b
    JOIN Categories_Book cb ON cb._ISBN = b._Books_ISBN
    JOIN Category c ON c._CategoryID = cb._Categories_Category_ID
    JOIN Publishers p ON p._PublisherID = b.PublisherID
    JOIN Writers_Books wb ON wb._Books_ISBN = b._ISBN
    JOIN Writer w ON w._WritersID = wb._Writers_WriterID

You use the join statement to indicate which fields from table A map to table B. I'm using aliases here thats why you see Books b the Books table will be referred to as b in the rest of the query. This makes for less typing.

FYI your naming convention is very strange, I would expect it to be more like this:

Book: ID, ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating
Category: ID, [Name]
BookCategory: ID, CategoryID, BookID
Publisher: ID, [Name]
Writer: ID, LastName
BookWriter: ID, WriterID, BookID

How to refresh page on back button click?

window.onbeforeunload = function() { redirect(window.history.back(1)); };

How to sync with a remote Git repository?

You need to add the original repository (the one that you forked) as a remote.

git remote add github (clone url for the orignal repository)

Then you need to bring in the changes to your local repository

git fetch github

Now you will have all the branches of the original repository in your local one. For example, the master branch will be github/master. With these branches you can do what you will. Merge them into your branches etc

MySQL DROP all tables, ignoring foreign keys

DB="your database name" \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=0" \
    && mysqldump --add-drop-table --no-data $DB | grep 'DROP TABLE' | grep -Ev "^$" | mysql $DB \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=1"

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Business logic in MVC

The term business logic is in my opinion not a precise definition. Evans talks in his book, Domain Driven Design, about two types of business logic:

  • Domain logic.
  • Application logic.

This separation is in my opinion a lot clearer. And with the realization that there are different types of business rules also comes the realization that they don't all necessarily go the same place.

Domain logic is logic that corresponds to the actual domain. So if you are creating an accounting application, then domain rules would be rules regarding accounts, postings, taxation, etc. In an agile software planning tool, the rules would be stuff like calculating release dates based on velocity and story points in the backlog, etc.

For both these types of application, CSV import/export could be relevant, but the rules of CSV import/export has nothing to do with the actual domain. This kind of logic is application logic.

Domain logic most certainly goes into the model layer. The model would also correspond to the domain layer in DDD.

Application logic however does not necessarily have to be placed in the model layer. That could be placed in the controllers directly, or you could create a separate application layer hosting those rules. What is most logical in this case would depend on the actual application.

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

Remove certain characters from a string

One issue with REPLACE will be where city names contain the district name. You can use something like.

SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM   dbo.tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004' 

Close virtual keyboard on button press

Crash Null Point Exception Fix: I had a case where the keyboard might not open when the user clicks the button. You have to write an if statement to check that getCurrentFocus() isn't a null:

            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

Iterating C++ vector from the end to the beginning

Here's a super simple implementation that allows use of the for each construct and relies only on C++14 std library:

namespace Details {

    // simple storage of a begin and end iterator
    template<class T>
    struct iterator_range
    {
        T beginning, ending;
        iterator_range(T beginning, T ending) : beginning(beginning), ending(ending) {}

        T begin() const { return beginning; }
        T end() const { return ending; }
    };

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// usage:
//  for (auto e : backwards(collection))
template<class T>
auto backwards(T & collection)
{
    using namespace std;
    return Details::iterator_range(rbegin(collection), rend(collection));
}

This works with things that supply an rbegin() and rend(), as well as with static arrays.

std::vector<int> collection{ 5, 9, 15, 22 };
for (auto e : backwards(collection))
    ;

long values[] = { 3, 6, 9, 12 };
for (auto e : backwards(values))
    ;

How to execute a raw update sql with dynamic binding in rails

It doesn't look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it's methods, e.g. for MySQL:

st = ActiveRecord::Base.connection.raw_connection.prepare("update table set f1=? where f2=? and f3=?")
st.execute(f1, f2, f3)
st.close

I'm not sure if there are other ramifications to doing this (connections left open, etc). I would trace the Rails code for a normal update to see what it's doing aside from the actual query.

Using prepared queries can save you a small amount of time in the database, but unless you're doing this a million times in a row, you'd probably be better off just building the update with normal Ruby substitution, e.g.

ActiveRecord::Base.connection.execute("update table set f1=#{ActiveRecord::Base.sanitize(f1)}")

or using ActiveRecord like the commenters said.

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

Android widget: How to change the text of a button

I had a button in my layout.xml that was defined as a View as in:

final View myButton = findViewById(R.id.button1);

I was not able to change the text on it until I also defined it as a button:

final View vButton = findViewById(R.id.button1);
final Button bButton = (Button) findViewById(R.id.button1);

When I needed to change the text, I used the bButton.setText("Some Text"); and when I wanted to alter the view, I used the vButton.

Worked great!

Figure out size of UILabel based on String in Swift

Swift 5:

If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.

extension UILabel {
    func getSize(constrainedWidth: CGFloat) -> CGSize {
        return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
    }
}

You can use it like this:

let label = UILabel()
label.text = "My text\nIs\nAwesome"
let labelSize = label.getSize(constrainedWidth:200.0)

Works for me

Local file access with JavaScript

Assuming that any file that JavaScript code might need, should be allowed directly by the user. Creators of famous browsers do not let JavaScript access files generally.

The main idea of the solution is: the JavaScript code cannot access the file by having its local URL. But it can use the file by having its DataURL: so if the user browses a file and opens it, JavaScript should get the "DataURL" directly from HTML instead of getting "URL".

Then it turns the DataURL into a file, using the readAsDataURL function and FileReader object. Source and a more complete guide with a nice example are in:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader?redirectlocale=en-US&redirectslug=DOM%2FFileReader

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

Windows equivalent to UNIX pwd

You can simply put "." the dot sign. I've had a cmd application that was requiring the path and I was already in the needed directory and I used the dot symbol.

Hope it helps.

How to get the path of the batch script in Windows?

That would be the %CD% variable.

@echo off
echo %CD%

%CD% returns the current directory the batch script is in.

How do you change the character encoding of a postgres database?

Daniel Kutik's answer is correct, but it can be even more safe, with database renaming.

So, the truly safe way is:

  1. Create new database with the different encoding and name
  2. Dump your database
  3. Restore dump to the new DB
  4. Test that your application runs correctly with the new DB
  5. Rename old DB to something meaningful
  6. Rename new DB
  7. Test application again
  8. Drop the old database

In case of emergency, just rename DBs back

How do I fix the npm UNMET PEER DEPENDENCY warning?

One of the most possible causes of this error could be that you have defined older version in your package.json. To solve this problem, change the versions in the package.json to match those npm is complaining about.

Once done, run npm install and voila!!.

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

React-redux 'connect' function accepts two arguments first is mapStateToProps and second is mapDispatchToProps check below ex.

export default connect(mapStateToProps, mapDispatchToProps)(Index); `

If we don't want retrieve state from redux then we set null instead of mapStateToProps.

export default connect(null, mapDispatchToProps)(Index);

How can I implement prepend and append with regular JavaScript?

This is not best way to do it but if anyone wants to insert an element before everything, here is a way.

var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

asp.net Button OnClick event not firing

If you are using updatepanel on onclick event, this may happen.

Use 'EnableEventValidation="false"' in your page markup like this :

<%@ Page Language="C#" MasterPageFile="~/ars_home.master" AutoEventWireup="true" CodeFile="Transaction_Window.aspx.cs" Inherits="Transaction_Window" EnableEventValidation="false" %>

Hope this helps

Is "&#160;" a replacement of "&nbsp;"?

&#160; is the numeric reference for the entity reference &nbsp; — they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.

See the Wikipedia page for the non-breaking space.

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

To do it the GUI way, you need to go edit your login. One of its properties is the default database used for that login. You can find the list of logins under the Logins node under the Security node. Then select your login and right-click and pick Properties. Change the default database and your life will be better!

Note that someone with sysadmin privs needs to be able to login to do this or to run the query from the previous post.

How to convert a timezone aware string to datetime in Python without dateutil?

I'm new to Python, but found a way to convert

2017-05-27T07:20:18.000-04:00 to

2017-05-27T07:20:18 without downloading new utilities.

from datetime import datetime, timedelta

time_zone1 = int("2017-05-27T07:20:18.000-04:00"[-6:][:3])
>>returns -04

item_date = datetime.strptime("2017-05-27T07:20:18.000-04:00".replace(".000", "")[:-6], "%Y-%m-%dT%H:%M:%S") + timedelta(hours=-time_zone1)

I'm sure there are better ways to do this without slicing up the string so much, but this got the job done.

How to extract numbers from a string and get an array of ints?

What about to use replaceAll java.lang.String method:

    String str = "qwerty-1qwerty-2 455 f0gfg 4";      
    str = str.replaceAll("[^-?0-9]+", " "); 
    System.out.println(Arrays.asList(str.trim().split(" ")));

Output:

[-1, -2, 455, 0, 4]

Description

[^-?0-9]+
  • [ and ] delimites a set of characters to be single matched, i.e., only one time in any order
  • ^ Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.
  • + Between one and unlimited times, as many times as possible, giving back as needed
  • -? One of the characters “-” and “?”
  • 0-9 A character in the range between “0” and “9”

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

You can have better performance by using the following method:

SELECT COUNT(1) FROM (SELECT /*+FIRST_ROWS*/ column_name 
FROM table_name 
WHERE column_name = 'xxxxx' AND ROWNUM = 1);

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

The fastest MySQL solution, without inner queries and without GROUP BY:

SELECT m.*                    -- get the row that contains the max value
FROM topten m                 -- "m" from "max"
    LEFT JOIN topten b        -- "b" from "bigger"
        ON m.home = b.home    -- match "max" row with "bigger" row by `home`
        AND m.datetime < b.datetime           -- want "bigger" than "max"
WHERE b.datetime IS NULL      -- keep only if there is no bigger than max

Explanation:

Join the table with itself using the home column. The use of LEFT JOIN ensures all the rows from table m appear in the result set. Those that don't have a match in table b will have NULLs for the columns of b.

The other condition on the JOIN asks to match only the rows from b that have bigger value on the datetime column than the row from m.

Using the data posted in the question, the LEFT JOIN will produce this pairs:

+------------------------------------------+--------------------------------+
|              the row from `m`            |    the matching row from `b`   |
|------------------------------------------|--------------------------------|
| id  home  datetime     player   resource | id    home   datetime      ... |
|----|-----|------------|--------|---------|------|------|------------|-----|
| 1  | 10  | 04/03/2009 | john   | 399     | NULL | NULL | NULL       | ... | *
| 2  | 11  | 04/03/2009 | juliet | 244     | NULL | NULL | NULL       | ... | *
| 5  | 12  | 04/03/2009 | borat  | 555     | NULL | NULL | NULL       | ... | *
| 3  | 10  | 03/03/2009 | john   | 300     | 1    | 10   | 04/03/2009 | ... |
| 4  | 11  | 03/03/2009 | juliet | 200     | 2    | 11   | 04/03/2009 | ... |
| 6  | 12  | 03/03/2009 | borat  | 500     | 5    | 12   | 04/03/2009 | ... |
| 7  | 13  | 24/12/2008 | borat  | 600     | 8    | 13   | 01/01/2009 | ... |
| 8  | 13  | 01/01/2009 | borat  | 700     | NULL | NULL | NULL       | ... | *
+------------------------------------------+--------------------------------+

Finally, the WHERE clause keeps only the pairs that have NULLs in the columns of b (they are marked with * in the table above); this means, due to the second condition from the JOIN clause, the row selected from m has the biggest value in column datetime.

Read the SQL Antipatterns: Avoiding the Pitfalls of Database Programming book for other SQL tips.

Get Current Session Value in JavaScript?

Take hidden field with id or class and value with session and get it in javascript.

Javascript var session = $('#session').val(); //get by jQuery

Removing duplicate characters from a string

If order does matter, how about:

>>> foo = 'mppmt'
>>> ''.join(sorted(set(foo), key=foo.index))
'mpt'

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

KOUT[i] is a single element of a list. But you are assigning a list to this element. your func is generating a list.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

how to remove "," from a string in javascript

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) {
  var string1 = x;
  for (y = 0; y < 12; y++) {
    string1 = string1.replace(/\,/g, '');
  }
  return string1;
}

Modify that for loop if you need bigger numbers.

How do you add a timer to a C# console application

That's very nice, however in order to simulate some time passing we need to run a command that takes some time and that's very clear in second example.

However, the style of using a for loop to do some functionality forever takes a lot of device resources and instead we can use the Garbage Collector to do some thing like that.

We can see this modification in the code from the same book CLR Via C# Third Ed.

using System;
using System.Threading;

public static class Program {

   public static void Main() {
      // Create a Timer object that knows to call our TimerCallback
      // method once every 2000 milliseconds.
      Timer t = new Timer(TimerCallback, null, 0, 2000);
      // Wait for the user to hit <Enter>
      Console.ReadLine();
   }

   private static void TimerCallback(Object o) {
      // Display the date/time when this method got called.
      Console.WriteLine("In TimerCallback: " + DateTime.Now);
      // Force a garbage collection to occur for this demo.
      GC.Collect();
   }
}

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Check date with todays date

Using pure Java:

public static boolean isToday(Date date){
        Calendar today = Calendar.getInstance();
        Calendar specifiedDate  = Calendar.getInstance();
        specifiedDate.setTime(date);

        return today.get(Calendar.DAY_OF_MONTH) == specifiedDate.get(Calendar.DAY_OF_MONTH)
                &&  today.get(Calendar.MONTH) == specifiedDate.get(Calendar.MONTH)
                &&  today.get(Calendar.YEAR) == specifiedDate.get(Calendar.YEAR);
    }

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

Sending data back to the Main Activity in Android

Call the child activity Intent using the startActivityForResult() method call

There is an example of this here: http://developer.android.com/training/notepad/notepad-ex2.html

and in the "Returning a Result from a Screen" of this: http://developer.android.com/guide/faq/commontasks.html#opennewscreen

Printing the value of a variable in SQL Developer

Go to the DBMS Output window (View->DBMS Output).

HTML input time in 24 format

In my case, it is taking time in AM and PM but sending data in 00-24 hours format to the server on form submit. and when use that DB data in its value then it will automatically select the appropriate AM or PM to edit form value.

remove / reset inherited css from an element

Only set the relevant / important CSS properties.

Example (only change the attributes which may cause your div to look completely different):

background: #FFF;
border: none;
color: #000;
display: block;
font: initial;
height: auto;
letter-spacing: normal;
line-height: normal;
margin: 0;
padding: 0;
text-transform: none;
visibility: visible;
width: auto;
word-spacing: normal;
z-index: auto;

Choose a very specific selector, such as div#donttouchme, <div id="donttouchme"></div>. Additionally, you can add `!important before every semicolon in the declaration. Your customers are deliberately trying to mess up your lay-out when this option fails.

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

When and how should I use a ThreadLocal variable?

Since a ThreadLocal is a reference to data within a given Thread, you can end up with classloading leaks when using ThreadLocals in application servers using thread pools. You need to be very careful about cleaning up any ThreadLocals you get() or set() by using the ThreadLocal's remove() method.

If you do not clean up when you're done, any references it holds to classes loaded as part of a deployed webapp will remain in the permanent heap and will never get garbage collected. Redeploying/undeploying the webapp will not clean up each Thread's reference to your webapp's class(es) since the Thread is not something owned by your webapp. Each successive deployment will create a new instance of the class which will never be garbage collected.

You will end up with out of memory exceptions due to java.lang.OutOfMemoryError: PermGen space and after some googling will probably just increase -XX:MaxPermSize instead of fixing the bug.

If you do end up experiencing these problems, you can determine which thread and class is retaining these references by using Eclipse's Memory Analyzer and/or by following Frank Kieviet's guide and followup.

Update: Re-discovered Alex Vasseur's blog entry that helped me track down some ThreadLocal issues I was having.

asp.net: Invalid postback or callback argument

If you have code in your Page_Load() event. Try adding this:

if (!Page.IsPostBack)
{ 
//your code here 
}

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

Adding elements to a collection during iteration

How about building a Queue with the elements you want to iterate over; when you want to add elements, enqueue them at the end of the queue, and keep removing elements until the queue is empty. This is how a breadth-first search usually works.

SELECT INTO a table variable in T-SQL

You could try using temporary tables...if you are not doing it from an application. (It may be ok to run this manually)

SELECT name, location INTO #userData FROM myTable
INNER JOIN otherTable ON ...
WHERE age>30

You skip the effort to declare the table that way... Helps for adhoc queries...This creates a local temp table which wont be visible to other sessions unless you are in the same session. Maybe a problem if you are running query from an app.

if you require it to running on an app, use variables declared this way :

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

Edit: as many of you mentioned updated visibility to session from connection. Creating temp tables is not an option for web applications, as sessions can be reused, stick to temp variables in those cases

How can I run a windows batch file but hide the command window?

Create a shortcut to your bat file by using the right-click and selecting Create shortcut. Right-click on the shortcut you created and click on properties. Click on the Run drop-down box and select Minimized.

Using find command in bash script

Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)

The option you're asking about is for the find command though, not for bash. From your command line, you can man find to see the options.

The one you're looking for is -o for "or":

  list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"

That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.

$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt

Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:

$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp

The Bash FAQ has lots of other excellent tips about programming in bash.

Changing an AIX password via script?

For me this worked in a vagrant VM:

sudo /usr/bin/passwd root <<EOF
12345678
12345678
EOF

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

android: how to use getApplication and getApplicationContext from non activity / service class

Casting a Context object to an Activity object compiles fine.

Try this:

((Activity) mContext).getApplication(...)

Typescript ReferenceError: exports is not defined

I had this same error too. In my case it was because we had an old-fashioned import statement in our TypeScript AngularJS project like this:

import { IAttributes, IScope } from "angular";

which was compiled to JavaScript like this:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

This was needed back in the old days because we then used IAttributes in the code and TypeScript wouldn't have known what to do with it otherwise. But after removing the import statement, and converting IAttributes to ng.IAttributes those two JavaScript lines disappeared - and so did the error message.

CSS vertical-align: text-bottom;

To use vertical-align properly, you should do it on table tag. But there is a way to make other html tags to behave as a table by assigning them a css of display:table to your parent, and display:table-cell on your child. Then vertical-align:bottom will work on that child.

HTML:

??????<div class="parent">
    <div class="child">
        This text is vertically aligned to bottom.    
    </div>
</div>????????????????????????

CSS:

?.parent {
    width: 300px;
    height: 50px;
    display:? table;
    border: 1px solid red;
}
.child { 
    display: table-cell;
    vertical-align: bottom;
}?

Here is a live example: link demo

Use index in pandas to plot data

You can use reset_index to turn the index back into a column:

monthly_mean.reset_index().plot(x='index', y='A')

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

What's in an Eclipse .classpath/.project file?

This eclipse documentation has details on the markups in .project file: The project description file

It describes the .project file as:

When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

vba pass a group of cells as range to function

As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.

So as on the above question I have putted my basic efforts.

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

Each one is a different type execution.

  • ExecuteScalar is going to be the type of query which will be returning a single value.

    An example would be returning a generated id after inserting.

    INSERT INTO my_profile (Address) VALUES ('123 Fake St.'); SELECT CAST(scope_identity() AS int)

  • ExecuteReader gives you a data reader back which will allow you to read all of the columns of the results a row at a time.

    An example would be pulling profile information for one or more users.

    SELECT * FROM my_profile WHERE id = '123456'

  • ExecuteNonQuery is any SQL which isn't returning values, but is actually performing some form of work like inserting deleting or modifying something.

    An example would be updating a user's profile in the database.

    UPDATE my_profile SET Address = '123 Fake St.' WHERE id = '123456'

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use this in your my.ini under

[mysqldump]
    user=root
    password=anything

What's the Android ADB shell "dumpsys" tool and what are its benefits?

i use dumpsys to catch if app is crashed and process is still active. situation i used it is to find about remote machine app is crashed or not.

dumpsys | grep myapp | grep "Application Error" 

or

adb shell dumpsys | grep myapp | grep Error

or anything that helps...etc

if app is not running you will get nothing as result. When app is stoped messsage is shown on screen by android, process is still active and if you check via "ps" command or anything else, you will see process state is not showing any error or crash meaning. But when you click button to close message, app process will cleaned from process list. so catching crash state without any code in application is hard to find. but dumpsys helps you.

String comparison in bash. [[: not found

Is the first line in your script:

#!/bin/bash

or

#!/bin/sh

the sh shell produces this error messages, not bash

Get Absolute URL from Relative path (refactored method)

This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.

/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the 
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
    if (string.IsNullOrEmpty(relativeUrl))
        return relativeUrl;

    if (HttpContext.Current == null)
        return relativeUrl;

    if (relativeUrl.StartsWith("/"))
        relativeUrl = relativeUrl.Insert(0, "~");
    if (!relativeUrl.StartsWith("~/"))
        relativeUrl = relativeUrl.Insert(0, "~/");

    var url = HttpContext.Current.Request.Url;
    var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

    return String.Format("{0}://{1}{2}{3}",
        url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}

How to get the changes on a branch in Git

What you want to see is the list of outgoing commits. You can do this using

git log master..branchName 

or

git log master..branchName --oneline

Where I assume that "branchName" was created as a tracking branch of "master".

Similarly, to see the incoming changes you can use:

git log branchName..master

Get the first key name of a JavaScript object

In Javascript you can do the following:

Object.keys(ahash)[0];

How to write to a JSON file in the correct format

This question is for ruby 1.8 but it still comes on top when googling.

in ruby >= 1.9 you can use

File.write("public/temp.json",tempHash.to_json)

other than what mentioned in other answers, in ruby 1.8 you can also use one liner form

File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I too had this problem, when I checked I image that I was pulling from a private registry was removed If we describe pod it will show pulling event and the image it's trying to pull

kubectl describe pod <POD_NAME>

Events:
 Type     Reason   Age                  From              Message
 ----     ------   ----                 ----              -------
 Normal   Pulling  18h (x35 over 20h)   kubelet, gsk-kub  Pulling image "registeryName:tag"
 Normal   BackOff  11m (x822 over 20h)  kubelet, gsk-kub  Back-off pulling image "registeryName:tag"
 Warning  Failed   91s (x858 over 20h)  kubelet, gsk-kub  Error: ImagePullBackOff

How to create radio buttons and checkbox in swift (iOS)?

You can simply subclass UIButton and write your own drawing code to suit your needs. I implemented a radio button like that of android using the following code. It can be used in storyboard as well.See example in Github repo

import UIKit

@IBDesignable
class SPRadioButton: UIButton {

@IBInspectable
var gap:CGFloat = 8 {
    didSet {
        self.setNeedsDisplay()
    }
}

@IBInspectable
var btnColor: UIColor = UIColor.green{
    didSet{
        self.setNeedsDisplay()
    }
}

@IBInspectable
var isOn: Bool = true{
    didSet{
        self.setNeedsDisplay()
    }
}

override func draw(_ rect: CGRect) {
    self.contentMode = .scaleAspectFill
    drawCircles(rect: rect)
}


//MARK:- Draw inner and outer circles
func drawCircles(rect: CGRect){
    var path = UIBezierPath()
    path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: rect.width, height: rect.height))

    let circleLayer = CAShapeLayer()
    circleLayer.path = path.cgPath
    circleLayer.lineWidth = 3
    circleLayer.strokeColor = btnColor.cgColor
    circleLayer.fillColor = UIColor.white.cgColor
    layer.addSublayer(circleLayer)

    if isOn {
        let innerCircleLayer = CAShapeLayer()
        let rectForInnerCircle = CGRect(x: gap, y: gap, width: rect.width - 2 * gap, height: rect.height - 2 * gap)
        innerCircleLayer.path = UIBezierPath(ovalIn: rectForInnerCircle).cgPath
        innerCircleLayer.fillColor = btnColor.cgColor
        layer.addSublayer(innerCircleLayer)
    }
    self.layer.shouldRasterize =  true
    self.layer.rasterizationScale = UIScreen.main.nativeScale
}

/*
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    isOn = !isOn
    self.setNeedsDisplay()
}
*/    

override func awakeFromNib() {
    super.awakeFromNib()
    addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
    isOn = false
}

@objc func buttonClicked(sender: UIButton) {
    if sender == self {
        isOn = !isOn
        setNeedsDisplay()
    }
}
}

html form - make inputs appear on the same line

A more modern solution:

Using display: flex and flex-direction: row

_x000D_
_x000D_
form {_x000D_
  display: flex; /* 2. display flex to the rescue */_x000D_
  flex-direction: row;_x000D_
}_x000D_
_x000D_
label, input {_x000D_
  display: block; /* 1. oh noes, my inputs are styled as block... */_x000D_
}
_x000D_
<form>_x000D_
  <label for="name">Name</label>_x000D_
  <input type="text" id="name" />_x000D_
  <label for="address">Address</label>_x000D_
  <input type="text" id="address" />_x000D_
  <button type="submit">_x000D_
    Submit_x000D_
  </button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to set radio button checked as default in radiogroup?

    RadioGroup radioGroup = new RadioGroup(WvActivity.this);
    RadioButton radioBtn1 = new RadioButton(this);
    RadioButton radioBtn2 = new RadioButton(this);
    RadioButton radioBtn3 = new RadioButton(this);

    radioBtn1.setText("Less");
    radioBtn2.setText("Normal");
    radioBtn3.setText("More");


    radioGroup.addView(radioBtn1);
    radioGroup.addView(radioBtn2);
    radioGroup.addView(radioBtn3);

    radioGroup.check(radioBtn2.getId());

How to use OAuth2RestTemplate?

In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.

...

public ResourceOwnerPasswordResourceDetails() {
    setGrantType("password");
}

...

The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form); was not set.

See the switch in: org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()

Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.

@EnableOAuth2Client
@Configuration
class MyConfig {

@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;

@Value("${security.oauth2.client.client-id}")
private String clientId;

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;

@Value("${security.oauth2.client.password-token}")
private String passwordToken;

@Value("${security.user.name}")
private String username;

@Value("${security.user.password}")
private String password;


@Bean
protected OAuth2ProtectedResourceDetails resource() {

    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

    resource.setAccessTokenUri(tokenUrl);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setClientAuthenticationScheme(AuthenticationScheme.form);
    resource.setUsername(username);
    resource.setPassword(password + passwordToken);

    return resource;
}

@Bean
 public OAuth2RestOperations restTemplate() {
    return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
    }
}


@Service
@SuppressWarnings("unchecked")
class MyService {
    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

How do I jump out of a foreach loop in C#?

Use break; and this will exit the foreach loop

dynamically add and remove view to viewpager

After figuring out which ViewPager methods are called by ViewPager and which are for other purposes, I came up with a solution. I present it here since I see a lot of people have struggled with this and I didn't see any other relevant answers.

First, here's my adapter; hopefully comments within the code are sufficient:

public class MainPagerAdapter extends PagerAdapter
{
  // This holds all the currently displayable views, in order from left to right.
  private ArrayList<View> views = new ArrayList<View>();

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  "Object" represents the page; tell the ViewPager where the
  // page should be displayed, from left-to-right.  If the page no longer exists,
  // return POSITION_NONE.
  @Override
  public int getItemPosition (Object object)
  {
    int index = views.indexOf (object);
    if (index == -1)
      return POSITION_NONE;
    else
      return index;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager needs a page to display; it is our job
  // to add the page to the container, which is normally the ViewPager itself.  Since
  // all our pages are persistent, we simply retrieve it from our "views" ArrayList.
  @Override
  public Object instantiateItem (ViewGroup container, int position)
  {
    View v = views.get (position);
    container.addView (v);
    return v;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager no longer needs a page to display; it
  // is our job to remove the page from the container, which is normally the
  // ViewPager itself.  Since all our pages are persistent, we do nothing to the
  // contents of our "views" ArrayList.
  @Override
  public void destroyItem (ViewGroup container, int position, Object object)
  {
    container.removeView (views.get (position));
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager; can be used by app as well.
  // Returns the total number of pages that the ViewPage can display.  This must
  // never be 0.
  @Override
  public int getCount ()
  {
    return views.size();
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.
  @Override
  public boolean isViewFromObject (View view, Object object)
  {
    return view == object;
  }

  //-----------------------------------------------------------------------------
  // Add "view" to right end of "views".
  // Returns the position of the new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v)
  {
    return addView (v, views.size());
  }

  //-----------------------------------------------------------------------------
  // Add "view" at "position" to "views".
  // Returns position of new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v, int position)
  {
    views.add (position, v);
    return position;
  }

  //-----------------------------------------------------------------------------
  // Removes "view" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, View v)
  {
    return removeView (pager, views.indexOf (v));
  }

  //-----------------------------------------------------------------------------
  // Removes the "view" at "position" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, int position)
  {
    // ViewPager doesn't have a delete method; the closest is to set the adapter
    // again.  When doing so, it deletes all its views.  Then we can delete the view
    // from from the adapter and finally set the adapter to the pager again.  Note
    // that we set the adapter to null before removing the view from "views" - that's
    // because while ViewPager deletes all its views, it will call destroyItem which
    // will in turn cause a null pointer ref.
    pager.setAdapter (null);
    views.remove (position);
    pager.setAdapter (this);

    return position;
  }

  //-----------------------------------------------------------------------------
  // Returns the "view" at "position".
  // The app should call this to retrieve a view; not used by ViewPager.
  public View getView (int position)
  {
    return views.get (position);
  }

  // Other relevant methods:

  // finishUpdate - called by the ViewPager - we don't care about what pages the
  // pager is displaying so we don't use this method.
}

And here's some snips of code showing how to use the adapter.

class MainActivity extends Activity
{
  private ViewPager pager = null;
  private MainPagerAdapter pagerAdapter = null;

  //-----------------------------------------------------------------------------
  @Override
  public void onCreate (Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView (R.layout.main_activity);

    ... do other initialization, such as create an ActionBar ...

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.view_pager);
    pager.setAdapter (pagerAdapter);

    // Create an initial view to display; must be a subclass of FrameLayout.
    LayoutInflater inflater = context.getLayoutInflater();
    FrameLayout v0 = (FrameLayout) inflater.inflate (R.layout.one_of_my_page_layouts, null);
    pagerAdapter.addView (v0, 0);
    pagerAdapter.notifyDataSetChanged();
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to add a view to the ViewPager.
  public void addView (View newPage)
  {
    int pageIndex = pagerAdapter.addView (newPage);
    // You might want to make "newPage" the currently displayed page:
    pager.setCurrentItem (pageIndex, true);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to remove a view from the ViewPager.
  public void removeView (View defunctPage)
  {
    int pageIndex = pagerAdapter.removeView (pager, defunctPage);
    // You might want to choose what page to display, if the current page was "defunctPage".
    if (pageIndex == pagerAdapter.getCount())
      pageIndex--;
    pager.setCurrentItem (pageIndex);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to get the currently displayed page.
  public View getCurrentPage ()
  {
    return pagerAdapter.getView (pager.getCurrentItem());
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to set the currently displayed page.  "pageToShow" must
  // currently be in the adapter, or this will crash.
  public void setCurrentPage (View pageToShow)
  {
    pager.setCurrentItem (pagerAdapter.getItemPosition (pageToShow), true);
  }
}

Finally, you can use the following for your activity_main.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</android.support.v4.view.ViewPager>

Javascript decoding html entities

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Live demo.

How to remove files that are listed in the .gitignore but still on the repository?

In linux you can use this commande :

for exemple i want to delete "*.py~" so my command should be ==>

find . -name "*.py~" -exec rm -f {} \;

Get ASCII value at input word

char a='a';
char A='A';
System.out.println((int)a +" "+(int)A);

Output:
97 65

Printing hexadecimal characters in C

You are seeing the ffffff because char is signed on your system. In C, vararg functions such as printf will promote all integers smaller than int to int. Since char is an integer (8-bit signed integer in your case), your chars are being promoted to int via sign-extension.

Since c0 and 80 have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.

char    int
c0 -> ffffffc0
80 -> ffffff80
61 -> 00000061

Here's a solution:

char ch = 0xC0;
printf("%x", ch & 0xff);

This will mask out the upper bits and keep only the lower 8 bits that you want.

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.

How to auto-indent code in the Atom editor?

I was working on some groovy code, which doesn't auto-format on save. What I did was right-click on the code pane, then chose ESLint Fix. That fixed my indents.

enter image description here

from jquery $.ajax to angular $http

You may use this :

Download "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

After following the steps from @Johnride, I still got the same error.

This fixed the problem:

Tools-> Options-> Select no proxy

source: https://www.youtube.com/watch?v=uI1j-8F8eN4

How to change font size in Eclipse for Java text editors?

If you are changing the font size, but it is only working for the currently open file, then I suspect that you are changing the wrong preferences.

  • On the Eclipse toolbar, select Window ? Preferences
  • Set the font size, General ? Appearance ? Colors and Fonts ? Java ? Java Editor Text Font).
  • Save the preferences.

Check that you do not have per-project preferences. These will override the top-level preferences.

Eclipse v4.2 (Juno) note

Per comment below, this has moved to the Eclipse Preferences menu (no longer named the Window menu).

Eclipse v4.3 (Kepler) note

The Window menu is live again, that is, menu Window ? Preferences.

Note Be sure to check out the ChandraBhan Singh's answer, it shows the key bindings to change the font size.

Unable to compile class for JSP

Either you can Downgrade to JRE 1.7.49

or if you want to run on JRE 8

Step to fix:-

  • Go to Lib folder of Liferay Tomcat .

  • Replace :- ecj-3.7.2.jar with ecj-4.4.2.

  • Restart the Server

How to add months to a date in JavaScript?

Split your date into year, month, and day components then use Date:

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

Date will take care of fixing the year.

Creating an empty list in Python

Just to highlight @Darkonaut answer because I think it should be more visible.

new_list = [] or new_list = list() are both fine (ignoring performance), but append() returns None, as result you can't do new_list = new_list.append(something).

How to get the index of an element in an IEnumerable?

The best way to catch the position is by FindIndex This function is available only for List<>

Example

int id = listMyObject.FindIndex(x => x.Id == 15); 

If you have enumerator or array use this way

int id = myEnumerator.ToList().FindIndex(x => x.Id == 15); 

or

 int id = myArray.ToList().FindIndex(x => x.Id == 15); 

Simple mediaplayer play mp3 from file path?

Here is the code to set up a MediaPlayer to play off of the SD card:

String PATH_TO_FILE = "/sdcard/music.mp3";    
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();   
mediaPlayer.start()

You can see the full example here. Let me know if you have any problems.

Check image width and height before upload with Javascript

You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Based on Mozilla docs:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

And the browser compatibility is listed too.

Copying Code from Inspect Element in Google Chrome

In earlier versions of Chrome we could simply select and copy an element (with Ctrl+C or Cmd+C) and then paste it inside an element by selecting it and then paste (with Ctrl+V or Cmd+V). It's not possible in the latest versions though (I'm running Chrome 58.0.3029.110) and it has set me up many times since then.

Instead of using the commands for copy and paste, we now have to right click the element -> Copy -> Copy Element and then right click the element that we want to append the copied element to -> Copy -> Paste Element.

I don't understand why the short commands are deactivated but at least it's still possible to do it in a more inconvenient way.

How to convert string to XML using C#

// using System.Xml;

String rawXml =
      @"<root>
          <person firstname=""Riley"" lastname=""Scott"" />
          <person firstname=""Thomas"" lastname=""Scott"" />
      </root>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);

I think this should work.

libpng warning: iCCP: known incorrect sRGB profile

To add to Glenn's great answer, here's what I did to find which files were faulty:

find . -name "*.png" -type f -print0 | xargs \
       -0 pngcrush_1_8_8_w64.exe -n -q > pngError.txt 2>&1

I used the find and xargs because pngcrush could not handle lots of arguments (which were returned by **/*.png). The -print0 and -0 is required to handle file names containing spaces.

Then search in the output for these lines: iCCP: Not recognizing known sRGB profile that has been edited.

./Installer/Images/installer_background.png:    
Total length of data found in critical chunks            =     11286  
pngcrush: iCCP: Not recognizing known sRGB profile that has been edited

And for each of those, run mogrify on it to fix them.

mogrify ./Installer/Images/installer_background.png

Doing this prevents having a commit changing every single png file in the repository when only a few have actually been modified. Plus it has the advantage to show exactly which files were faulty.

I tested this on Windows with a Cygwin console and a zsh shell. Thanks again to Glenn who put most of the above, I'm just adding an answer as it's usually easier to find than comments :)

Has Facebook sharer.php changed to no longer accept detailed parameters?

Your problem is caused by the lack of markers OpenGraph, as you say it is not possible that you implement for some reason.

For you, the only solution is to use the PHP Facebook API.

  1. First you must create the application in your facebook account.
  2. When creating the application you will have two key data for your code:

    YOUR_APP_ID 
    YOUR_APP_SECRET
    
  3. Download the Facebook PHP SDK from here.

  4. You can start with this code for share content from your site:

    <?php
      // Remember to copy files from the SDK's src/ directory to a
      // directory in your application on the server, such as php-sdk/
      require_once('php-sdk/facebook.php');
    
      $config = array(
        'appId' => 'YOUR_APP_ID',
        'secret' => 'YOUR_APP_SECRET',
        'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
      );
    
      $facebook = new Facebook($config);
      $user_id = $facebook->getUser();
    ?>
    <html>
      <head></head>
      <body>
    
      <?php
        if($user_id) {
    
          // We have a user ID, so probably a logged in user.
          // If not, we'll get an exception, which we handle below.
          try {
            $ret_obj = $facebook->api('/me/feed', 'POST',
                                        array(
                                          'link' => 'www.example.com',
                                          'message' => 'Posting with the PHP SDK!'
                                     ));
            echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
    
            // Give the user a logout link 
            echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
          } catch(FacebookApiException $e) {
            // If the user is logged out, you can have a 
            // user ID even though the access token is invalid.
            // In this case, we'll get an exception, so we'll
            // just ask the user to login again here.
            $login_url = $facebook->getLoginUrl( array(
                           'scope' => 'publish_stream'
                           )); 
            echo 'Please <a href="' . $login_url . '">login.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
          }   
        } else {
    
          // No user, so print a link for the user to login
          // To post to a user's wall, we need publish_stream permission
          // We'll use the current URL as the redirect_uri, so we don't
          // need to specify it here.
          $login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
          echo 'Please <a href="' . $login_url . '">login.</a>';
    
        } 
    
      ?>      
    
      </body> 
    </html>
    

You can find more examples in the Facebook Developers site:

https://developers.facebook.com/docs/reference/php

How to kill a child process by the parent process?

Try something like this:

#include <signal.h>

pid_t child_pid = -1 ; //Global

void kill_child(int sig)
{
    kill(child_pid,SIGKILL);
}

int main(int argc, char *argv[])
{
    signal(SIGALRM,(void (*)(int))kill_child);
    child_pid = fork();
    if (child_pid > 0) {
     /*PARENT*/
        alarm(30);
        /*
         * Do parent's tasks here.
         */
        wait(NULL);
    }
    else if (child_pid == 0){
     /*CHILD*/
        /*
         * Do child's tasks here.
         */
    }
}

Call to a member function fetch_assoc() on boolean in <path>

Please use if condition with while loop and try.

eg.

if ($result = $conn->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {

    }
    /* free result set */
    $result->free();
}

socket connect() vs bind()

bind tells the running process to claim a port. i.e, it should bind itself to port 80 and listen for incomming requests. with bind, your process becomes a server. when you use connect, you tell your process to connect to a port that is ALREADY in use. your process becomes a client. the difference is important: bind wants a port that is not in use (so that it can claim it and become a server), and connect wants a port that is already in use (so it can connect to it and talk to the server)

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

Mockito, JUnit and Spring

Your question seems to be asking about which of the three examples you have given is the preferred approach.

Example 1 using the Reflection TestUtils is not a good approach for Unit testing. You really don't want to be loading the spring context at all for a unit test. Just mock and inject what is required as shown by your other examples.

You do want to load the spring context if you want to do some Integration testing, however I would prefer using @RunWith(SpringJUnit4ClassRunner.class) to perform the loading of the context along with @Autowired if you need access to its' beans explicitly.

Example 2 is a valid approach and the use of @RunWith(MockitoJUnitRunner.class) will remove the need to specify a @Before method and an explicit call to MockitoAnnotations.initMocks(this);

Example 3 is another valid approach that doesn't use @RunWith(...). You haven't instantiated your class under test HelloFacadeImpl explicitly, but you could have done the same with Example 2.

My suggestion is to use Example 2 for your unit testing as it reduces the code clutter. You can fall back to the more verbose configuration if and when you're forced to do so.

Is there any good dynamic SQL builder library in Java?

ddlutils is my best choice:http://db.apache.org/ddlutils/api/org/apache/ddlutils/platform/SqlBuilder.html

here is create example(groovy):

Platform platform  = PlatformFactory.createNewPlatformInstance("oracle");//db2,...
//create schema    
def db =        new Database();
def t = new Table(name:"t1",description:"XXX");
def col1 = new Column(primaryKey:true,name:"id",type:"bigint",required:true);
t.addColumn(col1);
t.addColumn(new Column(name:"c2",type:"DECIMAL",size:"8,2"));
t.addColumn( new Column(name:"c3",type:"varchar"));
t.addColumn(new Column(name:"c4",type:"TIMESTAMP",description:"date"));        
db.addTable(t);
println platform.getCreateModelSql(db, false, false)

//you can read Table Object from  platform.readModelFromDatabase(....)
def sqlbuilder = platform.getSqlBuilder();
println "insert:"+sqlbuilder.getInsertSql(t,["id":1,c2:3],false);
println "update:"+sqlbuilder.getUpdateSql(t,["id":1,c2:3],false);
println "delete:"+sqlbuilder.getDeleteSql(t,["id":1,c2:3],false);
//http://db.apache.org/ddlutils/database-support.html

Web API optional parameters

you need only set default value to parameters(you do not need the Route attribute):

public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

Convert a 1D array to a 2D array in numpy

You have two options:

  • If you no longer want the original shape, the easiest is just to assign a new shape to the array

    a.shape = (a.size//ncols, ncols)
    

    You can switch the a.size//ncols by -1 to compute the proper shape automatically. Make sure that a.shape[0]*a.shape[1]=a.size, else you'll run into some problem.

  • You can get a new array with the np.reshape function, that works mostly like the version presented above

    new = np.reshape(a, (-1, ncols))
    

    When it's possible, new will be just a view of the initial array a, meaning that the data are shared. In some cases, though, new array will be acopy instead. Note that np.reshape also accepts an optional keyword order that lets you switch from row-major C order to column-major Fortran order. np.reshape is the function version of the a.reshape method.

If you can't respect the requirement a.shape[0]*a.shape[1]=a.size, you're stuck with having to create a new array. You can use the np.resize function and mixing it with np.reshape, such as

>>> a =np.arange(9)
>>> np.resize(a, 10).reshape(5,2)

Resize image proportionally with CSS?

Try this:

div.container {
    max-width: 200px;//real picture size
    max-height: 100px;
}

/* resize images */
div.container img {
    width: 100%;
    height: auto;
}

How to format font style and color in echo

echo "<span style = 'font-color: #ff0000'> Movie List for {$key} 2013 </span>";

Variables are only expanded inside double quotes, not single quotes. Since the above uses double quotes for the PHP string, I switched to single quotes for the embedded HTML, to avoid having to escape the quotes.

The other problem with your code is that <style> tags are for entering CSS blocks, not for styling individual elements. To style an element, you need an element tag with a style attribute; <span> is the simplest element -- it doesn't have any formatting of its own, it just serves as a place to attach attributes.

Another popular way to write it is with string concatenation:

echo '<span style = "font-color: #ff0000"> Movie List for ' . $key . ' 2013 </span>';

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

How to pass data to all views in Laravel 5?

In the documentation:

Typically, you would place calls to the share method within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them.

I'm agree with Marwelln, just put it in AppServiceProvider in the boot function:

public function boot() {
    View::share('youVarName', [1, 2, 3]);
}

I recommend use an specific name for the variable, to avoid confussions or mistakes with other no 'global' variables.

Get epoch for a specific date using Javascript

You can create a Date object, and call getTime on it:

new Date(2010, 6, 26).getTime() / 1000

Is this the proper way to do boolean test in SQL?

I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.

'Y' and 'N' also maps nicely when using (N)Hibernate.

find: missing argument to -exec

You have to put a space between {} and \;

So the command will be like:

find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 && rm {} \;

Regex: Remove lines containing "help", etc

This is also possible with Notepad++:

  • Go to the search menu, Ctrl + F, and open the Mark tab.
  • Check Bookmark line (if there is no Mark tab update to the current version).

  • Enter your search term and click Mark All

    • All lines containing the search term are bookmarked.
  • Now go to the menu SearchBookmarkRemove Bookmarked lines

  • Done.

Selenium Webdriver move mouse to Point

If you are using a RemoteWebDriver, you can cast WebElement into RemoteWebElement. You can then call getCoordinates() on that object to get the coordinates.

        WebElement el = driver.findElementById("elementId");
        Coordinates c = ((RemoteWebElement)el).getCoordinates();
        driver.getMouse().mouseMove(c);

simple HTTP server in Java using only Java SE API

checkout Simple. its a pretty simple embeddable server with built in support for quite a variety of operations. I particularly love its threading model..

Amazing!

Could not find method compile() for arguments Gradle

It should be exclude module: 'net.milkbowl:vault:1.2.27'(add module:) as explained in documentation for DependencyHandler linked from http://www.gradle.org/docs/current/javadoc/org/gradle/api/Project.html#dependencies(groovy.lang.Closure) because ModuleDependency.exclude(java.util.Map) method is used.

Can someone explain __all__ in Python?

This is defined in PEP8 here:

Global Variable Names

(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.

Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").

PEP8 provides coding conventions for the Python code comprising the standard library in the main Python distribution. The more you follow this, closer you are to the original intent.

Border around specific rows in a table?

the trick is with outline property thanks to enigment's answer with little modification

use this class

.row-border{
    outline: thin solid black;
    outline-offset: -1px;
}

then in the HTML

<tr>....</tr>
<tr class="row-border">
    <td>...</td>
    <td>...</td>
</tr>

and the result is enter image description here hope this helps you

Calling a JSON API with Node.js

Unirest library simplifies this a lot. If you want to use it, you have to install unirest npm package. Then your code could look like this:

unirest.get("http://graph.facebook.com/517267866/?fields=picture")
  .send()
  .end(response=> {
    if (response.ok) {
      console.log("Got a response: ", response.body.picture)
    } else {
      console.log("Got an error: ", response.error)
    }
  })

How to round an image with Glide library?

You can simply call the RoundedCornersTransformation constructor, which has cornerType enum input. Like this:

Glide.with(context)
            .load(bizList.get(position).getCover())
            .bitmapTransform(new RoundedCornersTransformation(context,20,0, RoundedCornersTransformation.CornerType.TOP))
            .into(holder.bizCellCoverImg);

but first you have to add Glide Transformations to your project.

Changing CSS for last <li>

If you know there are three li's in the list you're looking at, for example, you could do this:

li + li + li { /* Selects third to last li */
}

In IE6 you can use expressions:

li {
    color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}

I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child selector gets better support.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Please be advised:

JSONP supports only the GET request method.

*Send request by firefox:*

$.ajax({
   type: 'POST',//<<===
   contentType: 'application/json',
   url: url,
   dataType: "json"//<<=============
    ...
});

Above request send by OPTIONS(while ==>type: 'POST')!!!!

$.ajax({
    type: 'POST',//<<===
    contentType: 'application/json',
    url: url,
    dataType: "jsonp"//<<==============
    ...
});

But above request send by GET(while ==>type: 'POST')!!!!

When you are in "cross-domain communication" , pay attention and be careful.

Can you have multiline HTML5 placeholder text in a <textarea>?

Watermark solution in the original post works great. Thanks for it. In case anyone needs it, here is an angular directive for it.

(function () {
  'use strict';

  angular.module('app')
    .directive('placeholder', function () {
      return {
        restrict: 'A',
        link:     function (scope, element, attributes) {
          if (element.prop('nodeName') === 'TEXTAREA') {
            var placeholderText = attributes.placeholder.trim();

            if (placeholderText.length) {
              // support for both '\n' symbol and an actual newline in the placeholder element
              var placeholderLines = Array.prototype.concat
                .apply([], placeholderText.split('\n').map(line => line.split('\\n')))
                .map(line => line.trim());

              if (placeholderLines.length > 1) {
                element.watermark(placeholderLines.join('<br>\n'));
              }
            }
          }
        }
      };
    });
}());

How to improve Netbeans performance?

A more or less detailed description, why NetBeans if slow so often can be found in the article:

Boost your NetBeans performance

First. check what NetBeans is actually doing on your disk. On a Mac you can issue this command:

  sudo fs_usage | grep /path/to/workspace

In my special case I got a directory which didn't exist any longer, but NetBeans tries to access the folder all the time:

  14:08:05 getattrlist /path/to/workspaces/pii 0.000011 java

Repeated many, many, many times. If you have a similar problem, fix it by deleting your NetBeans cache folder here:

   ~/.netbeans/6.8/var/cache

If your NetBeans.app is still making a lot of disk I/O. Check if it's accessing the subverison folders and svncache.

I had to disable the subversion features with config file:

  ~/.netbeans/VERSION/config/Preferences/org/netbeans/modules/versioning.properties 

add a line:

  unversionedFolders=FULL_PATH_TO_PROJECT_FOLDER  

SOURCE: Netbeans forums

IMHO it's mainly related to a lot of disk I/O caused by missing files or folders and svncache.

Is there a way to programmatically minimize a window

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Me.Hide()

End Sub

How does HTTP file upload work?

An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.

http://www.tutorialspoint.com/http/http_messages.htm

CSS-Only Scrollable Table with fixed headers

Surprised a solution using flexbox hasn't been posted yet.

Here's my solution using display: flex and a basic use of :after (thanks to Luggage) to maintain the alignment even with the scrollbar padding the tbody a bit. This has been verified in Chrome 45, Firefox 39, and MS Edge. It can be modified with prefixed properties to work in IE11, and further in IE10 with a CSS hack and the 2012 flexbox syntax.

Note the table width can be modified; this even works at 100% width.

The only caveat is that all table cells must have the same width. Below is a clearly contrived example, but this works fine when cell contents vary (table cells all have the same width and word wrapping on, forcing flexbox to keep them the same width regardless of content). Here is an example where cell contents are different.

Just apply the .scroll class to a table you want scrollable, and make sure it has a thead:

_x000D_
_x000D_
.scroll {_x000D_
  border: 0;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.scroll tr {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.scroll td {_x000D_
  padding: 3px;_x000D_
  flex: 1 auto;_x000D_
  border: 1px solid #aaa;_x000D_
  width: 1px;_x000D_
  word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.scroll thead tr:after {_x000D_
  content: '';_x000D_
  overflow-y: scroll;_x000D_
  visibility: hidden;_x000D_
  height: 0;_x000D_
}_x000D_
_x000D_
.scroll thead th {_x000D_
  flex: 1 auto;_x000D_
  display: block;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.scroll tbody {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
  height: 200px;_x000D_
}
_x000D_
<table class="scroll" width="400px">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
      <th>Header</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
    <td>Data</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Setting Windows PowerShell environment variables

From the PowerShell prompt:

setx PATH "$env:path;\the\directory\to\add" -m

You should then see the text:

SUCCESS: Specified value was saved.

Restart your session, and the variable will be available. setx can also be used to set arbitrary variables. Type setx /? at the prompt for documentation.

Before messing with your path in this way, make sure that you save a copy of your existing path by doing $env:path >> a.out in a PowerShell prompt.

How to check version of python modules?

I suggest opening a python shell in terminal (in the python version you are interested), importing the library, and getting its __version__ attribute.

>>> import statlib
>>> statlib.__version__

>>> import construct
>>> contruct.__version__

Note 1: We must regard the python version. If we have installed different versions of python, we have to open the terminal in the python version we are interested in. For example, opening the terminal with python3.8 can (surely will) give a different version of a library than opening with python3.5 or python2.7.

Note 2: We avoid using the print function, because its behavior depends on python2 or python3. We do not need it, the terminal will show the value of the expression.