Programs & Examples On #Normals

In geometry, an object such as a line or vector is called a normal to another object if they are orthogonal to each other.

center a row using Bootstrap 3

Instead of trying to center div's, just add this to your local css.

.col-md-offset-15 {
    margin-left: 12.4999999%;
}

which is roughly  offset-1 and half of offset-1. (8.333% + 4.166%) = 12.4999%

This worked for me.

SecurityException: Permission denied (missing INTERNET permission?)

Well it's a very confusing kind of bug. There could be many reasons:

  1. You are not mentioning the permissions in right place. Like right above application.
  2. You are not using small letters.
  3. In some case you also have to add Network state permission.
  4. One which was my case there are some blank lines in manifest lines. Like there might be a blank line between permission tag and application line. Remove them and you are done. Hope it will help

Convert float to double without losing precision

A simple solution that works well, is to parse the double from the string representation of the float:

double val = Double.valueOf(String.valueOf(yourFloat));

Not super efficient, but it works!

MySQL stored procedure vs function, which would I use when?

A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.

A procedure is executed using the CALL query.

Programmatically register a broadcast receiver

Create a broadcast receiver

[BroadcastReceiver(Enabled = true, Exported = false)]

public class BCReceiver : BroadcastReceiver
{

    BCReceiver receiver;

    public override void OnReceive(Context context, Intent intent)
    {
        //Do something here
    }
}

From your activity add this code:

LocalBroadcastManager.getInstance(ApplicationContext)
    .registerReceiver(receiver, filter);

How to hide collapsible Bootstrap 4 navbar on click

The easiest way to do it using only Angular 2/4 template with no coding:

<nav class="navbar navbar-default" aria-expanded="false">
  <div class="container-wrapper">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div class="navbar-collapse collapse no-transition" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
      <ul class="nav navbar-nav" (click)="isCollapsed = !isCollapsed">
        <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}"><a routerLink="/">Home</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/about">About</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/portfolio">Portfolio</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/contacts">Contacts</a></li>
      </ul>
    </div>

  </div>
</nav>

How to create and add users to a group in Jenkins for authentication?

I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.

I didn't have high hopes, as that plugin was last updated in 2011

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

Check number of arguments passed to a Bash script

A simple one liner that works can be done using:

[ "$#" -ne 1 ] && ( usage && exit 1 ) || main

This breaks down to:

  1. test the bash variable for size of parameters $# not equals 1 (our number of sub commands)
  2. if true then call usage() function and exit with status 1
  3. else call main() function

Things to note:

  • usage() can just be simple echo "$0: params"
  • main can be one long script

jQuery Form Validation before Ajax submit

You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.

$('#form').validate({

    ... your validation rules come here,

    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {
                $('#answers').html(response);
            }            
        });
    }
});

The jQuery.validate plugin will invoke the submit handler if the validation has passed.

How to pass a callback as a parameter into another function

Also, could be simple as:

if( typeof foo == "function" )
    foo();

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

VBA for clear value in specific range of cell and protected cell from being wash away formula

Try this

Sheets("your sheetname").range("A5:X50").Value = ""

You can also use

ActiveSheet.range

How do I count cells that are between two numbers in Excel?

Example-

For cells containing the values between 21-31, the formula is:

=COUNTIF(M$7:M$83,">21")-COUNTIF(M$7:M$83,">31")

How to go back to previous page if back button is pressed in WebView?

You should the following libraries on your class handle the onBackKeyPressed. canGoBack() checks whether the webview can reference to the previous page. If it is possible then use the goBack() function to reference the previous page (go back).

 @Override
        public void onBackPressed() {
          if( mWebview.canGoBack()){
               mWebview.goBack(); 
           }else{
            //Do something else. like trigger pop up. Add rate app or see more app
           }
  }

Which characters need to be escaped when using Bash?

I presume that you're talking about bash strings. There are different types of strings which have a different set of requirements for escaping. eg. Single quotes strings are different from double quoted strings.

The best reference is the Quoting section of the bash manual.

It explains which characters needs escaping. Note that some characters may need escaping depending on which options are enabled such as history expansion.

Add a property to a JavaScript object using a variable as the name?

With ECMAScript 2015 you can do it directly in object declaration using bracket notation:

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value:

var obj = {
  ['hello']: 'World',
  [x + 2]: 42,
  [someObject.getId()]: someVar
}

Want to show/hide div based on dropdown box selection

you have error in your code unexpected token.use:

  $('#purpose').on('change', function () {
   if (this.value == '1') {
    $("#business").show();
    } else {
    $("#business").hide();
   }

   });

Demo

Update: You can narrow down the code using .toggle()

 $('#purpose').on('change', function () {
   $("#business").toggle(this.value == '1');
 });

How can I check the size of a collection within a Django template?

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count

What is the best way to initialize a JavaScript Date to midnight?

If calculating with dates summertime will cause often 1 uur more or one hour less than midnight (CEST). This causes 1 day difference when dates return. So the dates have to round to the nearest midnight. So the code will be (ths to jamisOn):

    var d = new Date();
    if(d.getHours() < 12) {
    d.setHours(0,0,0,0); // previous midnight day
    } else {
    d.setHours(24,0,0,0); // next midnight day
    }

How to change Java version used by TOMCAT?

In Eclipse it is very easy to point Tomcat to a new JVM (in this example JRE6). My problem was I couldn't find where to do it. Here is the trick:

  1. On the ECLIPSE top menu FILE pull down tab, select NEW, -->Other
  2. ...on the New Server: Select A Wizard window, select: Server-> Server... click NEXT
  3. . on the New Server: Define a New Server window, select Apache> Tomcat 7 Server
  4. ..now click the line in blue and underlined entitled: Configure Runtime Environments
  5. on the Server Runtime Environments window,
  6. ..select Apache, expand it(click on the arrow to the left), select TOMCAT v7.0, and click EDIT.
  7. you will see a window called EDIT SERVER RUNTIME ENVIRONMENT: TOMCAT SERVER
  8. On this screen there is a pulldown labeled JREs.
  9. You should find your JRE listed like JRE1.6.0.33. If not use the Installed JRE button.
  10. Select the desired JRE. Click the FINISH button.
  11. Gracefully exit, in the Server: Server Runtime Environments window, click OK
  12. in the New Server: Define a new Server window, hit NEXT
  13. in the New Server: Add and Remove Window, select apps and install them on the server.
  14. in the New Server: Add and Remove Window, click Finish

That's all. Interesting, only steps 7-10 seem to matter, and they will change the JRE used on all servers you have previously defined to use TOMCAT v7.0. The rest of the steps are just because I can't find any other way to get to the screen except by defining a new server. Does anyone else know an easier way?

What are ABAP and SAP?

SAP is really a big Company that offers incredible solutions oriented to medium-large companies.

Actually, I can say that the main IT products are: ERP, WEB, Human Resources, Integration, BI, Reports, Machine Learning, Mobile, Cloud, Robotics, and so on.

On the cloud, you can even find solutions using Cloud Foundry, NodeJS, HTML5, Java, etc.

It's really huge the solutions that offers to their customers.

How to delete/truncate tables from Hadoop-Hive?

You need to drop the table and then recreate it and then load it again

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

Difference between Relative path and absolute path in javascript

What is the difference between Relative path and absolute path?

One has to be calculated with respect to another URI. The other does not.

Is there any performance issues occures for using these paths?

Nothing significant.

We will get any secure for the sites ?

No

Is there any way to converting absolute path to relative

In really simplified terms: Working from left to right, try to match the scheme, hostname, then path segments with the URI you are trying to be relative to. Stop when you have a match.

Replace CRLF using powershell

You have not specified the version, I'm assuming you are using Powershell v3.

Try this:

$path = "C:\Users\abc\Desktop\File\abc.txt"
(Get-Content $path -Raw).Replace("`r`n","`n") | Set-Content $path -Force

Editor's note: As mike z points out in the comments, Set-Content appends a trailing CRLF, which is undesired. Verify with: 'hi' > t.txt; (Get-Content -Raw t.txt).Replace("`r`n","`n") | Set-Content t.txt; (Get-Content -Raw t.txt).EndsWith("`r`n"), which yields $True.

Note this loads the whole file in memory, so you might want a different solution if you want to process huge files.

UPDATE

This might work for v2 (sorry nowhere to test):

$in = "C:\Users\abc\Desktop\File\abc.txt"
$out = "C:\Users\abc\Desktop\File\abc-out.txt"
(Get-Content $in) -join "`n" > $out

Editor's note: Note that this solution (now) writes to a different file and is therefore not equivalent to the (still flawed) v3 solution. (A different file is targeted to avoid the pitfall Ansgar Wiechers points out in the comments: using > truncates the target file before execution begins). More importantly, though: this solution too appends a trailing CRLF, which may be undesired. Verify with 'hi' > t.txt; (Get-Content t.txt) -join "`n" > t.NEW.txt; [io.file]::ReadAllText((Convert-Path t.NEW.txt)).endswith("`r`n"), which yields $True.

Same reservation about being loaded to memory though.

How to print float to n decimal places including trailing 0s?

The cleanest way in modern Python >=3.6, is to use an f-string with string formatting:

>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'

"git pull" or "git merge" between master and development branches

If you are not sharing develop branch with anybody, then I would just rebase it every time master updated, that way you will not have merge commits all over your history once you will merge develop back into master. Workflow in this case would be as follows:

> git clone git://<remote_repo_path>/ <local_repo>
> cd <local_repo>
> git checkout -b develop
....do a lot of work on develop
....do all the commits
> git pull origin master
> git rebase master develop

Above steps will ensure that your develop branch will be always on top of the latest changes from the master branch. Once you are done with develop branch and it's rebased to the latest changes on master you can just merge it back:

> git checkout -b master
> git merge develop
> git branch -d develop

Visual Studio displaying errors even if projects build

Unload & reload the project fixed this problem.

