Programs & Examples On #Lame

LAME is a high quality MPEG Audio Layer III (MP3) encoder licensed under the LGPL. The name LAME is a recursive acronym for "LAME Ain't an MP3 Encoder". Use this tag for questions on LAME encoder. Also add mp3 tag.

How to import popper.js?

I had the same problem. Tried different approches, but this one worked for me. Read the instruction from http://getbootstrap.com/.

Copy the CDN paths of Javascripts (Popper, jQuery and Bootstrap) in same manner (it is important) as given.

enter image description here

_x000D_
_x000D_
<head>_x000D_
//Path to jQuery_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
_x000D_
////Path to Popper - it is for dropsdowns etc in bootstrap_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>_x000D_
_x000D_
//Path to bootsrap_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Just a simple solution is here...it worked for me:

  1. Clean Project
  2. Rebuild project
  3. Sync project with gradle file

What does 'git blame' do?

The command explains itself quite well. It's to figure out which co-worker wrote the specific line or ruined the project, so you can blame them :)

Store a closure as a variable in Swift

The compiler complains on

var completionHandler: (Float)->Void = {}

because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking a float argument. The following would assign a "do nothing" closure to the completion handler:

var completionHandler: (Float)->Void = {
    (arg: Float) -> Void in
}

and this can be shortened to

var completionHandler: (Float)->Void = { arg in }

due to the automatic type inference.

But what you probably want is that the completion handler is initialized to nil in the same way that an Objective-C instance variable is inititialized to nil. In Swift this can be realized with an optional:

var completionHandler: ((Float)->Void)?

Now the property is automatically initialized to nil ("no value"). In Swift you would use optional binding to check of a the completion handler has a value

if let handler = completionHandler {
    handler(result)
}

or optional chaining:

completionHandler?(result)

Simple CSS Animation Loop – Fading In & Out "Loading" Text

well looking for a simpler variation I found this:

it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.

demo and credit => http://codepen.io/Ahrengot/pen/bKdLC

_x000D_
_x000D_
@keyframes fadeIn { _x000D_
  from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
    animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
_x000D_
_x000D_

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Bit late to the party but this simple solution worked for me:

function chainError(err) {
  return Promise.reject(err)
};

stepOne()
.then(stepTwo, chainError)
.then(stepThreee, chainError);

This allows you to break out of the chain.

Concrete Javascript Regex for Accented Characters (Diacritics)

The accented Latin range \u00C0-\u017F was not quite enough for my database of names, so I extended the regex to

[a-zA-Z\u00C0-\u024F]
[a-zA-Z\u00C0-\u024F\u1E00-\u1EFF] // includes even more Latin chars

I added these code blocks (\u00C0-\u024F includes three adjacent blocks at once):

Note that \u00C0-\u00FF is actually only a part of Latin-1 Supplement. It skips unprintable control signals and all symbols except for the awkwardly-placed multiply × \u00D7 and divide ÷ \u00F7.

[a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F] // exclude ×÷

If you need more code points, you can find more ranges on Wikipedia's List of Unicode characters. For example, you could also add Latin Extended-C, D, and E, but I left them out because only historians seem interested in them now, and the D and E sets don't even render correctly in my browser.

The original regex stopping at \u017F borked on the name "?enol". According to FontSpace's Unicode Analyzer, that first character is \u0218, LATIN CAPITAL LETTER S WITH COMMA BELOW. (Yeah, it's usually spelled with a cedilla-S \u015E, "Senol." But I'm not flying to Turkey to go tell him, "You're spelling your name wrong!")

Swing vs JavaFx for desktop applications

No one has mentioned it, but JavaFX does not compile or run on certain architectures deemed "servers" by Oracle (e.g. Solaris), because of the missing "jfxrt.jar" support. Stick with SWT, until further notice.

Correct way to load a Nib for a UIView subclass

If you want to keep your CustomView and its xib independent of File's Owner, then follow these steps

  • Leave the File's Owner field empty.
  • Click on actual view in xib file of your CustomView and set its Custom Class as CustomView (name of your custom view class)
  • Add IBOutlet in .h file of your custom view.
  • In .xib file of your custom view, click on view and go in Connection Inspector. Here you will all your IBOutlets which you define in .h file
  • Connect them with their respective view.

in .m file of your CustomView class, override the init method as follow

-(CustomView *) init{
    CustomView *result = nil;
    NSArray* elements = [[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options: nil];
    for (id anObject in elements)
    {
        if ([anObject isKindOfClass:[self class]])
        {
            result = anObject;
            break;
        }
    }
    return result;
}

Now when you want to load your CustomView, use the following line of code [[CustomView alloc] init];

Get yesterday's date in bash on Linux, DST-safe

You can use:

date -d "yesterday 13:55" '+%Y-%m-%d'

Or whatever time you want to retrieve will retrieved by bash.

For month:

date -d "30 days ago" '+%Y-%m-%d'

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

Is there a shortcut to make a block comment in Xcode?

@Nikola Milicevic

Here is the screenshot of the indentation issue. This is very minor, but it is strange that it seems to work so well, in your example visual.

I am also adding a screenshot of my Automator set-up...

Thanks

enter image description here

enter image description here

Update:

If I change the script slightly to:

enter image description here

And then select full lines in XCode, I get the desired outcome:

enter image description here

enter image description here

Preventing an image from being draggable or selectable without using JS

I created a div element which has the same size as the image and is positioned on top of the image. Then, the mouse events do not go to the image element.

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Retrieve the commit log for a specific line in a file?

Here is a solution that defines a git alias, so you will be able use it like that :

git rblame -M -n -L '/REGEX/,+1' FILE

Output example :

00000000 18 (Not Committed Yet 2013-08-19 13:04:52 +0000 728) fooREGEXbar
15227b97 18 (User1 2013-07-11 18:51:26 +0000 728) fooREGEX
1748695d 23 (User2 2013-03-19 21:09:09 +0000 741) REGEXbar

You can define the alias in your .gitconfig or simply run the following command

git config alias.rblame !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); echo $line; done' dumb_param

This is an ugly one-liner, so here is a de-obfuscated equivalent bash function :

git-rblame () {
    local commit line
    while line=$(git blame "$@" $commit 2>/dev/null); do
        commit="${line:0:8}^"
        if [ "00000000^" == "$commit" ]; then
            commit=$(git rev-parse HEAD)
        fi
        echo $line
    done
}

The pickaxe solution ( git log --pickaxe-regex -S'REGEX' ) will only give you line additions/deletions, not the other alterations of the line containing the regular expression.

A limitation of this solution is that git blame only returns the 1st REGEX match, so if multiple matches exist the recursion may "jump" to follow another line. Be sure to check the full history output to spot those "jumps" and then fix your REGEX to ignore the parasite lines.

Finally, here is an alternate version that run git show on each commit to get the full diff :

git config alias.rblameshow !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); git show $commit; done' dumb_param

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.

LINQ Aggregate algorithm explained

The easiest-to-understand definition of Aggregate is that it performs an operation on each element of the list taking into account the operations that have gone before. That is to say it performs the action on the first and second element and carries the result forward. Then it operates on the previous result and the third element and carries forward. etc.

Example 1. Summing numbers

var nums = new[]{1,2,3,4};
var sum = nums.Aggregate( (a,b) => a + b);
Console.WriteLine(sum); // output: 10 (1+2+3+4)

This adds 1 and 2 to make 3. Then adds 3 (result of previous) and 3 (next element in sequence) to make 6. Then adds 6 and 4 to make 10.

Example 2. create a csv from an array of strings

var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate( (a,b) => a + ',' + b);
Console.WriteLine(csv); // Output a,b,c,d

This works in much the same way. Concatenate a a comma and b to make a,b. Then concatenates a,b with a comma and c to make a,b,c. and so on.

Example 3. Multiplying numbers using a seed

For completeness, there is an overload of Aggregate which takes a seed value.

var multipliers = new []{10,20,30,40};
var multiplied = multipliers.Aggregate(5, (a,b) => a * b);
Console.WriteLine(multiplied); //Output 1200000 ((((5*10)*20)*30)*40)

Much like the above examples, this starts with a value of 5 and multiplies it by the first element of the sequence 10 giving a result of 50. This result is carried forward and multiplied by the next number in the sequence 20 to give a result of 1000. This continues through the remaining 2 element of the sequence.

Live examples: http://rextester.com/ZXZ64749
Docs: http://msdn.microsoft.com/en-us/library/bb548651.aspx


Addendum

Example 2, above, uses string concatenation to create a list of values separated by a comma. This is a simplistic way to explain the use of Aggregate which was the intention of this answer. However, if using this technique to actually create a large amount of comma separated data, it would be more appropriate to use a StringBuilder, and this is entirely compatible with Aggregate using the seeded overload to initiate the StringBuilder.

var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate(new StringBuilder(), (a,b) => {
    if(a.Length>0)
        a.Append(",");
    a.Append(b);
    return a;
});
Console.WriteLine(csv);

Updated example: http://rextester.com/YZCVXV6464

Most Pythonic way to provide global configuration variables in config.py?

please check out the IPython configuration system, implemented via traitlets for the type enforcement you are doing manually.

Cut and pasted here to comply with SO guidelines for not just dropping links as the content of links changes over time.

traitlets documentation

Here are the main requirements we wanted our configuration system to have:

Support for hierarchical configuration information.

Full integration with command line option parsers. Often, you want to read a configuration file, but then override some of the values with command line options. Our configuration system automates this process and allows each command line option to be linked to a particular attribute in the configuration hierarchy that it will override.

Configuration files that are themselves valid Python code. This accomplishes many things. First, it becomes possible to put logic in your configuration files that sets attributes based on your operating system, network setup, Python version, etc. Second, Python has a super simple syntax for accessing hierarchical data structures, namely regular attribute access (Foo.Bar.Bam.name). Third, using Python makes it easy for users to import configuration attributes from one configuration file to another. Fourth, even though Python is dynamically typed, it does have types that can be checked at runtime. Thus, a 1 in a config file is the integer ‘1’, while a '1' is a string.

A fully automated method for getting the configuration information to the classes that need it at runtime. Writing code that walks a configuration hierarchy to extract a particular attribute is painful. When you have complex configuration information with hundreds of attributes, this makes you want to cry.

Type checking and validation that doesn’t require the entire configuration hierarchy to be specified statically before runtime. Python is a very dynamic language and you don’t always know everything that needs to be configured when a program starts.

To acheive this they basically define 3 object classes and their relations to each other:

1) Configuration - basically a ChainMap / basic dict with some enhancements for merging.

2) Configurable - base class to subclass all things you'd wish to configure.

3) Application - object that is instantiated to perform a specific application function, or your main application for single purpose software.

In their words:

Application: Application

An application is a process that does a specific job. The most obvious application is the ipython command line program. Each application reads one or more configuration files and a single set of command line options and then produces a master configuration object for the application. This configuration object is then passed to the configurable objects that the application creates. These configurable objects implement the actual logic of the application and know how to configure themselves given the configuration object.

Applications always have a log attribute that is a configured Logger. This allows centralized logging configuration per-application. Configurable: Configurable

A configurable is a regular Python class that serves as a base class for all main classes in an application. The Configurable base class is lightweight and only does one things.

This Configurable is a subclass of HasTraits that knows how to configure itself. Class level traits with the metadata config=True become values that can be configured from the command line and configuration files.

Developers create Configurable subclasses that implement all of the logic in the application. Each of these subclasses has its own configuration information that controls how instances are created.

Rails how to run rake task

Have you tried rake reklamer:iqmedier ?

My custom rake tasks are in the lib directory, not in lib/tasks. Not sure if that matters.

LINQ - Full Outer Join

I really hate these linq expressions, this is why SQL exists:

select isnull(fn.id, ln.id) as id, fn.firstname, ln.lastname
   from firstnames fn
   full join lastnames ln on ln.id=fn.id

Create this as sql view in database and import it as entity.

Of course, (distinct) union of left and right joins will make it too, but it is stupid.

Git blame -- prior commits?

Amber's answer is correct but I found it unclear; The syntax is:

git blame {commit_id} -- {path/to/file}

Note: the -- is used to separate the tree-ish sha1 from the relative file paths. 1

For example:

git blame master -- index.html

Full credit to Amber for knowing all the things! :)

Getting the text that follows after the regex match

Your regex "sentence(.*)" is right. To retrieve the contents of the group in parenthesis, you would call:

Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
   String s = m.group(1); // " that is awesome"
}

Note the use of m.find() in this case (attempts to find anywhere on the string) and not m.matches() (would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)")

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

Is it safe to use Project Lombok?

Go ahead and use Lombok, you can if necessary "delombok" your code afterwards http://projectlombok.org/features/delombok.html

Why does IE9 switch to compatibility mode on my website?

To force IE to render in IE9 standards mode you should use

<meta http-equiv="X-UA-Compatible" content="IE=edge">

