Programs & Examples On #Google gauges

How to access the local Django webserver from outside world

install ngrok in terminal

sudo apt-get install -y ngrok-client

after that run:

ngrok http 8000
or 
ngrok http example.com:9000 

Best way to structure a tkinter application?

OOP should be the approach and frame should be a class variable instead of instance variable.

from Tkinter import *
class App:
  def __init__(self, master):
    frame = Frame(master)
    frame.pack()
    self.button = Button(frame, 
                         text="QUIT", fg="red",
                         command=frame.quit)
    self.button.pack(side=LEFT)
    self.slogan = Button(frame,
                         text="Hello",
                         command=self.write_slogan)
    self.slogan.pack(side=LEFT)
  def write_slogan(self):
    print "Tkinter is easy to use!"

root = Tk()
app = App(root)
root.mainloop()

enter image description here

Reference: http://www.python-course.eu/tkinter_buttons.php

jQuery UI Slider (setting programmatically)

It depends on if you want to change the sliders in the current range or change the range of the sliders.

If it is the values in the current range you want to change, then the .slider() method is the one you should use, but the syntax is a bit different than you used:

$("#slider").slider('value',50);

or if you have a slider with two handles it would be:

$("#slider").slider('values',0,50); // sets first handle (index 0) to 50
$("#slider").slider('values',1,80); // sets second handle (index 1) to 80

If it is the range you want to change it would be:

$("#slider").slider('option',{min: 0, max: 500});

How to get a list of installed Jenkins plugins with name and version pair

You can be also interested what updates are available for plugins. For that, you have to merge the data about installed plugins with information about updates available here https://updates.jenkins.io/current/update-center.json .

To parse the downloaded file as a JSON you have to read online the second line (which is huge).

Finding the id of a parent div using Jquery

To get the id of the parent div:

$(buttonSelector).parents('div:eq(0)').attr('id');

Also, you can refactor your code quite a bit:

$('button').click( function() {
 var correct = Number($(this).attr('rel'));
 validate(Number($(this).siblings('input').val()), correct);
 $(this).parents('div:eq(0)').html(feedback);
});

Now there is no need for a button-class

explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.

You should have a look at the jQuery docs, particularly selectors and traversing:

How to call a method function from another class?

You need to understand the difference between classes and objects. From the Java tutorial:

An object is a software bundle of related state and behavior

A class is a blueprint or prototype from which objects are created

You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new keyword.

new Date();

You will need to assign the object to a variable of the same type as the class the object was created from.

Date d = new Date();

Once you have a reference to the object you can interact with it

d.date("01", "12", "14");

The exception to this is static methods that belong to the class and are referenced through it

public class MyDate{
  public static date(){ ... }
}

...
MyDate.date();

In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.

How can I set the value of a DropDownList using jQuery?

If you working with index you can set the selected index directly with .attr():

$("#mydropdownlist").attr('selectedIndex', 0);

This will set it to the first value in the droplist.

Edit: The way I did it above used to work. But it seems like it doesn't any longer.

But as Han so pleasantly points out in the comments, the correct way to do it is:

$("#mydropdownlist").get(0).selectedIndex = index_here;

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Haskell

foldl (+) 0 [1,2,3,4,5]

Python

reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

Ant build failed: "Target "build..xml" does not exist"

since your ant file's name is build.xml, you should just type ant without ant build.xml. that is: > ant [enter]

How to solve a timeout error in Laravel 5

Sometimes you just need to optimize your code or query, Setting more max_execution_time is not a solution.

It is not suggested to take more than 30 for loading a webpage if a task takes more time need to be a queue.

List all liquibase sql types

Well, since liquibase is open source there's always the source code which you could check.

Some of the data type classes seem to have a method toDatabaseDataType() which should give you information about what type works (is used) on a specific data base.

Why is my asynchronous function returning Promise { <pending> } instead of a value?

The then method returns a pending promise which can be resolved asynchronously by the return value of a result handler registered in the call to then, or rejected by throwing an error inside the handler called.

So calling AuthUser will not suddenly log the user in synchronously, but returns a promise whose then registered handlers will be called after the login succeeds ( or fails). I would suggest triggering all login processing by a then clause of the login promise. E.G. using named functions to highlight the sequence of flow:

let AuthUser = data => {   // just the login promise
  return google.login(data.username, data.password);
};

AuthUser(data).then( processLogin).catch(loginFail);

function processLogin( token) {
      // do logged in stuff:
      // enable, initiate, or do things after login
}
function loginFail( err) {
      console.log("login failed: " + err);
}

Foreach loop in C++ equivalent of C#

string[] strarr = {"ram","mohan","sita"};

#include <string>
std::string strarr = { "ram", "mohan", "sita" };

or

const char* strarr[] = { "ram", "mohan", "sita" };

foreach(string str in strarr) { listbox.items.add(str); }

for (int i = 0; i < sizeof strarr / sizeof *strarr; ++i)
    listbox.items.add(strarr[i]);

Note: you can also put the strings into a std::vector rather than an array:

std::vector<std::string> strvec;
strvec.push_back("ram");
strvec.push_back("mohan");
strvec.push_back("sita");

for (std::vector<std::string>::const_iterator i = strvec.begin(); i != strvec.end(); ++i)
    listbox.items.add(*i);

How to pass password automatically for rsync SSH command?

The official solution (and others) were incomplete when I first visited, so I came back, years later, to post this alternate approach in case any others wound up here intending to use a public/private key-pair:

Execute this from the target backup machine, which pulls from source to target backup

rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' [email protected]:/home/user/Server/ /home/keith/Server/

Execute this from the source machine, which sends from source to target backup

rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' /home/user/Server/ [email protected]:/home/user/Server/

And, if you are not using an alternate port for ssh, then consider the more elegant examples below:

Execute this from the target backup machine, which pulls from source to target backup:

sudo rsync -avi --delete [email protected]:/var/www/ /media/sdb1/backups/www/

Execute this from the source machine, which sends from source to target backup:

sudo rsync -avi --delete /media/sdb1/backups/www/ [email protected]:/var/www/

If you are still getting prompted for a password, then you need to check your ssh configuration in /etc/ssh/sshd_config and verify that the users in source and target each have the others' respective public ssh key by sending each over with ssh-copy-id [email protected].

(Again, this is for using ssh key-pairs without a password, as an alternate approach, and not for passing the password over via a file.)

Open two instances of a file in a single Visual Studio session

When working with Visual Studio 2013 and VB.NET I found that you can quite easily customize the menu and add the "New Window" command - there is no need to mess with the registry!

God only knows why Microsoft chose not to include the command for some languages...?

Given an array of numbers, return array of products of all other numbers (no division)

I came up with 2 solutions in Javascript, one with division and one without

_x000D_
_x000D_
// without division
function methodOne(arr) {
  return arr.map(item => {
    return arr.reduce((result, num) => {
      if (num !== item) {
        result = result * num;
      }
      return result;
    },1)
  });
}

// with division
function methodTwo(arr) {
  var mul = arr.reduce((result, num) => {
    result = result * num;
    return result;
  },1)
 return arr.map(item => mul/item);
}

console.log(methodOne([1, 2, 3, 4, 5]));
console.log(methodTwo([1, 2, 3, 4, 5]));
_x000D_
_x000D_
_x000D_

Cannot read property 'style' of undefined -- Uncaught Type Error

It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
  if (window.location.href.indexOf("test") <= -1) {_x000D_
    var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
    search_span[0].style.color = "blue";_x000D_
    search_span[0].style.fontWeight = "bold";_x000D_
    search_span[0].style.fontSize = "40px";_x000D_
_x000D_
  }_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_

How to leave/exit/deactivate a Python virtualenv

I found that when within a Miniconda3 environment I had to run:

conda deactivate

Neither deactivate nor source deactivate worked for me.

Link to "pin it" on pinterest without generating a button

I Found some code for wordpress:

 <script type="text/javascript">

    function insert_pinterest($content) {
        global $post;
        $posturl = urlencode(get_permalink()); //Get the post URL
        $pinspan = '<span class="pinterest-button">';
     $pinurl = '';
     $pinend = '</span>';
        $pattern = '//i';
        $replacement = $pinspan.$pinurl.'$2.$3'.$pindescription.$pinfinish.''.$pinend;
        $content = preg_replace( $pattern, $replacement, $content );
        //Fix the link problem
        $newpattern = '/<span class="pinterest-button"><\/a><\/span><\/a>/i';
     $replacement = '';
     $content = preg_replace( $newpattern, $replacement, $content );
     return $content;
    }
    add_filter( 'the_content', 'insert_pinterest' );

    </script>

Then you put the following in your PHP:

<?php $pinterestimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); ?>
<a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php echo $pinterestimage[0]; ?>&description=<?php the_title(); ?>">Pin It</a>

Bootstrap Navbar toggle button not working

because u have to have jquery set-up to enable the toggling functionality of the toggler button. So, all u have to do is to add bootstrap.bundle.js before bootstrap.css:

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

How should I unit test multithreaded code?

I have had the unfortunate task of testing threaded code and they are definitely the hardest tests I have ever written.

When writing my tests, I used a combination of delegates and events. Basically it is all about using PropertyNotifyChanged events with a WaitCallback or some kind of ConditionalWaiter that polls.

I am not sure if this was the best approach, but it has worked out for me.

What file uses .md extension and how should I edit them?

Microsoft's Visual Studio Code text editor has built in support for .md files written in markdown syntax.

The syntax is automatically color-coded inside of the .md file, and a preview window of the rendered markdown can be viewed by pressing Shift+Ctrl+V (Windows) or Shift+Cmd+V (Mac).

To see them side-by-side, drag the preview tab to the right side of the editor, or use Ctrl+K V (Windows) or Cmd+K V (Mac) instead.

enter image description here

VS Code uses the marked library for parsing, and has Github Flavored Markdown support enabled by default, but it will not display the Github Emoji inline like Github's Atom text editor does.

Also, VS Code supports has several markdown plugins available for extended functionality.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Try the below code snippet:

with open(path, 'rb') as f:
  text = f.read()

How to specify function types for void (not Void) methods in Java8?

I feel you should be using the Consumer interface instead of Function<T, R>.

A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)

In your case, you can create a consumer elsewhere in your code like this:

Consumer<Integer> myFunction = x -> {
    System.out.println("processing value: " + x);    
    .... do some more things with "x" which returns nothing...
}

Then you can replace your myForEach code with below snippet:

public static void myForEach(List<Integer> list, Consumer<Integer> myFunction) 
{
  list.forEach(x->myFunction.accept(x));
}

You treat myFunction as a first-class object.

How to change port number for apache in WAMP

Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.

How to find indices of all occurrences of one string in another in JavaScript?

If you just want to find the position of all matches I'd like to point you to a little hack:

_x000D_
_x000D_
var haystack = 'I learned to play the Ukulele in Lebanon.',
    needle = 'le',
    splitOnFound = haystack.split(needle).map(function (culm)
    {
        return this.pos += culm.length + needle.length
    }, {pos: -needle.length}).slice(0, -1); // {pos: ...} – Object wich is used as this

console.log(splitOnFound);
_x000D_
_x000D_
_x000D_

It might not be applikable if you have a RegExp with variable length but for some it might be helpful.

This is case sensitive. For case insensitivity use String.toLowerCase function before.

HTML form input tag name element array with JavaScript

1.) First off, what is the correct terminology for an array created on the end of the name element of an input tag in a form?

"Oftimes Confusing PHPism"

As far as JavaScript is concerned a bunch of form controls with the same name are just a bunch of form controls with the same name, and form controls with names that include square brackets are just form controls with names that include square brackets.

The PHP naming convention for form controls with the same name is sometimes useful (when you have a number of groups of controls so you can do things like this:

<input name="name[1]">
<input name="email[1]">
<input name="sex[1]" type="radio" value="m">
<input name="sex[1]" type="radio" value="f">

<input name="name[2]">
<input name="email[2]">
<input name="sex[2]" type="radio" value="m">
<input name="sex[2]" type="radio" value="f">

) but does confuse some people. Some other languages have adopted the convention since this was originally written, but generally only as an optional feature. For example, via this module for JavaScript.

2.) How do I get the information from that array with JavaScript?