Watch multiple $scope attributes

A slightly safer solution to combine values might be to use the following as your $watch function:

function() { return angular.toJson([item1, item2]) }

or

$scope.$watch(
  function() {
    return angular.toJson([item1, item2]);
  },
  function() {
    // Stuff to do after either value changes
  });

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

Bootstrap 3 grid with no gap

The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*) is NOT synonymous with a column in BS3 (col-sm-*, etc), but there is a way to achieve the same result.

Check out this update to your fiddle: http://jsfiddle.net/pjBzY/22/ (code copied below).

First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6 applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6" is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8).

As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row -- except at "xs" window sizes, where the columns aren't applied.

If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content in my jsfiddle. Put something like this in each column, and they will behave the way old col-* elements did in BS2.


jsfiddle HTML

<div class="container">
    <p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
    <div class="row">
        <div class="col-sm-6 my-column">
            Col 1
            <p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
        </div>
        <div class="col-sm-6 my-column">
            Col 2
        </div>
    </div>
</div>

and the CSS

.row {
    border: blue 1px solid;
}
.my-column {
    background-color: green;
    padding-top: 10px;
    padding-bottom: 10px;
}
.my-column:first-child {
    background-color: red;
}

.inner-content {
    background: #eee;
    border: #999;
    border-radius: 5px;
    padding: 15px;
}

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with Location: other.jsp header
  • Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
  • Server sends a HTTP response back with content of other.jsp.

You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.

Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.

  • Client sends a HTTP request to some.jsp.
  • Server sends a HTTP response back with content of other.jsp.

However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.


The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().

You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:

request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

When you submit a form, you normally want to use POST:

<form action="login" method="post">

This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).

If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.

If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
    request.setAttribute("error", "Unknown login, please try again."); // Set error.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}

A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.

See also:

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

How to put a List<class> into a JSONObject and then read that object?

Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();

    //if List not empty
    if (!(sList.size() ==0)) {

        //Loop index size()
        for(int index = 0; index < sList.size(); index++) {
            JSONObject eachData = new JSONObject();
            try {
                eachData.put("name", sList.get(index).getName());
                eachData.put("dob", sList.get(index).getDob());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            allDataArray.put(eachData);
        }
    } else {
        //Do something when sList is empty
    }

Finally, add the JSONArray to a JSONObject.

JSONObject root = new JSONObject();
    try {
        root.put("data", allDataArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

You can further get this data as a String too.

String jsonString = root.toString();

Which font is used in Visual Studio Code Editor and how to change fonts?

The default fonts are different across Windows, Mac, and Linux. As of VSCode 1.15.1, the default font settings can be found in the source code:

const DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace';
const DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace';
const DEFAULT_LINUX_FONT_FAMILY = '\'Droid Sans Mono\', \'Courier New\', monospace, \'Droid Sans Fallback\'';

How to run .jar file by double click on Windows 7 64-bit?

If you try unpopular's answer:

For Windows 7:

  1. Start "Control Panel"
  2. Click "Default Programs"
  3. Click "Associate a file type or protocol with a specific program"
  4. Double click .jar
  5. Browse C:\Program Files\Java\jre7\bin\javaw.exe
  6. Click the button Open
  7. Click the button OK

And jar files still fail to open (in my case it was like I never double clicked):
open the Command Prompt (to be safe with admin rights enabled) and type the following commands:

java -version This should return a version so you can safely assume java is installed.

Then run

java -jar "PATHTOFILE\FILENAME.JAR"

Read through the output generated. You may discover an error message.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

GitHub README.md center image

This is quite simple really.

-> This is centered Text <-

So taking that in mind you can apply this to the img syntax.

->![alt text](/link/to/img)<-

Invalid Host Header when ngrok tries to connect to React dev server

Option 1

If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain

Option 2

If you are using webpack you can add the following configuration

devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

How to position a Bootstrap popover?

Maybe you don't need this logic for a responsive behavior.

E.g.

placement: 'auto left'

Bootstrap 3 has auto value for placement. Bootstrap doc:

When "auto" is specified, it will dynamically reorient the tooltip. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right.

How to perform a real time search and filter on a HTML table

I found dfsq's answer its comments extremely useful. I made some minor modifications applicable to me (and I'm posting it here, in case it is of some use to others).

  1. Using class as hooks, instead of table elements tr
  2. Searching/comparing text within a child class while showing/hiding parent
  3. Making it more efficient by storing the $rows text elements into an array only once (and avoiding $rows.length times computation)

_x000D_
_x000D_
var $rows = $('.wrapper');
var rowsTextArray = [];

var i = 0;
$.each($rows, function () {
    rowsTextArray[i] = ($(this).find('.number').text() + $(this).find('.fruit').text())
        .replace(/\s+/g, '')
        .toLowerCase();
    i++;
});

$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/\s+/g, '').toLowerCase();
  $rows.show().filter(function(index) {
    return (rowsTextArray[index].indexOf(val) === -1);
  }).hide();
});
_x000D_
span {
  margin-right: 0.2em;
}
_x000D_
<input type="text" id="search" placeholder="type to search" />

<div class="wrapper"><span class="number">one</span><span class="fruit">apple</span></div>
<div class="wrapper"><span class="number">two</span><span class="fruit">banana</span></div>
<div class="wrapper"><span class="number">three</span><span class="fruit">cherry</span></div>
<div class="wrapper"><span class="number">four</span><span class="fruit">date</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

I want to calculate the distance between two points in Java

Math.sqrt returns a double so you'll have to cast it to int as well

distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

Which comment style should I use in batch files?

tl;dr: REM is the documented and supported way to embed comments in batch files.


:: is essentially a blank label that can never be jumped to, whereas REM is an actual command that just does nothing. In neither case (at least on Windows 7) does the presence of redirection operators cause a problem.

However, :: is known to misbehave in blocks under certain circumstances, being parsed not as a label but as some sort of drive letter. I'm a little fuzzy on where exactly but that alone is enough to make me use REM exclusively. It's the documented and supported way to embed comments in batch files whereas :: is merely an artifact of a particular implementation.


Here is an example where :: produces a problem in a FOR loop.

This example will not work in a file called test.bat on your desktop:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    ::echo hello>C:\Users\%username%\Desktop\text.txt
)
pause

While this example will work as a comment correctly:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    REM echo hello>C:\Users\%username%\Desktop\text.txt
)
pause

The problem appears to be when trying to redirect output into a file. My best guess is that it is interpreting :: as an escaped label called :echo.

Remove final character from string

Simple:

st =  "abcdefghij"
st = st[:-1]

There is also another way that shows how it is done with steps:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

This is also a way with user input:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

To make it take away the last word in a list:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

C# listView, how do I add items to columns 2, 3 and 4 etc?

Here is the msdn documentation on the listview object and the listviewItem object.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.aspx

I would highly recommend that you at least take the time to skim the documentation on any objects you use from the .net framework. While the documentation can be pretty poor at some times it is still invaluable especially when you run into situations like this.

But as James Atkinson said it's simply a matter of adding subitems to a listviewitem like so:

ListViewItem i = new ListViewItem("column1");
i.SubItems.Add("column2");
i.SubItems.Add("column3");

Add line break to ::after or ::before pseudo-element content

For people who will going to look for 'How to change dynamically content on pseudo element adding new line sign" here's answer

Html chars like &#13;&#10; will not work appending them to html using JavaScript because those characters are changed on document render

Instead you need to find unicode representation of this characters which are U+000D and U+000A so we can do something like

_x000D_
_x000D_
var el = document.querySelector('div');_x000D_
var string = el.getAttribute('text').replace(/, /, '\u000D\u000A');_x000D_
el.setAttribute('text', string);
_x000D_
div:before{_x000D_
   content: attr(text);_x000D_
   white-space: pre;_x000D_
}
_x000D_
<div text='I want to break it in javascript, after comma sign'></div> 
_x000D_
_x000D_
_x000D_

Hope this save someones time, good luck :)

Tracking Google Analytics Page Views with AngularJS

Merging the answers by wynnwu and dpineda was what worked for me.

angular.module('app', [])
  .run(['$rootScope', '$location', '$window',
    function($rootScope, $location, $window) {
      $rootScope.$on('$routeChangeSuccess',
        function(event) {
          if (!$window.ga) {
            return;
          }
          $window.ga('send', 'pageview', {
            page: $location.path()
          });
        });
    }
  ]);

Setting the third parameter as an object (instead of just $location.path()) and using $routeChangeSuccess instead of $stateChangeSuccess did the trick.

Hope this helps.

AWS Lambda import module error in python

No need to do that mess.

use python-lambda

https://github.com/nficano/python-lambda

with single command pylambda deploy it will automatically deploy your function

What is the Swift equivalent of isEqualToString in Objective-C?

In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:

if username == "" || password == ""
{
    println("Sign in failed. Empty character")
}

Remove commas from the string using JavaScript

To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

How to center icon and text in a android button with width set to "fill parent"

My way of solving it involved surrounding the the button with lightweight <View ../> elements that resize dynamically. Below are several examples of what can be achieved with this:

Demo by Dev-iL

Note that the clickable area of the buttons in example 3 is the same as in 2 (i.e. with spaces), which is different from example 4 where there are no "unclickable" gaps in between.

Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="Example 1: Button with a background color:"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="20dp"
            android:paddingEnd="20dp"
            android:layout_weight="0.3"/>
        <!-- Play around with the above 3 values to modify the clickable 
             area and image alignment with respect to text -->
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
    </LinearLayout>

    <TextView
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="Example 2: Button group + transparent layout + spacers:"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
    </LinearLayout>

    <TextView
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="Example 3: Button group + colored layout:"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray">
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
    </LinearLayout>

    <TextView
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="Example 4 (reference): Button group + no spacers:"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/darker_gray">
        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>
        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textColor="@android:color/white"
            android:drawableLeft="@android:drawable/ic_secure"
            android:drawableStart="@android:drawable/ic_secure"
            android:background="@android:color/darker_gray"
            android:paddingStart="10dp"
            android:paddingEnd="10dp"
            android:layout_weight="1"/>   
    </LinearLayout>