Some conditions may cause IE9 to jump down into the compatibility modes. By default this can occur on intranet sites.

Print to the same line and not a new line?

Just figured this out on my own for showing a countdown but it would also work for a percentage.

import time
#Number of seconds to wait
i=15
#Until seconds has reached zero
while i > -1:
    #Ensure string overwrites the previous line by adding spaces at end
    print("\r{} seconds left.   ".format(i),end='')
        time.sleep(1)
        i-=1
    print("") #Adds newline after it's done

As long as whatever comes after '/r' is the same length or longer (including spaces) than the previous string, it will overwrite it on the same line. Just make sure you include the end='' otherwise it will print to a newline. Hope that helps!

Do copyright dates need to be updated?

Copyright should be up to the date of publish.

So, if it's a static content (such as the Times article you linked to), it should probably be statically copyrighted.

If it's dynamically generated content, it should be copyrighted to the current year

jQuery vs. javascript?

Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.

Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.

Javascript is the source, the actual scripts that browser responds to.

Simple Java Client/Server Program

Outstream is not closed ... close the stream so that response goes back to test client. Hope this helps.

How to turn off the Eclipse code formatter for certain sections of Java code?

End each of the lines with a double slash "//". That will keep eclipse from moving them all onto the same line.

Change WPF controls from a non-main thread using Dispatcher.Invoke

When a thread is executing and you want to execute the main UI thread which is blocked by current thread, then use the below:

current thread:

Dispatcher.CurrentDispatcher.Invoke(MethodName,
    new object[] { parameter1, parameter2 }); // if passing 2 parameters to method.

Main UI thread:

Application.Current.Dispatcher.BeginInvoke(
    DispatcherPriority.Background, new Action(() => MethodName(parameter)));

Differences between Emacs and Vim

  1. Vim was always faster to start up than Emacs. I'm saying that on any machine, out-of-the-box installs of Vim will start up faster than out-of-the-box installs of Emacs. And I tend to think that after a moderate amount of customisation of either one, Vim will still start up faster than Emacs.

  2. After that, the other practical difference was Emacs' modes. They make your life tremendously easier when editing XML, C/C++/Java/whatever, LaTeX, and most popular languages you can think of. They make you want to keep the editor open for long sessions and work.

All in all, I'll say that Vim pulls you to it for short, fast editing tasks; while Emacs encourages you to dive in for long sessions.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

You've almost got it. Tell jquery you want to load only the script:

$("#myBtn").click(function() {
    $("#myDiv").load("trackingCode.html script");
});

Environment variables in Mac OS X

There's no need for duplication. You can set environment variables used by launchd (and child processes, i.e. anything you start from Spotlight) using launchctl setenv.

For example, if you want to mirror your current path in launchd after setting it up in .bashrc or wherever:

PATH=whatever:you:want
launchctl setenv PATH $PATH

Environment variables are not automatically updated in running applications. You will need to relaunch applications to get the updated environment variables (although you can just set variables in your shell, e.g. PATH=whatever:you:want; there's no need to relaunch the terminal).

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I've had this problem. See The Python "Connection Reset By Peer" Problem.

You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.

You can (sometimes) correct this with a time.sleep(0.01) placed strategically.

"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.

Best way to simulate "group by" from bash?

Most of the other solutions count duplicates. If you really need to group key value pairs, try this:

Here is my example data:

find . | xargs md5sum
fe4ab8e15432161f452e345ff30c68b0 a.txt
30c68b02161e15435ff52e34f4fe4ab8 b.txt
30c68b02161e15435ff52e34f4fe4ab8 c.txt
fe4ab8e15432161f452e345ff30c68b0 d.txt
fe4ab8e15432161f452e345ff30c68b0 e.txt

This will print the key value pairs grouped by the md5 checksum.

cat table.txt | awk '{print $1}' | sort | uniq  | xargs -i grep {} table.txt
30c68b02161e15435ff52e34f4fe4ab8 b.txt
30c68b02161e15435ff52e34f4fe4ab8 c.txt
fe4ab8e15432161f452e345ff30c68b0 a.txt
fe4ab8e15432161f452e345ff30c68b0 d.txt
fe4ab8e15432161f452e345ff30c68b0 e.txt

Things possible in IntelliJ that aren't possible in Eclipse?

There is only one reason I use intellij and not eclipse: Usability

Whether it is debugging, refactoring, auto-completion.. Intellij is much easier to use with consistent key bindings, options available where you look for them etc. Feature-wise, it will be tough for intellij to catch up with Eclipse, as the latter has much more plugins available that intellij, and is easily extensible.

Why should I use an IDE?

Saves time to develop
Makes life easier by providing features like Integrated debugging, intellisense.

There are lot many, but will recommend to use one, they are more than obvious.

Deprecated: mysql_connect()

mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.

Use mysqli_* function or pdo

Read Oracle Converting to MySQLi

How to view the roles and permissions granted to any database user in Azure SQL server instance?

if you want to find about object name e.g. table name and stored procedure on which particular user has permission, use the following query:

SELECT pr.principal_id, pr.name, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name, OBJECT_NAME(major_id) objectName
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
--INNER JOIN sys.schemas AS s ON s.principal_id =  sys.database_role_members.role_principal_id 
     where pr.name in ('youruser1','youruser2') 

Iterating through a JSON object

This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I've shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.

import json

def main():

    # create a simple JSON array
    jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'

    # change the JSON string into a JSON object
    jsonObject = json.loads(jsonString)

    # print the keys and values
    for key in jsonObject:
        value = jsonObject[key]
        print("The key and value are ({}) = ({})".format(key, value))

    pass

if __name__ == '__main__':
    main()

Capturing image from webcam in java?

Here is a similar question with some - yet unaccepted - answers. One of them mentions FMJ as a java alternative to JMF.

How to provide shadow to Button

If you are targeting pre-Lollipop devices, you can use Shadow-Layout, since it easy and you can use it in different kind of layouts.


Add shadow-layout to your Gradle file:

dependencies {
    compile 'com.github.dmytrodanylyk.shadow-layout:library:1.0.1'
}


At the top the xml layout where you have your button, add to the top:

xmlns:app="http://schemas.android.com/apk/res-auto"

it will make available the custom attributes.


Then you put a shadow layout around you Button:

<com.dd.ShadowLayout
        android:layout_marginTop="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:sl_shadowRadius="4dp"
        app:sl_shadowColor="#AA000000"
        app:sl_dx="0dp"
        app:sl_dy="0dp"
        app:sl_cornerRadius="56dp"> 

       <YourButton
          .... />

</com.dd.ShadowLayout>

You can then tweak the app: settings to match your required shadow.

Hope it helps.

Python function global variables?

As others have noted, you need to declare a variable global in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need global.

To go into a bit more detail on that, what "modify" means is this: if you want to re-bind the global name so it points to a different object, the name must be declared global in the function.

Many operations that modify (mutate) an object do not re-bind the global name to point to a different object, and so they are all valid without declaring the name global in the function.

d = {}
l = []
o = type("object", (object,), {})()

def valid():     # these are all valid without declaring any names global!
   d[0] = 1      # changes what's in d, but d still points to the same object
   d[0] += 1     # ditto
   d.clear()     # ditto! d is now empty but it`s still the same object!
   l.append(0)   # l is still the same list but has an additional member
   o.test = 1    # creating new attribute on o, but o is still the same object

Python 3.4.0 with MySQL database

mysqlclient is a fork of MySQLdb and can serve as a drop-in replacement with Python 3.4 support. If you have trouble building it on Windows, you can download it from Christoph Gohlke's Unofficial Windows Binaries for Python Extension Packages

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

How to extract code of .apk file which is not working?

step 1:

enter image description hereDownload dex2jar here. Create a java project and paste (dex2jar-0.0.7.11-SNAPSHOT/lib ) jar files .

Copy apk file into java project

Run it and after refresh the project ,you get jar file .Using java decompiler you can view all java class files

step 2: Download java decompiler here

AngularJS - Animate ng-view transitions

1.Install angular-animate

2.Add the animation effect to the class ng-enter for page entering animation and the class ng-leave for page exiting animation

for reference: this page has a free resource on angular view transition https://e21code.herokuapp.com/angularjs-page-transition/

How to detect current state within directive

If you are using ui-router, try $state.is();

You can use it like so:

$state.is('stateName');

Per the documentation:

$state.is ... similar to $state.includes, but only checks for the full state name.

How can VBA connect to MySQL database in Excel?

This piece of vba worked for me:

Sub connect()
    Dim Password As String
    Dim SQLStr As String
    'OMIT Dim Cn statement
    Dim Server_Name As String
    Dim User_ID As String
    Dim Database_Name As String
    'OMIT Dim rs statement

    Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
    Server_Name = Range("b2").Value
    Database_name = Range("b3").Value ' Name of database
    User_ID = Range("b4").Value 'id user or username
    Password = Range("b5").Value 'Password

    SQLStr = "SELECT * FROM ComputingNotesTable"

    Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
    Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _ 
            Server_Name & ";Database=" & Database_Name & _
            ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic

    Dim myArray()

    myArray = rs.GetRows()

    kolumner = UBound(myArray, 1)
    rader = UBound(myArray, 2)

    For K = 0 To kolumner ' Using For loop data are displayed
        Range("a5").Offset(0, K).Value = rs.Fields(K).Name
        For R = 0 To rader
           Range("A5").Offset(R + 1, K).Value = myArray(K, R)
        Next
    Next

    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
End Sub

Place API key in Headers or URL

passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.

Twitter Bootstrap and ASP.NET GridView

You need to set useaccessibleheader attribute of the gridview to true and also then also specify a TableSection to be a header after calling the DataBind() method on you GridView object. So if your grid view is mygv

mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader

This should result in a proper formatted grid with thead and tbody tags

How to add /usr/local/bin in $PATH on Mac

Try placing $PATH at the end.

export PATH=/usr/local/git/bin:/usr/local/bin:$PATH

php - insert a variable in an echo string

You can try this

$i = 1
echo '<p class="paragraph'.$i.'"></p>';
++i; 

Prevent linebreak after </div>

<div id="hassaan">
     <div class="label">My Label:</div>
     <div class="text">My text</div>
</div>

CSS:

#hassaan{ margin:auto; width:960px;}
#hassaan:nth-child(n){ clear:both;}
.label, .text{ width:480px; float:left;}

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")

Angular 2: Passing Data to Routes?

1. Set up your routes to accept data

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2. Navigate to route:

From HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

Or from Typescript:

import {Router} from '@angular/router';

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3. Get data from route

import {ActivatedRoute} from '@angular/router';

...

this.value = this.route.snapshot.params['key'];

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How do I ignore ampersands in a SQL script running from SQL Plus?

I resolved with the code below:

set escape on

and put a \ beside & in the left 'value_\&_intert'

Att

How to check the function's return value if true or false

ValidateForm returns boolean,not a string.
When you do this if(ValidateForm() == 'false'), is the same of if(false == 'false'), which is not true.

function post(url, formId) {
    if(!ValidateForm()) {
        // False
    } else {
        // True
    }
}

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

How to call Oracle MD5 hash function?

@user755806 I do not believe that your question was answered. I took your code but used the 'foo' example string, added a lower function and also found the length of the hash returned. In sqlplus or Oracle's sql developer Java database client you can use this to call the md5sum of a value. The column formats clean up the presentation.

column hash_key format a34;
column hash_key_len format 999999;
select dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo')) as hash_key,
       length(dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo'))) as hash_key_len
 from dual;

The result set

HASH_KEY                           HASH_KEY_LEN
---------------------------------- ------------
acbd18db4cc2f85cedef654fccc4a4d8             32

is the same value that is returned from a Linux md5sum command.

echo -n foo | md5sum
acbd18db4cc2f85cedef654fccc4a4d8  -
  1. Yes you can call or execute the sql statement directly in sqlplus or sql developer. I tested the sql statement in both clients against 11g.
  2. You can use any C, C#, Java or other programming language that can send a statement to the database. It is the database on the other end of the call that needs to be able to understand the sql statement. In the case of 11 g, the code will work.
  3. @tbone provides an excellent warning about the deprecation of the dbms_obfuscation_toolkit. However, that does not mean your code is unusable in 12c. It will work but you will want to eventually switch to dbms_crypto package. dbms_crypto is not available in my version of 11g.

How to calculate the number of days between two dates?

Adjusted to allow for daylight saving differences. try this:

  function daysBetween(date1, date2) {

 // adjust diff for for daylight savings
 var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
 // apply the tz offset
 date2.addHours(hoursToAdjust); 

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

// you'll want this addHours function too 

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

How to cache data in a MVC application

public sealed class CacheManager
{
    private static volatile CacheManager instance;
    private static object syncRoot = new Object();
    private ObjectCache cache = null;
    private CacheItemPolicy defaultCacheItemPolicy = null;

    private CacheEntryRemovedCallback callback = null;
    private bool allowCache = true;

    private CacheManager()
    {
        cache = MemoryCache.Default;
        callback = new CacheEntryRemovedCallback(this.CachedItemRemovedCallback);

        defaultCacheItemPolicy = new CacheItemPolicy();
        defaultCacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1.0);
        defaultCacheItemPolicy.RemovedCallback = callback;
        allowCache = StringUtils.Str2Bool(ConfigurationManager.AppSettings["AllowCache"]); ;
    }
    public static CacheManager Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new CacheManager();
                    }
                }
            }

            return instance;
        }
    }

    public IEnumerable GetCache(String Key)
    {
        if (Key == null || !allowCache)
        {
            return null;
        }

        try
        {
            String Key_ = Key;
            if (cache.Contains(Key_))
            {
                return (IEnumerable)cache.Get(Key_);
            }
            else
            {
                return null;
            }
        }
        catch (Exception)
        {
            return null;
        }
    }

    public void ClearCache(string key)
    {
        AddCache(key, null);
    }

    public bool AddCache(String Key, IEnumerable data, CacheItemPolicy cacheItemPolicy = null)
    {
        if (!allowCache) return true;
        try
        {
            if (Key == null)
            {
                return false;
            }

            if (cacheItemPolicy == null)
            {
                cacheItemPolicy = defaultCacheItemPolicy;
            }

            String Key_ = Key;

            lock (Key_)
            {
                return cache.Add(Key_, data, cacheItemPolicy);
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

    private void CachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
    {
        String strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), " | Key-Name: ", arguments.CacheItem.Key, " | Value-Object: ", arguments.CacheItem.Value.ToString());
        LogManager.Instance.Info(strLog);
    }
}