It is still just a matter of getting the property with the same name as the form control from elements. The trick is that since the name of the form controls includes square brackets, you can't use dot notation and have to use square bracket notation just like any other JavaScript property name that includes special characters.

Since you have multiple elements with that name, it will be a collection rather then a single control, so you can loop over it with a standard for loop that makes use of its length property.

var myForm = document.forms.id_of_form;
var myControls = myForm.elements['p_id[]'];
for (var i = 0; i < myControls.length; i++) {
    var aControl = myControls[i];
}

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

MassAssignmentException in Laravel

if you have table and fields on database you can simply use this command :

php artisan db:seed --class=UsersTableSeeder --database=YOURDATABSE

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

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

The Unsupported major.minor version 51.0 error could mean:

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

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

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

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

for the latest version of the JRE and JDK respectively.

EDIT:

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

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

Get the POST request body from HttpServletRequest

I resolved that situation in this way. I created a util method that return a object extracted from request body, using the readValue method of ObjectMapper that is capable of receiving a Reader.

public static <T> T getBody(ResourceRequest request, Class<T> class) {
    T objectFromBody = null;
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(request);
        objectFromBody = objectMapper.readValue(httpServletRequest.getReader(), class);
    } catch (IOException ex) {
        log.error("Error message", ex);
    }
    return objectFromBody;
}

Copy a file from one folder to another using vbscripting

Just posted my finished code for a similar project. It copies files of certain extensions in my code its pdf tif and tiff you can change them to whatever you want copied or delete the if statements if you only need 1 or 2 types. When a file is created or modified it gets the archive attribute this code also looks for that attribute and only copies it if it exists and then removes it after its copied so you dont copy unneeded files. It also has a log setup in it so that you will see a log of what time and day evetrything was transfered from the last time you ran the script. Hope it helps! the link is Error: Object Required; 'objDIR' Code: 800A01A8

DB2 Date format

One more solution REPLACE (CHAR(current date, ISO),'-','')

How to fix height of TR?

I had to do this to get the result that I wanted:

<td style="font-size:3px; float:left; height:5px; vertical-align:middle;" colspan="7"><div style="font-size:3px; height:5px; vertical-align:middle;"><b><hr></b></div></td>

It refused to work with only the cell or the div and needed both.

Javascript, viewing [object HTMLInputElement]

It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.

My code example: bank.html

<!doctype html>
<html>
<head>
    <title>Transaction Tracker</title>
    <script src="bank.js"></script> 
</head>
    <body>
        <div><button onclick="bitch()">Press me!</button></div>
    </body>
</html>

Javascript code: bank.js

function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }

function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);

you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about. So simple solution is to change either the variable name or the id or class name.

The model backing the 'ApplicationDbContext' context has changed since the database was created

I spent many days to solve this issue, analyzed many different posts and tried many options and finally fixed. This 2 projects in my solution using EF code first migrations:

  • Console Application "DataModel" that mainly using as assembly which contains all my code first entities, DbContext, Mirgations and generic repository. I have included to this project separate empty local database file (in DataModel/App_Data folder) to be able generate migrations from Package Manager Console.
  • WebApi, which references to DataModel project and uses local database file from WebApi/App_Data folder, that not included in project

I got this error when requested WebApi...

My environment:

  • Windows 8.1 x64
  • Visual Studio 2015 Professional with Update 1
  • all my projects targeted for .NET Framework 4.6.1
  • EntityFramework 6.1.3 from NuGet

Here I collected all the remarks you should pay attention and all conditions/requirements which must be met, to avoid mentioned exception :

  1. You should use only one version of EntityFramework Nuget package for all projects in your solution.
  2. Database, created by running sequentially all migration scripts should have the same structure/schema as you target database and correspond to entity model. Following 3 things must exactly correspond/reflect/match each other:
    • Your all migration script up to last
    • Current code first entity model state (DbContext, entities)
    • Target database
  3. Target database (mdf file) should be updated/correspond up to last migration script. Verify that "__MigrationHistory" table in your target database contains records for all migration scripts that you have, it means that all migration scripts was successfully applied to that database. I recommend you to use Visual Studio for generation correct code first entities and context that corresponds to your database, Project -> Add New Item -> ADO.NET Entity Data Model -> Code First from database: Of course, as an alternative, if you have no database you can write manually model (code first entities and context) and then generate initial migration and database.
  4. Name of connection string e.g. MyConnectionString in config file of startup project (Web.config/App.config):

    <configuration>
      <connectionStrings>
        <add name="MyConnectionString" connectionString="...">
      </connectionStrings>
    <configuration>
    

    should be equal to parameter passed in constructor of your DbContext:

     public partial class MyDbContext : DbContext
     {
        public MyDbContext()
           : base("name=MyConnectionString"){}
        ...
    
  5. Before using Package Manager Console, make sure that you are using correct database for update or generate migration and needed project is set as startup project of solution. For connect to database it will use connection string from that .config file, which in project, that is set as startup project.
  6. And the main, which fixed my issue: It is weird, but in my WebApi/bin folder DataModel.exe was old, not refreshed since last build. Since migrations was embedded in my assembly DataModel.exe then my WebApi updated database using old mirgations. I was confused why after updating database in WebApi it not corresponds to latest migration script from DataModel. Following code automatically creates(if not exists) or updates to latest migration local database in my WebApi/App_Data folder.

       public class WebApiApplication : System.Web.HttpApplication
       {
           protected void Application_Start()
           {
               Database.SetInitializer(new MigrateDatabaseToLatestVersion<ODS_DbContext, Configuration>()); 
               ...
    

    I tried clean and rebuild solution but it did not help, than I completely removed bin and obj folders from WebApi, deleted database files from WebApi/App_Data, built, restarted WebApi, made request to it, it created correct database - lazy initialization (using lines above), which corresponds to latest migration and exception didn't appear more. So, this may fix your problem:

    1. remove manually bin, obj folders from your startup project (which generates/updates your database)
    2. build your startup project or better clean and rebuild all you solution.
    3. recreate database by starting project (will execute lines above) or use Package Manager Console "update-database" command.
    4. manually check whether generated db and __MirgationHistory corresponds to latest migration script.

Difference between res.send and res.json in Express.js

Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json

edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.

How to check if a particular service is running on Ubuntu

Dirty way to find running services. (sometime it is not accurate because some custom script doesn't have |status| option)

[root@server ~]# for qw in `ls /etc/init.d/*`; do  $qw status | grep -i running; done
auditd (pid  1089) is running...
crond (pid  1296) is running...
fail2ban-server (pid  1309) is running...
httpd (pid  7895) is running...
messagebus (pid  1145) is running...
mysqld (pid  1994) is running...
master (pid  1272) is running...
radiusd (pid  1712) is running...
redis-server (pid  1133) is running...
rsyslogd (pid  1109) is running...
openssh-daemon (pid  7040) is running...

vuetify center items into v-flex

v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.

So, you should override it with display: flex in your HTML or CSS to make it work with justify-content.

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

C#: How to add subitems in ListView

Generally:

ListViewItem item = new ListViewItem("Column1Text")
   { Tag = optionalRefToSourceObject };

item.SubItems.Add("Column2Text");
item.SubItems.Add("Column3Text");
myListView.Items.Add(item);

Visual Studio - How to change a project's folder name and solution name without breaking the solution

You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.

Xcode 6 Storyboard the wrong size?

If you are using Xcode 6 and designing for iOS 8, none of these solutions are correct. To get your iPhone-only views to be sized correctly, don't turn off size classes, don't turn off inferred metrics, and don't set constraints (yet). Instead, use the size class control, which is an easy to miss text button at the bottom of Interface Builder that initially reads "wAny hAny".

Click the button, and choose Compact Width, Regular Height. This resize your views and cover all iPhone portrait orientations. Apple's docs here: https://developer.apple.com/library/ios/recipes/xcode_help-IB_adaptive_sizes/chapters/SelectingASizeClass.html or search on "Selecting a Size Class in Interface Builder"

How to refer environment variable in POM.xml?

Also, make sure that your environment variable is composed only by UPPER CASE LETTERS.... I don't know why (the documentation doesn't say nothing explicit about it, at least the link provided by @Andrew White), but if the variable is a lower case word (e.g. env.dummy), the variable always came empty or null...

i was struggling with this like an hour, until I decided to try an UPPER CASE VARIABLE, and problem solved.

OK Variables Examples:

  • DUMMY
  • DUMMY_ONE
  • JBOSS_SERVER_PATH

(NOTE: I was using maven v3.0.5)

I Hope that this can help someone....

Converting a date string to a DateTime object using Joda Time library

Use DateTimeFormat:

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);

Git: How to find a deleted file in the project commit history?

If you do not know the exact path you may use

git log --all --full-history -- "**/thefile.*"

If you know the path the file was at, you can do this:

git log --all --full-history -- <path-to-file>

This should show a list of commits in all branches which touched that file. Then, you can find the version of the file you want, and display it with...

git show <SHA> -- <path-to-file>

Or restore it into your working copy with:

git checkout <SHA>^ -- <path-to-file>

Note the caret symbol (^), which gets the checkout prior to the one identified, because at the moment of <SHA> commit the file is deleted, we need to look at the previous commit to get the deleted file's contents

What does "&" at the end of a linux command mean?

When not told otherwise commands take over the foreground. You only have one "foreground" process running in a single shell session. The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.

sh my_script.sh &

A background process will not stay alive after the shell session is closed. SIGHUP terminates all running processes. By default anyway. If your command is long-running or runs indefinitely (ie: microservice) you need to pr-pend it with nohup so it remains running after you disconnect from the session:

nohup sh my_script.sh &

EDIT: There does appear to be a gray area regarding the closing of background processes when & is used. Just be aware that the shell may close your process depending on your OS and local configurations (particularly on CENTOS/RHEL): https://serverfault.com/a/117157.

Python 3.1.1 string to hex

base64.b16encode and base64.b16decode convert bytes to and from hex and work across all Python versions. The codecs approach also works, but is less straightforward in Python 3.

How to convert base64 string to image?

Just use the method .decode('base64') and go to be happy.

You need, too, to detect the mimetype/extension of the image, as you can save it correctly, in a brief example, you can use the code below for a django view:

def receive_image(req):
    image_filename = req.REQUEST["image_filename"] # A field from the Android device
    image_data = req.REQUEST["image_data"].decode("base64") # The data image
    handler = open(image_filename, "wb+")
    handler.write(image_data)
    handler.close()

And, after this, use the file saved as you want.

Simple. Very simple. ;)

How to control the line spacing in UILabel

Another answer... If you're passing the string programmatically, you need to pass a attributed string instead a regular string and change it's style.(iOS10)

NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"Your \nregular \nstring"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:4];
[attrString addAttribute:NSParagraphStyleAttributeName
                   value:style
                   range:NSMakeRange(0, attrString.length)];
_label.attributedText = attrString;

Convert Go map to json

If you had caught the error, you would have seen this:

jsonString, err := json.Marshal(datas)
fmt.Println(err)

// [] json: unsupported type: map[int]main.Foo

The thing is you cannot use integers as keys in JSON; it is forbidden. Instead, you can convert these values to strings beforehand, for instance using strconv.Itoa.

See this post for more details: https://stackoverflow.com/a/24284721/2679935

Working with TIFFs (import, export) in Python using numpy

I use matplotlib for reading TIFF files:

import matplotlib.pyplot as plt
I = plt.imread(tiff_file)

and I will be of type ndarray.

According to the documentation though it is actually PIL that works behind the scenes when handling TIFFs as matplotlib only reads PNGs natively, but this has been working fine for me.

There's also a plt.imsave function for saving.

How to access full source of old commit in BitBucket?

Just in case anyone is in my boat where none of these answers worked exactly, here's what I did.

Perhaps our in house Bitbucket server is set up a little differently than most, but here's the URL that I'd normally go to just to view the files in the master branch:

https://<BITBUCKET_URL>/projects/<PROJECT_GROUP>/repos/<REPO_NAME>/browse

If I select a different branch than master from the drop down menu, I get this:

https://<BITBUCKET_URL>/projects/<PROJECT_GROUP>/repos/<REPO_NAME>/browse?at=refs%2Fheads%2F<BRANCH_NAME>

So I tried doing this and it worked:

https://<BITBUCKET_URL>/projects/<PROJECT_GROUP>/repos/<REPO_NAME>/browse?at=<COMMIT_ID>

Now I can browse the whole repo as it was at the time of that commit.

Html/PHP - Form - Input as array

If is ok for you to index the array you can do this:

<form>
    <input type="text" class="form-control" placeholder="Titel" name="levels[0][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[0][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[1][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[1][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[2][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[2][build_time]">
</form>

... to achieve that:

[levels] => Array ( 
  [0] => Array ( 
    [level] => 1 
    [build_time] => 2 
  ) 
  [1] => Array ( 
    [level] => 234 
   [build_time] => 456 
  )
  [2] => Array ( 
    [level] => 111
    [build_time] => 222 
  )
) 

But if you remove one pair of inputs (dynamically, I suppose) from the middle of the form then you'll get holes in your array, unless you update the input names...

How do I get sed to read from standard input?

use the --expression option

grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

You can easily use Node.JS in your web app only for real-time communication. Node.JS is really powerful when it's about WebSockets. Therefore "PHP Notifications via Node.js" would be a great concept.

See this example: Creating a Real-Time Chat App with PHP and Node.js

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

Try putting opacity:0; your select element will be invisible but the options will be visible when you click on it.

Angular2 module has no exported member

In my module i am exporting classes this way:

export { SigninComponent } from './SigninComponent';
export { RegisterComponent } from './RegisterComponent';

This allow me to import multiple classes in file from same module:

import { SigninComponent, RegisterComponent} from "../auth.module";

PS: Of course @Fjut answer is correct, but same time it doesn't support multiple imports from same file. I would suggest to use both answers for your needs. But importing from module makes folder structure refactorings more easier.

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

As you can see from this example: http://jsfiddle.net/UTwGS/

HTML:

<label><input type="radio" value="1" name="my-radio">Radio One</label>
<label><input type="radio" value="2" name="my-radio">Radio One</label>

jQuery:

$('input[type="radio"]').on('click change', function(e) {
    console.log(e.type);
});

both the click and change events are fired when selecting a radio button option (at least in some browsers).

I should also point out that in my example the click event is still fired when you use tab and the keyboard to select an option.

So, my point is that even though the change event is fired is some browsers, the click event should supply the coverage you need.

Get properties of a class

Use these

export class TableColumns<T> {
   constructor(private t: new () => T) {
        var fields: string[] = Object.keys(new t())

        console.log('fields', fields)
        console.log('t', t)

    }
}

Usage

columns_logs = new TableColumns<LogItem>(LogItem);

Output

fields (12) ["id", "code", "source", "title", "deleted", "checked", "body", "json", "dt_insert", "dt_checked", "screenshot", "uid"]

js class

t class LogItem {
constructor() {
    this.id = 0;
    this.code = 0;
    this.source = '';
    this.title = '';
    this.deleted = false;
    this.checked = false;
  …

how to stop a for loop

Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.

force Maven to copy dependencies into target/lib

If you make your project a war or ear type maven will copy the dependencies.

SQL: How to to SUM two values from different tables

you can also try this in sql-server !!

select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city 

demo

or try using sum,union

select sum(total)  as mytotal,city
from
(
    select * from cash union
    select * from cheque
) as vij
group by city 

What is the difference between 'E', 'T', and '?' for Java generics?

A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value

In Java 7 it is permitted to instantiate like this:

Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6

Flutter.io Android License Status Unknown

I faced the same problem, like mentioned above I tried these.

  1. Installed JDK 1.8 and set my JAVA_HOME env to 1.8 - This did not work
  2. My Android studio didn't show any "Android SDK Tools (Obsolete)" but had had an "Android SDK Tools"

This is what worked for me:

  1. Delete the "Android SDK Tools" from SDK Manager
  2. Reinstall it by first deselecting the "Hide Obsolete Packages" and then select "Android SDK Tools (Obsolete)", install it.
  3. run flutter doctor --android-licenses and select y for the prompts
  4. run flutter doctor and everything will be fine!!!!

How can I install the Beautiful Soup module on the Mac?

The "normal" way is to:

Another solution is to use easy_install. Go to http://peak.telecommunity.com/DevCenter/EasyInstall), install the package using the instructions on that page, and then type, in a Terminal window:

easy_install BeautifulSoup4
# for older v3:
# easy_install BeautifulSoup

easy_install will take care of downloading, unpacking, building, and installing the package. The advantage to using easy_install is that it knows how to search for many different Python packages, because it queries the PyPI registry. Thus, once you have easy_install on your machine, you install many, many different third-party packages simply by one command at a shell.

Maven is not working in Java 8 when Javadoc tags are incomplete

Since it depends on the version of your JRE which is used to run the maven command you propably dont want to disable DocLint per default in your pom.xml

Hence, from command line you can use the switch -Dadditionalparam=-Xdoclint:none.

Example: mvn clean install -Dadditionalparam=-Xdoclint:none

Removing elements by class name?

Brett - are you aware that getElementyByClassName support from IE 5.5 to 8 is not there according to quirksmode?. You would be better off following this pattern if you care about cross-browser compatibility:

  • Get container element by ID.
  • Get needed child elements by tag name.
  • Iterate over children, test for matching className property.
  • elements[i].parentNode.removeChild(elements[i]) like the other guys said.

Quick example:

var cells = document.getElementById("myTable").getElementsByTagName("td");
var len = cells.length;
for(var i = 0; i < len; i++) {
    if(cells[i].className.toLowerCase() == "column") {
        cells[i].parentNode.removeChild(cells[i]);
    }
}

Here's a quick demo.

EDIT: Here is the fixed version, specific to your markup:

var col_wrapper = document.getElementById("columns").getElementsByTagName("div");

var elementsToRemove = [];
for (var i = 0; i < col_wrapper.length; i++) {
    if (col_wrapper[i].className.toLowerCase() == "column") {
        elementsToRemove.push(col_wrapper[i]);
    }
}
for(var i = 0; i < elementsToRemove.length; i++) {
    elementsToRemove[i].parentNode.removeChild(elementsToRemove[i]);
}

The problem was my fault; when you remove an element from the resulting array of elements, the length changes, so one element gets skipped at each iteration. The solution is to store a reference to each element in a temporary array, then subsequently loop over those, removing each one from the DOM.

Try it here.

How to connect to LocalDb

You can connect with MSSMS to LocalDB. Type only in SERVER NAME: (localdb)\v11.0 and leave it by Windows Authentication and it connects to your LocalDB server and shows you the databases in it.

Abort Ajax requests using jQuery

If xhr.abort(); causes page reload,

Then you can set onreadystatechange before abort to prevent:

// ? prevent page reload by abort()
xhr.onreadystatechange = null;
// ? may cause page reload
xhr.abort();

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

I experienced this when missing an export statement for the JSX class.

For example:

class MyComponent extends React.Component {
}
export default MyComponent // <- add me

Laravel 5.4 redirection to custom url after login

in accord with Laravel documentation, I create in app/Http/Controllers/Auth/LoginController.php the following method :

protected function redirectTo()
{
    $user=Auth::user();

    if($user->account_type == 1){
        return '/admin';
    }else{
        return '/home';
    }

}

to get the user information from my db I used "Illuminate\Support\Facades\Auth;".

How can I echo a newline in a batch file?

Here you go, create a .bat file with the following in it :

@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM Example Usage:
echo There should be a newline%NL%inserted here.

echo.
pause

You should see output like the following:

There should be a newline
inserted here.

Press any key to continue . . .

You only need the code between the REM statements, obviously.

Dynamically updating css in Angular 2

To use % instead of px or em with @Gaurav's answer, it's just

<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>

How to store a command in a variable in a shell script?

I tried various different methods:

printexec() {
  printf -- "\033[1;37m$\033[0m"
  printf -- " %q" "$@"
  printf -- "\n"
  eval -- "$@"
  eval -- "$*"
  "$@"
  "$*"
}

Output:

$ printexec echo  -e "foo\n" bar
$ echo -e foo\\n bar
foon bar
foon bar
foo
 bar
bash: echo -e foo\n bar: command not found

As you can see, only the third one, "$@" gave the correct result.

Server Error in '/' Application. ASP.NET

Look at these two excerpts:

I uploaded my website to my domain under the public folder.

and

This error can be caused by a virtual directory not being configured as an application in IIS.

It's pretty clear to me that you did exactly what you said you did, and no more, i.e. you transfered the files to the web server, but nothing else. You need to configure that public folder as a virtual directory in IIS as the error is telling you, or it's just not going to work.

C compile error: "Variable-sized object may not be initialized"

You cannot do it. C compiler cannot do such a complex thing on stack.

You have to use heap and dynamic allocation.

What you really need to do:

  • compute size (nmsizeof(element)) of the memory you need
  • call malloc(size) to allocate the memory
  • create an accessor: int* access(ptr,x,y,rowSize) { return ptr + y*rowSize + x; }

Use *access(boardAux, x, y, size) = 42 to interact with the matrix.

Call a function with argument list in python

The literal answer to your question (to do exactly what you asked, changing only the wrapper, not the functions or the function calls) is simply to alter the line

func(args)

to read

func(*args)

This tells Python to take the list given (in this case, args) and pass its contents to the function as positional arguments.

This trick works on both "sides" of the function call, so a function defined like this:

def func2(*args):
    return sum(args)

would be able to accept as many positional arguments as you throw at it, and place them all into a list called args.

I hope this helps to clarify things a little. Note that this is all possible with dicts/keyword arguments as well, using ** instead of *.

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

_x000D_
_x000D_
$(function() {_x000D_
    $('#datepicker').datepicker({ dateFormat: 'yy-d-m ' }).val();_x000D_
});
_x000D_
<html>_x000D_
<head>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">_x000D_
  <title>snippet</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
  <input type="text" id="datepicker">_x000D_
_x000D_
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
  <script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
_x000D_
_x000D_
_x000D_

Difference between two lists

var list3 = list1.Where(x => !list2.Any(z => z.Id == x.Id)).ToList();

Note: list3 will contain the items or objects that are not in both lists. Note: Its ToList() not toList()

how to create dynamic two dimensional array in java?

Here is a simple example. this method will return a 2 dimensional tType array

public tType[][] allocate(Class<tType> c,int row,int column){
        tType [][] matrix = (tType[][]) Array.newInstance(c,row);
        for (int i = 0; i < column; i++) {
            matrix[i] = (tType[]) Array.newInstance(c,column);
        }
        return matrix;

    }

say you want a 2 dimensional String array, then call this function as

String [][] stringArray = allocate(String.class,3,3);

This will give you a two dimensional String array with 3 rows and 3 columns; Note that in Class<tType> c -> c cannot be primitive type like say, int or char or double. It must be non-primitive like, String or Double or Integer and so on.

Is it possible to Turn page programmatically in UIPageViewController?

Swift 4:

I needed to go to the next controller when i tap next on a pagecontroller view controller and also update the pageControl index, so this was the best and most straightforward solution for me:

let pageController = self.parent as! PageViewController

pageController.setViewControllers([parentVC.orderedViewControllers[1]], direction: .forward, animated: true, completion: nil)

pageController.pageControl.currentPage = 1

How to determine the current shell I'm working on

The following will always give the actual shell used - it gets the name of the actual executable and not the shell name (i.e. ksh93 instead of ksh, etc.). For /bin/sh, it will show the actual shell used, i.e. dash.

ls -l /proc/$$/exe | sed 's%.*/%%'

I know that there are many who say the ls output should never be processed, but what is the probability you'll have a shell you are using that is named with special characters or placed in a directory named with special characters? If this is still the case, there are plenty of other examples of doing it differently.

As pointed out by Toby Speight, this would be a more proper and cleaner way of achieving the same:

basename $(readlink /proc/$$/exe)

Can't bind to 'routerLink' since it isn't a known property

You are missing either the inclusion of the route package, or including the router module in your main app module.

Make sure your package.json has this:

"@angular/router": "^3.3.1"

Then in your app.module import the router and configure the routes:

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

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent}
        ])
    ],

Update:

Move the AppRoutingModule to be first in the imports:

imports: [
    AppRoutingModule.
    BrowserModule,
    FormsModule,
    HttpModule,
    AlertModule.forRoot(), // What is this?
    LayoutModule,
    UsersModule
  ],