</LinearLayout>

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How to provide animation when calling another activity in Android?

Wrote a tutorial so that you can animate your activity's in and out,

Enjoy:

http://blog.blundellapps.com/animate-an-activity/

RegEx for matching UK Postcodes

here's how we have been dealing with the UK postcode issue:

^([A-Za-z]{1,2}[0-9]{1,2}[A-Za-z]?[ ]?)([0-9]{1}[A-Za-z]{2})$

Explanation:

  • expect 1 or 2 a-z chars, upper or lower fine
  • expect 1 or 2 numbers
  • expect 0 or 1 a-z char, upper or lower fine
  • optional space allowed
  • expect 1 number
  • expect 2 a-z, upper or lower fine

This gets most formats, we then use the db to validate whether the postcode is actually real, this data is driven by openpoint https://www.ordnancesurvey.co.uk/opendatadownload/products.html

hope this helps

AngularJS - Passing data between pages

If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.

How to convert SQL Query result to PANDAS Data Structure?

Edit: Mar. 2015

As noted below, pandas now uses SQLAlchemy to both read from (read_sql) and insert into (to_sql) a database. The following should work

import pandas as pd

df = pd.read_sql(sql, cnxn)

Previous answer: Via mikebmassey from a similar question

import pyodbc
import pandas.io.sql as psql

cnxn = pyodbc.connect(connection_info) 
cursor = cnxn.cursor()
sql = "SELECT * FROM TABLE"

df = psql.frame_query(sql, cnxn)
cnxn.close()

Simple int to char[] conversion

main()
{
  int i = 247593;
  char str[10];

  sprintf(str, "%d", i);
// Now str contains the integer as characters
}

Hope it will be helpful to you.

How to change default format at created_at and updated_at value laravel

In laravel 6 the latest one can easily add in the "APP/user.php" model:

/**
 * The storage format of the model's date columns.
 *
 * @var string
 */
protected $dateFormat = 'U';

And in schema one can add

    $table->integer('created_at')->nullable();
    $table->integer('updated_at')->nullable();

Using the slash character in Git branch name

I could be wrong, but I thought that slashes only appeared in branch names when they related to a remote repo, for example origin/master.

How comment a JSP expression?

One of:

In html

<!-- map.size here because --> 
<%= map.size() %>

theoretically the following should work, but i never used it this way.

<%= map.size() // map.size here because %>

git: undo all working dir changes including new files

Safest method, which I use frequently:

git clean -fd

Syntax explanation as per /docs/git-clean page:

  • -f (alias: --force). If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f, -n or -i. Git will refuse to delete directories with .git sub directory or file unless a second -f is given.
  • -d. Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use -f option twice if you really want to remove such a directory.

As mentioned in the comments, it might be preferable to do a git clean -nd which does a dry run and tells you what would be deleted before actually deleting it.

Link to git clean doc page: https://git-scm.com/docs/git-clean

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

How do I run a Java program from the command line on Windows?

As of Java 9, the JDK includes jshell, a Java REPL.

Assuming the JDK 9+ bin directory is correctly added to your path, you will be able to simply:

  1. Run jshell File.javaFile.java being your file of course.
  2. A prompt will open, allowing you to call the main method: jshell> File.main(null).
  3. To close the prompt and end the JVM session, use /exit

Full documentation for JShell can be found here.

How to set Spinner default value to null?

Merge this:

private long previousItemId = 0;

@Override
public long getItemId(int position) {
    long nextItemId = random.nextInt(Integer.MAX_VALUE);
    while(previousItemId == nextItemId) {
        nextItemId = random.nextInt(Integer.MAX_VALUE);
    }
    previousItemId = nextItemId;
    return nextItemId;
}

With this answer:

public class SpinnerInteractionListener
        implements AdapterView.OnItemSelectedListener, View.OnTouchListener {

    private AdapterView.OnItemSelectedListener onItemSelectedListener;

    public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
        this.onItemSelectedListener = selectedListener;
    }

    boolean userSelect = false;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        userSelect = true;
        return false;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if(userSelect) {
            onItemSelectedListener.onItemSelected(parent, view, pos, id);
            userSelect = false;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        if(userSelect) {
            onItemSelectedListener.onNothingSelected(parent);
            userSelect = false;
        }
    }
}

Django. Override save for model

You may supply extra argument for confirming a new image is posted.
Something like:

def save(self, new_image=False, *args, **kwargs):
    if new_image:
        small=rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)
    super(Model, self).save(*args, **kwargs)

or pass request variable

def save(self, request=False, *args, **kwargs):
    if request and request.FILES.get('image',False):
        small=rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)
    super(Model, self).save(*args, **kwargs)

I think these wont break your save when called simply.

You may put this in your admin.py so that this work with admin site too (for second of above solutions):

class ModelAdmin(admin.ModelAdmin):

    ....
    def save_model(self, request, obj, form, change): 
        instance = form.save(commit=False)
        instance.save(request=request)
        return instance

How long do browsers cache HTTP 301s?

I will post answer that helped me:

go to url:

chrome://settings/clearBrowserData

it should invoke popup and then..

  • select only: cached images and files.
  • select time box : from beginning

"cannot be used as a function error"

You can't pass a function as a parameter. Simply remove it from estimatedPopulation() and replace it with 'float growthRate'. use this in your calculation instead of calling the function:

int estimatedPopulation (int currentPopulation, float growthRate)
{
    return (currentPopulation + currentPopulation * growthRate / 100);
}

and call it as:

int foo = estimatedPopulation (currentPopulation, growthRate (birthRate, deathRate));

java.net.SocketTimeoutException: Read timed out under Tomcat

I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works. If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.

Mac 11.1 appears to be interfering with Tomcat.

As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.

Spent several days trying to figure this out, but cannot resolve.

Suggestions very welcome! :)

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

How can I disable all views inside the layout?

Set

android:descendantFocusability="blocksDescendants"

for yor ViewGroup view. All descendants will not take focus.

How to pass an array within a query string?

Although there isn't a standard on the URL part, there is one standard for JavaScript. If you pass objects containing arrays to URLSearchParams, and call toString() on it, it will transform it into a comma separated list of items:

let data = {
  str: 'abc',
  arr: ['abc', 123]
}

new URLSearchParams(data).toString();
// ?str=abc&arr=abc,123 (with escaped characters)

Fetch: reject promise and catch the error if status is not OK?

I just checked the status of the response object:

$promise.then( function successCallback(response) {  
  console.log(response);
  if (response.status === 200) { ... }
});

How do I write a custom init for a UIView subclass in Swift?

The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:) version will be called. Since Swift now requires an implementation of the required init?(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time.

class TestView : UIView {
    var s: String?
    var i: Int?
    init(s: String, i: Int) {
        self.s = s
        self.i = i
        super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

How much does it cost to develop an iPhone application?

The Barack Obama app took 22 days to develop from first code to release. Three developers (although not all of them were full time). 10 people total. Figure 500-1000 man hours. Contracting rates are $100-150/hr. Figure $50000-$150000. Compare your app to Obama.app and scale accordingly.

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

Running Selenium WebDriver python bindings in chrome

Mac OSX only

An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:

brew install chromedriver

That should put the chromedriver in your path and you should be all set.

How to initialize a dict with keys from a list and empty value in Python?

nobody cared to give a dict-comprehension solution ?

>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}

Using OR operator in a jquery if statement

The logical OR '||' automatically short circuits if it meets a true condition once.

false || false || true || false = true, stops at second condition.

On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.

false && true && true && true = false, stops at first condition.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

How to add "class" to host element?

Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...

If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do:

@Component({
   selector: 'my-component',
   template: 'app-element',
   host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}

And if you use a class on the entry tag, Angular will merge the classes, i.e.,

<my-component class="someClass2">
  I have both someClass1 & someClass2 applied to me
</my-component>

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

JavaScript - Get minutes between two dates

var startTime = new Date('2012/10/09 12:00'); 
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);

How to include route handlers in multiple files in Express?

If you want a separate .js file to better organize your routes, just create a variable in the app.js file pointing to its location in the filesystem:

var wf = require(./routes/wf);

then,

app.get('/wf', wf.foo );

where .foo is some function declared in your wf.js file. e.g

// wf.js file 
exports.foo = function(req,res){

          console.log(` request object is ${req}, response object is ${res} `);

}

How do I get the XML SOAP request of an WCF Web service request?

I think you meant that you want to see the XML at the client, not trace it at the server. In that case, your answer is in the question I linked above, and also at How to Inspect or Modify Messages on the Client. But, since the .NET 4 version of that article is missing its C#, and the .NET 3.5 example has some confusion (if not a bug) in it, here it is expanded for your purpose.

You can intercept the message before it goes out using an IClientMessageInspector:

using System.ServiceModel.Dispatcher;
public class MyMessageInspector : IClientMessageInspector
{ }

The methods in that interface, BeforeSendRequest and AfterReceiveReply, give you access to the request and reply. To use the inspector, you need to add it to an IEndpointBehavior:

using System.ServiceModel.Description;
public class InspectorBehavior : IEndpointBehavior
{
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }
}

You can leave the other methods of that interface as empty implementations, unless you want to use their functionality, too. Read the how-to for more details.

After you instantiate the client, add the behavior to the endpoint. Using default names from the sample WCF project:

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.Endpoint.Behaviors.Add(new InspectorBehavior());
client.GetData(123);

Set a breakpoint in MyMessageInspector.BeforeSendRequest(); request.ToString() is overloaded to show the XML.

If you are going to manipulate the messages at all, you have to work on a copy of the message. See Using the Message Class for details.

Thanks to Zach Bonham's answer at another question for finding these links.

Limit the height of a responsive image with css

I set the below 3 styles to my img tag

max-height: 500px;
height: 70%;
width: auto;

What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

It also works width property.

javascript window.location in new tab

with jQuery its even easier and works on Chrome as well

$('#your-button').on('click', function(){
       $('<a href="https://www.some-page.com" target="blank"></a>')[0].click();    
})

Twitter Bootstrap - borders

If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.

For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:

.row {
    zoom: 1;
    margin-left: -20px;
}

.row > [class*="span"] {
    display: inline;
    float: left;
    margin-left: 20px;
}

.span4 {
    width: 220px;
}

To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).