Spring Security redirect to previous page after successful login

I found Utku Özdemir's solution works to some extent, but kind of defeats the purpose of the saved request since the session attribute will take precedence over it. This means that redirects to secure pages will not work as intended - after login you will be sent to the page you were on instead of the redirect target. So as an alternative you could use a modified version of SavedRequestAwareAuthenticationSuccessHandler instead of extending it. This will allow you to have better control over when to use the session attribute.

Here is an example:

private static class MyCustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest == null) {
            HttpSession session = request.getSession();
            if (session != null) {
                String redirectUrl = (String) session.getAttribute("url_prior_login");
                if (redirectUrl != null) {
                    session.removeAttribute("url_prior_login");
                    getRedirectStrategy().sendRedirect(request, response, redirectUrl);
                } else {
                    super.onAuthenticationSuccess(request, response, authentication);
                }
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }

            return;
        }

        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        clearAuthenticationAttributes(request);

        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}

Also, you don't want to save the referrer when authentication has failed, since the referrer will then be the login page itself. So check for the error param manually or provide a separate RequestMapping like below.

@RequestMapping(value = "/login", params = "error")
public String loginError() {
    // Don't save referrer here!
}

What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for.

The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

Difference between Convert.ToString() and .ToString()

In C# if you declare a string variable and if you don’t assign any value to that variable, then by default that variable takes a null value. In such a case, if you use the ToString() method then your program will throw the null reference exception. On the other hand, if you use the Convert.ToString() method then your program will not throw an exception.

jQuery validate: How to add a rule for regular expression validation?

Have you tried this??

$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$", messages: { regex: "The text is invalid..." } })

Note: make sure to escape all the "\" of ur regex by adding another "\" in front of them else the regex wont work as expected.

Vue 2 - Mutating props vue-warn

According to the VueJs 2.0, you should not mutate a prop inside the component. They are only mutated by their parents. Therefore, you should define variables in data with different names and keep them updated by watching actual props. In case the list prop is changed by a parent, you can parse it and assign it to mutableList. Here is a complete solution.

Vue.component('task', {
    template: ´<ul>
                  <li v-for="item in mutableList">
                      {{item.name}}
                  </li>
              </ul>´,
    props: ['list'],
    data: function () {
        return {
            mutableList = JSON.parse(this.list);
        }
    },
    watch:{
        list: function(){
            this.mutableList = JSON.parse(this.list);
        }
    }
});

It uses mutableList to render your template, thus you keep your list prop safe in the component.

When to use StringBuilder in Java

Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

When you define concatenation you need to use an ALIAS for the new column if you want to order on it combined with DISTINCT Some Ex with sql 2008

--this works 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by FullName

--this works too

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
    from SalesLT.Customer c 
    order by 1

-- this doesn't 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by c.FirstName, c.LastName

-- the problem the DISTINCT needs an order on the new concatenated column, here I order on the singular column
-- this works

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
        as FullName, CustomerID 
        from SalesLT.Customer c 

order by 1, CustomerID

-- this doesn't

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
     from SalesLT.Customer c 
      order by 1, CustomerID

Setting dropdownlist selecteditem programmatically

var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);

OR

foreach (var listItem in ctx.Items)
  listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);

Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!

Does JavaScript guarantee object property order?

In ES2015, it does, but not to what you might think

The order of keys in an object wasn't guaranteed until ES2015. It was implementation-defined.

However, in ES2015 in was specified. Like many things in JavaScript, this was done for compatibility purposes and generally reflected an existing unofficial standard among most JS engines (with you-know-who being an exception).

The order is defined in the spec, under the abstract operation OrdinaryOwnPropertyKeys, which underpins all methods of iterating over an object's own keys. Paraphrased, the order is as follows:

  1. All integer index keys (stuff like "1123", "55", etc) in ascending numeric order.

  2. All string keys which are not integer indices, in order of creation (oldest-first).

  3. All symbol keys, in order of creation (oldest-first).

It's silly to say that the order is unreliable - it is reliable, it's just probably not what you want, and modern browsers implement this order correctly.

Some exceptions include methods of enumerating inherited keys, such as the for .. in loop. The for .. in loop doesn't guarantee order according to the specification.

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

In runtime problems like these firstly open logcat if you are using android studio, try to analyse trace tree, go to the beginning from where exception started to rise, since that is usually the source of the problem. Now check for two things:

  1. Check in device file explorer(on the bottom right) there exist a database created by you. mostly you find it in DATA -> DATA -> com.example.hpc.demo(your pakage name) -> DATABASE -> demo.db

  2. Check that in your helper class you have added required '/' for example like below
    DB_location = "data/data/" + mcontext.getPackageName() + "/database/";

How to iterate over the file in python

This is probably because an empty line at the end of your input file.

Try this:

for x in f:
    try:
        print int(x.strip(),16)
    except ValueError:
        print "Invalid input:", x

ViewBag, ViewData and TempData

TempData

Basically it's like a DataReader, once read, data will be lost.

Check this Video

Example

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        TempData["T"] = "T";
        return RedirectToAction("About");
    }

    public ActionResult About()
    {
        return RedirectToAction("Test1");
    }

    public ActionResult Test1()
    {
        String str = TempData["T"]; //Output - T
        return View();
    }
}

If you pay attention to the above code, RedirectToAction has no impact over the TempData until TempData is read. So, once TempData is read, values will be lost.

How can i keep the TempData after reading?

Check the output in Action Method Test 1 and Test 2

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        TempData["T"] = "T";
        return RedirectToAction("About");
    }

    public ActionResult About()
    {
        return RedirectToAction("Test1");
    }

    public ActionResult Test1()
    {
        string Str = Convert.ToString(TempData["T"]);
        TempData.Keep(); // Keep TempData
        return RedirectToAction("Test2");
    }

    public ActionResult Test2()
    {
        string Str = Convert.ToString(TempData["T"]); //OutPut - T
        return View();
    }
}

If you pay attention to the above code, data is not lost after RedirectToAction as well as after Reading the Data and the reason is, We are using TempData.Keep(). is that

In this way you can make it persist as long as you wish in other controllers also.

ViewBag/ViewData

The Data will persist to the corresponding View

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Git - remote: Repository not found

I was also facing the same issue

remote: Repository not found
fatal: repository 'https://github.com/MyRepo/project.git/' not found

I uninstalled the git credentials manager and reinstalled it and then I could easily pull and push to the repository. Here are the commands

$ git credential-manager uninstall

$ git credential-manager install

How to find out the server IP address (using JavaScript) that the browser is connected to?

Not sure how to get the IP address specifically, but the location object provides part of the answer.

e.g. these variables might be helpful:

  • self.location.host - Sets or retrieves the hostname and port number of the location
  • self.location.hostname - Sets or retrieves the host name part of the location or URL.

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

What is the most efficient way to deep clone an object in JavaScript?

There’s a library (called “clone”), that does this quite well. It provides the most complete recursive cloning/copying of arbitrary objects that I know of. It also supports circular references, which is not covered by the other answers, yet.

You can find it on npm, too. It can be used for the browser as well as Node.js.

Here is an example on how to use it:

Install it with

npm install clone

or package it with Ender.

ender build clone [...]

You can also download the source code manually.

Then you can use it in your source code.

var clone = require('clone');

var a = { foo: { bar: 'baz' } };  // inital value of a
var b = clone(a);                 // clone a -> b
a.foo.bar = 'foo';                // change a

console.log(a);                   // { foo: { bar: 'foo' } }
console.log(b);                   // { foo: { bar: 'baz' } }

(Disclaimer: I’m the author of the library.)

How do I empty an input value with jQuery?

A better way is:

$("#element").val(null);

Defining a HTML template to append using JQuery

Use HTML template instead!

Since the accepted answer would represent overloading script method, I would like to suggest another which is, in my opinion, much cleaner and more secure due to XSS risks which come with overloading scripts.

I made a demo to show you how to use it in an action and how to inject one template into another, edit and then add to the document DOM.

example html

<template id="mytemplate">
  <style>
     .image{
        width: 100%;
        height: auto;
     }
  </style>
  <a href="#" class="list-group-item">
    <div class="image">
      <img src="" />
    </div>
    <p class="list-group-item-text"></p>
  </a>
</template>

example js

// select
var t = document.querySelector('#mytemplate');

// set
t.content.querySelector('img').src = 'demo.png';
t.content.querySelector('p').textContent= 'demo text';

// add to document DOM
var clone = document.importNode(t.content, true); // where true means deep copy
document.body.appendChild(clone);

HTML <template>

  • +Its content is effectively inert until activated. Essentially, your markup is hidden DOM and does not render.

  • +Any content within a template won't have side effects. Scripts don't run, images don't load, audio doesn't play ...until the template is used.

  • +Content is considered not to be in the document. Using document.getElementById() or querySelector() in the main page won't return child nodes of a template.

  • +Templates can be placed anywhere inside of <head>, <body>, or <frameset> and can contain any type of content which is allowed in those elements. Note that "anywhere" means that <template> can safely be used in places that the HTML parser disallows.

Fall back

Browser support should not be an issue but if you want to cover all possibilities you can make an easy check:

To feature detect <template>, create the DOM element and check that the .content property exists:

function supportsTemplate() {
  return 'content' in document.createElement('template');
}

if (supportsTemplate()) {
  // Good to go!
} else {
  // Use old templating techniques or libraries.
}

Some insights about Overloading script method

  • +Nothing is rendered - the browser doesn't render this block because the <script> tag has display:none by default.
  • +Inert - the browser doesn't parse the script content as JS because its type is set to something other than "text/javascript".
  • -Security issues - encourages the use of .innerHTML. Run-time string parsing of user-supplied data can easily lead to XSS vulnerabilities.

Full article: https://www.html5rocks.com/en/tutorials/webcomponents/template/#toc-old

Useful reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode http://caniuse.com/#feat=queryselector

CREATING WEB COMPONENTS Creating custom web components tutorial using HTML templates by Trawersy Media: https://youtu.be/PCWaFLy3VUo

GROUP BY without aggregate function

Let me give some examples.

Consider this data.

CREATE TABLE DATASET ( VAL1 CHAR ( 1 CHAR ),
                   VAL2 VARCHAR2 ( 10 CHAR ),
                   VAL3 NUMBER );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'b', 'b-details', 2 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'a-details', 1 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 3 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'dup', 4 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 5 );

COMMIT;

Whats there in table now

SELECT * FROM DATASET;

VAL1 VAL2             VAL3
---- ---------- ----------
b    b-details           2
a    a-details           1
c    c-details           3
a    dup                 4
c    c-details           5

5 rows selected.

--aggregate with group by

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1;

VAL1   COUNT(*)
---- ----------
b             1
a             2
c             2

3 rows selected.

--aggregate with group by multiple columns but select partial column

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

VAL1  
---- 
b             
c             
a             
a             

4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1,
      VAL2
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b    b-details
    c    c-details
    a    dup
    a    a-details

    4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b
    c
    a
    a

    4 rows selected.

You have N columns in select (excluding aggregations), then you should have N or N+x columns

Jquery .on('scroll') not firing the event while scrolling

Binding the scroll event after the ul has loaded using ajax has solved the issue. In my findings $(document).on( 'scroll', '#id', function () {...}) is not working and binding the scroll event after the ajax load found working.