Sort a Map<Key, Value> by values

The commons-collections library contains a solution called TreeBidiMap. Or, you could have a look at the Google Collections API. It has TreeMultimap which you could use.

And if you don't want to use these framework... they come with source code.

Can I limit the length of an array in JavaScript?

You're not using splice correctly:

arr.splice(4, 1)

this will remove 1 item at index 4. see here

I think you want to use slice:

arr.slice(0,5)

this will return elements in position 0 through 4.

This assumes all the rest of your code (cookies etc) works correctly

Running a command as Administrator using PowerShell?

The problem with the @pgk and @Andrew Odri's answers is when you have script parameters, specially when they are mandatory. You can solve this problem using the following approach:

  1. The user right-clicks the .ps1 file and selects 'Run with PowerShell': ask him for the parameters through input boxes (this is a much better option than use the HelpMessage parameter attribute);
  2. The user executes the script through the console: allow him to pass the desired parameters and let the console force him to inform the mandatory ones.

Here is how would be the code if the script had the ComputerName and Port mandatory parameters:

[CmdletBinding(DefaultParametersetName='RunWithPowerShellContextMenu')]
param (
    [parameter(ParameterSetName='CallFromCommandLine')]
    [switch] $CallFromCommandLine,

    [parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
    [parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
    [string] $ComputerName,

    [parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
    [parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
    [UInt16] $Port
)

function Assert-AdministrativePrivileges([bool] $CalledFromRunWithPowerShellMenu)
{
    $isAdministrator = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

    if ($isAdministrator)
    {
        if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
        {
            # Must call itself asking for obligatory parameters
            & "$PSCommandPath" @script:PSBoundParameters -CallFromCommandLine
            Exit
        }
    }
    else
    {
        if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
        {
            $serializedParams = [Management.Automation.PSSerializer]::Serialize($script:PSBoundParameters)

            $scriptStr = @"
                `$serializedParams = '$($serializedParams -replace "'", "''")'

                `$params = [Management.Automation.PSSerializer]::Deserialize(`$serializedParams)

                & "$PSCommandPath" @params -CallFromCommandLine
"@

            $scriptBytes = [System.Text.Encoding]::Unicode.GetBytes($scriptStr)
            $encodedCommand = [Convert]::ToBase64String($scriptBytes)

            # If this script is called from another one, the execution flow must wait for this script to finish.
            Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -EncodedCommand $encodedCommand" -Verb 'RunAs' -Wait
        }
        else
        {
            # When you use the "Run with PowerShell" feature, the Windows PowerShell console window appears only briefly.
            # The NoExit option makes the window stay visible, so the user can see the script result.
            Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -NoExit -File ""$PSCommandPath""" -Verb 'RunAs'
        }

        Exit
    }
}

function Get-UserParameters()
{
    [string] $script:ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a computer name:', 'Testing Network Connection')

    if ($script:ComputerName -eq '')
    {
        throw 'The computer name is required.'
    }

    [string] $inputPort = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a TCP port:', 'Testing Network Connection')

    if ($inputPort -ne '')
    {
        if (-not [UInt16]::TryParse($inputPort, [ref]$script:Port))
        {
            throw "The value '$inputPort' is invalid for a port number."
        }
    }
    else
    {
        throw 'The TCP port is required.'
    }
}

# $MyInvocation.Line is empty in the second script execution, when a new powershell session
# is started for this script via Start-Process with the -File option.
$calledFromRunWithPowerShellMenu = $MyInvocation.Line -eq '' -or $MyInvocation.Line.StartsWith('if((Get-ExecutionPolicy')

Assert-AdministrativePrivileges $calledFromRunWithPowerShellMenu

# Necessary for InputBox
[System.Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') | Out-Null

if ($calledFromRunWithPowerShellMenu)
{
    Get-UserParameters
}

# ... script code
Test-NetConnection -ComputerName $ComputerName -Port $Port

Microsoft.ReportViewer.Common Version=12.0.0.0

First install SQLSysClrTypes for Ms SQL 2014 and secondly install ReportViewer for ms sql 2014

Restart your application or project, in my case its resolved.

Execute a command line binary with Node.js

If you don't mind a dependency and want to use promises, child-process-promise works:

installation

npm install child-process-promise --save

exec Usage

var exec = require('child-process-promise').exec;

exec('echo hello')
    .then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
    })
    .catch(function (err) {
        console.error('ERROR: ', err);
    });

spawn usage

var spawn = require('child-process-promise').spawn;

var promise = spawn('echo', ['hello']);

var childProcess = promise.childProcess;

console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
    console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
    console.log('[spawn] stderr: ', data.toString());
});

promise.then(function () {
        console.log('[spawn] done!');
    })
    .catch(function (err) {
        console.error('[spawn] ERROR: ', err);
    });

Replace console output in Python

The other answer may be better, but here's what I was doing. First, I made a function called progress which prints off the backspace character:

def progress(x):
    out = '%s things done' % x  # The output
    bs = '\b' * 1000            # The backspace
    print bs,
    print out,

Then I called it in a loop in my main function like so:

def main():
    for x in range(20):
        progress(x)
    return

This will of course erase the entire line, but you can mess with it to do exactly what you want. I ended up make a progress bar using this method.

How can I make an "are you sure" prompt in a Windows batchfile?

You want something like:

@echo off
setlocal
:PROMPT
SET /P AREYOUSURE=Are you sure (Y/[N])?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO END

echo ... rest of file ...


:END
endlocal

get original element from ng-click

You need $event.currentTarget instead of $event.target.

Slide right to left Android Animations

You can make your own animations. For example create xml file in res/anim like this

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/linear_interpolator">
    <translate
            android:fromXDelta="100%p"
            android:toXDelta="0"
            android:startOffset="0"
            android:duration="500"
            /> </set>

Then override animations in selected activity:

   overridePendingTransition(R.anim.animationIN, R.anim.animationOUT);

How to install SQL Server Management Studio 2012 (SSMS) Express?

Easiest way to install MSSQL 2012 MS SQL INSTALLATION

Here i am showing the easiest way to install ms sql 2012.

My opinion is the installation will be easier with windows 8.1 rather than windows 7.

This is my personnal opinion only.

We can install in windows 7 as well.

The steps to be followed:

Download any one of the link using the following URL

http://www.microsoft.com/en-us/download/details.aspx?id=43351

SQLEXPRWT_x86_ENU.exe or SQLEXPRWT_x64_ENU.exe

http://www.microsoft.com/en-us/download/details.aspx?id=42299

SQLEXPRWT_x86_ENU.exe or SQLEXPRWT_x64_ENU.exe

Right click on .exe file and run it

We should leave everything default while installing.

During installation, there will be 2 options:

1)If you are New user,then click on new sql-server stand alone application.

2)If you have already MS SQL application then you can upgrade by using the other option.

Then accept the Licence terms and click Next.

Now you will move on to Product Updates and press next then Setup support rules.

After this Feature selection.According to me we can check all the boxes except localdb.

Next it will take you to Instance Configuration where you should select Named Instance as

"SQLEXPRESS".

Then go to Server Configuration and press next.

Now Database engine configuration:

Authentication Mode:we can click on any one that is windows authentication mode or mixed.

Windows authentication mode (default for windows).

Mixed authentication mode:then should create username and password.

Then move on Error reporting,we can move further by clicking next to install process.

Finally we can see the Complete windows by showing the products added .

We can close and run the MSSQL server.

I hope it's useful.

Regards

Ramya

Jquery checking success of ajax post

using jQuery 1.8 and above, should use the following:

var request = $.ajax({
    type: 'POST',
    url: 'mmm.php',
    data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
    .done(function(data) { alert("success"+data.slice(0, 100)); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

check out the docs as @hitautodestruct stated.

Duplicating a MySQL table, indices, and data

The better way to duplicate a table is using only DDL statement. In this way, independently from the number of records in the table, you can perform the duplication instantly.

My purpose is:

DROP TABLE IF EXISTS table_name_OLD;
CREATE TABLE table_name_NEW LIKE table_name;
RENAME TABLE table_name TO table_name_OLD;
RENAME TABLE table_name _NEW TO table_name;

This avoids the INSERT AS SELECT statement that, in case of table with a lot of records can take time to be executed.

I suggest also to create a PLSQL procedure as the following example:

DELIMITER //
CREATE PROCEDURE backup_table(tbl_name varchar(255))
BEGIN
  -- DROP TABLE IF EXISTS GLS_DEVICES_OLD;
  SET @query = concat('DROP TABLE IF EXISTS ',tbl_name,'_OLD');
  PREPARE stmt FROM @query;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

  -- CREATE TABLE GLS_DEVICES_NEW LIKE GLS_DEVICES;
  SET @query = concat('CREATE TABLE ',tbl_name,'_NEW LIKE ',tbl_name);
  PREPARE stmt FROM @query;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

  -- RENAME TABLE GLS_DEVICES TO GLS_DEVICES_OLD;
  SET @query = concat('RENAME TABLE ',tbl_name,' TO ',tbl_name,'_OLD');
  PREPARE stmt FROM @query;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;  

  --  RENAME TABLE GLS_DEVICES_NEW TO GLS_DEVICES;
  SET @query = concat('RENAME TABLE ',tbl_name,'_NEW TO ',tbl_name);
  PREPARE stmt FROM @query;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt; 
END//
DELIMITER ;

Have a nice day! Alex

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

All those answers didnt help me, BUT I found another solution.

I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.

I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:

@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,

I simply removed orphanRemoval and the update worked.

Angular ng-if not true

you are not using the $scope you must use $ctrl.area or $scope.area instead of area

ant warning: "'includeantruntime' was not set"

Ant Runtime

Simply set includeantruntime="false":

<javac includeantruntime="false" ...>...</javac>

If you have to use the javac-task multiple times you might want to consider using PreSetDef to define your own javac-task that always sets includeantruntime="false".

Additional Details

From http://www.coderanch.com/t/503097/tools/warning-includeantruntime-was-not-set:

That's caused by a misfeature introduced in Ant 1.8. Just add an attribute of that name to the javac task, set it to false, and forget it ever happened.

From http://ant.apache.org/manual/Tasks/javac.html:

Whether to include the Ant run-time libraries in the classpath; defaults to yes, unless build.sysclasspath is set. It is usually best to set this to false so the script's behavior is not sensitive to the environment in which it is run.

JOIN queries vs multiple queries

For inner joins, a single query makes sense, since you only get matching rows. For left joins, multiple queries is much better... look at the following benchmark I did:

  1. Single query with 5 Joins

    query: 8.074508 seconds

    result size: 2268000

  2. 5 queries in a row

    combined query time: 0.00262 seconds

    result size: 165 (6 + 50 + 7 + 12 + 90)

.

Note that we get the same results in both cases (6 x 50 x 7 x 12 x 90 = 2268000)

left joins use exponentially more memory with redundant data.

The memory limit might not be as bad if you only do a join of two tables, but generally three or more and it becomes worth different queries.

As a side note, my MySQL server is right beside my application server... so connection time is negligible. If your connection time is in the seconds, then maybe there is a benefit

Frank

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

Static array vs. dynamic array in C++

Static array :Efficiency. No dynamic allocation or deallocation is required.

Arrays declared in C, C++ in function including static modifier are static. Example: static int foo[5];

Display TIFF image in all web browser

I found this resource that details the various methods: How to embed TIFF files in HTML documents

As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.

It would also be helpful if you posted the code you've tried already.

How to check if a file exists in a shell script

The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let's delete it. But there are a few treacherous rapids on this river:

  • Everything is a file.

  • Scripts have real power only if they solve general tasks

  • To be general, we use variables

  • We often use -f force in scripts to avoid manual intervention

  • And also love -r recursive to make sure we create, copy and destroy in a timely fashion.

Consider the following scenario:

We have the file we want to delete: filesexists.json

This filename is stored in a variable

<host>:~/Documents/thisfolderexists filevariable="filesexists.json"

We also hava a path variable to make things really flexible

<host>:~/Documents/thisfolderexists pathtofile=".."

<host>:~/Documents/thisfolderexists ls $pathtofile

filesexists.json  history20170728  SE-Data-API.pem  thisfolderexists

So let's see if -e does what it is supposed to. Does the files exist?

<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?

0

It does. Magic.

However, what would happen, if the file variable got accidentally be evaluated to nuffin'

<host>:~/Documents/thisfolderexists filevariable=""

<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?

0

What? It is supposed to return with an error... And this is the beginning of the story how that entire folder got deleted by accident

An alternative could be to test specifically for what we understand to be a 'file'

<host>:~/Documents/thisfolderexists filevariable="filesexists.json"

<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?

0

So the file exists...

<host>:~/Documents/thisfolderexists filevariable=""

<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?

1

So this is not a file and maybe, we do not want to delete that entire directory

man test has the following to say:

-b FILE

       FILE exists and is block special

-c FILE

       FILE exists and is character special

-d FILE

       FILE exists and is a directory

-e FILE

       FILE exists

-f FILE

       FILE exists and is a regular file

...

-h FILE

       FILE exists and is a symbolic link (same as -L)

Check existence of directory and create if doesn't exist

One-liner:

if (!dir.exists(output_dir)) {dir.create(output_dir)}

Example:

dateDIR <- as.character(Sys.Date())
outputDIR <- file.path(outD, dateDIR)
if (!dir.exists(outputDIR)) {dir.create(outputDIR)}

How to mock private method for testing using PowerMock?

A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.

  1. Change your private method to protected.
  2. In your test class extend the class
  3. override the previously-private method to return whatever constant you want

This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.

To mock a private method directly, you'll need to use PowerMock as shown in the other answer.

How to set and reference a variable in a Jenkinsfile

The error is due to that you're only allowed to use pipeline steps inside the steps directive. One workaround that I know is to use the script step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.

So in your case:

pipeline {
    agent any
    stages {
        stage("foo") {
            steps {
                script {
                    env.FILENAME = readFile 'output.txt'
                }
                echo "${env.FILENAME}"
            }
        }
    }
}

Handle Guzzle exception and get HTTP body

While the answers above are good they will not catch network errors. As Mark mentioned, BadResponseException is just a super class for ClientException and ServerException. But RequestException is also a super class of BadResponseException. RequestException will be thrown for not only 400 and 500 errors but network errors and infinite redirects too. So let's say you request the page below but your network is playing up and your catch is only expecting a BadResponseException. Well your application will throw an error.

It's better in this case to expect RequestException and check for a response.

try {
  $client->get('http://123123123.com')
} catch (RequestException $e) {

  // If there are network errors, we need to ensure the application doesn't crash.
  // if $e->hasResponse is not null we can attempt to get the message
  // Otherwise, we'll just pass a network unavailable message.
  if ($e->hasResponse()) {
    $exception = (string) $e->getResponse()->getBody();
    $exception = json_decode($exception);
    return new JsonResponse($exception, $e->getCode());
  } else {
    return new JsonResponse($e->getMessage(), 503);
  }

}

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

I had this problem, it is for foreign-key

Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key

enter image description here

Hope that works!

CSS checkbox input styling

Something I recently discovered for styling Radio Buttons AND Checkboxes. Before, I had to use jQuery and other things. But this is stupidly simple.

input[type=radio] {
    padding-left:5px;
    padding-right:5px;
    border-radius:15px;

    -webkit-appearance:button;

    border: double 2px #00F;

    background-color:#0b0095;
    color:#FFF;
    white-space: nowrap;
    overflow:hidden;

    width:15px;
    height:15px;
}

input[type=radio]:checked {
    background-color:#000;
    border-left-color:#06F;
    border-right-color:#06F;
}

input[type=radio]:hover {
    box-shadow:0px 0px 10px #1300ff;
}

You can do the same for a checkbox, obviously change the input[type=radio] to input[type=checkbox] and change border-radius:15px; to border-radius:4px;.

Hope this is somewhat useful to you.

How to work with progress indicator in flutter?

I suggest to use this plugin flutter_easyloading

flutter_easyloading is clean and lightweight Loading widget for Flutter App, easy to use without context, support iOS and Android

Add this to your package's pubspec.yaml file:

dependencies:
  flutter_easyloading: ^2.0.0

Now in your Dart code, you can use:

import 'package:flutter_easyloading/flutter_easyloading.dart';

To use First, initialize FlutterEasyLoading in MaterialApp/CupertinoApp

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter EasyLoading',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter EasyLoading'),
      builder: EasyLoading.init(),
    );
  }
}

EasyLoading is a singleton, so you can custom loading style any where like this:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import './custom_animation.dart';

void main() {
  runApp(MyApp());
  configLoading();
}

void configLoading() {
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.fadingCircle
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor = Colors.green
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor = Colors.blue.withOpacity(0.5)
    ..userInteractions = true
    ..customAnimation = CustomAnimation();
}

Then, use per your requirement

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  @override
  void initState() {
    super.initState();
    // EasyLoading.show();
  }

  @override
  void deactivate() {
    EasyLoading.dismiss();
    super.deactivate();
  }

  void loadData() async {
    try {
      EasyLoading.show();
      Response response = await Dio().get('https://github.com');
      print(response);
      EasyLoading.dismiss();
    } catch (e) {
      EasyLoading.showError(e.toString());
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter EasyLoading'),
      ),
      body: Center(
        child: FlatButton(
          textColor: Colors.blue,
          child: Text('loadData'),
          onPressed: () {
            loadData();
            // await Future.delayed(Duration(seconds: 2));
            // EasyLoading.show(status: 'loading...');
            // await Future.delayed(Duration(seconds: 5));
            // EasyLoading.dismiss();
          },
        ),
      ),
    );
  }
}

enter image description here

Remove Duplicates from range of cells in excel vba

To remove duplicates from a single column

 Sub removeDuplicate()
 'removeDuplicate Macro
 Columns("A:A").Select
 ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _ 
 Header:=xlNo 
 Range("A1").Select
 End Sub

if you have header then use Header:=xlYes

Increase your range as per your requirement.
you can make it to 1000 like this :

ActiveSheet.Range("$A$1:$A$1000")

More info here here

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

It is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.

You could just make your data members public without using this shortcut but then if you decided to change the implementation of the data member to have some logic then you would need to break the interface. So in short it is a shortcut to create more flexible code.

How to iterate over rows in a DataFrame in Pandas

This example uses iloc to isolate each digit in the data frame.

import pandas as pd

 a = [1, 2, 3, 4]
 b = [5, 6, 7, 8]

 mjr = pd.DataFrame({'a':a, 'b':b})

 size = mjr.shape

 for i in range(size[0]):
     for j in range(size[1]):
         print(mjr.iloc[i, j])

How to add link to flash banner

@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.

movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
  var url:String = "http://site";
  var request:URLRequest = new URLRequest(url);
  try {
    navigateToURL(request, '_blank');
  } catch (e:Error) {
    trace("Error occurred!");
  }
}

source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

Why doesn't C++ have a garbage collector?

If you want automatic garbage collection, there are good commercial and public-domain garbage collectors for C++. For applications where garbage collection is suitable, C++ is an excellent garbage collected language with a performance that compares favorably with other garbage collected languages. See The C++ Programming Language (4rd Edition) for a discussion of automatic garbage collection in C++. See also, Hans-J. Boehm's site for C and C++ garbage collection (archive).

Also, C++ supports programming techniques that allow memory management to be safe and implicit without a garbage collector. I consider garbage collection a last choice and an imperfect way of handling for resource management. That does not mean that it is never useful, just that there are better approaches in many situations.

Source: http://www.stroustrup.com/bs_faq.html#garbage-collection

As for why it doesnt have it built in, If I remember correctly it was invented before GC was the thing, and I don't believe the language could have had GC for several reasons(I.E Backwards compatibilty with C)

Hope this helps.

How to remove empty cells in UITableView?

Swift 3 syntax:

tableView.tableFooterView = UIView(frame: .zero)

Swift syntax: < 2.0

tableView.tableFooterView = UIView(frame: CGRect.zeroRect)

Swift 2.0 syntax:

tableView.tableFooterView = UIView(frame: CGRect.zero)

Hashing a file in Python

I have programmed a module wich is able to hash big files with different algorithms.

pip3 install py_essentials

Use the module like this:

from py_essentials import hashing as hs
hash = hs.fileChecksum("path/to/the/file.txt", "sha256")

Default optional parameter in Swift function

"Optional parameter" means "type of this parameter is optional". It does not mean "This parameter is optional and, therefore, can be ignored when you call the function".

The term "optional parameter" appears to be confusing. To clarify, it's more accurate to say "optional type parameter" instead of "optional parameter" as the word "optional" here is only meant to describe the type of parameter value and nothing else.

Attributes / member variables in interfaces?

The point of an interface is to specify the public API. An interface has no state. Any variables that you create are really constants (so be careful about making mutable objects in interfaces).

Basically an interface says here are all of the methods that a class that implements it must support. It probably would have been better if the creators of Java had not allowed constants in interfaces, but too late to get rid of that now (and there are some cases where constants are sensible in interfaces).

Because you are just specifying what methods have to be implemented there is no idea of state (no instance variables). If you want to require that every class has a certain variable you need to use an abstract class.

Finally, you should, generally speaking, not use public variables, so the idea of putting variables into an interface is a bad idea to begin with.

Short answer - you can't do what you want because it is "wrong" in Java.

Edit:

class Tile 
    implements Rectangle 
{
    private int height;
    private int width;

     @Override
    public int getHeight() {
        return height;
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public void setHeight(int h) {
        height = h;
    }

    @Override
    public void setWidth(int w) { 
        width = w;  
    }
}

an alternative version would be:

abstract class AbstractRectangle 
    implements Rectangle 
{
    private int height;
    private int width;

     @Override
    public int getHeight() {
        return height;
    }

    @Override
    public int getWidth() {
        return width;
    }

    @Override
    public void setHeight(int h) {
        height = h;
    }

    @Override
    public void setWidth(int w) { 
        width = w;  
    }
}

class Tile 
    extends AbstractRectangle 
{
}

MongoError: connect ECONNREFUSED 127.0.0.1:27017

If you already installed "MongoDB", if you accidentally exit from the MongoDB server, then "restart your system".

This method solved me...

[On Windows only]

And also another method is there:

press:

Windows + R

type:

services.msc

and click "ok", it opens "services" window, and then search for "MongoDB Server" in the list. After you find "MongoDB Server", right-click and choose "start" from the pop-up menu.

The MongoDb Server will start running.

Hope it works!!

How can I convert an image into a Base64 string?

This code runs perfect in my project:

profile_image.buildDrawingCache();
Bitmap bmap = profile_image.getDrawingCache();
String encodedImageData = getEncoded64ImageStringFromBitmap(bmap);


public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    byte[] byteFormat = stream.toByteArray();

    // Get the Base64 string
    String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

    return imgString;
}

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

How to add items to array in nodejs

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {
    newArray.push(item);
});

console.log(newArray);

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

What is the difference between Java RMI and RPC?

RMI or Remote Method Invokation is very similar to RPC or Remote Procedure call in that the client both send proxy objects (or stubs) to the server however the subtle difference is that client side RPC invokes FUNCTIONS through the proxy function and RMI invokes METHODS through the proxy function. RMI is considered slightly superior as it is an object-oriented version of RPC.

From here.

For more information and examples, have a look here.

Emulator: ERROR: x86 emulation currently requires hardware acceleration

Open Android SDK manager,"intelhaxm-86 emulator" install that

TypeScript static classes

See http://www.basarat.com/2013/04/typescript-static-constructors-for.html

This is a way to 'fake' a static constructor. It's not without its dangers - see the referenced codeplex item.

class Test {
    static foo = "orig";

    // Non void static function
    static stat() {
        console.log("Do any static construction here");
        foo = "static initialized";
        // Required to make function non void
        return null;
    }
    // Static variable assignment
    static statrun = Test.stat();
}

// Static construction will have been done:
console.log(Test.foo);

How to determine whether an object has a given property in JavaScript

includes

Object.keys(x).includes('y');

The Array.prototype.includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

and

Object.keys() returns an array of strings that represent all the enumerable properties of the given object.

.hasOwnProperty() and the ES6+ .? -optional-chaining like: if (x?.y) are very good 2020+ options as well.

How to concatenate characters in java?

I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:

String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";

The first is evaluated at compile-time. The second is evaluated at run-time.

So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.

If the characters are constant, this is fine:

String s = "" + 'a' + 'b' + 'c';

If however they aren't, consider this:

String concat(char... chars) {
  if (chars.length == 0) {
    return "";
  }
  StringBuilder s = new StringBuilder(chars.length);
  for (char c : chars) {
    s.append(c);
  }
  return s.toString();
}

as an appropriate solution.

However some might be tempted to optimise:

String s = "Name: '" + name + "'"; // String name;

into this:

String s = new StringBuilder().append("Name: ").append(name).append("'").toString();

While this is well-intentioned, the bottom line is DON'T.

Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.

For low-level optimisation the compiler is better at optimising code than you are.

Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.

Simple way to read single record from MySQL

function getSingleRow($table, $where_clause="", $column=" * ",$debug=0) {
    $SelectQuery = createQuery($table, $where_clause, $column);

    $result = executeQuery($SelectQuery,$debug);
    while($row = mysql_fetch_array($result)) {
        $row_val = $row;
    }
    return $row_val;
}

Android: How do bluetooth UUIDs work?

In Bluetooth, all objects are identified by UUIDs. These include services, characteristics and many other things. Bluetooth maintains a database of assigned numbers for standard objects, and assigns sub-ranges for vendors (that have paid enough for a reservation). You can view this list here:

https://www.bluetooth.com/specifications/assigned-numbers/

If you are implementing a standard service (e.g. a serial port, keyboard, headset, etc.) then you should use that service's standard UUID - that will allow you to be interoperable with devices that you didn't develop.

If you are implementing a custom service, then you should generate unique UUIDs, in order to make sure incompatible third-party devices don't try to use your service thinking it is something else. The easiest way is to generate random ones and then hard-code the result in your application (and use the same UUIDs in the devices that will connect to your service, of course).

How to turn a string formula into a "real" formula

I prefer the VBA-solution for professional solutions.

With the replace-procedure part in the question search and replace WHOLE WORDS ONLY, I use the following VBA-procedure:

''
' Evaluate Formula-Text in Excel
'
Function wm_Eval(myFormula As String, ParamArray variablesAndValues() As Variant) As Variant
    Dim i As Long

    '
    ' replace strings by values
    '
    For i = LBound(variablesAndValues) To UBound(variablesAndValues) Step 2
        myFormula = RegExpReplaceWord(myFormula, variablesAndValues(i), variablesAndValues(i + 1))
    Next

    '
    ' internationalisation
    '
    myFormula = Replace(myFormula, Application.ThousandsSeparator, "")
    myFormula = Replace(myFormula, Application.DecimalSeparator, ".")
    myFormula = Replace(myFormula, Application.International(xlListSeparator), ",")

    '
    ' return value
    '
    wm_Eval = Application.Evaluate(myFormula)
End Function


''
' Replace Whole Word
'
' Purpose   : replace [strFind] with [strReplace] in [strSource]
' Comment   : [strFind] can be plain text or a regexp pattern;
'             all occurences of [strFind] are replaced
Public Function RegExpReplaceWord(ByVal strSource As String, _
ByVal strFind As String, _
ByVal strReplace As String) As String

    ' early binding requires reference to Microsoft VBScript
    ' Regular Expressions:
    ' with late binding, no reference needed:
    Dim re As Object
    Set re = CreateObject("VBScript.RegExp")

    re.Global = True
    're.IgnoreCase = True ' <-- case insensitve
    re.Pattern = "\b" & strFind & "\b"
    RegExpReplaceWord = re.Replace(strSource, strReplace)
    Set re = Nothing
End Function

Usage of the procedure in an excel sheet looks like:

usage in excel-sheet

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

href="tel:" and mobile numbers

When dialing a number within the country you are in, you still need to dial the national trunk number before the rest of the number. For example, in Australia one would dial:

   0 - trunk prefix
   2 - Area code for New South Wales
6555 - STD code for a specific telephone exchange
1234 - Telephone Exchange specific extension.

For a mobile phone this becomes

   0 -      trunk prefix
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

Now, when I want to dial via the international trunk, you need to drop the trunk prefix and replace it with the international dialing prefix

   + -      Short hand for the country trunk number
  61 -      Country code for Australia
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

This is why you often find that the first digit of a telephone number is dropped when dialling internationally, even when using international prefixing to dial within the same country.

So as per the trunk prefix for Germany drop the 0 and add the +49 for Germany's international calling code (for example) giving:

_x000D_
_x000D_
<a href="tel:+496170961709" class="Blondie">_x000D_
    Call me, call me any, anytime_x000D_
      <b>Call me (call me) I'll arrive</b>_x000D_
        When you're ready we can share the wine!_x000D_
</a>
_x000D_
_x000D_
_x000D_

Find and replace specific text characters across a document with JS

Here is something that might help someone looking for this answer: The following uses jquery it searches the whole document and only replaces the text. for example if we had

<a href="/i-am/123/a/overpopulation">overpopulation</a>

and we wanted to add a span with the class overpop around the word overpopulation

<a href="/i-am/123/a/overpopulation"><span class="overpop">overpopulation</span></a>

we would run the following

        $("*:containsIN('overpopulation')").filter(
            function() {
                return $(this).find("*:contains('" + str + "')").length == 0
            }
        ).html(function(_, html) {
            if (html != 'undefined') {
                return html.replace(/(overpopulation)/gi, '<span class="overpop">$1</span>');
            }

        });

the search is case insensitive searches the whole document and only replaces the text portions in this case we are searching for the string 'overpopulation'

    $.extend($.expr[":"], {
        "containsIN": function(elem, i, match, array) {
            return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
        }
    });

String vs. StringBuilder

StringBuilder will perform better, from a memory stand point. As for processing, the difference in time of execution may be negligible.

How to step through Python code to help debug issues?

PyCharm is an IDE for Python that includes a debugger. Watch this YouTube video for an introduction on using PyCharm's debugger to step through code.

PyCharm Tutorial - Debug python code using PyCharm

Note: This is not intended to be an endorsement or review. PyCharm is a commercial product that one needs to pay for, but the company does provide a free license to students and teachers, as well as a "lightweight" Community version that is free and open-source.

Screenshot

Store output of sed into a variable

In general,

variable=$(command)

or

variable=`command`

The latter one is the old syntax, prefer $(command).

Note: variable = .... means execute the command variable with the first argument =, the second ....

Select multiple columns in data.table by their numeric indices

It's a bit verbose, but i've gotten used to using the hidden .SD variable.

b<-data.table(a=1,b=2,c=3,d=4)
b[,.SD,.SDcols=c(1:2)]

It's a bit of a hassle, but you don't lose out on other data.table features (I don't think), so you should still be able to use other important functions like join tables etc.

Could not find a version that satisfies the requirement <package>

I got this error while installing awscli on Windows 10 in anaconda (python 3.7). While troubleshooting, I went to the answer https://stackoverflow.com/a/49991357/6862405 and then to https://stackoverflow.com/a/54582701/6862405. Finally found that I need to install the libraries PyOpenSSL, cryptography, enum34, idna and ipaddress. After installing these (using simply pip install command), I was able to install awscli.

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

Option 1

If one doesn't know the sheets names

# Read all sheets in your File
df = pd.read_excel('FILENAME.xlsm', sheet_name=None)
    
# Prints all the sheets name in an ordered dictionary
print(df.keys())

Then, depending on the sheet one wants to read, one can pass each of them to a specific dataframe, such as

sheet1_df = pd.read_excel('FILENAME.xlsm', sheet_name=SHEET1NAME)
sheet2_df = pd.read_excel('FILENAME.xlsm', sheet_name=SHEET2NAME)

Option 2

If the name is not relevant and all one cares about is the position of the sheet. Let's say one wants only the first sheet,

# Read all sheets in your File
df = pd.read_excel('FILENAME.xlsm', sheet_name=None)

sheet1 = list(df.keys())[0]

Then, depending on the sheet name, one can pass each it to a specific dataframe, such as

sheet1_df = pd.read_excel('FILENAME.xlsm', sheet_name=SHEET1NAME)

How to concatenate two layers in keras?

Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0


import tensorflow as tf

# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)

# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)

# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])

# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])

# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)

Result:

------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------

Bootstrap 3 Glyphicons are not working

I modified my less variables.less file I modified the variable

@icon-font-path:          "fonts/";    

the original was

@icon-font-path:          "../fonts/"; 

It was causing a problem

How to convert a normal Git repository to a bare one?

Here is the definition of a bare repository from gitglossary:

A bare repository is normally an appropriately named directory with a .git suffix that does not have a locally checked-out copy of any of the files under revision control. That is, all of the Git administrative and control files that would normally be present in the hidden .git sub-directory are directly present in the repository.git directory instead, and no other files are present and checked out. Usually publishers of public repositories make bare repositories available.

I arrived here because I was playing around with a "local repository" and wanted to be able to do whatever I wanted as if it were a remote repository. I was just playing around, trying to learn about git. I'll assume that this is the situation for whoever wants to read this answer.

I would love for an expert opinion or some specific counter-examples, however it seems that (after rummaging through some git source code that I found) simply going to the file .git/config and setting the core attribute bare to true, git will let you do whatever you want to do to the repository remotely. I.e. the following lines should exist in .git/config:

[core]
    ...
    bare = true
...

(This is roughly what the command git config --bool core.bare true will do, which is probably recommended to deal with more complicated situations)

My justification for this claim is that, in the git source code, there seems to be two different ways of testing if a repo is bare or not. One is by checking a global variable is_bare_repository_cfg. This is set during some setup phase of execution, and reflects the value found in the .git/config file. The other is a function is_bare_repository(). Here is the definition of this function:

int is_bare_repository(void)
{
    /* if core.bare is not 'false', let's see if there is a work tree */
    return is_bare_repository_cfg && !get_git_work_tree();
} 

I've not the time nor expertise to say this with absolute confidence, but as far as I could tell if you have the bare attribute set to true in .git/config, this should always return 1. The rest of the function probably is for the following situation:

  1. core.bare is undefined (i.e. neither true nor false)
  2. There is no worktree (i.e. the .git subdirectory is the main directory)

I'll experiment with it when I can later, but this would seem to indicate that setting core.bare = true is equivalent to removeing core.bare from the config file and setting up the directories properly.

At any rate, setting core.bare = true certainly will let you push to it, but I'm not sure if the presence of project files will cause some other operations to go awry. It's interesting and I suppose instructive to push to the repository and see what happened locally (i.e. run git status and make sense of the results).

How to save CSS changes of Styles panel of Chrome Developer Tools?

Tincr Chrome extension is easier to install (no need to run node server) AND also comes with LiveReload like functionality out the box! Talk about bi-directional editing! :)

Tin.cr Website

Chrome Web Store Link

Andy's Blog Article

How to remove spaces from a string using JavaScript?

var input = '/var/www/site/Brand new document.docx';

//remove space
input = input.replace(/\s/g, '');

//make string lower
input = input.toLowerCase();

alert(input);

Click here for working example

How do I count unique visitors to my site?

for finding out that user is new or old , Get user IP .

create a table for IPs and their visits timestamp .

check IF IP does not exists OR time()-saved_timestamp > 60*60*24 (for 1 day) ,edit the IP's timestamp to time() (means now) and increase your view one .

else , do nothing .

FYI : user IP is stored in $_SERVER['REMOTE_ADDR'] variable

What's the most efficient way to erase duplicates and sort a vector?

If you do not want to change the order of elements, then you can try this solution:

template <class T>
void RemoveDuplicatesInVector(std::vector<T> & vec)
{
    set<T> values;
    vec.erase(std::remove_if(vec.begin(), vec.end(), [&](const T & value) { return !values.insert(value).second; }), vec.end());
}

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

I got same error message. I was giving

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe "C:\MyService\MyService.exe"

Instead of

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "C:\MyService\MyService.exe"

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

Why doesn't indexOf work on an array IE8?

For a really thorough explanation and workaround, not only for indexOf but other array functions missing in IE check out the StackOverflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.)

What is the difference between a URI, a URL and a URN?

In order to answer this I'll lean on an answer I modified to another question. A good example of a URI is how you identify an Amazon S3 resource. Let's take:

s3://www-example-com/index.html [fig. 1]

which I created as a cached copy of

http://www.example.com/index.html [fig. 2]

in Amazon's S3-US-West-2 datacenter.

Even if StackOverflow would allow me to hyperlink to the s3:// protocol scheme, it wouldn't do you any good in locating the resource. Because it Identifies a Resource, fig. 1 is a valid URI. It is also a valid URN, because Amazon requires that the bucket (their term for the authority portion of the URI) be unique across datacenters. It is helpful in locating it, but it does not indicate the datacenter. Therefore it does not work as a URL.

So, how do URI, URL, and URN differ in this case?

NOTE: RFC 3986 defines URIs as scheme://authority/path?query#fragment

How to install plugins to Sublime Text 2 editor?

Install the Package Control first.

The simplest method of installation is through the Sublime Text console. The console is accessed via the Ctrl+` shortcut or the View > Show Console menu. Once open, paste the appropriate Python code for your version of Sublime Text into the console.

Code for Sublime Text 3

import urllib.request,os; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); open(os.path.join(ipp, pf), 'wb').write(urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ','%20')).read())

Code for Sublime Text 2

import urllib2,os; pf='Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler( ))); open( os.path.join( ipp, pf), 'wb' ).write( urllib2.urlopen( 'http://sublime.wbond.net/' +pf.replace( ' ','%20' )).read()); print( 'Please restart Sublime Text to finish installation')

For the up-to-date installation code, please check Package Control Installation Guide.

Manual

If for some reason the console installation instructions do not work for you (such as having a proxy on your network), perform the following steps to manually install Package Control:

  1. Click the Preferences > Browse Packages… menu
  2. Browse up a folder and then into the Installed Packages/ folder
  3. Download Package Control.sublime-package and copy it into the Installed Packages/ directory
  4. Restart Sublime Text

Usage

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+p (Win, Linux) or CMD+Shift+p (OSX). All Package Control commands begin with Package Control:, so start by typing Package.

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

This could be a issue in mvn home path in IntellijIdea IDE. For me it worked out when I set the mvn home directory correctly.enter image description here

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

How do I move focus to next input with jQuery?

Try using something like:

var inputs = $(this).closest('form').find(':focusable');
inputs.eq(inputs.index(this) + 1).focus();

How to Query an NTP Server using C#?

A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)

public static DateTime GetNetworkTime()
{
  const string NtpServer = "pool.ntp.org";

  const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
  const long TicksPerSecond = 10000000L;
  const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
  const long TicksTo1900 = DaysTo1900 * TicksPerDay;

  var ntpData = new byte[48];
  ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

  var addresses = Dns.GetHostEntry(NtpServer).AddressList;
  var ipEndPoint = new IPEndPoint(addresses[0], 123);
  long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  {
    socket.Connect(ipEndPoint);
    socket.ReceiveTimeout = 5000;
    socket.Send(ntpData);
    pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time

    socket.Receive(ntpData);
    pingDuration = Stopwatch.GetTimestamp() - pingDuration;
  }

  long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;

  // optional: display response-time
  // Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);

  long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
  long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
  long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);

  var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);

  return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}

Length of the String without using length() method

try below code

    public static int Length(String str) {
    str = str + '\0';
    int count = 0;

    for (int i = 0; str.charAt(i) != '\0'; i++) {
        count++;
    }

    return count;
    }

Query for documents where array size is greater than 1

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

you can use $gt and $lt in query.

Usage of __slots__?

The original question was about general use cases not only about memory. So it should be mentioned here that you also get better performance when instantiating large amounts of objects - interesting e.g. when parsing large documents into objects or from a database.

Here is a comparison of creating object trees with a million entries, using slots and without slots. As a reference also the performance when using plain dicts for the trees (Py2.7.10 on OSX):

********** RUN 1 **********
1.96036410332 <class 'css_tree_select.element.Element'>
3.02922606468 <class 'css_tree_select.element.ElementNoSlots'>
2.90828204155 dict
********** RUN 2 **********
1.77050495148 <class 'css_tree_select.element.Element'>
3.10655999184 <class 'css_tree_select.element.ElementNoSlots'>
2.84120798111 dict
********** RUN 3 **********
1.84069895744 <class 'css_tree_select.element.Element'>
3.21540498734 <class 'css_tree_select.element.ElementNoSlots'>
2.59615707397 dict
********** RUN 4 **********
1.75041103363 <class 'css_tree_select.element.Element'>
3.17366290092 <class 'css_tree_select.element.ElementNoSlots'>
2.70941114426 dict

Test classes (ident, appart from slots):

class Element(object):
    __slots__ = ['_typ', 'id', 'parent', 'childs']
    def __init__(self, typ, id, parent=None):
        self._typ = typ
        self.id = id
        self.childs = []
        if parent:
            self.parent = parent
            parent.childs.append(self)

class ElementNoSlots(object): (same, w/o slots)

testcode, verbose mode:

na, nb, nc = 100, 100, 100
for i in (1, 2, 3, 4):
    print '*' * 10, 'RUN', i, '*' * 10
    # tree with slot and no slot:
    for cls in Element, ElementNoSlots:
        t1 = time.time()
        root = cls('root', 'root')
        for i in xrange(na):
            ela = cls(typ='a', id=i, parent=root)
            for j in xrange(nb):
                elb = cls(typ='b', id=(i, j), parent=ela)
                for k in xrange(nc):
                    elc = cls(typ='c', id=(i, j, k), parent=elb)
        to =  time.time() - t1
        print to, cls
        del root

    # ref: tree with dicts only:
    t1 = time.time()
    droot = {'childs': []}
    for i in xrange(na):
        ela =  {'typ': 'a', id: i, 'childs': []}
        droot['childs'].append(ela)
        for j in xrange(nb):
            elb =  {'typ': 'b', id: (i, j), 'childs': []}
            ela['childs'].append(elb)
            for k in xrange(nc):
                elc =  {'typ': 'c', id: (i, j, k), 'childs': []}
                elb['childs'].append(elc)
    td = time.time() - t1
    print td, 'dict'
    del droot

What is the difference between persist() and merge() in JPA and Hibernate?

JPA specification contains a very precise description of semantics of these operations, better than in javadoc:

The semantics of the persist operation, applied to an entity X are as follows:

  • If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.

  • If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the cascade=PERSIST or cascade=ALL annotation element value or specified with the equivalent XML descriptor element.

  • If X is a removed entity, it becomes managed.

  • If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

  • For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value cascade=PERSIST or cascade=ALL, the persist operation is applied to Y.


The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.

  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.

  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).

  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)

  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

Which comment style should I use in batch files?

James K, I'm sorry I was wrong in a fair portion of what I said. The test I did was the following:

@ECHO OFF
(
  :: But
   : neither
  :: does
   : this
  :: also.
)

This meets your description of alternating but fails with a ") was unexpected at this time." error message.

I did some farther testing today and found that alternating isn't the key but it appears the key is having an even number of lines, not having any two lines in a row starting with double colons (::) and not ending in double colons. Consider the following:

@ECHO OFF
(
   : But
   : neither
   : does
   : this
   : cause
   : problems.
)

This works!

But also consider this:

@ECHO OFF
(
   : Test1
   : Test2
   : Test3
   : Test4
   : Test5
   ECHO.
)

The rule of having an even number of comments doesn't seems to apply when ending in a command.

Unfortunately this is just squirrelly enough that I'm not sure I want to use it.

Really, the best solution, and the safest that I can think of, is if a program like Notepad++ would read REM as double colons and then would write double colons back as REM statements when the file is saved. But I'm not aware of such a program and I'm not aware of any plugins for Notepad++ that does that either.

How to disable a button when an input is empty?

You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.

Example using state:

_x000D_
_x000D_
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
  getInitialState() {_x000D_
    return {email: ''}_x000D_
  },_x000D_
  handleChange(e) {_x000D_
    this.setState({email: e.target.value})_x000D_
  },_x000D_
  render() {_x000D_
    return <div>_x000D_
      <input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
      <button type="button" disabled={!this.state.email}>Button</button>_x000D_
    </div>_x000D_
  }_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
_x000D_
_x000D_

How to change the scrollbar color using css

Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.

So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.

Solution:

By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution

See This Demo

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

As per my personal experience Adobe edge is the best tool for HTML5. It's still in preview mode but you will download it free from Adobe site.

Is it possible to use 'else' in a list comprehension?

If you want an else you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value as the statement instead, and remove the filter from the end:

table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))

How to call a JavaScript function within an HTML body

First include the file in head tag of html , then call the function in script tags under body tags e.g.

Js file function to be called

function tryMe(arg) {
    document.write(arg);
}

HTML FILE

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src='object.js'> </script>
    <title>abc</title><meta charset="utf-8"/>
</head>
<body>
    <script>
    tryMe('This is me vishal bhasin signing in');
    </script>
</body>
</html>

finish

Warning: Cannot modify header information - headers already sent by ERROR

The long-term answer is that all output from your PHP scripts should be buffered in variables. This includes headers and body output. Then at the end of your scripts do any output you need.

The very quick fix for your problem will be to add

ob_start();

as the very first thing in your script, if you only need it in this one script. If you need it in all your scripts add it as the very first thing in your header.php file.

This turns on PHP's output buffering feature. In PHP when you output something (do an echo or print) it has to send the HTTP headers at that time. If you turn on output buffering you can output in the script but PHP doesn't have to send the headers until the buffer is flushed. If you turn it on and don't turn it off PHP will automatically flush everything in the buffer after the script finishes running. There really is no harm in just turning it on in almost all cases and could give you a small performance increase under some configurations.

If you have access to change your php.ini configuration file you can find and change or add the following

output_buffering = On

This will turn output buffering out without the need to call ob_start().

To find out more about output buffering check out http://php.net/manual/en/book.outcontrol.php

Android Material and appcompat Manifest merger failed

I had similar problem. Added two lines in gradle.properties file:

android.useAndroidX=true
android.enableJetifier=true

These two lines automatically resolved my dependency conflicts between google's files and third party dependencies. Here's the link to follow: https://developer.android.com/topic/libraries/support-library/androidx-overview#new-project

Replace multiple characters in a C# string

This is the shortest way:

myString = Regex.Replace(myString, @"[;,\t\r ]|[\n]{2}", "\n");

SQL update from one Table to another based on a ID match

Seems you are using MSSQL, then, if I remember correctly, it is done like this:

UPDATE [Sales_Lead].[dbo].[Sales_Import] SET [AccountNumber] = 
RetrieveAccountNumber.AccountNumber 
FROM RetrieveAccountNumber 
WHERE [Sales_Lead].[dbo].[Sales_Import].LeadID = RetrieveAccountNumber.LeadID

Generating random numbers in C

You should call srand() before calling rand to initialize the random number generator.

Either call it with a specific seed, and you will always get the same pseudo-random sequence

#include <stdlib.h>

int main ()
{
  srand ( 123 );
  int random_number = rand();
  return 0;
}

or call it with a changing sources, ie the time function

#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) );
  int random_number = rand();
  return 0;
}