Screenshot of Example Page

For example, to allow for the left border on the sidebar, they added this CSS in the <head> after the the main <link href="../bootstrap.css" rel="stylesheet">.

.content .span4 {
    margin-left: 0;
    padding-left: 19px;
    border-left: 1px solid #eee;
}

You'll see they've reduced padding-left by 1px to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.

I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

Might help some else - I came here because I missed putting two // after http:. This is what I had:

http:/abc.my.domain.com:55555/update

How to add a form load event (currently not working)

Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load from the dropdown.

A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);

A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error() needs you to pass the connection to the database as a parameter. Documentation here has some helpful examples:

http://php.net/manual/en/mysqli.error.php

Try altering your problem line like so and you should be in good shape:

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error($myConnection)); 

Using an array as needles in strpos

@Dave an updated snippet from http://www.php.net/manual/en/function.strpos.php#107351

function strposa($haystack, $needles=array(), $offset=0) {
        $chr = array();
        foreach($needles as $needle) {
                $res = strpos($haystack, $needle, $offset);
                if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
}

How to use:

$string = 'Whis string contains word "cheese" and "tea".';
$array  = array('burger', 'melon', 'cheese', 'milk');

if (strposa($string, $array, 1)) {
    echo 'true';
} else {
    echo 'false';
}

will return true, because of array "cheese".

Update: Improved code with stop when the first of the needles is found:

function strposa($haystack, $needle, $offset=0) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $query) {
        if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
    }
    return false;
}
$string = 'Whis string contains word "cheese" and "tea".';
$array  = array('burger', 'melon', 'cheese', 'milk');
var_dump(strposa($string, $array)); // will return true, since "cheese" has been found

Determine version of Entity Framework I am using?

In Solution Explorer Under Project Click on Dependencies->NuGet->Microsoft.NetCore.All-> Here list of all Microsoft .NetCore pakcages will appear. Search for Microsoft.EntityFrameworkCore(2.0.3) in bracket version can be seen Like this

After finding package

Fundamental difference between Hashing and Encryption algorithms

Basic overview of hashing and encryption/decryption techniques are.

Hashing:

If you hash any plain text again you can not get the same plain text from hashed text. Simply, It's a one-way process.

hashing


Encryption and Decryption:

If you encrypt any plain text with a key again you can get same plain text by doing decryption on encrypted text with same(symetric)/diffrent(asymentric) key.

encryption and decryption


UPDATE: To address the points mentioned in the edited question.

1. When to use hashes vs encryptions

Hashing is useful if you want to send someone a file. But you are afraid that someone else might intercept the file and change it. So a way that the recipient can make sure that it is the right file is if you post the hash value publicly. That way the recipient can compute the hash value of the file received and check that it matches the hash value.

Encryption is good if you say have a message to send to someone. You encrypt the message with a key and the recipient decrypts with the same (or maybe even a different) key to get back the original message. credits


2. What makes a hash or encryption algorithm different (from a theoretical/mathematical level) i.e. what makes hashes irreversible (without aid of a rainbow tree)

Basically hashing is an operation that loses information but not encryption. Let's look at the difference in simple mathematical way for our easy understanding, of course both have much more complicated mathematical operation with repetitions involved in it

Encryption/Decryption (Reversible):


Addition:

4 + 3 = 7  

This can be reversed by taking the sum and subtracting one of the addends

7 - 3 = 4     

Multiplication:

4 * 5 = 20  

This can be reversed by taking the product and dividing by one of the factors

20 / 4 = 5    

So, here we could assume one of the addends/factors is a decrpytion key and result(7,20) is an excrypted text.


Hashing (Not Reversible):


Modulo division:

22 % 7 = 1   

This can not be reversed because there is no operation that you can do to the quotient and the dividend to reconstitute the divisor (or vice versa).

Can you find an operation to fill in where the '?' is?

1  ?  7 = 22  
1  ?  22 = 7

So hash functions have the same mathematical quality as modulo division and looses the information.

credits

To get total number of columns in a table in sql

Correction to top query above, to allow to run from any database

SELECT COUNT(COLUMN_NAME) FROM [*database*].INFORMATION_SCHEMA.COLUMNS WHERE 
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'

Java - remove last known item from ArrayList

clients.get will return a ClientThread and not a String, and it will bomb with an IndexOutOfBoundsException if it would compile as Java is zero based for indexing.

Similarly I think you should call remove on the clients list.

ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());

I would use the stack functions of a LinkedList in this case though.

ClientThread hey = clients.removeLast()

Parameter in like clause JPQL

I don't know if I am late or out of scope but in my opinion I could do it like:

String orgName = "anyParamValue";

Query q = em.createQuery("Select O from Organization O where O.orgName LIKE '%:orgName%'");

q.setParameter("orgName", orgName);

How to get folder path from file path with CMD

The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:

@echo off
setlocal enabledelayedexpansion enableextensions

set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof

:file_name_from_path <resultVar> <pathVar>
(
    set "%~1=%~nx2"
    exit /b
)

:eof
endlocal

Now the :file_name_from_path function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.

Callback when DOM is loaded in react.js

I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.

eg:

componentDidUpdate: function() {
        $(".tbl-tr").height($(".tbl-tr ").height());
    }

Send Message in C#

You are almost there. (note change in the return value of FindWindow declaration). I'd recommend using RegisterWindowMessage in this case so you don't have to worry about the ins and outs of WM_USER.

[DllImport("user32.dll")]    
public static extern IntPtr FindWindow(string lpClassName, String lpWindowName);    
[DllImport("user32.dll")]    
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);    
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);

public void button1_Click(object sender, EventArgs e)   
{        
     // this would likely go in a constructor because you only need to call it 
     // once per process to get the id - multiple calls in the same instance 
     // of a windows session return the same value for a given string
     uint id = RegisterWindowMessage("MyUniqueMessageIdentifier");
     IntPtr WindowToFind = FindWindow(null, "Form1");    
     Debug.Assert(WindowToFind != IntPtr.Zero);
     SendMessage(WindowToFind, id, IntPtr.Zero, IntPtr.Zero);
}

And then in your Form1 class:

class Form1 : Form
{
    [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
    static extern uint RegisterWindowMessage(string lpString);

    private uint _messageId = RegisterWindowMessage("MyUniqueMessageIdentifier");

    protected override void WndProc(ref Message m)
    {
       if (m.Msg == _messageId)
       {
           // do stuff

       }
       base.WndProc(ref m);
    }
}

Bear in mind I haven't compiled any of the above so some tweaking may be necessary. Also bear in mind that other answers warning you away from SendMessage are spot on. It's not the preferred way of inter module communication nowadays and genrally speaking overriding the WndProc and using SendMessage/PostMessage implies a good understanding of how the Win32 message infrastructure works.

But if you want/need to go this route I think the above will get you going in the right direction.

Create Elasticsearch curl query for not null and not empty("")

On elasticsearch 5.6, I have to use command below to filter out empty string:

    GET /_search
    {
        "query" : {
            "regexp":{
                "<your_field_name_here>": ".+"
            }
        }
    }  

Access mysql remote database from command line

This one worked for me in mysql 8, replace hostname with your hostname and port_number with your port_number, you can also change your mysql_user if he is not root

      mysql --host=host_name --port=port_number -u root -p

Further Information Here

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

This is the normal behavior and the reason is that your sqlCommandHandlerService.persist method needs a TX when being executed (because it is marked with @Transactional annotation). But when it is called inside processNextRegistrationMessage, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist method, it causes TX to be set to rollBackOnly (even if you catch the exception in the caller and ignore it).

To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.

Update; Read this!

Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.


EDIT Link to current version of the documentation

How to redirect output of systemd service to a file

If for a some reason can't use rsyslog, this will do: ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"

Check existence of directory and create if doesn't exist

The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.

I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".

Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.

So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).

The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:

mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"

options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")

if (!file_test("-d", file.path(mainDir, subDir)){
  if(file_test("-f", file.path(mainDir, subDir)) {
    stop("Path can't be created because a file with that name already exists.")
  } else {
    dir.create(file.path(mainDir, subDir))
  }
}

Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:

mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))

This solution leaves the working directory under the control of the user.

How to remove all CSS classes using jQuery/JavaScript?

Heh, came searching for a similar answer. Then it hit me.

Remove Specific Classes

$('.class').removeClass('class');

Say if element has class="class another-class"

Using Apache POI how to read a specific excel column

  Sheet sheet  = workBook.getSheetAt(0); // Get Your Sheet.

  for (Row row : sheet) { // For each Row.
      Cell cell = row.getCell(0); // Get the Cell at the Index / Column you want.
  }

My solution, a bit simpler code wise.

How to upload images into MySQL database using PHP code

This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

No Activity found to handle Intent : android.intent.action.VIEW

Check this useful method:

URLUtil.guessUrl(urlString)

It makes google.com -> http://google.com

How to convert a DataFrame back to normal RDD in pyspark?

Use the method .rdd like this:

rdd = df.rdd

Deserialize a json string to an object in python

Another way is to simply pass the json string as a dict to the constructor of your object. For example your object is:

class Payload(object):
    def __init__(self, action, method, data, *args, **kwargs):
        self.action = action
        self.method = method
        self.data = data