$("#ulId").bind('scroll', function() {
   console.log('Event worked');
}); 

You may unbind the event after removing or replacing the ul.

Hope it may help someone.

Generating random numbers in Objective-C

There are some great, articulate answers already, but the question asks for a random number between 0 and 74. Use:

arc4random_uniform(75)

Using CSS to affect div style inside iframe

Use Jquery and wait till the source is loaded, This is how I have achieved(Used angular interval, you can use javascript setInterval method):

var addCssToIframe = function() {
    if ($('#myIframe').contents().find("head") != undefined) {
        $('#myIframe')
                .contents()
                .find("head")
                .append(
                        '<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
        $interval.cancel(addCssInterval);
    }
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);

Java method to swap primitives

You can't create a method swap, so that after calling swap(x,y) the values of x and y will be swapped. You could create such a method for mutable classes by swapping their contents¹, but this would not change their object identity and you could not define a general method for this.

You can however write a method that swaps two items in an array or list if that's what you want.

¹ For example you could create a swap method that takes two lists and after executing the method, list x will have the previous contents of list y and list y will have the previous contents of list x.

Javascript - validation, numbers only

here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313

<input type="text" 
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>

and this will not accept entering the dot (.), so it will only accept integers

<input type="text" 
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>

this way you will not permit the user to input anything but numbers

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

Recover SVN password from local cache

Just use this this decrypter to decrypt your locally cached username & password.

By default, TortoiseSVN stores your cached credentials inside files in the %APPDATA%\Subversion\auth\svn.simple directory. The passwords are encrypted using the Windows Data Protection API, with a key tied to your user account. This tool reads the files and uses the API to decrypt your passwords

svn password decryptor

What is lazy loading in Hibernate?

Lazy fetching decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class. Lazy = true (means not to load child) By default the lazy loading of the child objects is true.

This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.

But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.

Example : If you have a TABLE ? EMPLOYEE mapped to Employee object and contains set of Address objects. Parent Class : Employee class, Child class : Address Class

public class Employee { 
private Set address = new HashSet(); // contains set of child Address objects 
public Set getAddress () { 
return address; 
} 
public void setAddresss(Set address) { 
this. address = address; 
} 
} 

In the Employee.hbm.xml file

<set name="address" inverse="true" cascade="delete" lazy="false"> 
<key column="a_id" /> 
<one-to-many class="beans Address"/> 
</set> 

In the above configuration. If lazy="false" : - when you load the Employee object that time child object Address is also loaded and set to setAddresss() method. If you call employee.getAdress() then loaded data returns.No fresh database call.

If lazy="true" :- This the default configuration. If you don?t mention then hibernate consider lazy=true. when you load the Employee object that time child object Adress is not loaded. You need extra call to data base to get address objects. If you call employee.getAdress() then that time database query fires and return results. Fresh database call.

How to sort ArrayList<Long> in decreasing order?

Comparator<Long> comparator = Collections.reverseOrder();
Collections.sort(arrayList, comparator);

open resource with relative path in Java

Use this:

resourcesloader.class.getClassLoader().getResource("/path/to/file").**getPath();**

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

How to get a index value from foreach loop in jstl

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>

Check string length in PHP

[0]=> string(141) means that $message is an array, not string, and $message[0] is a string with 141 characters in length.

PHP - print all properties of an object

var_dump($obj); 

If you want more info you can use a ReflectionClass:

http://www.phpro.org/manual/language.oop5.reflection.html

Python object deleting itself

If you're using a single reference to the object, then the object can kill itself by resetting that outside reference to itself, as in:

class Zero:
    pOne = None

class One:

    pTwo = None   

    def process(self):
        self.pTwo = Two()
        self.pTwo.dothing()
        self.pTwo.kill()

        # now this fails:
        self.pTwo.dothing()


class Two:

    def dothing(self):
        print "two says: doing something"

    def kill(self):
        Zero.pOne.pTwo = None


def main():
    Zero.pOne = One() # just a global
    Zero.pOne.process()


if __name__=="__main__":
    main()

You can of course do the logic control by checking for the object existence from outside the object (rather than object state), as for instance in:

if object_exists:
   use_existing_obj()
else: 
   obj = Obj()

How to create a folder with name as current date in batch (.bat) files

I had a problem with this because my server ABSOLUTELY had to have its date in MM/dd/yyyy format, while I wanted the directory to be in YYYY-MM-DD format for neatness sake. Here's how to get it in YYYY-MM-DD format, no matter what your regional settings are set as.

Find out what gets displayed when you use %DATE%:

From a command prompt type:

ECHO %DATE%

Mine came out 03/06/2013 (as in 6th March 2013)

Therefore, to get a directory name as 2013-03-06, code this into your batch file:

SET dirname="%date:~6,4%-%date:~0,2%-%date:~3,2%"
mkdir %dirname%

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

TypeScript static classes

I was searching for something similar and came accross something called the Singleton Pattern.

Reference: Singleton Pattern

I am working on a BulkLoader class to load different types of files and wanted to use the Singleton pattern for it. This way I can load files from my main application class and retrieve the loaded files easily from other classes.

Below is a simple example how you can make a score manager for a game with TypeScript and the Singleton pattern.

class SingletonClass {

private static _instance:SingletonClass = new SingletonClass();

private _score:number = 0;

constructor() {
    if(SingletonClass._instance){
        throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new.");
    }
    SingletonClass._instance = this;
}

public static getInstance():SingletonClass
{
    return SingletonClass._instance;
}

public setScore(value:number):void
{
    this._score = value;
}

public getScore():number
{
    return this._score;
}

public addPoints(value:number):void
{
    this._score += value;
}

public removePoints(value:number):void
{
    this._score -= value;
}   }

Then anywhere in your other classes you would get access to the Singleton by:

var scoreManager = SingletonClass.getInstance();
scoreManager.setScore(10); scoreManager.addPoints(1);
scoreManager.removePoints(2); console.log( scoreManager.getScore() );

Ruby: Easiest Way to Filter Hash Keys?

As for bonus question:

  1. If you have output from #select method like this (list of 2-element arrays):

    [[:choice1, "Oh look, another one"], [:choice2, "Even more strings"], [:choice3, "But wait"]]
    

    then simply take this result and execute:

    filtered_params.join("\t")
    # or if you want only values instead of pairs key-value
    filtered_params.map(&:last).join("\t")
    
  2. If you have output from #delete_if method like this (hash):

    {:choice1=>"Oh look, another one", :choice2=>"Even more strings", :choice3=>"But wait"}
    

    then:

    filtered_params.to_a.join("\t")
    # or
    filtered_params.values.join("\t")
    

Remove Duplicates from range of cells in excel vba

If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:

 Sub norepeat()

    Range("C8:C16").RemoveDuplicates (1)

End Sub

Regards

Count number of 1's in binary representation

The best way in javascript to do so is

function getBinaryValue(num){
 return num.toString(2);
}

function checkOnces(binaryValue){
    return binaryValue.toString().replace(/0/g, "").length;
}

where binaryValue is the binary String eg: 1100

When to use DataContract and DataMember attributes?

  1. Data contract: It specifies that your entity class is ready for Serialization process.

  2. Data members: It specifies that the particular field is part of the data contract and it can be serialized.

HttpListener Access Denied

You can start your application as administrator if you add Application Manifest to your project.

Just Add New Item to your project and select "Application Manifest File". Change the <requestedExecutionLevel> element to:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Tokenizing strings in C

You can simplify the code by introducing an extra variable.

#include <string.h>
#include <stdio.h>

int main()
{
    char str[100], *s = str, *t = NULL;

    strcpy(str, "a space delimited string");
    while ((t = strtok(s, " ")) != NULL) {
        s = NULL;
        printf(":%s:\n", t);
    }
    return 0;
}

Stacked bar chart

You need to transform your data to long format and shouldn't use $ inside aes:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

Google Maps API v3 marker with label

the above solutions wont work on ipad-2

recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)

How to access the local Django webserver from outside world

just do this:

python manage.py runserver 0:8000

by the above command you are actually binding it to the external IP address. so now when you access your IP address with the port number, you will be able to access it in the browser without any problem.

just type in the following in the browser address bar:

<your ip address>:8000

eg:

192.168.1.130:8000

you may have to edit the settings.py add the following in the settings.py in the last line:

ALLOWED_HOSTS = ['*']

hope this will help...

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

Count number of rows by group using dplyr

another approach is to use the double colons:

mtcars %>% 
  dplyr::group_by(cyl, gear) %>%
  dplyr::summarise(length(gear))

Server did not recognize the value of HTTP Header SOAPAction

Just to help someone on this problem, after an afternoon of debug, the problem was that the web service was developed with framework 4.5 and the call from android must be done with SoapEnvelope.VER12 and not with SoapEnvelope.VER11

Notepad++ Multi editing

Notepad++ has a powerful regex engine, capable to search and replace patterns at will.

In your scenario:

  1. Click the menu item Search\Replace...

  2. Fill the 'Find what' field with the search pattern:

    ^(\d{4})\s+(\w{3})\s+(\w{3})$
    
  3. Fill the replace pattern:

    Insert into tbl (\1, \2) where clm = \3
    
  4. Click the Replace All button.

And that's it.

NotePad++ replace window screenshot

Failed linking file resources

I have this problem.The main problem was i added an attribute to an BottomAppBar in the xml file.I found error message in android bottom build section explained that error i replaced the attribute and every thing was ok. For others who have the same error but my solution not ok with them you have to read the error message it will guide you to the pain point.

Show loading image while $.ajax is performed

Before your call either insert the loading image in a div/span somewhere and then on the success function remove that image. Alternatively you can set up a css class like loading that might look like this

.loading
{
    width: 16px;
    height: 16px;
    background:transparent url('loading.gif') no-repeat 0 0;
    font-size: 0px;
    display: inline-block;
}

And then assign this class to a span/div and clear it in the success function

Node.js Error: connect ECONNREFUSED

You're trying to connect to localhost:8080 ... is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

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

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

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

Create a folder if it doesn't already exist

You can try also:

$dirpath = "path/to/dir";
$mode = "0764";
is_dir($dirpath) || mkdir($dirpath, $mode, true);

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Yes you can run JavaFX application on iOS, android, desktop, RaspberryPI (no windows8 mobile yet).

Work in Action :

We did it! JavaFX8 multimedia project on iPad, Android, Windows and Mac!

JavaFX Everywhere

Ensemble8 Javafx8 Android Demo

My Sample JavaFX application Running on Raspberry Pi

My Sample Application Running on Android

JavaFX on iOS and Android

Dev Resources :

Android :

Building and deploying JavaFX Applications on Android

iOS :

NetBeans support for JavaFX for iOS is out!

Develop a JavaFX + iOS app with RoboVM + e(fx)clipse tools in 10 minutes

If you are going to develop serious applications here is some more info

Misc :

At present for JavaFX Oracle priority list is Desktop (Mac,windows,linux) and Embedded (Raspberry Pi, beagle Board etc) .For iOS/android oracle done most of the hardwork and opnesourced javafxports of these platforms as part of OpenJFX ,but there is no JVM from oracle for ios/android.Community is putting all together by filling missing piece(JVM) for ios/android,Community made good progress in running JavaFX on ios (RoboVM) / android(DalvikVM). If you want you can also contribute to the community by sponsoring (Become a RoboVM sponsor) or start developing apps and report issues.

Edit 06/23/2014 :

Johan Vos created a website for javafx ports JavaFX on Mobile and Tablets,check this for updated info ..

How do you count the lines of code in a Visual Studio solution?

I came up with a quick and dirty powershell script for counting lines in a folder structure. It's not nearly as full featured as some of the other tools referenced in other answers, but I think it's good enough to provide a rough comparison of the size of code files relative to one another in a project or solution.

The script can be found here:

https://gist.github.com/1674457

Build Step Progress Bar (css and jquery)

This is what I did:

  1. Create jQuery .progressbar() to load a div into a progress bar.
  2. Create the step title on the bottom of the progress bar. Position them with CSS.
  3. Then I create function in jQuery that change the value of the progressbar everytime user move on to next step.

HTML

<div id="divProgress"></div>
<div id="divStepTitle">
    <span class="spanStep">Step 1</span> <span class="spanStep">Step 2</span> <span class="spanStep">Step 3</span>
</div>

<input type="button" id="btnPrev" name="btnPrev" value="Prev" />
<input type="button" id="btnNext" name="btnNext" value="Next" />

CSS

#divProgress
{
    width: 600px;
}

#divStepTitle
{
    width: 600px;
}

.spanStep
{
    text-align: center;
    width: 200px;
}

Javascript/jQuery

var progress = 0;