In response to Moon's Comment rand() generates a random number with an equal probability between 0 and RAND_MAX (a macro pre-defined in stdlib.h)

You can then map this value to a smaller range, e.g.

int random_value = rand(); //between 0 and RAND_MAX

//you can mod the result
int N = 33;
int rand_capped = random_value % N;  //between 0 and 32
int S = 50;
int rand_range = rand_capped + S; //between 50 and 82

//you can convert it to a float
float unit_random = random_value / (float) RAND_MAX; //between 0 and 1 (floating point)

This might be sufficient for most uses, but its worth pointing out that in the first case using the mod operator introduces a slight bias if N does not divide evenly into RAND_MAX+1.

Random number generators are interesting and complex, it is widely said that the rand() generator in the C standard library is not a great quality random number generator, read (http://en.wikipedia.org/wiki/Random_number_generation for a definition of quality).

http://en.wikipedia.org/wiki/Mersenne_twister (source http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html ) is a popular high quality random number generator.

Also, I am not aware of arc4rand() or random() so I cannot comment.

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

Could not load type from assembly error

Version=1.0.3.0 indicates Castle RC3, however the fluent interface was developed some months after the release of RC3. Therefore, it looks like you have a versioning problem. Maybe you have Castle RC3 registered in the GAC and it's using that one...

How to connect to remote Oracle DB with PL/SQL Developer?

I would recommend creating a TNSNAMES.ORA file. From your Oracle Client install directory, navigate to NETWORK\ADMIN. You may already have a file called TNSNAMES.ORA, if so edit it, else create it using your favorite text editor.

Next, simply add an entry like this:

MYDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521))
    (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED))
  )