And the following two lines of python code will construct it:

j = json.loads(yourJsonString)
payload = Payload(**j)

Basically, we first create a generic json object from the json string. Then, we pass the generic json object as a dict to the constructor of the Payload class. The constructor of Payload class interprets the dict as keyword arguments and sets all the appropriate fields.

How to Create simple drag and Drop in angularjs

Modified from the angular-drag-and-drop-lists examples page

Markup

<div class="row">
    <div ng-repeat="(listName, list) in models.lists" class="col-md-6">
        <ul dnd-list="list">
            <li ng-repeat="item in list" 
                dnd-draggable="item" 
                dnd-moved="list.splice($index, 1)" 
                dnd-effect-allowed="move" 
                dnd-selected="models.selected = item" 
                ng-class="{'selected': models.selected === item}" 
                draggable="true">{{item.label}}</li>
        </ul>
    </div>
</div>

Angular

var app = angular.module('angular-starter', [
    'ui.router',
    'dndLists'
]);

app.controller('MainCtrl', function($scope){

    $scope.models = {
        selected: null,
        lists: {"A": [], "B": []}
    };

    // Generate initial model
    for (var i = 1; i <= 3; ++i) {
        $scope.models.lists.A.push({label: "Item A" + i});
        $scope.models.lists.B.push({label: "Item B" + i});
    }

    // Model to JSON for demo purpose
    $scope.$watch('models', function(model) {
        $scope.modelAsJson = angular.toJson(model, true);
    }, true);
});

Library can be installed via bower or npm: angular-drag-and-drop-lists

Characters allowed in a URL

If you like to give a special kind of experience to the users you could use pushState to bring a wide range of characters to the browser's url:

enter image description here

var u="";var tt=168;
for(var i=0; i< 250;i++){
 var x = i+250*tt;
console.log(x);
 var c = String.fromCharCode(x);
 u+=c; 
}
history.pushState({},"",250*tt+u);

How to keep the console window open in Visual C++?

Simply add a Breakpoint to the closing bracket of your _tmain method. This is the easier way plus you don't have to add code in order to debug.

How to print to console using swift playground?

Just Press Alt + Command + Enter to open the Assistant editor. Assistant Editor will open up the Timeline view. Timeline by default shows your console output.

Additionally You can add any line to Timeline view by pressing the small circle next to the eye icon in the results area. This will enable history for this expression. So you can see the output of the variable over last 30 secs (you can change this as well) of execution.

How to play a sound using Swift?

Swift 4, 4.2 and 5

Play audio from URL and from your project (Local File)

import UIKit
import AVFoundation

class ViewController: UIViewController{

var audioPlayer : AVPlayer!

override func viewDidLoad() {
        super.viewDidLoad()
// call what ever function you want.
    }

    private func playAudioFromURL() {
        guard let url = URL(string: "https://geekanddummy.com/wp-content/uploads/2014/01/coin-spin-light.mp3") else {
            print("error to get the mp3 file")
            return
        }
        do {
            audioPlayer = try AVPlayer(url: url as URL)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

    private func playAudioFromProject() {
        guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else {
            print("error to get the mp3 file")
            return
        }

        do {
            audioPlayer = try AVPlayer(url: url)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

}

MySQL - UPDATE multiple rows with different values in one query

update table_name
set cod_user = 
    CASE 
    WHEN user_rol = 'student' THEN '622057'
    WHEN user_rol = 'assistant' THEN '2913659'
    WHEN user_rol = 'admin' THEN '6160230'?
    END,date = '12082014'

WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

If none of these works, please check this answer:

https://stackoverflow.com/a/12011221/150370

(TL;DR: Remove xml namespace from configuration tag in your config file. Otherwise binding redirects will be ignored)

How to Select Every Row Where Column Value is NOT Distinct

select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1

iOS change navigation bar title font and color

Anyone needs a Swift 3 version. redColor() has changed to just red.

self.navigationController?.navigationBar.titleTextAttributes =
        [NSForegroundColorAttributeName: UIColor.red,
         NSFontAttributeName: UIFont(name: "{your-font-name}", size: 21)!]

Angular 2 - Setting selected value on dropdown list

Angular 2 simple dropdown selected value

It may help someone as I need to only show selected value, don't need to declare something in component and etc.

If your status is coming from the database then you can show selected value this way.

<div class="form-group">
    <label for="status">Status</label>
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>
</div>

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

How does the stack work in assembly language?

You confuse an abstract stack and the hardware implemented stack. The latter is already implemented.

How to rebuild docker container in docker-compose.yml?

With docker-compose 1.19 up

docker-compose up --build --force-recreate --no-deps [-d] [<service_name>..]

Without one or more service_name arguments all images will be built if missing and all containers will be recreated.

From the help menu

Options:
    -d, --detach        Detached mode: Run containers in the background,
                        print new container names. Incompatible with
                        --abort-on-container-exit.
    --no-deps           Don't start linked services.
    --force-recreate    Recreate containers even if their configuration
                        and image haven't changed.
    --build             Build images before starting containers.

Without cache

To force a rebuild to ignore cached layers, we have to first build a new image

docker-compose build --no-cache [<service_name>..]

From the help menu

Options:
    --force-rm              Always remove intermediate containers.
    -m, --memory MEM        Set memory limit for the build container.
    --no-cache              Do not use cache when building the image.
    --no-rm                 Do not remove intermediate containers after a successful build.

Then recreate the container

docker-compose up --force-recreate --no-deps [-d] [<service_name>..]

Can't update: no tracked branch

I have faced The same problem So I used the Git directly to push the project to GitHub.

In your android studio

Go to VCS=>Git=> Push: use the Branch Name You Commit and hit Push Button

Note: tested for android studio version 3.3

How to handle static content in Spring MVC?

There's another stack overflow post that has an excellent solution.

It doesn't seem to be Tomcat specific, is simple, and works great. I've tried a couple of the solutions in this post with spring mvc 3.1 but then had problems getting my dynamic content served.

In brief, it says add a servlet mapping like this:

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>

[ :Unexpected operator in shell programming

you can use case/esac instead of if/else

case "$choose" in
  [yY]) echo "Yes" && exit;;
  [nN]) echo "No" && exit;;
  * ) echo "wrong input" && exit;;
esac

Flask raises TemplateNotFound error even though template file exists

Check that:

  1. the template file has the right name
  2. the template file is in a subdirectory called templates
  3. the name you pass to render_template is relative to the template directory (index.html would be directly in the templates directory, auth/login.html would be under the auth directory in the templates directory.)
  4. you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.

If that doesn't work, turn on debugging (app.debug = True) which might help figure out what's wrong.

Using CMake with GNU Make: How can I see the exact commands?

cmake --build . --verbose

On Linux and with Makefile generation, this is likely just calling make VERBOSE=1 under the hood, but cmake --build can be more portable for your build system, e.g. working across OSes or if you decide to do e.g. Ninja builds later on:

mkdir build
cd build
cmake ..
cmake --build . --verbose

Its documentation also suggests that it is equivalent to VERBOSE=1:

--verbose, -v

Enable verbose output - if supported - including the build commands to be executed.

This option can be omitted if VERBOSE environment variable or CMAKE_VERBOSE_MAKEFILE cached variable is set.

How do I Sort a Multidimensional Array in PHP

You can use array_multisort()

Try something like this:

foreach ($mdarray as $key => $row) {
    // replace 0 with the field's index/key
    $dates[$key]  = $row[0];
}

array_multisort($dates, SORT_DESC, $mdarray);

For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:

array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

std::string formatting like sprintf

You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string:

  char buff[100];
  snprintf(buff, sizeof(buff), "%s", "Hello");
  std::string buffAsStdStr = buff;

But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this:

  std::ostringstream stringStream;
  stringStream << "Hello";
  std::string copyOfStr = stringStream.str();

Share data between AngularJS controllers

A simple solution is to have your factory return an object and let your controllers work with a reference to the same object:

JS:

// declare the app with no dependencies
var myApp = angular.module('myApp', []);

// Create the factory that share the Fact
myApp.factory('Fact', function(){
  return { Field: '' };
});

// Two controllers sharing an object that has a string in it
myApp.controller('FirstCtrl', function( $scope, Fact ){
  $scope.Alpha = Fact;
});

myApp.controller('SecondCtrl', function( $scope, Fact ){
  $scope.Beta = Fact;
});

HTML:

<div ng-controller="FirstCtrl">
    <input type="text" ng-model="Alpha.Field">
    First {{Alpha.Field}}
</div>

<div ng-controller="SecondCtrl">
<input type="text" ng-model="Beta.Field">
    Second {{Beta.Field}}
</div>

Demo: http://jsfiddle.net/HEdJF/

When applications get larger, more complex and harder to test you might not want to expose the entire object from the factory this way, but instead give limited access for example via getters and setters:

myApp.factory('Data', function () {

    var data = {
        FirstName: ''
    };

    return {
        getFirstName: function () {
            return data.FirstName;
        },
        setFirstName: function (firstName) {
            data.FirstName = firstName;
        }
    };
});

With this approach it is up to the consuming controllers to update the factory with new values, and to watch for changes to get them:

myApp.controller('FirstCtrl', function ($scope, Data) {

    $scope.firstName = '';

    $scope.$watch('firstName', function (newValue, oldValue) {
        if (newValue !== oldValue) Data.setFirstName(newValue);
    });
});

myApp.controller('SecondCtrl', function ($scope, Data) {

    $scope.$watch(function () { return Data.getFirstName(); }, function (newValue, oldValue) {
        if (newValue !== oldValue) $scope.firstName = newValue;
    });
});

HTML:

<div ng-controller="FirstCtrl">
  <input type="text" ng-model="firstName">
  <br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
  Input should also be here: {{firstName}}
</div>

Demo: http://jsfiddle.net/27mk1n1o/

In Spring MVC, how can I set the mime type header when using @ResponseBody

You may not be able to do it with @ResponseBody, but something like this should work:

package xxx;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class FooBar {
  @RequestMapping(value="foo/bar", method = RequestMethod.GET)
  public void fooBar(HttpServletResponse response) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(myService.getJson().getBytes());
    response.setContentType("application/json");
    response.setContentLength(out.size());
    response.getOutputStream().write(out.toByteArray());
    response.getOutputStream().flush();
  }
}

How to get UTC value for SYSDATE on Oracle

If you want a timestamp instead of just a date with sysdate, you can specify a timezone using systimestamp:

select systimestamp at time zone 'UTC' from dual

outputs: 29-AUG-17 06.51.14.781998000 PM UTC

console.log timestamps in Chrome?

You can use dev tools profiler.

console.time('Timer name');
//do critical time stuff
console.timeEnd('Timer name');

"Timer name" must be the same. You can use multiple instances of timer with different names.

Unable to create migrations after upgrading to ASP.NET Core 2.0

If you want to avoid those IDesignTimeDbContextFactory thing: Just make sure that you don't use any Seed method in your startup. I was using a static seed method in my startup and it was causing this error for me.

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

Java 8 lambdas, Function.identity() or t->t

In your example there is no big difference between str -> str and Function.identity() since internally it is simply t->t.

But sometimes we can't use Function.identity because we can't use a Function. Take a look here:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

this will compile fine

int[] arrayOK = list.stream().mapToInt(i -> i).toArray();

but if you try to compile

int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();

you will get compilation error since mapToInt expects ToIntFunction, which is not related to Function. Also ToIntFunction doesn't have identity() method.

Can a CSS class inherit one or more other classes?

While direct inheritance isn't possible.

It is possible to use a class (or id) for a parent tag and then use CSS combinators to alter child tag behaviour from it's heirarchy.

_x000D_
_x000D_
p.test{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}_x000D_
p.test > span > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
_x000D_
<p class="test"><span>One <span>possible <span>solution <span>is <span>using <span>multiple <span>nested <span>tags</span></span></span></span></span></span></span></span></p>
_x000D_
_x000D_
_x000D_

I wouldn't suggest using so many spans like the example, however it's just a proof of concept. There are still many bugs that can arise when trying to apply CSS in this manner. (For example altering text-decoration types).

How can I resize an image dynamically with CSS as the browser width/height changes?

Are you using jQuery?

Because I did a quickly search on the jQuery plugings and they seem to have some plugin to do this, check this one, should work:

http://plugins.jquery.com/project/jquery-afterresize

EDIT:

This is the CSS solution, I just add a style="width: 100%", and works for me at least in chrome and Safari. I dont have ie, so just test there, and let me know, here is the code:

            <div id="gallery" style="width: 100%">
                <img src="images/fullsize.jpg" alt="" id="fullsize" />
                <a href="#" id="prev">prev</a>
                <a href="#" id="next">next</a>
            </div>

How to calculate distance between two locations using their longitude and latitude value

You should use Haversine Distance Formulas

Haversine Formulas used to calculate the great distance between two points on the earth.

    public void haversine(double lat1, double lon1, double lat2, double lon2) {
 double Rad = 6372.8; //Earth's Radius In kilometers
            // TODO Auto-generated method stub
            double dLat = Math.toRadians(lat2 - lat1);
            double dLon = Math.toRadians(lon2 - lon1);
            lat1 = Math.toRadians(lat1);
            lat2 = Math.toRadians(lat2);
            double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
            double c = 2 * Math.asin(Math.sqrt(a));
            haverdistanceKM = Rad * c;

        }

SSH to Vagrant box in Windows?

Windows 7 ( not tested on other versions )

  1. Right Click on "My Computer" and click properties
  2. Click Advanced System Settings
  3. Click Environment Variables
  4. In second box under "System Variables" scroll down and click on variable "Path" and click EDIT
  5. Make sure the path is included in the Variable Value by appending (a semicolon if it's not there and) C:\Program Files (x86)\Git\bin; ( or whatever is the path to your ssh.exe )
  6. OK > OK > OK and RESTART WINDOWS
  7. You'll have to run vagrant up but after that vagrant ssh should work permanently

More Info which might help with other versions ... http://www.computerhope.com/issues/ch000549.htm

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

I realize this question is over a year old, but I just stumbled across it in dealing with a similar problem and thought I would share another potential solution in case it might help a future traveler (or myself, when I forget this later and find myself flopping around on StackOverflow between screams and throwings of the nearest object on my desk).

In my case I was able to get the effect I wanted by using a DataGridTemplateColumn instead of a DataGridComboBoxColumn, a la the following snippet. [caveat: I'm using .NET 4.0, and what I've been reading leads me to believe the DataGrid has done a lot of evolving, so YMMV if using earlier version]

<DataGridTemplateColumn Header="Identifier_TEMPLATED">
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox IsEditable="False" 
                Text="{Binding ComponentIdentifier,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                ItemsSource="{Binding Path=ApplicableIdentifiers, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ComponentIdentifier}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

How to set my default shell on Mac?

The only thing that worked for me was a combination of all these methods.

  1. First I had to add fish to the /etc/shells file

  2. Then I ran chsh -s /usr/local/bin/fish

  3. Finally, I typed Command+, and added /usr/local/bin/fish to the default path there

Only after I had done all three things did fish start popping up as the default for new terminal windows.

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

How to update std::map after using the find method?

You can use std::map::at member function, it returns a reference to the mapped value of the element identified with key k.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

Blur or dim background when Android PopupWindow active

I've found a solution for this

Create a custom transparent dialog and inside that dialog open the popup window:

dialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
emptyDialog = LayoutInflater.from(context).inflate(R.layout.empty, null);

/* blur background*/
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();  
lp.dimAmount=0.0f;  
dialog.getWindow().setAttributes(lp);  
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); 
dialog.setContentView(emptyDialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnShowListener(new OnShowListener()
{
    @Override
    public void onShow(DialogInterface dialogIx)
    {
        mQuickAction.show(emptyDialog); //open the PopupWindow here
    }
});
dialog.show();

xml for the dialog(R.layout.empty):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="match_parent" android:layout_width="match_parent"
     style="@android:style/Theme.Translucent.NoTitleBar" />

now you want to dismiss the dialog when Popup window dismisses. so

mQuickAction.setOnDismissListener(new OnDismissListener()
{
    @Override
    public void onDismiss()
    {
        if(dialog!=null)
        {
            dialog.dismiss(); // dismiss the empty dialog when the PopupWindow closes
            dialog = null;
        }
    }
});

Note: I've used NewQuickAction plugin for creating PopupWindow here. It can also be done on native Popup Windows

Event detect when css property changed using Jquery

For properties for which css transition will affect, can use transitionend event, example for z-index:

_x000D_
_x000D_
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {_x000D_
  console.log("end", e);_x000D_
  alert("z-index changed");_x000D_
});_x000D_
_x000D_
$(".changeButton").on("click", function() {_x000D_
  console.log("click");_x000D_
  document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;_x000D_
});
_x000D_
.observed-element {_x000D_
  transition: z-index 1ms;_x000D_
  -webkit-transition: z-index 1ms;_x000D_
}_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
  position: absolute;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button class="changeButton">change z-index</button>_x000D_
<div class="observed-element"></div>
_x000D_
_x000D_
_x000D_

git pull keeping local changes

If you have a file in your repo that it is supposed to be customized by most pullers, then rename the file to something like config.php.template and add config.php to your .gitignore.

'any' vs 'Object'

Bit old, but doesn't hurt to add some notes.

When you write something like this

let a: any;
let b: Object;
let c: {};
  • a has no interface, it can be anything, the compiler knows nothing about its members so no type checking is performed when accessing/assigning both to it and its members. Basically, you're telling the compiler to "back off, I know what I'm doing, so just trust me";
  • b has the Object interface, so ONLY the members defined in that interface are available for b. It's still JavaScript, so everything extends Object;
  • c extends Object, like anything else in TypeScript, but adds no members. Since type compatibility in TypeScript is based on structural subtyping, not nominal subtyping, c ends up being the same as b because they have the same interface: the Object interface.

And that's why

a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object

and why

a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object

So Object and {} are equivalents in TypeScript.

If you declare functions like these

function fa(param: any): void {}
function fb(param: Object): void {}

with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that

  • inside fa, the compiler will let you do whatever you want with param;
  • inside fb, the compiler will only let you reference Object's members.

It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in

function fc(param: string|number): void {}

Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in

interface IPerson {
    gender: string;
}

class Person implements IPerson {
    gender: string;
}

class Teacher extends Person {}

function func(person: IPerson): void {
    console.log(person.gender);
}

func(new Person());     // Ok
func(new Teacher());    // Ok
func({gender: 'male'}); // Ok
func({name: 'male'});   // Error: no gender..

the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.

UPDATE:

Typescript 2.2 added an object type, which specifies that a value is a non-primitive: (i.e. not a number, string, boolean, symbol, undefined, or null).

Consider functions defined as:

function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}

x will have the same available properties within all of these functions, but it's a type error to call d with a primitive:

b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive

how to get the host url using javascript from the current page

// will return the host name and port
var host = window.location.host; 

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

If you have or expect custom ports use window.location.host instead of window.location.hostname

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

Refresh (reload) a page once using jQuery?

Add this to the top of your file and the site will refresh every 30 seconds.

<script type="text/javascript">
    window.onload = Refresh;

    function Refresh() {
        setTimeout("refreshPage();", 30000);
    }
    function refreshPage() {
        window.location = location.href;
    }
</script>

Another one is: Add in the head tag

<meta http-equiv="refresh" content="30">

Regex to match URL end-of-line or "/" character

In Ruby and Bash, you can use $ inside parentheses.

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|$)