$(function({
    //set step progress bar
    $("#divProgress").progressbar();

    //event handler for prev and next button
    $("#btnPrev, #btnNext").click(function(){
        step($(this));
    });
});

function step(obj)
{
    //switch to prev/next page
    if (obj.val() == "Prev")
    {
        //set new value for progress bar
        progress -= 20;
        $("#divProgress").progressbar({ value: progress });

        //do extra step for showing previous page
    }
    else if (obj.val() == "Next")
    {
        //set new value for progress bar
        progress += 20;
        $("#divProgress").progressbar({ value: progress });

        //do extra step for showing next page
    }
}

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

I know it's late in the day but might help someone else!

body,html {
  height: 100%;
}

.contentarea {

 /* 
  * replace 160px with the sum of height of all other divs 
  * inc padding, margins etc 
  */
  min-height: calc(100% - 160px); 
}

Hide vertical scrollbar in <select> element

No, you can't control the look of a select box in such detail.

A select box is usually displayed as a dropdown list, but there is nothing that says that it always has to be displayed that way. How it is displayed depends on the system, and on some mobile phones for example you don't get a dropdown at all, but a selector that covers most or all of the screen.

If you want to control how your form elements look in such detail, you have to make your own form controls out of regular HTML elements (or find someone else who has already done that).

Submitting form and pass data to controller method of type FileStreamResult

When in doubt, follow MVC conventions.

Create a viewModel if you haven't already that contains a property for JobID

public class Model
{
     public string JobId {get; set;}
     public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
     //...any other properties you may need
}

Strongly type your view

@model Fully.Qualified.Path.To.Model

Add a hidden field for JobId to the form

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{   
    //...    
    @Html.HiddenFor(m => m.JobId)
}

And accept the model as the parameter in your controller action:

[HttpPost]
public FileStreamResult myMethod(Model model)
{
    sting str = model.JobId;
}

Why is it string.join(list) instead of list.join(string)?

This was discussed in the String methods... finally thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and str.join was included in Python 1.6 which was released in Sep 2000 (and supported Unicode). Python 2.0 (supported str methods including join) was released in Oct 2000.

  • There were four options proposed in this thread:
    • str.join(seq)
    • seq.join(str)
    • seq.reduce(str)
    • join as a built-in function
  • Guido wanted to support not only lists, tuples, but all sequences/iterables.
  • seq.reduce(str) is difficult for new-comers.
  • seq.join(str) introduces unexpected dependency from sequences to str/unicode.
  • join() as a built-in function would support only specific data types. So using a built in namespace is not good. If join() supports many datatypes, creating optimized implementation would be difficult, if implemented using the __add__ method then it's O(n²).
  • The separator string (sep) should not be omitted. Explicit is better than implicit.

There are no other reasons offered in this thread.

Here are some additional thoughts (my own, and my friend's):

  • Unicode support was coming, but it was not final. At that time UTF-8 was the most likely about to replace UCS2/4. To calculate total buffer length of UTF-8 strings it needs to know character coding rule.
  • At that time, Python had already decided on a common sequence interface rule where a user could create a sequence-like (iterable) class. But Python didn't support extending built-in types until 2.2. At that time it was difficult to provide basic iterable class (which is mentioned in another comment).

Guido's decision is recorded in a historical mail, deciding on str.join(seq):

Funny, but it does seem right! Barry, go for it...
--Guido van Rossum

How to upload folders on GitHub

I've just gone through that process again. Always end up cloning the repo locally, upload the folder I want to have in that repo to that cloned location, commit the changes and then push it.

Note that if you're dealing with large files, you'll need to consider using something like Git LFS.

Best way to pass parameters to jQuery's .load()

As Davide Gualano has been told. This one

$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")

use GET method for sending the request, and this one

$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.

For example: url length limits the amount of sending data in GET method.

How do I show my global Git configuration?

git config --list

is one way to go. I usually just open up .gitconfig though.

Android: Scale a Drawable or background image?

There is an easy way to do this from the drawable:

your_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@color/bg_color"/>
    <item>
        <bitmap
            android:gravity="center|bottom|clip_vertical"
            android:src="@drawable/your_image" />
    </item>

</layer-list>

The only downside is that if there is not enough space, your image won't be fully shown, but it will be clipped, I couldn't find an way to do this directly from a drawable. But from the tests I did it works pretty well, and it doesn't clip that much of the image. You could play more with the gravity options.

Another way will be to just create an layout, where you will use an ImageView and set the scaleType to fitCenter.

Entity framework linq query Include() multiple children entities

Use extension methods. Replace NameOfContext with the name of your object context.

public static class Extensions{
   public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country") ;
     }

     public static Company CompanyById(this NameOfContext context, int companyID){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country")
             .FirstOrDefault(c => c.Id == companyID) ;
      }

}

Then your code becomes

     Company company = 
          context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);

     //or if you want even more
     Company company = 
          context.CompanyById(companyID);

Jquery UI datepicker. Disable array of Dates

For DD-MM-YY use this code:

var array = ["03-03-2017', '03-10-2017', '03-25-2017"]

$('#datepicker').datepicker({
    beforeShowDay: function(date){
    var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
    return [ array.indexOf(string) == -1 ]
    }
});

function highlightDays(date) {
    for (var i = 0; i < dates.length; i++) {
    if (new Date(dates[i]).toString() == date.toString()) {
        return [true, 'highlight'];
    }
}
return [true, ''];
}

"Unable to find remote helper for 'https'" during git clone

For those using git with Jenkins under a windows system, you need to configure the location of git.exe under: Manage Jenkins => Global Tool Configuration => Git => Path to Git executable and fill-in the path to git.exe, for example; C:\Program Files\Git\bin\git.exe

How do I select last 5 rows in a table without sorting?

  1. You need to count number of rows inside table ( say we have 12 rows )
  2. then subtract 5 rows from them ( we are now in 7 )
  3. select * where index_column > 7

    select * from users
    where user_id > 
    ( (select COUNT(*) from users) - 5)
    

    you can order them ASC or DESC

    But when using this code

    select TOP 5 from users order by user_id DESC
    

    it will not be ordered easily.

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

error: use of deleted function

I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.

Text to speech(TTS)-Android

public class Texttovoice extends ActionBarActivity implements OnInitListener {
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_texttovoice);
    tts = new TextToSpeech(this, this);

    // Refer 'Speak' button
    btnSpeak = (Button) findViewById(R.id.btnSpeak);
    // Refer 'Text' control
    txtText = (EditText) findViewById(R.id.txtText);
    // Handle onClick event for button 'Speak'
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // Method yet to be defined
            speakOut();
        }

    });

}

private void speakOut() {
    // Get the text typed
    String text = txtText.getText().toString();
    // If no text is typed, tts will read out 'You haven't typed text'
    // else it reads out the text you typed
    if (text.length() == 0) {
        tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
    } else {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

    }

}

public void onDestroy() {
    // Don't forget to shutdown!
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.texttovoice, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void onInit(int status) {
    // TODO Auto-generated method stub
    // TTS is successfully initialized
    if (status == TextToSpeech.SUCCESS) {
        // Setting speech language
        int result = tts.setLanguage(Locale.US);
        // If your device doesn't support language you set above
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            // Cook simple toast message with message
            Toast.makeText(getApplicationContext(), "Language not supported",
                    Toast.LENGTH_LONG).show();
            Log.e("TTS", "Language is not supported");
        }
        // Enable the button - It was disabled in main.xml (Go back and
        // Check it)
        else {
            btnSpeak.setEnabled(true);
        }
        // TTS is not initialized properly
    } else {
        Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
                .show();
        Log.e("TTS", "Initilization Failed");
    }
}
   //-------------------------------XML---------------

  <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText" >

    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="15dip"
    android:text="listen your text"
    android:textColor="#0587d9"
    android:textSize="26dip"
    android:textStyle="bold" />

<EditText
    android:id="@+id/txtText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dip"
    android:layout_marginTop="20dip"
    android:hint="Enter text to speak" />

<Button
    android:id="@+id/btnSpeak"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dip"
    android:enabled="false"
    android:text="Speak" 
    android:onClick="speakout"/>

Copy table to a different database on a different SQL Server

If it’s only copying tables then linked servers will work fine or creating scripts but if secondary table already contains some data then I’d suggest using some third party comparison tool.

I’m using Apex Diff but there are also a lot of other tools out there such as those from Red Gate or Dev Art...

Third party tools are not necessary of course and you can do everything natively it’s just more convenient. Even if you’re on a tight budget you can use these in trial mode to get things done….

Here is a good thread on similar topic with a lot more examples on how to do this in pure sql.

ASP.NET email validator regex

E-mail addresses are very difficult to verify correctly with a mere regex. Here is a pretty scary regex that supposedly implements RFC822, chapter 6, the specification of valid e-mail addresses.

Not really an answer, but maybe related to what you're trying to accomplish.

Altering a column: null to not null

In my case I had difficulties with the posted answers. I ended up using the following:

ALTER TABLE table_name CHANGE COLUMN column_name column_name VARCHAR(200) NOT NULL DEFAULT '';

Change VARCHAR(200) to your datatype, and optionally change the default value.

If you don't have a default value you're going to have a problem making this change, as default would be null creating a conflict.

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

Cannot connect to repo with TortoiseSVN

Try clearing the settings under "Saved Data" - refer to:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html

This worked for me with Windows 7.

Eric

Insert Picture into SQL Server 2005 Image Field using only SQL

For updating a record:

 UPDATE Employees SET [Photo] = (SELECT
 MyImage.* from Openrowset(Bulk
 'C:\photo.bmp', Single_Blob) MyImage)
 where Id = 10

Notes:

  • Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
  • Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!

How to connect to a remote Windows machine to execute commands using python?

is it too late?

I personally agree with Beatrice Len, I used paramiko maybe is an extra step for windows, but I have an example project git hub, feel free to clone or ask me.

https://github.com/davcastroruiz/django-ssh-monitor

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

As a general rule (i.e. in vanilla kernels), fork/clone failures with ENOMEM occur specifically because of either an honest to God out-of-memory condition (dup_mm, dup_task_struct, alloc_pid, mpol_dup, mm_init etc. croak), or because security_vm_enough_memory_mm failed you while enforcing the overcommit policy.

Start by checking the vmsize of the process that failed to fork, at the time of the fork attempt, and then compare to the amount of free memory (physical and swap) as it relates to the overcommit policy (plug the numbers in.)

In your particular case, note that Virtuozzo has additional checks in overcommit enforcement. Moreover, I'm not sure how much control you truly have, from within your container, over swap and overcommit configuration (in order to influence the outcome of the enforcement.)

Now, in order to actually move forward I'd say you're left with two options:

  • switch to a larger instance, or
  • put some coding effort into more effectively controlling your script's memory footprint

NOTE that the coding effort may be all for naught if it turns out that it's not you, but some other guy collocated in a different instance on the same server as you running amock.

Memory-wise, we already know that subprocess.Popen uses fork/clone under the hood, meaning that every time you call it you're requesting once more as much memory as Python is already eating up, i.e. in the hundreds of additional MB, all in order to then exec a puny 10kB executable such as free or ps. In the case of an unfavourable overcommit policy, you'll soon see ENOMEM.

Alternatives to fork that do not have this parent page tables etc. copy problem are vfork and posix_spawn. But if you do not feel like rewriting chunks of subprocess.Popen in terms of vfork/posix_spawn, consider using suprocess.Popen only once, at the beginning of your script (when Python's memory footprint is minimal), to spawn a shell script that then runs free/ps/sleep and whatever else in a loop parallel to your script; poll the script's output or read it synchronously, possibly from a separate thread if you have other stuff to take care of asynchronously -- do your data crunching in Python but leave the forking to the subordinate process.

HOWEVER, in your particular case you can skip invoking ps and free altogether; that information is readily available to you in Python directly from procfs, whether you choose to access it yourself or via existing libraries and/or packages. If ps and free were the only utilities you were running, then you can do away with subprocess.Popen completely.

Finally, whatever you do as far as subprocess.Popen is concerned, if your script leaks memory you will still hit the wall eventually. Keep an eye on it, and check for memory leaks.

How to analyse the heap dump using jmap in java

You can use jhat (Java Heap Analysis Tool) to read the generated file:

jhat [ options ] <heap-dump-file>

The jhat command parses a java heap dump file and launches a webserver. jhat enables you to browse heap dumps using your favorite webbrowser.

Note that you should have a hprof binary format output to be able to parse it with jhat. You can use format=b option to generate the dump in this format.

-dump:format=b,file=<filename>

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

<select [(ngModel)]="selectedcarrera" (change)="mostrardatos()" class="form-control" name="carreras">
    <option *ngFor="let x of carreras" [ngValue]="x"> {{x.nombre}} </option>
</select>

In ts

mostrardatos(){

}

Is there a git-merge --dry-run option?

Undoing a merge with git is so easy you shouldn't even worry about the dry run:

$ git pull $REMOTE $BRANCH
# uh oh, that wasn't right
$ git reset --hard ORIG_HEAD
# all is right with the world

EDIT: As noted in the comments below, if you have changes in your working directory or staging area you'll probably want to stash them before doing the above (otherwise they will disappear following the git reset above)

How to refresh app upon shaking the device?

// Need to implement SensorListener
public class ShakeActivity extends Activity implements SensorListener {
// For shake motion detection.
private SensorManager sensorMgr;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 800;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start motion detection
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported = sensorMgr.registerListener(this,
    SensorManager.SENSOR_ACCELEROMETER,
    SensorManager.SENSOR_DELAY_GAME);

if (!accelSupported) {
    // on accelerometer on this device
    sensorMgr.unregisterListener(this,
            SensorManager.SENSOR_ACCELEROMETER);
}
}

protected void onPause() {
if (sensorMgr != null) {
    sensorMgr.unregisterListener(this,
            SensorManager.SENSOR_ACCELEROMETER);
    sensorMgr = null;
    }
super.onPause();
}

public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
}