You can change MYDB to whatever you like, this is the identifier that applications will will use to find the database using the info from TNSNAMES.

Finally, login with MYDB as your database in PL/SQL Developer. It should automatically find the connection string in the TNSNAMES.ORA.

If that does not work, hit Help->About then click the icon with an "i" in it in the upper-lefthand corner. The fourth tab is the "TNS Names" tab, check it to confirm that it is loading the proper TNSNAMES.ORA file. If it is not, you may have multiple Oracle installations on your computer, and you will need to find the one that is in use.

Easiest way to convert a List to a Set in Java

I agree with sepp2k, but there are some other details that might matter:

new HashSet<Foo>(myList);

will give you an unsorted set which doesn't have duplicates. In this case, duplication is identified using the .equals() method on your objects. This is done in combination with the .hashCode() method. (For more on equality look here)

An alternative that gives a sorted set is:

new TreeSet<Foo>(myList);

This works if Foo implements Comparable. If it doesn't then you may want to use a comparator:

Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);

This depends on either compareTo() (from the comparable interface) or compare() (from the comparator) to ensure uniqueness. So, if you just care about uniqueness, use the HashSet. If you're after sorting, then consider the TreeSet. (Remember: Optimize later!) If time efficiency matters use a HashSet if space efficiency matters, look at TreeSet. Note that more efficient implementations of Set and Map are available through Trove (and other locations).