(This solution is similar to Pete Boughton's, but preserves the usage of $, which means end of line, rather than using \z, which means end of string.)

Is there an equivalent method to C's scanf in Java?

You can format your output in Java as described in below code snippet.

public class TestFormat {

    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"
   }
}

You can read more here.

mysql alphabetical order

You can use:

SELECT name FROM user WHERE name like 'b%' ORDER BY name

Create an empty data.frame

Say your column names are dynamic, you can create an empty row-named matrix and transform it to a data frame.

nms <- sample(LETTERS,sample(1:10))
as.data.frame(t(matrix(nrow=length(nms),ncol=0,dimnames=list(nms))))

PHP fopen() Error: failed to open stream: Permission denied

[function.fopen]: failed to open stream

If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :

allow_url_fopen = off
should bee this 
allow_url_fopen = On

And add this line below it:
allow_url_include = off
should bee this 
allow_url_include = on

How to re-enable right click so that I can inspect HTML elements in Chrome?

Open inspect mode before navigating to the page. It worked.hehe

How to create full path with node's fs.mkdirSync?

I solved the problem this way - similar to other recursive answers but to me this is much easier to understand and read.

const path = require('path');
const fs = require('fs');

function mkdirRecurse(inputPath) {
  if (fs.existsSync(inputPath)) {
    return;
  }
  const basePath = path.dirname(inputPath);
  if (fs.existsSync(basePath)) {
    fs.mkdirSync(inputPath);
  }
  mkdirRecurse(basePath);
}

How to delete the last row of data of a pandas dataframe

stats = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv")

The Output of stats:

       A            B          C
0   0.120064    0.785538    0.465853
1   0.431655    0.436866    0.640136
2   0.445904    0.311565    0.934073
3   0.981609    0.695210    0.911697
4   0.008632    0.629269    0.226454
5   0.577577    0.467475    0.510031
6   0.580909    0.232846    0.271254
7   0.696596    0.362825    0.556433
8   0.738912    0.932779    0.029723
9   0.834706    0.002989    0.333436

just use skipfooter=1

skipfooter : int, default 0

Number of lines at bottom of file to skip

stats_2 = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv", skipfooter=1, engine='python')

Output of stats_2

       A          B            C
0   0.120064    0.785538    0.465853
1   0.431655    0.436866    0.640136
2   0.445904    0.311565    0.934073
3   0.981609    0.695210    0.911697
4   0.008632    0.629269    0.226454
5   0.577577    0.467475    0.510031
6   0.580909    0.232846    0.271254
7   0.696596    0.362825    0.556433
8   0.738912    0.932779    0.029723

The view or its master was not found or no view engine supports the searched locations

Check the build action of your view (.cshtml file) It should be set to content. In some cases, I have seen that the build action was set to None (by mistake) and this particular view was not deploy on the target machine even though you see that view present in visual studio project file under valid folder

Installing TensorFlow on Windows (Python 3.6.x)

Just found Tensorflow 1.1 for python 3.6 on windows x64 (including GPU version, but i tested only cpu): http://www.lfd.uci.edu/~gohlke/pythonlibs/#tensorflow. Unofficial apparently, but worked for me when I import tensorflow or tflearn in my code. They have scipy for windows there and bunch of other packages.

For some reason pip install URL returns code 404, so the installation would be the following:

1) Download protobuf whl package from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/vu0h7y4r/protobuf-3.3.0-py3-none-any.whl

2) pip install {DownloadFolder}\protobuf-3.3.0-py3-none-any.whl

3) Download TF whl file: http://www.lfd.uci.edu/~gohlke/pythonlibs/vu0h7y4r/tensorflow-1.1.0-cp36-cp36m-win_amd64.whl

4) pip install {DownloadFolder}\tensorflow-1.1.0-cp36-cp36m-win_amd64.whl

It worked for me.

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

What is a method group in C#?

The first result in your MSDN search said:

The method group identifies the one method to invoke or the set of overloaded methods from which to choose a specific method to invoke

my understanding is that basically because when you just write someInteger.ToString, it may refer to:

Int32.ToString(IFormatProvider) 

or it can refer to:

Int32.ToString()

so it is called a method group.

Composer: how can I install another dependency without updating old ones?

To install a new package and only that, you have two options:

  1. Using the require command, just run:

    composer require new/package
    

    Composer will guess the best version constraint to use, install the package, and add it to composer.lock.

    You can also specify an explicit version constraint by running:

    composer require new/package ~2.5
    

–OR–

  1. Using the update command, add the new package manually to composer.json, then run:

    composer update new/package
    

If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).

Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m doesn't list mcrypt then it's missing.

Important: Don't forget to specify new/package when using composer update! Omitting that argument will cause all dependencies, as well as composer.lock, to be updated.

Generics/templates in python?

Since python is dynamically typed, this is super easy. In fact, you'd have to do extra work for your BinaryTree class not to work with any data type.

For example, if you want the key values which are used to place the object in the tree available within the object from a method like key() you just call key() on the objects. For example:

class BinaryTree(object):

    def insert(self, object_to_insert):
        key = object_to_insert.key()

Note that you never need to define what kind of class object_to_insert is. So long as it has a key() method, it will work.

The exception is if you want it to work with basic data types like strings or integers. You'll have to wrap them in a class to get them to work with your generic BinaryTree. If that sounds too heavy weight and you want the extra efficiency of actually just storing strings, sorry, that's not what Python is good at.

Modifying Objects within stream in Java8 while iterating

This might be a little late. But here is one of the usage. This to get the count of the number of files.

Create a pointer to memory (a new obj in this case) and have the property of the object modified. Java 8 stream doesn't allow to modify the pointer itself and hence if you declare just count as a variable and try to increment within the stream it will never work and throw a compiler exception in the first place

Path path = Paths.get("/Users/XXXX/static/test.txt");



Count c = new Count();
            c.setCount(0);
            Files.lines(path).forEach(item -> {
                c.setCount(c.getCount()+1);
                System.out.println(item);});
            System.out.println("line count,"+c);

public static class Count{
        private int count;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        @Override
        public String toString() {
            return "Count [count=" + count + "]";
        }



    }

Reading Data From Database and storing in Array List object

If your customer class has static variables remove them so your class should look something like this.

public class customer {

     private int id;
     private String name;
     private String DOB;

    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getDOB() {
        return DOB;
    }
     public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setDOB(String dOB) {
        this.DOB = dOB;
    }

instead of something like

public class customer {

     private static int id;
     private static String name;
     private static String DOB;

    public static int getId() {
        return id;
    }
    public static String getName() {
        return name;
    }
    public static String getDOB() {
        return DOB;
    }
     public static void setId(int id) {
        custumer.id = id;
    }
    public  static void setName(String name) {
        customer.name = name;
    }
    public static void setDOB(String dOB) {
        customer.DOB = dOB;
    }

git error: failed to push some refs to remote

In my case branch name prefix was already present at remote so basically if you have a branch name 'fix' you cannot push another branch with name 'fix/new_branch_name', renaming branch solved my problem.

What is move semantics?

In easy (practical) terms:

Copying an object means copying its "static" members and calling the new operator for its dynamic objects. Right?

class A
{
   int i, *p;

public:
   A(const A& a) : i(a.i), p(new int(*a.p)) {}
   ~A() { delete p; }
};

However, to move an object (I repeat, in a practical point of view) implies only to copy the pointers of dynamic objects, and not to create new ones.

But, is that not dangerous? Of course, you could destruct a dynamic object twice (segmentation fault). So, to avoid that, you should "invalidate" the source pointers to avoid destructing them twice:

class A
{
   int i, *p;

public:
   // Movement of an object inside a copy constructor.
   A(const A& a) : i(a.i), p(a.p)
   {
     a.p = nullptr; // pointer invalidated.
   }

   ~A() { delete p; }
   // Deleting NULL, 0 or nullptr (address 0x0) is safe. 
};

Ok, but if I move an object, the source object becomes useless, no? Of course, but in certain situations that's very useful. The most evident one is when I call a function with an anonymous object (temporal, rvalue object, ..., you can call it with different names):

void heavyFunction(HeavyType());

In that situation, an anonymous object is created, next copied to the function parameter, and afterwards deleted. So, here it is better to move the object, because you don't need the anonymous object and you can save time and memory.

This leads to the concept of an "rvalue" reference. They exist in C++11 only to detect if the received object is anonymous or not. I think you do already know that an "lvalue" is an assignable entity (the left part of the = operator), so you need a named reference to an object to be capable to act as an lvalue. A rvalue is exactly the opposite, an object with no named references. Because of that, anonymous object and rvalue are synonyms. So:

class A
{
   int i, *p;

public:
   // Copy
   A(const A& a) : i(a.i), p(new int(*a.p)) {}

   // Movement (&& means "rvalue reference to")
   A(A&& a) : i(a.i), p(a.p)
   {
      a.p = nullptr;
   }

   ~A() { delete p; }
};

In this case, when an object of type A should be "copied", the compiler creates a lvalue reference or a rvalue reference according to if the passed object is named or not. When not, your move-constructor is called and you know the object is temporal and you can move its dynamic objects instead of copying them, saving space and memory.

It is important to remember that "static" objects are always copied. There's no ways to "move" a static object (object in stack and not on heap). So, the distinction "move"/ "copy" when an object has no dynamic members (directly or indirectly) is irrelevant.

If your object is complex and the destructor has other secondary effects, like calling to a library's function, calling to other global functions or whatever it is, perhaps is better to signal a movement with a flag:

class Heavy
{
   bool b_moved;
   // staff

public:
   A(const A& a) { /* definition */ }
   A(A&& a) : // initialization list
   {
      a.b_moved = true;
   }