public void onSensorChanged(int sensor, float[] values) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
    long curTime = System.currentTimeMillis();
    // only allow one update every 100ms.
    if ((curTime - lastUpdate)> 100) {
    long diffTime = (curTime - lastUpdate);
    lastUpdate = curTime;

    x = values[SensorManager.DATA_X];
    y = values[SensorManager.DATA_Y];
    z = values[SensorManager.DATA_Z];

    float speed = Math.abs(x+y+z - last_x - last_y - last_z)
                          / diffTime * 10000;
    if (speed > SHAKE_THRESHOLD) {
        // yes, this is a shake action! Do something about it!
    }
    last_x = x;
    last_y = y;
    last_z = z;
    }
}
}
}

HTML5: Slider with two inputs possible?

The question was: "Is it possible to make a HTML5 slider with two input values, for example to select a price range? If so, how can it be done?"

Ten years ago the answer was probably 'No'. However, times have changed. In 2020 it is finally possible to create a fully accessible, native, non-jquery HTML5 slider with two thumbs for price ranges. If found this posted after I already created this solution and I thought that it would be nice to share my implementation here.

This implementation has been tested on mobile Chrome and Firefox (Android) and Chrome and Firefox (Linux). I am not sure about other platforms, but it should be quite good. I would love to get your feedback and improve this solution.

This solution allows multiple instances on one page and it consists of just two inputs (each) with descriptive labels for screen readers. You can set the thumb size in the amount of grid labels. Also, you can use touch, keyboard and mouse to interact with the slider. The value is updated during adjustment, due to the 'on input' event listener.

My first approach was to overlay the sliders and clip them. However, that resulted in complex code with a lot of browser dependencies. Then I recreated the solution with two sliders that were 'inline'. This is the solution you will find below.

_x000D_
_x000D_
var thumbsize = 14;

function draw(slider,splitvalue) {

    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var lower = slider.querySelector('.lower');
    var upper = slider.querySelector('.upper');
    var legend = slider.querySelector('.legend');
    var thumbsize = parseInt(slider.getAttribute('data-thumbsize'));
    var rangewidth = parseInt(slider.getAttribute('data-rangewidth'));
    var rangemin = parseInt(slider.getAttribute('data-rangemin'));
    var rangemax = parseInt(slider.getAttribute('data-rangemax'));

    /* set min and max attributes */
    min.setAttribute('max',splitvalue);
    max.setAttribute('min',splitvalue);

    /* set css */
    min.style.width = parseInt(thumbsize + ((splitvalue - rangemin)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    max.style.width = parseInt(thumbsize + ((rangemax - splitvalue)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    min.style.left = '0px';
    max.style.left = parseInt(min.style.width)+'px';
    min.style.top = lower.offsetHeight+'px';
    max.style.top = lower.offsetHeight+'px';
    legend.style.marginTop = min.offsetHeight+'px';
    slider.style.height = (lower.offsetHeight + min.offsetHeight + legend.offsetHeight)+'px';
    
    /* correct for 1 off at the end */
    if(max.value>(rangemax - 1)) max.setAttribute('data-value',rangemax);

    /* write value and labels */
    max.value = max.getAttribute('data-value'); 
    min.value = min.getAttribute('data-value');
    lower.innerHTML = min.getAttribute('data-value');
    upper.innerHTML = max.getAttribute('data-value');

}

function init(slider) {
    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var rangemin = parseInt(min.getAttribute('min'));
    var rangemax = parseInt(max.getAttribute('max'));
    var avgvalue = (rangemin + rangemax)/2;
    var legendnum = slider.getAttribute('data-legendnum');

    /* set data-values */
    min.setAttribute('data-value',rangemin);
    max.setAttribute('data-value',rangemax);
    
    /* set data vars */
    slider.setAttribute('data-rangemin',rangemin); 
    slider.setAttribute('data-rangemax',rangemax); 
    slider.setAttribute('data-thumbsize',thumbsize); 
    slider.setAttribute('data-rangewidth',slider.offsetWidth);

    /* write labels */
    var lower = document.createElement('span');
    var upper = document.createElement('span');
    lower.classList.add('lower','value');
    upper.classList.add('upper','value');
    lower.appendChild(document.createTextNode(rangemin));
    upper.appendChild(document.createTextNode(rangemax));
    slider.insertBefore(lower,min.previousElementSibling);
    slider.insertBefore(upper,min.previousElementSibling);
    
    /* write legend */
    var legend = document.createElement('div');
    legend.classList.add('legend');
    var legendvalues = [];
    for (var i = 0; i < legendnum; i++) {
        legendvalues[i] = document.createElement('div');
        var val = Math.round(rangemin+(i/(legendnum-1))*(rangemax - rangemin));
        legendvalues[i].appendChild(document.createTextNode(val));
        legend.appendChild(legendvalues[i]);

    } 
    slider.appendChild(legend);

    /* draw */
    draw(slider,avgvalue);

    /* events */
    min.addEventListener("input", function() {update(min);});
    max.addEventListener("input", function() {update(max);});
}

function update(el){
    /* set function vars */
    var slider = el.parentElement;
    var min = slider.querySelector('#min');
    var max = slider.querySelector('#max');
    var minvalue = Math.floor(min.value);
    var maxvalue = Math.floor(max.value);
    
    /* set inactive values before draw */
    min.setAttribute('data-value',minvalue);
    max.setAttribute('data-value',maxvalue);

    var avgvalue = (minvalue + maxvalue)/2;

    /* draw */
    draw(slider,avgvalue);
}

var sliders = document.querySelectorAll('.min-max-slider');
sliders.forEach( function(slider) {
    init(slider);
});
_x000D_
* {padding: 0; margin: 0;}
body {padding: 40px;}

.min-max-slider {position: relative; width: 200px; text-align: center; margin-bottom: 50px;}
.min-max-slider > label {display: none;}
span.value {height: 1.7em; font-weight: bold; display: inline-block;}
span.value.lower::before {content: "€"; display: inline-block;}
span.value.upper::before {content: "- €"; display: inline-block; margin-left: 0.4em;}
.min-max-slider > .legend {display: flex; justify-content: space-between;}
.min-max-slider > .legend > * {font-size: small; opacity: 0.25;}
.min-max-slider > input {cursor: pointer; position: absolute;}

/* webkit specific styling */
.min-max-slider > input {
  -webkit-appearance: none;
  outline: none!important;
  background: transparent;
  background-image: linear-gradient(to bottom, transparent 0%, transparent 30%, silver 30%, silver 60%, transparent 60%, transparent 100%);
}
.min-max-slider > input::-webkit-slider-thumb {
  -webkit-appearance: none; /* Override default look */
  appearance: none;
  width: 14px; /* Set a specific slider handle width */
  height: 14px; /* Slider handle height */
  background: #eee; /* Green background */
  cursor: pointer; /* Cursor on hover */
  border: 1px solid gray;
  border-radius: 100%;
}
.min-max-slider > input::-webkit-slider-runnable-track {cursor: pointer;}
_x000D_
<div class="min-max-slider" data-legendnum="2">
    <label for="min">Minimum price</label>
    <input id="min" class="min" name="min" type="range" step="1" min="0" max="3000" />
    <label for="max">Maximum price</label>
    <input id="max" class="max" name="max" type="range" step="1" min="0" max="3000" />
</div>
_x000D_
_x000D_
_x000D_

Note that you should keep the step size to 1 to prevent the values to change due to redraws/redraw bugs.

View online at: https://codepen.io/joosts/pen/rNLdxvK

Overcoming "Display forbidden by X-Frame-Options"

i had this problem, and resolved it editing httd.conf

<IfModule headers_module>
    <IfVersion >= 2.4.7 >
        Header always setifempty X-Frame-Options GOFORIT
    </IfVersion>
    <IfVersion < 2.4.7 >
        Header always merge X-Frame-Options GOFORIT
    </IfVersion>
</IfModule>

i changed SAMEORIGIN to GOFORIT and restarted server

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

How to expand/collapse a diff sections in Vimdiff?

set vimdiff to ignore case

Having started vim diff with

 gvim -d main.sql backup.sql &

I find that annoyingly one file has MySQL keywords in lowercase the other uppercase showing differences on practically every other line

:set diffopt+=icase

this updates the screen dynamically & you can just as easily switch it off again

Early exit from function?

This:

function myfunction()
{
     if (a == 'stop')  // How can I stop working of function here?
     {
         return;
     }
}

How can I check whether a radio button is selected with JavaScript?

You can use this simple script. You may have multiple radio buttons with same names and different values.

var checked_gender = document.querySelector('input[name = "gender"]:checked');

if(checked_gender != null){  //Test if something was checked
alert(checked_gender.value); //Alert the value of the checked.
} else {
alert('Nothing checked'); //Alert, nothing was checked.
}

How to check if a "lateinit" variable has been initialized?

You can easily do this by:

::variableName.isInitialized

or

this::variableName.isInitialized

But if you are inside a listener or inner class, do this:

this@OuterClassName::variableName.isInitialized

Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:

class Test {
    lateinit var str:String
}

And to check if str is initialized:

enter image description here

What we are doing here: checking isInitialized for field str of Test class in Test2 class. And we get an error backing field of var is not accessible at this point. Check a question already raised about this.

How to convert a multipart file to File?

  private File convertMultiPartToFile(MultipartFile file ) throws IOException
    {
        File convFile = new File( file.getOriginalFilename() );
        FileOutputStream fos = new FileOutputStream( convFile );
        fos.write( file.getBytes() );
        fos.close();
        return convFile;
    }

MongoDB: Is it possible to make a case-insensitive query?

One very important thing to keep in mind when using a Regex based query - When you are doing this for a login system, escape every single character you are searching for, and don't forget the ^ and $ operators. Lodash has a nice function for this, should you be using it already:

db.stuff.find({$regex: new RegExp(_.escapeRegExp(bar), $options: 'i'})

Why? Imagine a user entering .* as his username. That would match all usernames, enabling a login by just guessing any user's password.

How remove border around image in css?

Here's how I got rid of mine:

.main .row .thumbnail {
    display: inline-block;
    border: 0px;
    background-color: transparent;
}

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

How can change width of dropdown list?

Create a css and set the value style="width:50px;" in css code. Call the class of CSS in the drop down list. Then it will work.

How to force JS to do math instead of putting two strings together

DON'T FORGET - Use parseFloat(); if your dealing with decimals.

how to append a css class to an element by javascript?

classList is a convenient alternative to accessing an element's list of classes.. see http://developer.mozilla.org/en-US/docs/Web/API/Element.classList.

Not supported in IE < 10

How to increase buffer size in Oracle SQL Developer to view all records?

If you are running a script, instead of a statement, you can increase this by selecting Tools/Preferences/Worksheet and increasing "Max Rows to print in a script". The default is 5000, you can change it to any size.

How to use an existing database with an Android application

If you are having pre built data base than copy it in asset folder and create an new class as DataBaseHelper which implements SQLiteOpenHelper Than use following code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelperClass extends SQLiteOpenHelper{
 //The Android's default system path of your application database.
private static String DB_PATH = "/data/data/package_name/databases/";
// Data Base Name.
private static final String DATABASE_NAME = "DBName.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "tableName";

public Context context;
static SQLiteDatabase sqliteDataBase;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 * Parameters of super() are    1. Context
 *                              2. Data Base Name.
 *                              3. Cursor Factory.
 *                              4. Data Base Version.
 */
public DataBaseHelperClass(Context context) {       
    super(context, DATABASE_NAME, null ,DATABASE_VERSION);
    this.context = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * By calling this method and empty database will be created into the default system path
 * of your application so we are gonna be able to overwrite that database with our database.
 * */
public void createDataBase() throws IOException{
    //check if the database exists
    boolean databaseExist = checkDataBase();

    if(databaseExist){
        // Do Nothing.
    }else{
        this.getWritableDatabase();         
        copyDataBase(); 
    }// end if else dbExist
} // end createDataBase().

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
public boolean checkDataBase(){
    File databaseFile = new File(DB_PATH + DATABASE_NAME);
    return databaseFile.exists();        
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transferring byte stream.
 * */
private void copyDataBase() throws IOException{ 
    //Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DATABASE_NAME); 
    // Path to the just created empty db
    String outFileName = DB_PATH + DATABASE_NAME; 
    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName); 
    //transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close(); 
}

/**
 * This method opens the data base connection.
 * First it create the path up till data base of the device.
 * Then create connection with data base.
 */
public void openDataBase() throws SQLException{      
    //Open the database
    String myPath = DB_PATH + DATABASE_NAME;
    sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
}

/**
 * This Method is used to close the data base connection.
 */
@Override
public synchronized void close() { 
    if(sqliteDataBase != null)
        sqliteDataBase.close(); 
    super.close(); 
}

/**
* Apply your methods and class to fetch data using raw or queries on data base using 
* following demo example code as:
*/
public String getUserNameFromDB(){
    String query = "select User_First_Name From "+TABLE_USER_DETAILS;
    Cursor cursor = sqliteDataBase.rawQuery(query, null);
    String userName = null;
    if(cursor.getCount()>0){
        if(cursor.moveToFirst()){
    do{
                userName = cursor.getString(0);
            }while (cursor.moveToNext());
        }
    }
    return userName;
}


@Override
public void onCreate(SQLiteDatabase db) {
    // No need to write the create table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // No need to write the update table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
    // We should not update it as requirements of application.
}   
}

Hope this will help you...

Upgrade python without breaking yum

I recommend, instead, updating the path in the associated script(s) (such as /usr/bin/yum) to point at your previous Python as the interpreter.

Ideally, you want to upgrade yum and its associated scripts so that they are supported by the default Python installed.

If that is not possible, the above is entirely workable and tested.

Change:

#!/usr/bin/python

to whatever the path is of your old version until you can make the above yum improvement.

Cases where you couldn't do the above are if you have an isolated machine, don't have the time to upgrade rpm manually or can't connect temporarily or permanently to a standard yum repository.

python capitalize first letter only

def solve(s):

names = list(s.split(" "))
return " ".join([i.capitalize() for i in names])

Takes a input like your name: john doe

Returns the first letter capitalized.(if first character is a number, then no capitalization occurs)

works for any name length

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

Install express using npm: https://expressjs.com/en/starter/installing.html

Create a file named server.js at the same level of your index.html with this content:

var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);

If you wish to put it in a different location, set the path on the third line:

server.use('/', express.static(__dirname + '/public'));

CD to the folder containing your file and run node from the console with this command:

node server.js

Browse to localhost:8080

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

You can use following commands to extract public/private key from a PKCS#12 container:

  • PKCS#1 Private key

    openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
    
  • Certificates:

    openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem
    

Start an external application from a Google Chrome Extension?

You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.

E.g. you have the users set things up so that some-app:// links start "SomeApp", and then in my-awesome-extension you open a tab pointing to some-app://some-data-the-app-wants, and you're good to go!

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

R doesn't have a concept of increment operator (as for example ++ in C). However, it is not difficult to implement one yourself, for example:

inc <- function(x)
{
 eval.parent(substitute(x <- x + 1))
}

In that case you would call

x <- 10
inc(x)

However, it introduces function call overhead, so it's slower than typing x <- x + 1 yourself. If I'm not mistaken increment operator was introduced to make job for compiler easier, as it could convert the code to those machine language instructions directly.

How can I make a link from a <td> table cell

Here is my solution:

<td>
   <a href="/yourURL"></a>
   <div class="item-container">
      <img class="icon" src="/iconURL" />
      <p class="name">
         SomeText
      </p>
   </div>
</td>

(LESS)

td {
  padding: 1%;
  vertical-align: bottom;
  position:relative;

     a {
        height: 100%;
        display: block;
        position: absolute;
        top:0;
        bottom:0;
        right:0;
        left:0;
       }

     .item-container {
         /*...*/
     }
}

Like this you can still benefit from some table cell properties like vertical-align. (Tested on Chrome)

How to get the entire document HTML as a string?

I just need doctype html and should work fine in IE11, Edge and Chrome. I used below code it works fine.

function downloadPage(element, event) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
        document.execCommand('SaveAs', '1', 'page.html');
        event.preventDefault();
    } else {
        if(isChrome) {
            element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
        }
        element.setAttribute('download', 'page.html');
    }
}

and in your anchor tag use like this.

<a href="#" onclick="downloadPage(this,event);" download>Download entire page.</a>

Example

_x000D_
_x000D_
    function downloadPage(element, event) {_x000D_
     var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);_x000D_
    _x000D_
     if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {_x000D_
      document.execCommand('SaveAs', '1', 'page.html');_x000D_
      event.preventDefault();_x000D_
     } else {_x000D_
      if(isChrome) {_x000D_
                element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));_x000D_
      }_x000D_
      element.setAttribute('download', 'page.html');_x000D_
     }_x000D_
    }