Adding onClick event dynamically using jQuery

try this approach if you know your object client name ( it is not important that it is Button or TextBox )

$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');

try this ones if you want add onClick event to a server object with JQuery

$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');

Why does ANT tell me that JAVA_HOME is wrong when it is not?

I was also facing the same problem. I am using Windows 7 and I had two versions of java installed. First I have installed latest version java 7 and then version 5.

Contents of my java installation directory:

C:\Program Files\Java>
jdk1.5.0_14
jdk1.7.0_17
jre1.5.0_14
jre7

and my JAVA_HOME was set to the correct value, which was:

C:\>set ja
JAVA_HOME=C:\Program Files\Java\jdk1.5.0_14

But still I was getting the same problem:

XXXXXXX\build.xml:478: The following error occurred while
executing this line:
XXXXXXX\build.xml:477: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\Program Files\Java\jre7"

After trying out all the suggestion in this thread I realized my mistake. I was trying to set the environment variable in "User variables" instead of "System Variables" section. After setting it in "System Variables" it worked fine. I am facing another problem though.

The default version of java it points to is still 7.

C:\>java -version
java version "1.7.0_17"
Java(TM) SE Runtime Environment (build 1.7.0_17-b02)
Java HotSpot(TM) Client VM (build 23.7-b01, mixed mode, sharing)