   ~A() { if (!b_moved) /* destruct object */ }
};

So, your code is shorter (you don't need to do a nullptr assignment for each dynamic member) and more general.

Other typical question: what is the difference between A&& and const A&&? Of course, in the first case, you can modify the object and in the second not, but, practical meaning? In the second case, you can't modify it, so you have no ways to invalidate the object (except with a mutable flag or something like that), and there is no practical difference to a copy constructor.

And what is perfect forwarding? It is important to know that a "rvalue reference" is a reference to a named object in the "caller's scope". But in the actual scope, a rvalue reference is a name to an object, so, it acts as a named object. If you pass an rvalue reference to another function, you are passing a named object, so, the object isn't received like a temporal object.

void some_function(A&& a)
{
   other_function(a);
}

The object a would be copied to the actual parameter of other_function. If you want the object a continues being treated as a temporary object, you should use the std::move function:

other_function(std::move(a));

With this line, std::move will cast a to an rvalue and other_function will receive the object as a unnamed object. Of course, if other_function has not specific overloading to work with unnamed objects, this distinction is not important.

Is that perfect forwarding? Not, but we are very close. Perfect forwarding is only useful to work with templates, with the purpose to say: if I need to pass an object to another function, I need that if I receive a named object, the object is passed as a named object, and when not, I want to pass it like a unnamed object:

template<typename T>
void some_function(T&& a)
{
   other_function(std::forward<T>(a));
}

That's the signature of a prototypical function that uses perfect forwarding, implemented in C++11 by means of std::forward. This function exploits some rules of template instantiation:

 `A& && == A&`
 `A&& && == A&&`

So, if T is a lvalue reference to A (T = A&), a also (A& && => A&). If T is a rvalue reference to A, a also (A&& && => A&&). In both cases, a is a named object in the actual scope, but T contains the information of its "reference type" from the caller scope's point of view. This information (T) is passed as template parameter to forward and 'a' is moved or not according to the type of T.

ARM compilation error, VFP registers used by executable, not object file

In my case CFLAGS = -O0 -g -Wall -I. -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=soft has helped. As you can see, i used it for my stm32f407.

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Try either of the following

1.Removing and adding ios platform and rebuild the project for ios

ionic cordova platform rm ios
ionic cordova platform add ios
ionic cordova build ios --release

2.Changing the Xcode Build Setting

The solution was to uncheck it, then check it again and reselect the Team. Xcode then fixed whatever was causing the issue on its own.

3.Change the following code in platform

This didn’t make any sense to me, since I had set the project to auto sign in xcode. Like you, the check and uncheck didn’t work. But then I read the last file path given and followed it. The file path is APP > Platforms > ios > Cordova > build-release.xconfig

And in the file, iPhone Distribution is explicitly set for CODE_SIGN_IDENTITY.

Change:

CODE_SIGN_IDENTITY = iPhone Distribution
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution

To:

CODE_SIGN_IDENTITY = iPhone Developer
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Developer

Python loop counter in a for loop

enumerate is what you are looking for.

You might also be interested in unpacking:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.

How to configure custom PYTHONPATH with VM and PyCharm?

In my experience, using a PYTHONPATH variable at all is usually the wrong approach, because it does not play nicely with VENV on windows. PYTHON on loading will prepare the path by prepending PYTHONPATH to the path, which can result in your carefully prepared Venv preferentially fetching global site packages.

Instead of using PYTHON path, include a pythonpath.pth file in the relevant site-packages directory (although beware custom pythons occasionally look for them in different locations, e.g. enthought looks in the same directory as python.exe for its .pth files) with each virtual environment. This will act like a PYTHONPATH only it will be specific to the python installation, so you can have a separate one for each python installation/environment. Pycharm integrates strongly with VENV if you just go to yse the VENV's python as your python installation.

See e.g. this SO question for more details on .pth files....

How do I fill arrays in Java?

Arrays.fill(arrayName,value);

in java

int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
  System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
  System.out.println(arrnum[i]+" ");
}

Output

5 6 9 2 10
0 0 0 0 0

ClassNotFoundException com.mysql.jdbc.Driver

In IntelliJ Do as they say in eclipse "If you're facing this problem with Eclipse, I've been following many different solutions but the one that worked for me is this:

Right click your project folder and open up Properties.

From the right panel, select Java Build Path then go to Libraries tab.

Select Add External JARs to import the mysql driver.

From the right panel, select Deployment Assembly.

Select Add..., then select Java Build Path Entries and click Next.

You should see the sql driver on the list. Select it and click first.

And that's it! Try to run it again! Cheers!"

Here we have to add the jar file in Project Structure -> Libraries -> +(add)

Writing an input integer into a cell

I've done this kind of thing with a form that contains a TextBox.

So if you wanted to put this in say cell H1, then use:

ActiveSheet.Range("H1").Value = txtBoxName.Text

Trying to detect browser close event

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {

            var ref="load";
      $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref               
            },
             success:function(data)
            {
                console.log(data);
            }
            });
     endSession();
  }
 }

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
}
});

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});

 // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
 });

 // Attach the event click for all inputs in the page
 $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();  
}); 
</script> 

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...

How do I check if a number is a palindrome?

Personally I do it this way, and there's no overlap; the code stops checking for matching characters in the correct spot whether the string has an even or odd length. Some of the other methods posted above will attempt to match one extra time when it doesn't need to.

If we use length/2, it will still work but it will do one additional check that it doesn't need to do. For instance, "pop" is 3 in length. 3/2 = 1.5, so it will stop checking when i = 2(since 1<1.5 it will check when i = 1 as well) but we need it to stop at 0, not one. The first "p" is in position 0, and it will check itself against length-1-0(current position) which is the last "p" in position 2, and then we are left with the center letter that needs no checking. When we do length/2 we stop at 1, so what happens is an extra check is performed with i being on the 1 position(the "o") and compares it to itself (length-1-i).

// Checks if our string is palindromic.
var ourString = "A Man, /.,.()^&*A Plan, A Canal__-Panama!";
isPalin(ourString);

function isPalin(string) {
// Make all lower case for case insensitivity and replace all spaces, underscores and non-words.
string = string.toLowerCase().replace(/\s+/g, "").replace(/\W/g,"").replace(/_/g,"");
for(i=0; i<=Math.floor(string.length/2-1); i++) {
      if(string[i] !== string[string.length-1-i]) {
        console.log("Your string is not palindromic!");
        break;
      } else if(i === Math.floor(string.length/2-1)) {
        console.log("Your string is palindromic!");
      }
    }
}

https://repl.it/FNVZ/1

JavaScript Chart.js - Custom data formatting to display on tooltip

In Chart.Js 2.8.0, the configuration for custom tooltips can be found here: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback (Thanks to @prokaktus)

If you want to e.g. show some values with a prefix or postfix (In the example, the script adds a unit of kWh to the values in the chart), you could do this like:

options: {
  rotation: 1 * Math.PI,
  circumference: 1 * Math.PI,
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        console.log(data);
        console.log(tooltipItem);

        var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] || '';

        if (label) {
          label += ' kWh';
        }

        return label;
      }
    }
  }
}

An example fiddle is here, too: https://jsfiddle.net/y3petw58/1/

What is the proper declaration of main in C++?

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

as the type of main.

This makes it clear that alternative spellings are permitted so long as the type of main is the type int() or int(int, char**). So the following are also permitted:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

Firefox and SSL: sec_error_unknown_issuer

I've being going round in circles with Firefox 43, El Capitan and WHM/cPanel SSL installation continually getting the Untrusted site error - I didn't buy the certificate it was handed over to me to install as the last guy walked out the door. Turns out I was installing under the wrong domain because I missed off the www - but the certificate still installed against the domain, when I installed the certificate in WHM using www.domain.com.au it installed now worries and the FF error has gone - the certificate works fine for both www and non-www.

How can I solve a connection pool problem between ASP.NET and SQL Server?

If you are working on complex legacy code where a simple using(..) {..} isn't possible - as I was - you may want to check out the code snippet I posted in this SO question for a way to determine the call stack of the connection creation when a connection is potentially leaked (not closed after a set timeout). This makes it fairly easy to spot the cause of the leaks.

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

how to toggle attr() in jquery

For readonly/disabled and other attributes with true/false values

$(':submit').attr('disabled', function(_, attr){ return !attr});

How to reload current page?

Here is the simple one

if (this.router && this.router.url === '/') { or your current page url e.g '/home' 
    window.location.reload();
  } else {
    this.router.navigate([url]);
  }

What are "res" and "req" parameters in Express functions?

I noticed one error in Dave Ward's answer (perhaps a recent change?): The query string paramaters are in request.query, not request.params. (See https://stackoverflow.com/a/6913287/166530 )

request.params by default is filled with the value of any "component matches" in routes, i.e.

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

and, if you have configured express to use its bodyparser (app.use(express.bodyParser());) also with POST'ed formdata. (See How to retrieve POST query parameters? )

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

This is a simple solution for merging two dictionaries where += can be applied to the values, it has to iterate over a dictionary only once

a = {'a':1, 'b':2, 'c':3}

dicts = [{'b':3, 'c':4, 'd':5},
         {'c':9, 'a':9, 'd':9}]

def merge_dicts(merged,mergedfrom):
    for k,v in mergedfrom.items():
        if k in merged:
            merged[k] += v
        else:
            merged[k] = v
    return merged

for dct in dicts:
    a = merge_dicts(a,dct)
print (a)
#{'c': 16, 'b': 5, 'd': 14, 'a': 10}

How can I check if a View exists in a Database?

IN SQL Server ,

declare @ViewName nvarchar(20)='ViewNameExample'

if exists(SELECT 1 from sys.objects where object_Id=object_Id(@ViewName) and Type_Desc='VIEW')
begin
    -- Your SQL Code goes here ...

end

How can I switch themes in Visual Studio 2012

Try the steps in here: If you don't have Visual Studio 2010 installed, some icons are provided.

http://supunlivera.blogspot.com/2012/09/visual-studio-2012-theme-change-get-vs.html

How to embed a .mov file in HTML?

Well, if you don't want to do the work yourself (object elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/