_x000D_
I just need doctype html and should work fine in IE11, Edge and Chrome. _x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
_x000D_
<p>_x000D_
<a href="#" onclick="downloadPage(this,event);"  download><h2>Download entire page.</h2></a></p>_x000D_
_x000D_
<p>Some image here</p>_x000D_
_x000D_
<p><img src="https://placeimg.com/250/150/animals"/></p>
_x000D_
_x000D_
_x000D_

Bootstrap Responsive Text Size

Well, my solution is sort of hack, but it works and I am using it.

1vw = 1% of viewport width

1vh = 1% of viewport height

1vmin = 1vw or 1vh, whichever is smaller

1vmax = 1vw or 1vh, whichever is larger

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

Set multiple system properties Java command line

There's nothing on the Documentation that mentions about anything like that.

Here's a quote:

-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:

java -Dfoo="some string" SomeClass

Delete duplicate records from a SQL table without a primary key

select distinct * into newtablename from oldtablename

Now, the newtablename will have no duplicate records.

Simply change the table name(newtablename) by pressing F2 in object explorer in sql server.

Select parent element of known element in Selenium

Little more about XPath axes

Lets say we have below HTML structure:

<div class="third_level_ancestor">
    <nav class="second_level_ancestor">
        <div class="parent">
            <span>Child</span>
        </div>
    </nav>
</div>
  1. //span/parent::* - returns any element which is direct parent.

In this case output is <div class="parent">

  1. //span/parent::div[@class="parent"] - returns parent element only of exact node type and only if specified predicate is True.

Output: <div class="parent">

  1. //span/ancestor::* - returns all ancestors (including parent).

Output: <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor-or-self::* - returns all ancestors and current element itself.

Output: <span>Child</span>, <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor::div[2] - returns second ancestor (starting from parent) of type div.

Output: <div class="third_level_ancestor">

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Perl - If string contains text?

if ($string =~ m/something/) {
   # Do work
}

Where something is a regular expression.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

There are two problems with your attempt.

First, you've used n+1 instead of i+1, so you're going to return something like [5, 5, 5, 5] instead of [1, 2, 3, 4].

Second, you can't for-loop over a number like n, you need to loop over some kind of sequence, like range(n).

So:

def naturalNumbers(n):
    return [i+1 for i in range(n)]

But if you already have the range function, you don't need this at all; you can just return range(1, n+1), as arshaji showed.

So, how would you build this yourself? You don't have a sequence to loop over, so instead of for, you have to build it yourself with while:

def naturalNumbers(n):
    results = []
    i = 1
    while i <= n:
        results.append(i)
        i += 1
    return results

Of course in real-life code, you should always use for with a range, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range function first, just to use it for naturalNumbers. (It's already pretty close.)


There is one more option, if you want to get clever.

If you have a list, you can slice it. For example, the first 5 elements of my_list are my_list[:5]. So, if you had an infinitely-long list starting with 1, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice. So:

from itertools import count, islice
def naturalNumbers(n):
    return list(islice(count(1), n))

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

Collection was modified; enumeration operation may not execute

You can copy subscribers dictionary object to a same type of temporary dictionary object and then iterate the temporary dictionary object using foreach loop.

Android, How can I Convert String to Date?

From String to Date

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

From Date to String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = new Date();  
    String dateTime = dateFormat.format(date);
    System.out.println("Current Date Time : " + dateTime); 
} catch (ParseException e) {
    e.printStackTrace();  
}

For Loop on Lua

Your problem is simple:

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end

This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously been defined with names is entirely irrelevant. Any use of names inside the for loop will refer to the local one, not the global one.

The for loop says that the inner part of the loop will be called with names = 1, then names = 2, and finally names = 3. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.

What you actually wanted was something like this:

names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).

Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.

However, this has a flaw. What happens if you remove one of the elements from the list?

names = {'John', 'Joe'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

Now, we get John Joe nil, because attempting to access values from a table that don't exist results in nil. To prevent this, we need to count from 1 to the length of the table:

names = {'John', 'Joe'}
for nameCount = 1, #names do
  print (names[nameCount])
end

The # is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names gets, this will always work.

However, there is a more convenient way to iterate through an array of items:

names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
  print (name)
end

ipairs is a Lua standard function that iterates over a list. This style of for loop, the iterator for loop, uses this kind of iterator function. The i value is the index of the entry in the array. The name value is the value at that index. So it basically does a lot of grunt work for you.

How to unnest a nested list

the first case can also be easily done as:

A=A[0]

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

Show default value in Spinner in android

Try below:

   <Spinner
    android:id="@+id/YourSpinnerId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="Gender" />

Regex - Should hyphens be escaped?

Typically you would always put the hyphen first in the [] match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]

List of strings to one string

string.Concat(los.ToArray());

If you just want to concatenate the strings then use string.Concat() instead of string.Join().

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

Use .corr to get the correlation between two columns

My solution would be after converting data to numerical type:

Top15[['Citable docs per Capita','Energy Supply per Capita']].corr()

How to clear all input fields in a specific div with jQuery?

$.each($('.fetch_results input'), function(idx, input){
  $(input).val('');
});

npm check and update package if needed

To check if any module in a project is 'old':

npm outdated

'outdated' will check every module defined in package.json and see if there is a newer version in the NPM registry.

For example, say xml2js 0.2.6 (located in node_modules in the current project) is outdated because a newer version exists (0.2.7). You would see:

[email protected] node_modules/xml2js current=0.2.6

To update all dependencies, if you are confident this is desirable:

npm update

Or, to update a single dependency such as xml2js:

npm update xml2js

Update statement using with clause

If anyone comes here after me, this is the answer that worked for me.

NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)

update mytable t
set z = (
  with comp as (
    select b.*, 42 as computed 
    from mytable t 
    where bs_id = 1
  )
  select c.computed
  from  comp c
  where c.id = t.id
)

Good luck,

GJ

Android overlay a view ontop of everything?

I have tried the awnsers before but this did not work. Now I jsut used a LinearLayout instead of a TextureView, now it is working without any problem. Hope it helps some others who have the same problem. :)

    view = (LinearLayout) findViewById(R.id.view); //this is initialized in the constructor
    openWindowOnButtonClick();