I am not sure how to make it point to version 5.

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

I had the similar issue. The problem was in the passwords: the Keystore and private key used different passwords. (KeyStore explorer was used)

After creating Keystore with the same password as private key had the issue was resolved.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

When this happened to me (out of nowhere) I was about to dive into the top answer above, and then I figured I'd close the project, close Visual Studio, and then re-open everything. Problem solved. VS bug?

Resolving require paths with webpack

resolve.alias should work exactly the way you described, so I'm providing this as an answer to help mitigate any confusion that may result from the suggestion in the original question that it does not work.

a resolve configuration like the one below will give you the desired results:

// used to resolve absolute path to project's root directory (where web pack.config.js should be located)
var path = require( 'path' );
...
{
  ...
  resolve: {
    // add alias for application code directory
    alias:{
      mydir: path.resolve( __dirname, 'path', 'to', 'mydir' )
    },
    extensions: [ '', '.js' ]
  }
}

require( 'mydir/myfile.js' ) will work as expected. If it does not, there must be some other issue.

If you have multiple modules that you want to add to the search path, resolve.root makes sense, but if you just want to be able to reference components within your application code without relative paths, alias seems to be the most straight-forward and explicit.

An important advantage of alias is that it gives you the opportunity to namespace your requires which can add clarity to your code; just like it is easy to see from other requires what module is being referenced, alias allows you to write descriptive requires that make it obvious you're requiring internal modules, e.g. require( 'my-project/component' ). resolve.root just plops you into the desired directory without giving you the opportunity to namespace it further.

Operator overloading in Java

Or, you can make Java Groovy and just overload these functions to achieve what you want

//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...

class Fish {
    def leftShift(Fish fish) {
        print "You just << (left shifted) some fish "
    }
}


def fish = new Fish()
def fish2 = new Fish()

fish << fish2

Who doesnt want to be/use groovy? :D

No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.

CSS: background image on background color

Based on MDN Web Docs you can set multiple background using shorthand background property or individual properties except for background-color. In your case, you can do a trick using linear-gradient like this:

background-image: url('images/checked.png'), linear-gradient(to right, #6DB3F2, #6DB3F2);

The first item (image) in the parameter will be put on top. The second item (color background) will be put underneath the first. You can also set other properties individually. For example, to set the image size and position.

background-size: 30px 30px;
background-position: bottom right;
background-repeat: no-repeat;

Benefit of this method is you can implement it for other cases easily, for example, you want to make the blue color overlaying the image with certain opacity.

background-image: linear-gradient(to right, rgba(109, 179, 242, .6), rgba(109, 179, 242, .6)), url('images/checked.png');
background-size: cover, contain;
background-position: center, right bottom;
background-repeat: no-repeat, no-repeat;

Individual property parameters are set respectively. Because the image is put underneath the color overlay, its property parameters are also placed after color overlay parameters.

How to pass multiple values to single parameter in stored procedure

I think, below procedure help you to what you are looking for.

 CREATE PROCEDURE [dbo].[FindEmployeeRecord]
        @EmployeeID nvarchar(Max)
    AS
    BEGIN
    DECLARE @sqLQuery VARCHAR(MAX)
    Declare @AnswersTempTable Table
    (  
        EmpId int,         
        EmployeeName nvarchar (250),       
        EmployeeAddress nvarchar (250),  
        PostalCode nvarchar (50),
        TelephoneNo nvarchar (50),
        Email nvarchar (250),
        status nvarchar (50),  
        Sex nvarchar (50) 
    )

    Set @sqlQuery =
    'select e.EmpId,e.EmployeeName,e.Email,e.Sex,ed.EmployeeAddress,ed.PostalCode,ed.TelephoneNo,ed.status
    from Employee e
    join EmployeeDetail ed on e.Empid = ed.iEmpID
    where Convert(nvarchar(Max),e.EmpId) in ('+@EmployeeId+')
    order by EmpId'
    Insert into @AnswersTempTable
    exec (@sqlQuery)
    select * from @AnswersTempTable
    END

Vertical divider doesn't work in Bootstrap 3

I think this will bring it back using 3.0

.navbar .divider-vertical {
    height: 50px;
    margin: 0 9px;
    border-right: 1px solid #ffffff;
    border-left: 1px solid #f2f2f2;
}

.navbar-inverse .divider-vertical {
    border-right-color: #222222;
    border-left-color: #111111;
}

@media (max-width: 767px) {
    .navbar-collapse .nav > .divider-vertical {
        display: none;
     }
}

PHP Check for NULL

Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero):

if (!$result['column']>0){

}

Is there a performance difference between i++ and ++i in C?

Short answer:

There is never any difference between i++ and ++i in terms of speed. A good compiler should not generate different code in the two cases.

Long answer:

What every other answer fails to mention is that the difference between ++i versus i++ only makes sense within the expression it is found.

In the case of for(i=0; i<n; i++), the i++ is alone in its own expression: there is a sequence point before the i++ and there is one after it. Thus the only machine code generated is "increase i by 1" and it is well-defined how this is sequenced in relation to the rest of the program. So if you would change it to prefix ++, it wouldn't matter in the slightest, you would still just get the machine code "increase i by 1".

The differences between ++i and i++ only matters in expressions such as array[i++] = x; versus array[++i] = x;. Some may argue and say that the postfix will be slower in such operations because the register where i resides have to be reloaded later. But then note that the compiler is free to order your instructions in any way it pleases, as long as it doesn't "break the behavior of the abstract machine" as the C standard calls it.

So while you may assume that array[i++] = x; gets translated to machine code as:

  • Store value of i in register A.
  • Store address of array in register B.
  • Add A and B, store results in A.
  • At this new address represented by A, store the value of x.
  • Store value of i in register A // inefficient because extra instruction here, we already did this once.
  • Increment register A.
  • Store register A in i.

the compiler might as well produce the code more efficiently, such as:

  • Store value of i in register A.
  • Store address of array in register B.
  • Add A and B, store results in B.
  • Increment register A.
  • Store register A in i.
  • ... // rest of the code.

Just because you as a C programmer is trained to think that the postfix ++ happens at the end, the machine code doesn't have to be ordered in that way.

So there is no difference between prefix and postfix ++ in C. Now what you as a C programmer should be vary of, is people who inconsistently use prefix in some cases and postfix in other cases, without any rationale why. This suggests that they are uncertain about how C works or that they have incorrect knowledge of the language. This is always a bad sign, it does in turn suggest that they are making other questionable decisions in their program, based on superstition or "religious dogmas".

"Prefix ++ is always faster" is indeed one such false dogma that is common among would-be C programmers.

What is the purpose of Node.js module.exports and how do you use it?

Some few things you must take care if you assign a reference to a new object to exports and /or modules.exports:

1. All properties/methods previously attached to the original exports or module.exports are of course lost because the exported object will now reference another new one

This one is obvious, but if you add an exported method at the beginning of an existing module, be sure the native exported object is not referencing another object at the end

exports.method1 = function () {}; // exposed to the original exported object
exports.method2 = function () {}; // exposed to the original exported object

module.exports.method3 = function () {}; // exposed with method1 & method2

var otherAPI = {
    // some properties and/or methods
}

exports = otherAPI; // replace the original API (works also with module.exports)

2. In case one of exports or module.exports reference a new value, they don't reference to the same object any more

exports = function AConstructor() {}; // override the original exported object
exports.method2 = function () {}; // exposed to the new exported object

// method added to the original exports object which not exposed any more
module.exports.method3 = function () {}; 

3. Tricky consequence. If you change the reference to both exports and module.exports, hard to say which API is exposed (it looks like module.exports wins)

// override the original exported object
module.exports = function AConstructor() {};

// try to override the original exported object
// but module.exports will be exposed instead
exports = function AnotherConstructor() {}; 

How to determine the version of Gradle?

You can also add the following line to your build script:

println "Running gradle version: $gradle.gradleVersion"

or (it won't be printed with -q switch)

logger.lifecycle "Running gradle version: $gradle.gradleVersion"

How to align an image dead center with bootstrap

Twitter bootstrap has a class that centers: .pagination-centered

It worked for me to do:

<div class="row-fluid">
   <div class="span12 pagination-centered"><img src="header.png" alt="header" /></div>
</div>

The css for the class is:

.pagination-centered {
  text-align: center;
}

How to get number of rows using SqlDataReader in C#

If you do not need to retrieve all the row and want to avoid to make a double query, you can probably try something like that:

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
      {
        sqlCon.Open();

        var com = sqlCon.CreateCommand();
        com.CommandText = "select * from BigTable";
        using (var reader = com.ExecuteReader())
        {
            //here you retrieve what you need
        }

        com.CommandText = "select @@ROWCOUNT";
        var totalRow = com.ExecuteScalar();

        sqlCon.Close();
      }

You may have to add a transaction not sure if reusing the same command will automatically add a transaction on it...

How do I get my solution in Visual Studio back online in TFS?

I searched for the solution online and found this solution but wasn't too keen on the registry change.

I found a better way: right-click on the solution name right at the top of the Solution Explorer and select the Go Online option. Clicking this allowed me to select the files that had been changed when I was offline and make the solution online again.

After finding the solution, I found the following msdn forum thread which confirmed the above.