public void openWindowOnButtonClick()
{
    view.setAlpha((float)0.5);
    FloatingActionButton fb = (FloatingActionButton) findViewById(R.id.floatingActionButton);
    final InputMethodManager keyboard = (InputMethodManager) getSystemService(getBaseContext().INPUT_METHOD_SERVICE);
    fb.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // check if the Overlay should be visible. If this value is false, it is not shown -> show it.
            if(view.getVisibility() == View.INVISIBLE)
            {
                view.setVisibility(View.VISIBLE);
                keyboard.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
                Log.d("Overlay", "Klick");
            }
            else if(view.getVisibility() == View.VISIBLE)
            {
                view.setVisibility(View.INVISIBLE);
                keyboard.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
            }

JSONObject - How to get a value?

You can try the below function to get value from JSON string,

public static String GetJSONValue(String JSONString, String Field)
{
       return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");   
}

ExecJS and could not find a JavaScript runtime

I started getting this problem when I started using rbenv with Ruby 1.9.3 where as my system ruby is 1.8.7. The gem is installed in both places but for some reason the rails script didn't pick it up. But adding the "execjs" and "therubyracer" to the Gemfile did the trick.

Regular Expression to match only alphabetic characters

If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then

\A\pL+\z

would be the correct regex.

Some regex engines don't support this Unicode syntax but allow the \w alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w like this:

\A[^\W\d_]+\z

\A matches at the start of the string, \z at the end of the string (^ and $ also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).

How to use jQuery to show/hide divs based on radio button selection?

Update 2015/06

As jQuery has evolved since the question was posted, the recommended approach now is using $.on

$(document).ready(function() {
    $("input[name=group2]").on( "change", function() {

         var test = $(this).val();
         $(".desc").hide();
         $("#"+test).show();
    } );
});

or outside $.ready()

$(document).on( "change", "input[name=group2]", function() { ... } );

Original answer

You should use .change() event handler:

$(document).ready(function(){ 
    $("input[name=group2]").change(function() {
        var test = $(this).val();
        $(".desc").hide();
        $("#"+test).show();
    }); 
});

should work

How to filter empty or NULL names in a QuerySet?

You can simply do this:

Name.objects.exclude(alias="").exclude(alias=None)

It's really just that simple. filter is used to match and exclude is to match everything but what it specifies. This would evaluate into SQL as NOT alias='' AND alias IS NOT NULL.

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

Why aren't python nested functions called closures?

A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.

def make_printer(msg):
    def printer():
        print msg
    return printer

printer = make_printer('Foo!')
printer()

When make_printer is called, a new frame is put on the stack with the compiled code for the printer function as a constant and the value of msg as a local. It then creates and returns the function. Because the function printer references the msg variable, it is kept alive after the make_printer function has returned.

So, if your nested functions don't

  1. access variables that are local to enclosing scopes,
  2. do so when they are executed outside of that scope,

then they are not closures.

Here's an example of a nested function which is not a closure.

def make_printer(msg):
    def printer(msg=msg):
        print msg
    return printer

printer = make_printer("Foo!")
printer()  #Output: Foo!

Here, we are binding the value to the default value of a parameter. This occurs when the function printer is created and so no reference to the value of msg external to printer needs to be maintained after make_printer returns. msg is just a normal local variable of the function printer in this context.

Populate one dropdown based on selection in another

Setup mine within a closure and with straight JavaScript, explanation provided in comments

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  //setup an object fully of arrays_x000D_
  //alternativly it could be something like_x000D_
  //{"yes":[{value:sweet, text:Sweet}.....]}_x000D_
  //so you could set the label of the option tag something different than the name_x000D_
  var bOptions = {_x000D_
    "yes": ["sweet", "wohoo", "yay"],_x000D_
    "no": ["you suck!", "common son"]_x000D_
  };_x000D_
_x000D_
  var A = document.getElementById('A');_x000D_
  var B = document.getElementById('B');_x000D_
_x000D_
  //on change is a good event for this because you are guarenteed the value is different_x000D_
  A.onchange = function() {_x000D_
    //clear out B_x000D_
    B.length = 0;_x000D_
    //get the selected value from A_x000D_
    var _val = this.options[this.selectedIndex].value;_x000D_
    //loop through bOption at the selected value_x000D_
    for (var i in bOptions[_val]) {_x000D_
      //create option tag_x000D_
      var op = document.createElement('option');_x000D_
      //set its value_x000D_
      op.value = bOptions[_val][i];_x000D_
      //set the display label_x000D_
      op.text = bOptions[_val][i];_x000D_
      //append it to B_x000D_
      B.appendChild(op);_x000D_
    }_x000D_
  };_x000D_
  //fire this to update B on load_x000D_
  A.onchange();_x000D_
_x000D_
})();
_x000D_
<select id='A' name='A'>_x000D_
  <option value='yes' selected='selected'>yes_x000D_
  <option value='no'> no_x000D_
</select>_x000D_
<select id='B' name='B'>_x000D_
</select>
_x000D_
_x000D_
_x000D_

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I had this error on AWS Lightsail, used the top answer above

from

listen [::]:80;

to

listen [::]:80 ipv6only=on default_server;

and then click on "reboot" button inside my AWS account, I have main server Apache and Nginx as proxy.

how to mysqldump remote db from local machine

Bassed on this page here:

Compare two MySQL databases

I modified it so you can use ddbb in diferent hosts.


#!/bin/sh

echo "Usage: dbdiff [user1:pass1@dbname1:host] [user2:pass2@dbname2:host] [ignore_table1:ignore_table2...]"

dump () {
  up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
  mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname -h $host $table > $2
}

rm -f /tmp/db.diff

# Compare
up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
for table in `mysql -u $user -p$pass $dbname -h $host -N -e "show tables" --batch`; do
  if [ "`echo $3 | grep $table`" = "" ]; then
    echo "Comparing '$table'..."
    dump $1 /tmp/file1.sql
    dump $2 /tmp/file2.sql
    diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff
  else
    echo "Ignored '$table'..."
  fi
done
less /tmp/db.diff
rm -f /tmp/file1.sql /tmp/file2.sql

Hash table in JavaScript

You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.

printf() formatting for hex

The # part gives you a 0x in the output string. The 0 and the x count against your "8" characters listed in the 08 part. You need to ask for 10 characters if you want it to be the same.

int i = 7;

printf("%#010x\n", i);  // gives 0x00000007
printf("0x%08x\n", i);  // gives 0x00000007
printf("%#08x\n", i);   // gives 0x000007

Also changing the case of x, affects the casing of the outputted characters.

printf("%04x", 4779); // gives 12ab
printf("%04X", 4779); // gives 12AB

High-precision clock in Python

If Python 3 is an option, you have two choices:

  • time.perf_counter which always use the most accurate clock on your platform. It does include time spent outside of the process.
  • time.process_time which returns the CPU time. It does NOT include time spent outside of the process.

The difference between the two can be shown with:

from time import (
    process_time,
    perf_counter,
    sleep,
)

print(process_time())
sleep(1)
print(process_time())

print(perf_counter())
sleep(1)
print(perf_counter())

Which outputs:

0.03125
0.03125
2.560001310720671e-07
1.0005455362793145

C# Creating an array of arrays

The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.

int[,] list = new int[4,4] {
 {1,2,3,4},
 {5,6,7,8},
 {1,3,2,1},
 {5,4,3,2}};

You could also do

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4,4] {
 {list1[0],list1[1],list1[2],list1[3]},
 {list2[0],list2[1],list2[2],list2[3]},
 etc...};

How do I change db schema to dbo

Way to do it for an individual thing:

alter schema dbo transfer jonathan.MovieData

How to show and update echo on same line

If I have understood well, you can get it replacing your echo with the following line:

echo -ne "Movie $movies - $dir ADDED! \033[0K\r"

Here is a small example that you can run to understand its behaviour:

#!/bin/bash
for pc in $(seq 1 100); do
    echo -ne "$pc%\033[0K\r"
    sleep 1
done
echo

Can an Android App connect directly to an online mysql database

step 1 : make a web service on your server

step 2 : make your application make a call to the web service and receive result sets

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

In my case the problem was - I had my app_folder and settings.py in it. Then I decided to make Settings folder inside app_folder - and that made a collision with settings.py. Just renamed that Settings folder - and everything worked.

How to keep environment variables when using sudo

You can also combine the two env_keep statements in Ahmed Aswani's answer into a single statement like this:

Defaults env_keep += "http_proxy https_proxy"

You should also consider specifying env_keep for only a single command like this:

Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"

Serializing class instance to JSON

You can specify the default named parameter in the json.dumps() function:

json.dumps(obj, default=lambda x: x.__dict__)

Explanation:

Form the docs (2.7, 3.6):

``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.

(Works on Python 2.7 and Python 3.x)

Note: In this case you need instance variables and not class variables, as the example in the question tries to do. (I am assuming the asker meant class instance to be an object of a class)

I learned this first from @phihag's answer here. Found it to be the simplest and cleanest way to do the job.

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

Git on Windows: How do you set up a mergetool?

I'm using Portable Git on WinXP (works a treat!), and needed to resolve a conflict that came up in branching. Of all the gui's I checked, KDiff3 proved to be the most transparent to use.

But I found the instructions I needed to get it working in Windows in this blog post, instructions which differ slightly from the other approaches listed here. It basically amounted to adding these lines to my .gitconfig file:

[merge]
    tool = kdiff3

[mergetool "kdiff3"]
    path = C:/YourPathToBinaryHere/KDiff3/kdiff3.exe
    keepBackup = false
    trustExitCode = false

Working nicely now!

PHP - iterate on string characters

Expanded from @SeaBrightSystems answer, you could try this:

$s1 = "textasstringwoohoo";
$arr = str_split($s1); //$arr now has character array

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

WooCommerce return product object by id

Use this method:

$_product = wc_get_product( $id );

Official API-docs: wc_get_product

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

Gson and deserializing an array of objects with arrays in it

Use your bean class like this, if your JSON data starts with an an array object. it helps you.

Users[] bean = gson.fromJson(response,Users[].class);

Users is my bean class.

Response is my JSON data.

Using iFrames In ASP.NET

try this

<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>

Expose this iframe in the master page's codebehind:

public HtmlControl iframe
{
get
{
return this.myIframe;
}
}

Add the MasterType directive for the content page to strongly typed Master Page.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>

In code behind

protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}

How do I concatenate two arrays in C#?

I've found an elegant one line solution using LINQ or Lambda expression, both work the same (LINQ is converted to Lambda when program is compiled). The solution works for any array type and for any number of arrays.

Using LINQ:

public static T[] ConcatArraysLinq<T>(params T[][] arrays)
{
    return (from array in arrays
            from arr in array
            select arr).ToArray();
}

Using Lambda:

public static T[] ConcatArraysLambda<T>(params T[][] arrays)
{
    return arrays.SelectMany(array => array.Select(arr => arr)).ToArray();
}

I've provided both for one's preference. Performance wise @Sergey Shteyn's or @deepee1's solutions are a bit faster, Lambda expression being the slowest. Time taken is dependant on type(s) of array elements, but unless there are millions of calls, there is no significant difference between the methods.

Bootstrap 3 - 100% height of custom div inside column

You need to set the height of every parent element of the one you want the height defined.

<html style="height: 100%;">
  <body style="height: 100%;">
    <div style="height: 100%;">
      <p>
        Make this division 100% height.
      </p>
    </div>
  </body>
</html>

Article.

JsFiddle example

c# dictionary one key many values

As of .net3.5+ instead of using a Dictionary<IKey, List<IValue>> you can use a Lookup from the Linq namespace:

// lookup Order by payment status (1:m) 
// would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
IEnumerable<Order> payedOrders = byPayment[false];

From msdn:

A Lookup resembles a Dictionary. The difference is that a Dictionary maps keys to single values, whereas a Lookup maps keys to collections of values.

You can create an instance of a Lookup by calling ToLookup on an object that implements IEnumerable.

You may also want to read this answer to a related question. For more info, consult msdn.

Full example:

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqLookupSpike
{
    class Program
    {
        static void Main(String[] args)
        {
            // init 
            var orderList = new List<Order>();
            orderList.Add(new Order(1, 1, 2010, true));//(orderId, customerId, year, isPayed)
            orderList.Add(new Order(2, 2, 2010, true));
            orderList.Add(new Order(3, 1, 2010, true));
            orderList.Add(new Order(4, 2, 2011, true));
            orderList.Add(new Order(5, 2, 2011, false));
            orderList.Add(new Order(6, 1, 2011, true));
            orderList.Add(new Order(7, 3, 2012, false));

            // lookup Order by its id (1:1, so usual dictionary is ok)
            Dictionary<Int32, Order> orders = orderList.ToDictionary(o => o.OrderId, o => o);

            // lookup Order by customer (1:n) 
            // would need something like Dictionary<Int32, IEnumerable<Order>> orderIdByCustomer
            ILookup<Int32, Order> byCustomerId = orderList.ToLookup(o => o.CustomerId);
            foreach (var customerOrders in byCustomerId)
            {
                Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
                foreach (var order in customerOrders)
                {
                    Console.WriteLine("    Order {0} is payed: {1}", order.OrderId, order.IsPayed);
                }
            }

            // the same using old fashioned Dictionary
            Dictionary<Int32, List<Order>> orderIdByCustomer;
            orderIdByCustomer = byCustomerId.ToDictionary(g => g.Key, g => g.ToList());
            foreach (var customerOrders in orderIdByCustomer)
            {
                Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
                foreach (var order in customerOrders.Value)
                {
                    Console.WriteLine("    Order {0} is payed: {1}", order.OrderId, order.IsPayed);
                }
            }

            // lookup Order by payment status (1:m) 
            // would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
            ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
            IEnumerable<Order> payedOrders = byPayment[false];
            foreach (var payedOrder in payedOrders)
            {
                Console.WriteLine("Order {0} from Customer {1} is not payed.", payedOrder.OrderId, payedOrder.CustomerId);
            }
        }

        class Order
        {
            // key properties
            public Int32 OrderId { get; private set; }
            public Int32 CustomerId { get; private set; }
            public Int32 Year { get; private set; }
            public Boolean IsPayed { get; private set; }

            // additional properties
            // private List<OrderItem> _items;

            public Order(Int32 orderId, Int32 customerId, Int32 year, Boolean isPayed)
            {
                OrderId = orderId;
                CustomerId = customerId;
                Year = year;
                IsPayed = isPayed;
            }
        }
    }
}

Remark on Immutability

By default, Lookups are kind of immutable and accessing the internals would involve reflection. If you need mutability and don't want to write your own wrapper, you could use MultiValueDictionary (formerly known as MultiDictionary) from corefxlab (formerly part ofMicrosoft.Experimental.Collections which isn't updated anymore).