Programs & Examples On #Code templates

shell init issue when click tab, what's wrong with getcwd?

Just change the directory to another one and come back. Probably that one has been deleted or moved.

Execute action when back bar button of UINavigationController is pressed

When back button is pressed, ignore interactive pop with screen edge gesture.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    if isMovingFromParent, transitionCoordinator?.isInteractive == false {
      // code here
    }
  }

$(this).attr("id") not working

In the function context "this" its not referring to the select element, but to the page itself

  • Change var ID = $(this).attr("id"); to var ID = $(obj).attr("id");

If obj is already a jQuery Object, just remove the $() around it.

Using global variables in a function

There are 2 ways to declare a variable as global:

1. assign variable inside functions and use global line

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1

# Note to use the function to global variables
declare_a_global_variable() 

2. assign variable outside functions:

global_variable_2 = 2

Now we can use these declared global variables in the other functions:

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1

# Note to use the function to global variables
declare_a_global_variable() 
global_variable_2 = 2

def print_variables():
    print(global_variable_1)
    print(global_variable_2)
print_variables() # prints 1 & 2

Note 1:

If you want to change a global variable inside another function like update_variables() you should use global line in that function before assigning the variable:

global_variable_1 = 1
global_variable_2 = 2

def update_variables():
    global global_variable_1
    global_variable_1 = 11
    global_variable_2 = 12 # will update just locally for this function

update_variables()
print(global_variable_1) # prints 11
print(global_variable_2) # prints 2

Note 2:

There is a exception for note 1 for list and dictionary variables while not using global line inside a function:

# declaring some global variables
variable = 'peter'
list_variable_1 = ['a','b']
list_variable_2 = ['c','d']

def update_global_variables():
    """without using global line"""
    variable = 'PETER' # won't update in global scope
    list_variable_1 = ['A','B'] # won't update in global scope
    list_variable_2[0] = 'C' # updated in global scope surprisingly this way
    list_variable_2[1] = 'D' # updated in global scope surprisingly this way

update_global_variables()

print('variable is: %s'%variable) # prints peter
print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b']
print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D']

What's the difference between primitive and reference types?

these are primitive data types

  • boolean
  • character
  • byte
  • short
  • integer
  • long
  • float
  • double

saved in stack in the memory which is managed memory on the other hand object data type or reference data type stored in head in the memory managed by GC

this is the most important difference

How to get all checked checkboxes

For a simple two- (or one) liner this code can be:

checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);

Here the Array.prototype.slice.call() part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value) on the end of line 2. The => is javascript's arrow function notation.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

If you're just playing around in local mode, you can drop metastore DB and reinstate it:

rm -rf metastore_db/
$HIVE_HOME/bin/schematool -initSchema -dbType derby

one line if statement in php

The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well

function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();

Get Request and Session Parameters and Attributes from JSF pages

Assuming that you already put your object as attribute on the session map of the current instance of the FacesContext from your managed-bean, you can get it from the JSF page by :

<h:outputText value="#{sessionScope['yourObject'] }" />

If your object has a property, get it by:

<h:ouputText value="#{sessionScope['yourObject'].anyProperty }" />

Removing the fragment identifier from AngularJS urls (# symbol)

To remove the Hash tag for a pretty URL and also for your code to work after minification you need to structure your code like the example below:

jobApp.config(['$routeProvider','$locationProvider',
    function($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'views/job-list.html',
                controller: 'JobListController'
            }).
            when('/menus', {
                templateUrl: 'views/job-list.html',
                controller: 'JobListController'
            }).
            when('/menus/:id', {
                templateUrl: 'views/job-detail.html',
                controller: 'JobDetailController'
            });

         //you can include a fallback by  including .otherwise({
          //redirectTo: '/jobs'
        //});


        //check browser support
        if(window.history && window.history.pushState){
            //$locationProvider.html5Mode(true); will cause an error $location in HTML5 mode requires a  tag to be present! Unless you set baseUrl tag after head tag like so: <head> <base href="/">

         // to know more about setting base URL visit: https://docs.angularjs.org/error/$location/nobase

         // if you don't wish to set base URL then use this
         $locationProvider.html5Mode({
                 enabled: true,
                 requireBase: false
          });
        }
    }]);

z-index not working with fixed positioning

Add position: relative; to #over

_x000D_
_x000D_
    #over {_x000D_
      width: 600px;_x000D_
      z-index: 10;_x000D_
      position: relative;    _x000D_
    }_x000D_
    _x000D_
    #under {_x000D_
      position: fixed;_x000D_
      top: 5px;_x000D_
      width: 420px;_x000D_
      left: 20px;_x000D_
      border: 1px solid;_x000D_
      height: 10%;_x000D_
      background: #fff;_x000D_
      z-index: 1;_x000D_
    }
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
     <div id="over">_x000D_
      Hello Hello HelloHelloHelloHelloHello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello_x000D_
     </div>  _x000D_
    _x000D_
     <div id="under"></div>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Fiddle

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Here is snippet that allowed me to log out programmatically from facebook. Let me know if you see anything that I might need to improve.

private void logout(){
    // clear any user information
    mApp.clearUserPrefs();
    // find the active session which can only be facebook in my app
    Session session = Session.getActiveSession();
    // run the closeAndClearTokenInformation which does the following
    // DOCS : Closes the local in-memory Session object and clears any persistent 
    // cache related to the Session.
    session.closeAndClearTokenInformation();
    // return the user to the login screen
    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
    // make sure the user can not access the page after he/she is logged out
    // clear the activity stack
    finish();
}

libstdc++-6.dll not found

useful to windows users who use eclipse for c/c++ but run *.exe file and get an error: "missing libstdc++6.dll"

4 ways to solve it

  1. Eclipse ->"Project" -> "Properties" -> "C/C++ Build" -> "Settings" -> "Tool Settings" -> "MinGW C++ Linker" -> "Misscellaneous" -> "Linker flags" (add '-static' to it)

  2. Add '{{the path where your MinGW was installed}}/bin' to current user environment variable - "Path" in Windows, then reboot eclipse, and finally recompile.

  3. Add '{{the path where your MinGW was installed}}/bin' to Windows environment variable - "Path", then reboot eclipse, and finally recompile.

  4. Copy the file "libstdc++-6.dll" to the path where the *.exe file is running, then rerun. (this is not a good way)

Note: the file "libstdc++-6.dll" is in the folder '{{the path where your MinGW was installed}}/bin'

How to determine if a list of polygon points are in clockwise order?

As also explained in this Wikipedia article Curve orientation, given 3 points p, q and r on the plane (i.e. with x and y coordinates), you can calculate the sign of the following determinant

enter image description here

If the determinant is negative (i.e. Orient(p, q, r) < 0), then the polygon is oriented clockwise (CW). If the determinant is positive (i.e. Orient(p, q, r) > 0), the polygon is oriented counterclockwise (CCW). The determinant is zero (i.e. Orient(p, q, r) == 0) if points p, q and r are collinear.

In the formula above, we prepend the ones in front of the coordinates of p, q and r because we are using homogeneous coordinates.

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

Purpose of "%matplotlib inline"

It is not mandatory to write that. It worked fine for me without (%matplotlib) magic function. I am using Sypder compiler, one that comes with in Anaconda.

Comparing floating point number to zero

You are correct with your observation.

If x == 0.0, then abs(x) * epsilon is zero and you're testing whether abs(y) <= 0.0.

If y == 0.0 then you're testing abs(x) <= abs(x) * epsilon which means either epsilon >= 1 (it isn't) or x == 0.0.

So either is_equal(val, 0.0) or is_equal(0.0, val) would be pointless, and you could just say val == 0.0. If you want to only accept exactly +0.0 and -0.0.

The FAQ's recommendation in this case is of limited utility. There is no "one size fits all" floating-point comparison. You have to think about the semantics of your variables, the acceptable range of values, and the magnitude of error introduced by your computations. Even the FAQ mentions a caveat, saying this function is not usually a problem "when the magnitudes of x and y are significantly larger than epsilon, but your mileage may vary".

.NET - Get protocol, host, and port

Request.Url will return you the Uri of the request. Once you have that, you can retrieve pretty much anything you want. To get the protocol, call the Scheme property.

Sample:

Uri url = Request.Url;
string protocol = url.Scheme;

Hope this helps.

How to fix date format in ASP .NET BoundField (DataFormatString)?

The following links will help you:

In Client side design page you can try this: {0:G}

OR

You can convert that datetime format inside the query itself from the database:

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

2 Steps to fix this.. 1, connect to internet. 2, Click on clean project. this will fix it :)

Bootstrap radio button "checked" flag

A javascript fix to apply the 'active' class to all labels that are parents of checked inputs:

$(':input:checked').parent('.btn').addClass('active');

insert right after

$('.btn').button();

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

How to convert Java String to JSON Object

@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.

See this link for more information on that particular constructor.

http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29

When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it any class and expect it to work.

At any rate, this particular constructor is explained as such:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".

So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.

public String getName() {...}

or

public boolean isValid() {...}

So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.

So, you can very simply call toString() on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:

...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
    jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

Parse v. TryParse

For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign number to zero.

        if (!Int32.TryParse(txt,out tmpint)) {
            tmpint = 0;
        }

and:

        try {
            tmpint = Convert.ToInt32(txt);
        } catch (Exception) {
            tmpint = 0;
        }

For c#, the best option is to use tryparse because try&Catch alternative thrown the exception

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.

MVC Razor view nested foreach's model

You can simply use EditorTemplates to do that, you need to create a directory named "EditorTemplates" in your controller's view folder and place a seperate view for each of your nested entities (named as entity class name)

Main view :

@model ViewModels.MyViewModels.Theme

@Html.LabelFor(Model.Theme.name)
@Html.EditorFor(Model.Theme.Categories)

Category view (/MyController/EditorTemplates/Category.cshtml) :

@model ViewModels.MyViewModels.Category

@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Products)

Product view (/MyController/EditorTemplates/Product.cshtml) :

@model ViewModels.MyViewModels.Product

@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Orders)

and so on

this way Html.EditorFor helper will generate element's names in an ordered manner and therefore you won't have any further problem for retrieving the posted Theme entity as a whole

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

Select datatype of the field in postgres

The information schema views and pg_typeof() return incomplete type information. Of these answers, psql gives the most precise type information. (The OP might not need such precise information, but should know the limitations.)

create domain test_domain as varchar(15);

create table test (
  test_id test_domain, 
  test_vc varchar(15), 
  test_n numeric(15, 3), 
  big_n bigint,
  ip_addr inet
);

Using psql and \d public.test correctly shows the use of the data type test_domain, the length of varchar(n) columns, and the precision and scale of numeric(p, s) columns.

sandbox=# \d public.test
             Table "public.test"
 Column  |         Type          | Modifiers
---------+-----------------------+-----------
 test_id | test_domain           |
 test_vc | character varying(15) |
 test_n  | numeric(15,3)         |
 big_n   | bigint                |
 ip_addr | inet                  |

This query against an information_schema view does not show the use of test_domain at all. It also doesn't report the details of varchar(n) and numeric(p, s) columns.

select column_name, data_type 
from information_schema.columns 
where table_catalog = 'sandbox'
  and table_schema = 'public'
  and table_name = 'test';
 column_name |     data_type
-------------+-------------------
 test_id     | character varying
 test_vc     | character varying
 test_n      | numeric
 big_n       | bigint
 ip_addr     | inet

You might be able to get all that information by joining other information_schema views, or by querying the system tables directly. psql -E might help with that.

The function pg_typeof() correctly shows the use of test_domain, but doesn't report the details of varchar(n) and numeric(p, s) columns.

select pg_typeof(test_id) as test_id, 
       pg_typeof(test_vc) as test_vc,
       pg_typeof(test_n) as test_n,
       pg_typeof(big_n) as big_n,
       pg_typeof(ip_addr) as ip_addr
from test;
   test_id   |      test_vc      | test_n  | big_n  | ip_addr
-------------+-------------------+---------+--------+---------
 test_domain | character varying | numeric | bigint | inet

Differences between git pull origin master & git pull origin/master

git pull origin master will pull changes from the origin remote, master branch and merge them to the local checked-out branch.

git pull origin/master will pull changes from the locally stored branch origin/master and merge that to the local checked-out branch. The origin/master branch is essentially a "cached copy" of what was last pulled from origin, which is why it's called a remote branch in git parlance. This might be somewhat confusing.

You can see what branches are available with git branch and git branch -r to see the "remote branches".

Clear the value of bootstrap-datepicker

Current version 1.4.0 has clearBtn option:

$('.datepicker').datepicker({
    clearBtn: true
});

Besides adding button to interface it allows to delete value from input box manually.

Is the Javascript date object always one day off?

It means 2011-09-24 00:00:00 GMT, and since you're at GMT -4, it will be 20:00 the previous day.

Personally, I get 2011-09-24 02:00:00, because I'm living at GMT +2.

How to remove button shadow (android)

Material desing buttons add to button xml: style="@style/Widget.MaterialComponents.Button.UnelevatedButton"

Launch custom android application from android browser

Look @JRuns answer in here. The idea is to create html with your custom scheme and upload it somewhere. Then if you click on your custom link on your html-file, you will be redirected to your app. I used this article for android. But dont forget to set full name Name = "MyApp.Mobile.Droid.MainActivity" attribute to your target activity.

Inheritance and Overriding __init__ in python

The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.

It looks like this nowadays:

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super(FileInfo, self).__init__()
        self["name"] = filename

Note the following:

  1. We can directly subclass built-in classes, like dict, list, tuple, etc.

  2. The super function handles tracking down this class's superclasses and calling functions in them appropriately.

How to import load a .sql or .csv file into SQLite?

if you are using it in windows, be sure to add the path to the db in "" and also to use double slash \ in the path to make sure windows understands it.

Fill remaining vertical space - only CSS

Flexbox solution

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 300px;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.first {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.second {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="first" style="background:#b2efd8">First</div>_x000D_
  <div class="second" style="background:#80c7cd">Second</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I display a list view in an Android Alert Dialog?

As a beginner I would suggest you go through http://www.mkyong.com/android/android-custom-dialog-example/

I'll rundown what it basically does

  1. Creates an XML file for the dialog and main Activity
  2. In the main activity in the required place creates an object of android class Dialog
  3. Adds custom styling and text based on the XML file
  4. Calls the dialog.show() method.

IntelliJ show JavaDocs tooltip on mouse over

I tried many ways mentioned here, especially the preference - editor - general - code completion - show documentation popup in.. isn't working in version 2019.2.2

Finally, i am just using F1 while caret is on the type/method and it displays the documentation nicely. This is not ideal but helpful.

echo key and value of an array without and with loop

If you must not use a loop (why?), you could use array_walk,

function printer($v, $k) {
   echo "$k is at $v\n";
}

array_walk($page, "printer");

See http://www.ideone.com/aV5X6.

What are the differences between virtual memory and physical memory?

Softwares run on the OS on a very simple premise - they require memory. The device OS provides it in the form of RAM. The amount of memory required may vary - some softwares need huge memory, some require paltry memory. Most (if not all) users run multiple applications on the OS simultaneously, and given that memory is expensive (and device size is finite), the amount of memory available is always limited. So given that all softwares require a certain amount of RAM, and all of them can be made to run at the same time, OS has to take care of two things:

  1. That the software always runs until user aborts it, i.e. it should not auto-abort because OS has run out of memory.
  2. The above activity, while maintaining a respectable performance for the softwares running.

Now the main question boils down to how the memory is being managed. What exactly governs where in the memory will the data belonging to a given software reside?

Possible solution 1: Let individual softwares specify explicitly the memory address they will use in the device. Suppose Photoshop declares that it will always use memory addresses ranging from 0 to 1023 (imagine the memory as a linear array of bytes, so first byte is at location 0, 1024th byte is at location 1023) - i.e. occupying 1 GB memory. Similarly, VLC declares that it will occupy memory range 1244 to 1876, etc.

Advantages:

  1. Every application is pre-assigned a memory slot, so when it is installed and executed, it just stores its data in that memory area, and everything works fine.

Disadvantages:

  1. This does not scale. Theoretically, an app may require a huge amount of memory when it is doing something really heavy-duty. So to ensure that it never runs out of memory, the memory area allocated to it must always be more than or equal to that amount of memory. What if a software, whose maximal theoretical memory usage is 2 GB (hence requiring 2 GB memory allocation from RAM), is installed in a machine with only 1 GB memory? Should the software just abort on startup, saying that the available RAM is less than 2 GB? Or should it continue, and the moment the memory required exceeds 2 GB, just abort and bail out with the message that not enough memory is available?

  2. It is not possible to prevent memory mangling. There are millions of softwares out there, even if each of them was allotted just 1 kB memory, the total memory required would exceed 16 GB, which is more than most devices offer. How can, then, different softwares be allotted memory slots that do not encroach upon each other's areas? Firstly, there is no centralized software market which can regulate that when a new software is being released, it must assign itself this much memory from this yet unoccupied area, and secondly, even if there were, it is not possible to do it because the no. of softwares is practically infinite (thus requiring infinite memory to accommodate all of them), and the total RAM available on any device is not sufficient to accommodate even a fraction of what is required, thus making inevitable the encroaching of the memory bounds of one software upon that of another. So what happens when Photoshop is assigned memory locations 1 to 1023 and VLC is assigned 1000 to 1676? What if Photoshop stores some data at location 1008, then VLC overwrites that with its own data, and later Photoshop accesses it thinking that it is the same data is had stored there previously? As you can imagine, bad things will happen.

So clearly, as you can see, this idea is rather naive.

Possible solution 2: Let's try another scheme - where OS will do majority of the memory management. Softwares, whenever they require any memory, will just request the OS, and the OS will accommodate accordingly. Say OS ensures that whenever a new process is requesting for memory, it will allocate the memory from the lowest byte address possible (as said earlier, RAM can be imagined as a linear array of bytes, so for a 4 GB RAM, the addresses range for a byte from 0 to 2^32-1) if the process is starting, else if it is a running process requesting the memory, it will allocate from the last memory location where that process still resides. Since the softwares will be emitting addresses without considering what the actual memory address is going to be where that data is stored, OS will have to maintain a mapping, per software, of the address emitted by the software to the actual physical address (Note: that is one of the two reasons we call this concept Virtual Memory. Softwares are not caring about the real memory address where their data are getting stored, they just spit out addresses on the fly, and the OS finds the right place to fit it and find it later if required).

Say the device has just been turned on, OS has just launched, right now there is no other process running (ignoring the OS, which is also a process!), and you decide to launch VLC. So VLC is allocated a part of the RAM from the lowest byte addresses. Good. Now while the video is running, you need to start your browser to view some webpage. Then you need to launch Notepad to scribble some text. And then Eclipse to do some coding.. Pretty soon your memory of 4 GB is all used up, and the RAM looks like this:

                                   enter image description here

Problem 1: Now you cannot start any other process, for all RAM is used up. Thus programs have to be written keeping the maximum memory available in mind (practically even less will be available, as other softwares will be running parallelly as well!). In other words, you cannot run a high-memory consuming app in your ramshackle 1 GB PC.

Okay, so now you decide that you no longer need to keep Eclipse and Chrome open, you close them to free up some memory. The space occupied in RAM by those processes is reclaimed by OS, and it looks like this now:

                                    enter image description here

Suppose that closing these two frees up 700 MB space - (400 + 300) MB. Now you need to launch Opera, which will take up 450 MB space. Well, you do have more than 450 MB space available in total, but...it is not contiguous, it is divided into individual chunks, none of which is big enough to fit 450 MB. So you hit upon a brilliant idea, let's move all the processes below to as much above as possible, which will leave the 700 MB empty space in one chunk at the bottom. This is called compaction. Great, except that...all the processes which are there are running. Moving them will mean moving the address of all their contents (remember, OS maintains a mapping of the memory spat out by the software to the actual memory address. Imagine software had spat out an address of 45 with data 123, and OS had stored it in location 2012 and created an entry in the map, mapping 45 to 2012. If the software is now moved in memory, what used to be at location 2012 will no longer be at 2012, but in a new location, and OS has to update the map accordingly to map 45 to the new address, so that the software can get the expected data (123) when it queries for memory location 45. As far as the software is concerned, all it knows is that address 45 contains the data 123!)! Imagine a process that is referencing a local variable i. By the time it is accessed again, its address has changed, and it won't be able to find it any more. The same will hold for all functions, objects, variables, basically everything has an address, and moving a process will mean changing the address of all of them. Which leads us to:

Problem 2: You cannot move a process. The values of all variables, functions and objects within that process have hardcoded values as spat out by the compiler during compilation, the process depends on them being at the same location during its lifetime, and changing them is expensive. As a result, processes leave behind big "holes" when they exit. This is called External Fragmentation.

Fine. Suppose somehow, by some miraculous manner, you do manage to move the processes up. Now there is 700 MB of free space at the bottom:

                        enter image description here

Opera smoothly fits in at the bottom. Now your RAM looks like this:

                                    enter image description here

Good. Everything is looking fine. However, there is not much space left, and now you need to launch Chrome again, a known memory-hog! It needs lots of memory to start, and you have hardly any left...Except.. you now notice that some of the processes, which were initially occupying large space, now is not needing much space. May be you have stopped your video in VLC, hence it is still occupying some space, but not as much as it required while running a high resolution video. Similarly for Notepad and Photos. Your RAM now looks like this:

                                        enter image description here

Holes, once again! Back to square one! Except, previously, the holes occurred due to processes terminating, now it is due to processes requiring less space than before! And you again have the same problem, the holes combined yield more space than required, but they are scattered around, not much of use in isolation. So you have to move those processes again, an expensive operation, and a very frequent one at that, since processes will frequently reduce in size over their lifetime.

Problem 3: Processes, over their lifetime, may reduce in size, leaving behind unused space, which if needed to be used, will require the expensive operation of moving many processes. This is called Internal Fragmentation.

Fine, so now, your OS does the required thing, moves processes around and start Chrome and after some time, your RAM looks like this:

enter image description here

Cool. Now suppose you again resume watching Avatar in VLC. Its memory requirement will shoot up! But...there is no space left for it to grow, as Notepad is snuggled at its bottom. So, again, all processes has to move below until VLC has found sufficient space!

Problem 4: If processes needs to grow, it will be a very expensive operation

Fine. Now suppose, Photos is being used to load some photos from an external hard disk. Accessing hard-disk takes you from the realm of caches and RAM to that of disk, which is slower by orders of magnitudes. Painfully, irrevocably, transcendentally slower. It is an I/O operation, which means it is not CPU bound (it is rather the exact opposite), which means it does not need to occupy RAM right now. However, it still occupies RAM stubbornly. If you want to launch Firefox in the meantime, you can't, because there is not much memory available, whereas if Photos was taken out of memory for the duration of its I/O bound activity, it would have freed lot of memory, followed by (expensive) compaction, followed by Firefox fitting in.

Problem 5: I/O bound jobs keep on occupying RAM, leading to under-utilization of RAM, which could have been used by CPU bound jobs in the meantime.

So, as we can see, we have so many problems even with the approach of virtual memory.


There are two approaches to tackle these problems - paging and segmentation. Let us discuss paging. In this approach, the virtual address space of a process is mapped to the physical memory in chunks - called pages. A typical page size is 4 kB. The mapping is maintained by something called a page table, given a virtual address, all now we have to do is find out which page the address belong to, then from the page table, find the corresponding location for that page in actual physical memory (known as frame), and given that the offset of the virtual address within the page is same for the page as well as the frame, find out the actual address by adding that offset to the address returned by the page table. For example:

enter image description here

On the left is the virtual address space of a process. Say the virtual address space requires 40 units of memory. If the physical address space (on the right) had 40 units of memory as well, it would have been possible to map all location from the left to a location on the right, and we would have been so happy. But as ill luck would have it, not only does the physical memory have less (24 here) memory units available, it has to be shared between multiple processes as well! Fine, let's see how we make do with it.

When the process starts, say a memory access request for location 35 is made. Here the page size is 8 (each page contains 8 locations, the entire virtual address space of 40 locations thus contains 5 pages). So this location belongs to page no. 4 (35/8). Within this page, this location has an offset of 3 (35%8). So this location can be specified by the tuple (pageIndex, offset) = (4,3). This is just the starting, so no part of the process is stored in the actual physical memory yet. So the page table, which maintains a mapping of the pages on the left to the actual pages on the right (where they are called frames) is currently empty. So OS relinquishes the CPU, lets a device driver access the disk and fetch the page no. 4 for this process (basically a memory chunk from the program on the disk whose addresses range from 32 to 39). When it arrives, OS allocates the page somewhere in the RAM, say first frame itself, and the page table for this process takes note that page 4 maps to frame 0 in the RAM. Now the data is finally there in the physical memory. OS again queries the page table for the tuple (4,3), and this time, page table says that page 4 is already mapped to frame 0 in the RAM. So OS simply goes to the 0th frame in RAM, accesses the data at offset 3 in that frame (Take a moment to understand this. The entire page, which was fetched from disk, is moved to frame. So whatever the offset of an individual memory location in a page was, it will be the same in the frame as well, since within the page/frame, the memory unit still resides at the same place relatively!), and returns the data! Because the data was not found in memory at first query itself, but rather had to be fetched from disk to be loaded into memory, it constitutes a miss.

Fine. Now suppose, a memory access for location 28 is made. It boils down to (3,4). Page table right now has only one entry, mapping page 4 to frame 0. So this is again a miss, the process relinquishes the CPU, device driver fetches the page from disk, process regains control of CPU again, and its page table is updated. Say now the page 3 is mapped to frame 1 in the RAM. So (3,4) becomes (1,4), and the data at that location in RAM is returned. Good. In this way, suppose the next memory access is for location 8, which translates to (1,0). Page 1 is not in memory yet, the same procedure is repeated, and the page is allocated at frame 2 in RAM. Now the RAM-process mapping looks like the picture above. At this point in time, the RAM, which had only 24 units of memory available, is filled up. Suppose the next memory access request for this process is from address 30. It maps to (3,6), and page table says that page 3 is in RAM, and it maps to frame 1. Yay! So the data is fetched from RAM location (1,6), and returned. This constitutes a hit, as data required can be obtained directly from RAM, thus being very fast. Similarly, the next few access requests, say for locations 11, 32, 26, 27 all are hits, i.e. data requested by the process is found directly in the RAM without needing to look elsewhere.

Now suppose a memory access request for location 3 comes. It translates to (0,3), and page table for this process, which currently has 3 entries, for pages 1, 3 and 4 says that this page is not in memory. Like previous cases, it is fetched from disk, however, unlike previous cases, RAM is filled up! So what to do now? Here lies the beauty of virtual memory, a frame from the RAM is evicted! (Various factors govern which frame is to be evicted. It may be LRU based, where the frame which was least recently accessed for a process is to be evicted. It may be first-come-first-evicted basis, where the frame which allocated longest time ago, is evicted, etc.) So some frame is evicted. Say frame 1 (just randomly choosing it). However, that frame is mapped to some page! (Currently, it is mapped by the page table to page 3 of our one and only one process). So that process has to be told this tragic news, that one frame, which unfortunate belongs to you, is to be evicted from RAM to make room for another pages. The process has to ensure that it updates its page table with this information, that is, removing the entry for that page-frame duo, so that the next time a request is made for that page, it right tells the process that this page is no longer in memory, and has to be fetched from disk. Good. So frame 1 is evicted, page 0 is brought in and placed there in the RAM, and the entry for page 3 is removed, and replaced by page 0 mapping to the same frame 1. So now our mapping looks like this (note the colour change in the second frame on the right side):

enter image description here

Saw what just happened? The process had to grow, it needed more space than the available RAM, but unlike our earlier scenario where every process in the RAM had to move to accommodate a growing process, here it happened by just one page replacement! This was made possible by the fact that the memory for a process no longer needs to be contiguous, it can reside at different places in chunks, OS maintains the information as to where they are, and when required, they are appropriately queried. Note: you might be thinking, huh, what if most of the times it is a miss, and the data has to be constantly loaded from disk into memory? Yes, theoretically, it is possible, but most compilers are designed in such a manner that follows locality of reference, i.e. if data from some memory location is used, the next data needed will be located somewhere very close, perhaps from the same page, the page which was just loaded into memory. As a result, the next miss will happen after quite some time, most of the upcoming memory requirements will be met by the page just brought in, or the pages already in memory which were recently used. The exact same principle allows us to evict the least recently used page as well, with the logic that what has not been used in a while, is not likely to be used in a while as well. However, it is not always so, and in exceptional cases, yes, performance may suffer. More about it later.

Solution to Problem 4: Processes can now grow easily, if space problem is faced, all it requires is to do a simple page replacement, without moving any other process.


Solution to Problem 1: A process can access unlimited memory. When more memory than available is needed, the disk is used as backup, the new data required is loaded into memory from the disk, and the least recently used data frame (or page) is moved to disk. This can go on infinitely, and since disk space is cheap and virtually unlimited, it gives an illusion of unlimited memory. Another reason for the name Virtual Memory, it gives you illusion of memory which is not really available!

Cool. Earlier we were facing a problem where even though a process reduces in size, the empty space is difficult to be reclaimed by other processes (because it would require costly compaction). Now it is easy, when a process becomes smaller in size, many of its pages are no longer used, so when other processes need more memory, a simple LRU based eviction automatically evicts those less-used pages from RAM, and replaces them with the new pages from the other processes (and of course updating the page tables of all those processes as well as the original process which now requires less space), all these without any costly compaction operation!

Solution to Problem 3: Whenever processes reduce in size, its frames in RAM will be less used, so a simple LRU based eviction can evict those pages out and replace them with pages required by new processes, thus avoiding Internal Fragmentation without need for compaction.

As for problem 2, take a moment to understand this, the scenario itself is completely removed! There is no need to move a process to accommodate a new process, because now the entire process never needs to fit at once, only certain pages of it need to fit ad hoc, that happens by evicting frames from RAM. Everything happens in units of pages, thus there is no concept of hole now, and hence no question of anything moving! May be 10 pages had to be moved because of this new requirement, there are thousands of pages which are left untouched. Whereas, earlier, all processes (every bit of them) had to be moved!

Solution to Problem 2: To accommodate a new process, data from only less recently used parts of other processes have to be evicted as required, and this happens in fixed size units called pages. Thus there is no possibility of hole or External Fragmentation with this system.

Now when the process needs to do some I/O operation, it can relinquish CPU easily! OS simply evicts all its pages from the RAM (perhaps store it in some cache) while new processes occupy the RAM in the meantime. When the I/O operation is done, OS simply restores those pages to the RAM (of course by replacing the pages from some other processes, may be from the ones which replaced the original process, or may be from some which themselves need to do I/O now, and hence can relinquish the memory!)

Solution to Problem 5: When a process is doing I/O operations, it can easily give up RAM usage, which can be utilized by other processes. This leads to proper utilization of RAM.

And of course, now no process is accessing the RAM directly. Each process is accessing a virtual memory location, which is mapped to a physical RAM address and maintained by the page-table of that process. The mapping is OS-backed, OS lets the process know which frame is empty so that a new page for a process can be fitted there. Since this memory allocation is overseen by the OS itself, it can easily ensure that no process encroaches upon the contents of another process by allocating only empty frames from RAM, or upon encroaching upon the contents of another process in the RAM, communicate to the process to update it page-table.

Solution to Original Problem: There is no possibility of a process accessing the contents of another process, since the entire allocation is managed by the OS itself, and every process runs in its own sandboxed virtual address space.

So paging (among other techniques), in conjunction with virtual memory, is what powers today's softwares running on OS-es! This frees the software developer from worrying about how much memory is available on the user's device, where to store the data, how to prevent other processes from corrupting their software's data, etc. However, it is of course, not full-proof. There are flaws:

  1. Paging is, ultimately, giving user the illusion of infinite memory by using disk as secondary backup. Retrieving data from secondary storage to fit into memory (called page swap, and the event of not finding the desired page in RAM is called page fault) is expensive as it is an IO operation. This slows down the process. Several such page swaps happen in succession, and the process becomes painfully slow. Ever seen your software running fine and dandy, and suddenly it becomes so slow that it nearly hangs, or leaves you with no option that to restart it? Possibly too many page swaps were happening, making it slow (called thrashing).

So coming back to OP,

Why do we need the virtual memory for executing a process? - As the answer explains at length, to give softwares the illusion of the device/OS having infinite memory, so that any software, big or small, can be run, without worrying about memory allocation, or other processes corrupting its data, even when running in parallel. It is a concept, implemented in practice through various techniques, one of which, as described here, is Paging. It may also be Segmentation.

Where does this virtual memory stand when the process (program) from the external hard drive is brought to the main memory (physical memory) for the execution? - Virtual memory doesn't stand anywhere per se, it is an abstraction, always present, when the software/process/program is booted, a new page table is created for it, and it contains the mapping from the addresses spat out by that process to the actual physical address in RAM. Since the addresses spat out by the process are not real addresses, in one sense, they are, actually, what you can say, the virtual memory.

Who takes care of the virtual memory and what is the size of the virtual memory? - It is taken care of by, in tandem, the OS and the software. Imagine a function in your code (which eventually compiled and made into the executable that spawned the process) which contains a local variable - an int i. When the code executes, i gets a memory address within the stack of the function. That function is itself stored as an object somewhere else. These addresses are compiler generated (the compiler which compiled your code into the executable) - virtual addresses. When executed, i has to reside somewhere in actual physical address for duration of that function at least (unless it is a static variable!), so OS maps the compiler generated virtual address of i into an actual physical address, so that whenever, within that function, some code requires the value of i, that process can query the OS for that virtual address, and OS in turn can query the physical a

How to set HTML5 required attribute in Javascript?

let formelems = document.querySelectorAll('input,textarea,select');
formelems.forEach((formelem) => {
  formelem.required = true;

});

If you wish to make all input, textarea, and select elements required.

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

where to place CASE WHEN column IS NULL in this query

Thanks for all your help! @Svetoslav Tsolov had it very close, but I was still getting an error, until I figured out the closing parenthesis was in the wrong place. Here's the final query that works:

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

HTTPS setup in Amazon EC2

Use Elastic Load Balacing, it supports SSL termination at the Load Balancer, including offloading SSL decryption from application instances and providing centralized management of SSL certificates.

How to use switch statement inside a React component?

How about:

mySwitchFunction = (param) => {
   switch (param) {
      case 'A':
         return ([
            <div />,
         ]);
      // etc...
   }
}
render() {
    return (
       <div>
          <div>
               // removed for brevity
          </div>

          { this.mySwitchFunction(param) }

          <div>
              // removed for brevity
          </div>
      </div>
   );
}

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

UDP vs TCP, how much faster is it?

If you need to quickly blast a message across the net between two IP's that haven't even talked yet, then a UDP is going to arrive at least 3 times faster, usually 5 times faster.

Remove old Fragment from fragment manager

You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();

That is it.

Change jsp on button click

You have several options, I'll start from the easiest:

1- Change the input buttons to links, you can style them with css so they look like buttons:

<a href="CreateCourse.jsp">Creazione Nuovo Corso</a>

instead of

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" />

2- Use javascript to change the action of the form depending on the button you click:

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" 
onclick="document.forms[0].action = 'CreateCourse.jsp'; return true;" />

3- Use a servlet or JSP to handle the request and redirect or forward to the appropriate JSP page.

Count how many files in directory PHP

  simple code add for file .php then your folder which number of file to count its      

    $directory = "images/icons";
    $files = scandir($directory);
    for($i = 0 ; $i < count($files) ; $i++){
        if($files[$i] !='.' && $files[$i] !='..')
        { echo $files[$i]; echo "<br>";
            $file_new[] = $files[$i];
        }
    }
    echo $num_files = count($file_new);

simple add its done ....

Difference between 'cls' and 'self' in Python classes?

This is very good question but not as wanting as question. There is difference between 'self' and 'cls' used method though analogically they are at same place

def moon(self, moon_name):
    self.MName = moon_name

#but here cls method its use is different 

@classmethod
def moon(cls, moon_name):
    instance = cls()
    instance.MName = moon_name

Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.

For practical programming approach :

While designing circle class we use area method as cls instead of self because we don't want area to be limited to particular class of circle only .

Getting an Embedded YouTube Video to Auto Play and Loop

Had same experience, however what did the magic for me is not to change embed to v.

So the code will look like this...

<iframe width="560" height="315" src="https://www.youtube.com/embed/cTYuscQu-Og?Version=3&loop=1&playlist=cTYuscQu-Og" frameborder="0" allowfullscreen></iframe>

Hope it helps...

Windows equivalent of linux cksum command

It looks as if there is an unsupported tool for checksums from MS. It's light on features but appears to do what you're asking for. It was published in August of 2012. It's called "Microsoft File Checksum Integrity Verifier".

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

How do I send an HTML Form in an Email .. not just MAILTO

You are making sense, but you seem to misunderstand the concept of sending emails.

HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.

Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST superglobal) and use the email sending function (mail()).

Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.

A simple example code:

form.html:

<form method="post" action="email.php">
    <input type="text" name="subject" /><br />
    <textarea name="message"></textarea>
</form>

email.php:

<?php
    mail('[email protected]', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>

Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).

Define an alias in fish shell

I found the prior answers and comments to be needlessly incomplete and/or confusing. The minimum that I needed to do was:

  1. Create ~/.config/fish/config.fish. This file can optionally be a softlink.
  2. Add to it the line alias myalias echo foo bar.
  3. Restart fish. To confirm the definition, try type myalias. Try the alias.

How to read data from a file in Lua

Try this:

-- http://lua-users.org/wiki/FileInputOutput

-- see if the file exists
function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

-- get all lines from a file, returns an empty 
-- list/table if the file does not exist
function lines_from(file)
  if not file_exists(file) then return {} end
  lines = {}
  for line in io.lines(file) do 
    lines[#lines + 1] = line
  end
  return lines
end

-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)

-- print all line numbers and their contents
for k,v in pairs(lines) do
  print('line[' .. k .. ']', v)
end

MSIE and addEventListener Problem in Javascript?

The problem is that IE does not have the standard addEventListener method. IE uses its own attachEvent which does pretty much the same.

Good explanation of the differences, and also about the 3rd parameter can be found at quirksmode.

How to add leading zeros?

For other circumstances in which you want the number string to be consistent, I made a function.

Someone may find this useful:

idnamer<-function(x,y){#Alphabetical designation and number of integers required
    id<-c(1:y)
    for (i in 1:length(id)){
         if(nchar(id[i])<2){
            id[i]<-paste("0",id[i],sep="")
         }
    }
    id<-paste(x,id,sep="")
    return(id)
}
idnamer("EF",28)

Sorry about the formatting.

:first-child not working as expected

The h1:first-child selector means

Select the first child of its parent
if and only if it's an h1 element.

The :first-child of the container here is the ul, and as such cannot satisfy h1:first-child.

There is CSS3's :first-of-type for your case:

.detail_container h1:first-of-type
{
    color: blue;
} 

But with browser compatibility woes and whatnot, you're better off giving the first h1 a class, then targeting that class:

.detail_container h1.first
{
    color: blue;
}

How do I delete unpushed git commits?

Don't delete it: for just one commit git cherry-pick is enough.

But if you had several commits on the wrong branch, that is where git rebase --onto shines:

Suppose you have this:

 x--x--x--x <-- master
           \
            -y--y--m--m <- y branch, with commits which should have been on master

, then you can mark master and move it where you would want to be:

 git checkout master
 git branch tmp
 git checkout y
 git branch -f master

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- y branch, master branch

, reset y branch where it should have been:

 git checkout y
 git reset --hard HEAD~2 # ~1 in your case, 
                         # or ~n, n = number of commits to cancel

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- master branch
                ^
                |
                -- y branch

, and finally move your commits (reapply them, making actually new commits)

 git rebase --onto tmp y master
 git branch -D tmp


 x--x--x--x--m'--m' <-- master
           \
            -y--y <- y branch

Convert UTF-8 encoded NSData to NSString

If the data is not null-terminated, you should use -initWithData:encoding:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.

NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];

(Note that if the input is not properly UTF-8-encoded, you will get nil.)


Swift variant:

let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.

If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.

// safe way, provided data is \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I had a similar issue when calling the WPF window out of WinForms.

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Show();

However, showing window as a dialog, it worked

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.ShowDialog();

Hope this helps.

Is it possible to have placeholders in strings.xml for runtime values?

Supplemental Answer

When I first saw %1$s and %2$d in the accepted answer, it made no sense. Here is a little more explanation.

They are called format specifiers. In the xml string they are in the form of

%[parameter_index$][format_type] 
  • %: The percent sign marks the beginning of the format specifier.
  • parameter index: This is a number followed by a dollar sign. If you had three parameters that you wanted to insert into the string, then they would be called 1$, 2$, and 3$. The order you place them in the resource string doesn't matter, only the order that you supply the parameters.
  • format type: There are a lot of ways that you can format things (see the documentation). Here are some common ones:

    • s string
    • d decimal integer
    • f floating point number

Example

We will create the following formatted string where the gray parts are inserted programmatically.

My sister Mary is 12 years old.

string.xml

<string name="my_xml_string">My sister %1$s is %2$d years old.</string>

MyActivity.java

String myString = "Mary";
int myInt = 12;
String formatted = getString(R.string.my_xml_string, myString, myInt);

Notes

  • I could use getString because I was in an Activity. You can use context.getResources().getString(...) if it is not available.
  • String.format() will also format a String.
  • The 1$ and 2$ terms don't need to be used in that order. That is, 2$ can come before 1$. This is useful when internationalizing an app for languages that use a different word order.
  • You can use a format specifier like %1$s multiple times in the xml if you want to repeat it.
  • Use %% to get the actual % character.
  • For more details read the following helpful tutorial: Android SDK Quick Tip: Formatting Resource Strings

Regex: match word that ends with "Id"

I would use
\b[A-Za-z]*Id\b
The \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string.

The [A-Za-z] will match any letter, and the * means that 0+ get matched. Finally there is the Id.

Note that this will match words that have capital letters in the middle such as 'teStId'.

I use http://www.regular-expressions.info/ for regex reference

Chart.js canvas resize

 let canvasBox = ReactDOM.findDOMNode(this.refs.canvasBox);
 let width = canvasBox.clientWidth;
 let height = canvasBox.clientHeight;
 let charts = ReactDOM.findDOMNode(this.refs.charts);
 let ctx = charts.getContext('2d');
 ctx.canvas.width = width;
 ctx.canvas.height = height;
 this.myChart = new Chart(ctx);

How to redirect docker container logs to a single file?

Assuming that you have multiple containers and you want to aggregate the logs into a single file, you need to use some log aggregator like fluentd. fluentd is supported as logging driver for docker containers.

So in docker-compose, you need to define the logging driver

  service1:
    image: webapp:0.0.1
    logging:
      driver: "fluentd"
      options:
        tag: service1 

  service2:
        image: myapp:0.0.1
        logging:
          driver: "fluentd"
          options:
            tag: service2

The second step would be update the fluentd conf to cater the logs for both service 1 and service 2

 <match service1>
   @type copy
   <store>
    @type file
    path /fluentd/log/service/service.*.log
    time_slice_format %Y%m%d
    time_slice_wait 10m
    time_format %Y%m%dT%H%M%S%z
  </store>
 </match> 
 <match service2>
    @type copy
   <store>
    @type file
    path /fluentd/log/service/service.*.log
    time_slice_format %Y%m%d
    time_slice_wait 10m
    time_format %Y%m%dT%H%M%S%
  </store>
 </match> 

In this config, we are asking logs to be written to a single file to this path
/fluentd/log/service/service.*.log

and the third step would be to run the customized fluentd which will start writing the logs to file.

Here is the link for step by step instructions

Bit Long, but correct way since you get more control over log files path etc and it works well in Docker Swarm too .

How do I use a custom Serializer with Jackson?

You can put @JsonSerialize(using = CustomDateSerializer.class) over any date field of object to be serialized.

public class CustomDateSerializer extends SerializerBase<Date> {

    public CustomDateSerializer() {
        super(Date.class, true);
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)");
        String format = formatter.format(value);
        jgen.writeString(format);
    }

}

Creating threads - Task.Factory.StartNew vs new Thread()

Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.

Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.

This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.

How can I change the color of pagination dots of UIPageControl?

In cased of Swift 2.0 and up, the below code will work:

pageControl.pageIndicatorTintColor = UIColor.whiteColor()
pageControl.currentPageIndicatorTintColor = UIColor.redColor()

How to re-index all subarray elements of a multidimensional array?

PHP native function exists for this. See http://php.net/manual/en/function.reset.php

Simply do this: mixed reset ( array &$array )

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Open the file in Notepad. Click 'Save As...'. In the 'Encoding:' combo box you will see the current file format.

Get generic type of class at runtime

As others mentioned, it's only possible via reflection in certain circumstances.

If you really need the type, this is the usual (type-safe) workaround pattern:

public class GenericClass<T> {

     private final Class<T> type;

     public GenericClass(Class<T> type) {
          this.type = type;
     }

     public Class<T> getMyType() {
         return this.type;
     }
}

How to find largest objects in a SQL Server database?

You may also use the following code:

USE AdventureWork
GO
CREATE TABLE #GetLargest 
(
  table_name    sysname ,
  row_count     INT,
  reserved_size VARCHAR(50),
  data_size     VARCHAR(50),
  index_size    VARCHAR(50),
  unused_size   VARCHAR(50)
)

SET NOCOUNT ON

INSERT #GetLargest

EXEC sp_msforeachtable 'sp_spaceused ''?'''

SELECT 
  a.table_name,
  a.row_count,
  COUNT(*) AS col_count,
  a.data_size
  FROM #GetLargest a
     INNER JOIN information_schema.columns b
     ON a.table_name collate database_default
     = b.table_name collate database_default
       GROUP BY a.table_name, a.row_count, a.data_size
       ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC

DROP TABLE #GetLargest

How do I print part of a rendered HTML page in JavaScript?

Try this JavaScript code:

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}

How to load json into my angular.js ng-model?

As Kris mentions, you can use the $resource service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http service. In this case you can call its get method.

If you have the following JSON

[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

You can load it like this

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;                
        });
});

The get method returns a promise object which first argument is a success callback and the second an error callback.

When you add $http as a parameter of a function Angular does it magic and injects the $http resource into your controller.

I've put some examples here

How to increment a JavaScript variable using a button press event

I believe you need something similar to the following:

<script type="text/javascript">
var count;
function increment(){
    count++;
}
</script>

...

and

<input type="button" onClick="increment()" value="Increment"/>

or

<input type="button" onClick="count++" value="Increment"/>

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

Enter

git log .

from the specific directory, it also gives commits in that directory.

Git Stash vs Shelve in IntelliJ IDEA

When using JetBrains IDE's with Git, "stashing and unstashing actions are supported in addition to shelving and unshelving. These features have much in common; the major difference is in the way patches are generated and applied. Shelve can operate with either individual files or bunch of files, while Stash can only operate with a whole bunch of changed files at once. Here are some more details on the differences between them."

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

How to create a self-signed certificate with OpenSSL

Modern browsers now throw a security error for otherwise well-formed self-signed certificates if they are missing a SAN (Subject Alternate Name). OpenSSL does not provide a command-line way to specify this, so many developers' tutorials and bookmarks are suddenly outdated.

The quickest way to get running again is a short, stand-alone conf file:

  1. Create an OpenSSL config file (example: req.cnf)

    [req]
    distinguished_name = req_distinguished_name
    x509_extensions = v3_req
    prompt = no
    [req_distinguished_name]
    C = US
    ST = VA
    L = SomeCity
    O = MyCompany
    OU = MyDivision
    CN = www.company.com
    [v3_req]
    keyUsage = critical, digitalSignature, keyAgreement
    extendedKeyUsage = serverAuth
    subjectAltName = @alt_names
    [alt_names]
    DNS.1 = www.company.com
    DNS.2 = company.com
    DNS.3 = company.net
    
  2. Create the certificate referencing this config file

    openssl req -x509 -nodes -days 730 -newkey rsa:2048 \
     -keyout cert.key -out cert.pem -config req.cnf -sha256
    

Example config from https://support.citrix.com/article/CTX135602

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

#False positive cases
train = pd.merge(X_train, y_train,left_index=True, right_index=True)
y_train_pred = pd.DataFrame(y_train_pred)
y_train_pred.rename(columns={0 :'Predicted'}, inplace=True )
train = train.reset_index(drop=True).merge(y_train_pred.reset_index(drop=True),
left_index=True,right_index=True)
train['FP'] = np.where((train['Banknote']=="Forged") & (train['Predicted']=="Genuine"),1,0)
train[train.FP != 0]

Determine the process pid listening on a certain port

netstat -nlp should tell you the PID of what's listening on which port.

How to load html string in a webview?

You also can try out this

   final WebView webView = new WebView(this);
            webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

Set Response Status Code

Since PHP 5.4 you can use http_response_code.

http_response_code(404);

This will take care of setting the proper HTTP headers.

If you are running PHP < 5.4 then you have two options:

  1. Upgrade.
  2. Use this http_response_code function implemented in PHP.

How to run multiple SQL commands in a single SQL connection?

I have not tested , but what the main idea is: put semicolon on each query.

SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
     update table
     set somecol = somevalue;
     insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;

try
{
    connection.Open();
}
finally
{
    command.Dispose();
    connection.Dispose();
}

Update: you can follow Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too

Single controller with multiple GET methods in ASP.NET Web API

You need to define further routes in global.asax.cs like this:

routes.MapHttpRoute(
    name: "Api with action",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

The technical limitations with using PUT and DELETE requests does not lie with PHP or Apache2; it is instead on the burden of the browser to sent those types of requests.

Simply putting <form action="" method="PUT"> will not work because there are no browsers that support that method (and they would simply default to GET, treating PUT the same as it would treat gibberish like FDSFGS). Sadly those HTTP verbs are limited to the realm of non-desktop application browsers (ie: web service consumers).

Disable keyboard on EditText

This worked for me. First add this android:windowSoftInputMode="stateHidden" in your android manifest file, under your activity. like below:

<activity ... android:windowSoftInputMode="stateHidden">

Then on onCreate method of youractivity, add the foloowing code:

EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethod!= null) {
            inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }                
        return true;
    }
});

Then if you want the pointer to be visible add this on your xml android:textIsSelectable="true".

This will make the pointer visible. In this way the keyboard will not popup when your activity starts and also will be hidden when you click on the edittext.

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Run PHP function on html button click

A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

Depending on the data sent in the POST/GET you can have a switch statement running a different function.

Specifying Function via GET

You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.

So on PHP side you can have something like this:

<?php

//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";

function test()
{
echo("test");
}

function hello()
{
echo("hello");
}

?>

and you can make the simplest get request using the address bar as testing:

http://127.0.0.1/test.php?runFunction=hellodddddd

results in:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello

results in:

hello

Sending the Data

GET Request via JQuery

See: http://api.jquery.com/jQuery.get/

$.get("test.cgi", { name: "John"})
.done(function(data) {
  alert("Data Loaded: " + data);
});

POST Request via JQuery

See: http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );

GET Request via Javascript location

See: http://www.javascripter.net/faq/buttonli.htm

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">

Reading the Data (PHP)

See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

Useful Links

http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

LINQ select in C# dictionary

This will return all the values matching your key valueTitle

subList.SelectMany(m => m).Where(kvp => kvp.Key == "valueTitle").Select(k => k.Value).ToList();

vb.net get file names in directory?

Dim fileEntries As String() = Directory.GetFiles("YourPath", "*.txt")
' Process the list of .txt files found in the directory. '
Dim fileName As String

For Each fileName In fileEntries
    If (System.IO.File.Exists(fileName)) Then
        'Read File and Print Result if its true
        ReadFile(fileName)
    End If
    TransfereFile(fileName, 1)
Next

How do I connect to a MySQL Database in Python?

Run this command in your terminal to install mysql connector:

pip install mysql-connector-python

And run this in your python editor to connect to MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      passwd="password",
      database="database_name"
)

Samples to execute MySQL Commands (in your python edior):

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
mycursor.execute("SHOW TABLES")

mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
mydb.commit() # Use this command after insert or update

For more commands: https://www.w3schools.com/python/python_mysql_getstarted.asp

How to remove the URL from the printing page?

This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.

@print {
    @page :footer {
        display: none
    }

    @page :header {
        display: none
    }
}

JavaScript - Get minutes between two dates

A simple function to perform this calculation:

function getMinutesBetweenDates(startDate, endDate) {
    var diff = endDate.getTime() - startDate.getTime();
    return (diff / 60000);
}

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

How to link home brew python version and set it as default

After installing python3 with brew install python3 I was getting the error:

Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks

After typing brew link python3 the error was:

Linking /usr/local/Cellar/python/3.6.4_3... Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks

To solve the problem:

sudo mkdir -p /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/*
brew link python3

After this, I could open python3 by typing python3

(From https://github.com/Homebrew/homebrew-core/issues/20985)

Check if decimal value is null

Assuming you are reading from a data row, what you want is:

if ( !rdrSelect.IsNull(23) ) 
{ 
   //handle parsing
}

Multiple left joins on multiple tables in one query

You can do like this

SELECT something
FROM
    (a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'

Checking if any elements in one list are in another

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")

Delete all the queues from RabbitMQ?

You need not reset rabbitmq server to delete non-durable queues. Simply stop the server and start again and it will remove all the non-durable queues available.

How can I convert this foreach code to Parallel.ForEach?

Foreach loop:

  • Iterations takes place sequentially, one by one
  • foreach loop is run from a single Thread.
  • foreach loop is defined in every framework of .NET
  • Execution of slow processes can be slower, as they're run serially
    • Process 2 can't start until 1 is done. Process 3 can't start until 2 & 1 are done...
  • Execution of quick processes can be faster, as there is no threading overhead

Parallel.ForEach:

  • Execution takes place in parallel way.
  • Parallel.ForEach uses multiple Threads.
  • Parallel.ForEach is defined in .Net 4.0 and above frameworks.
  • Execution of slow processes can be faster, as they can be run in parallel
    • Processes 1, 2, & 3 may run concurrently (see reused threads in example, below)
  • Execution of quick processes can be slower, because of additional threading overhead

The following example clearly demonstrates the difference between traditional foreach loop and

Parallel.ForEach() Example

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelForEachExample
{
    class Program
    {
        static void Main()
        {
            string[] colors = {
                                  "1. Red",
                                  "2. Green",
                                  "3. Blue",
                                  "4. Yellow",
                                  "5. White",
                                  "6. Black",
                                  "7. Violet",
                                  "8. Brown",
                                  "9. Orange",
                                  "10. Pink"
                              };
            Console.WriteLine("Traditional foreach loop\n");
            //start the stopwatch for "for" loop
            var sw = Stopwatch.StartNew();
            foreach (string color in colors)
            {
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            }
            Console.WriteLine("foreach loop execution time = {0} seconds\n", sw.Elapsed.TotalSeconds);
            Console.WriteLine("Using Parallel.ForEach");
            //start the stopwatch for "Parallel.ForEach"
             sw = Stopwatch.StartNew();
            Parallel.ForEach(colors, color =>
            {
                Console.WriteLine("{0}, Thread Id= {1}", color, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            }
            );
            Console.WriteLine("Parallel.ForEach() execution time = {0} seconds", sw.Elapsed.TotalSeconds);
            Console.Read();
        }
    }
}

Output

Traditional foreach loop
1. Red, Thread Id= 10
2. Green, Thread Id= 10
3. Blue, Thread Id= 10
4. Yellow, Thread Id= 10
5. White, Thread Id= 10
6. Black, Thread Id= 10
7. Violet, Thread Id= 10
8. Brown, Thread Id= 10
9. Orange, Thread Id= 10
10. Pink, Thread Id= 10
foreach loop execution time = 0.1054376 seconds

Using Parallel.ForEach example

1. Red, Thread Id= 10
3. Blue, Thread Id= 11
4. Yellow, Thread Id= 11
2. Green, Thread Id= 10
5. White, Thread Id= 12
7. Violet, Thread Id= 14
9. Orange, Thread Id= 13
6. Black, Thread Id= 11
8. Brown, Thread Id= 10
10. Pink, Thread Id= 12
Parallel.ForEach() execution time = 0.055976 seconds

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

TNS Protocol adapter error while starting Oracle SQL*Plus

Ensure the OracleService is running. I keep running into this error, but when I go into Services, find OracleServiceXE and manually start it, the problem is resolved. I have it set to start automatically, but sometimes it just seems to stop on its own; at least, I can't find anything I am doing to stop it.

Disabling Chrome Autofill

<input readonly onfocus="this.removeAttribute('readonly');" type="text">

adding readonly attribute to the tag along with the onfocus event removing it fixes the issue

Error during SSL Handshake with remote server

I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.

So, I had to generate the SSL certificate again and it started working...

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

SQL Server 2005 Setting a variable to the result of a select query

This will work for original question asked:

DECLARE @Result INT;
SELECT @Result = COUNT(*)
FROM  TableName
WHERE Condition

What does bundle exec rake mean?

It means use rake that bundler is aware of and is part of your Gemfile over any rake that bundler is not aware of and run the db:migrate task.

Encoding an image file with base64

Borrowing from what Ivo van der Wijk and gnibbler have developed earlier, this is a dynamic solution

import cStringIO
import PIL.Image

image_data = None

def imagetopy(image, output_file):
    with open(image, 'rb') as fin:
        image_data = fin.read()

    with open(output_file, 'w') as fout:
        fout.write('image_data = '+ repr(image_data))

def pytoimage(pyfile):
    pymodule = __import__(pyfile)
    img = PIL.Image.open(cStringIO.StringIO(pymodule.image_data))
    img.show()

if __name__ == '__main__':
    imagetopy('spot.png', 'wishes.py')
    pytoimage('wishes')

You can then decide to compile the output image file with Cython to make it cool. With this method, you can bundle all your graphics into one module.

How to send json data in the Http request using NSURLRequest

Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as

This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer

I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.

    NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
      [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
    NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
     receivedData = [[NSMutableData data] retain];
    }

The receivedData is then handled by:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];

Does "git fetch --tags" include "git fetch"?

Note: this answer is only valid for git v1.8 and older.

Most of this has been said in the other answers and comments, but here's a concise explanation:

  • git fetch fetches all branch heads (or all specified by the remote.fetch config option), all commits necessary for them, and all tags which are reachable from these branches. In most cases, all tags are reachable in this way.
  • git fetch --tags fetches all tags, all commits necessary for them. It will not update branch heads, even if they are reachable from the tags which were fetched.

Summary: If you really want to be totally up to date, using only fetch, you must do both.

It's also not "twice as slow" unless you mean in terms of typing on the command-line, in which case aliases solve your problem. There is essentially no overhead in making the two requests, since they are asking for different information.

What do the result codes in SVN mean?

You can always get a list by running:

svn status --help

Is there a destructor for Java?

With Java 1.7 released, you now have the additional option of using the try-with-resources block. For example,

public class Closeable implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("closing..."); 
    }
    public static void main(String[] args) {
        try (Closeable c = new Closeable()) {
            System.out.println("trying..."); 
            throw new Exception("throwing..."); 
        }
        catch (Exception e) {
            System.out.println("catching..."); 
        }
        finally {
            System.out.println("finalizing..."); 
        } 
    }
}

If you execute this class, c.close() will be executed when the try block is left, and before the catch and finally blocks are executed. Unlike in the case of the finalize() method, close() is guaranteed to be executed. However, there is no need of executing it explicitly in the finally clause.

Best way to convert string to bytes in Python 3?

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

Is there "\n" equivalent in VBscript?

I had to use vbLf only in an ASP script where the original data was POSTed from a PHP script on a cPanel box over to ASP on a win server

(VBScript)

EmailText = Replace(EmailText, vbLf, "<br>")

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

Maximum length of the textual representation of an IPv6 address?

On Linux, see constant INET6_ADDRSTRLEN (include <arpa/inet.h>, see man inet_ntop). On my system (header "in.h"):

#define INET6_ADDRSTRLEN 46

The last character is for terminating NULL, as I belive, so the max length is 45, as other answers.

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

// detect IE8 and above, and Edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    ... do something
}

Explanation:

document.documentMode

An IE only property, first available in IE8.

/Edge/

A regular expression to search for the string 'Edge' - which we then test against the 'navigator.userAgent' property

Update Mar 2020

@Jam comments that the latest version of Edge now reports Edg as the user agent. So the check would be:

if (document.documentMode || /Edge/.test(navigator.userAgent) || /Edg/.test(navigator.userAgent)) {
    ... do something
}

Storing data into list with class

  public IEnumerable<CustInfo> SaveCustdata(CustInfo cust)
        {
            try
            {
                var customerinfo = new CustInfo
                {
                    Name = cust.Name,
                    AccountNo = cust.AccountNo,
                    Address = cust.Address
                };
                List<CustInfo> custlist = new List<CustInfo>();
                custlist.Add(customerinfo);
                return custlist;
            }
            catch (Exception)
            {
                return null;
            }
        }

Xcopy Command excluding files and folders

Like Andrew said /exclude parameter of xcopy should be existing file that has list of excludes.

Documentation of xcopy says:

Using /exclude

List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

Example:

xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

and list-of-excluded-files.txt should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:

exclusion.txt

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

Using PHP with Socket.io

I know the struggle man! But I recently had it pretty much working with Workerman. If you have not stumbled upon this php framework then you better check this out!

Well, Workerman is an asynchronous event driven PHP framework for easily building fast, scalable network applications. (I just copied and pasted that from their website hahahah http://www.workerman.net/en/)

The easy way to explain this is that when it comes web socket programming all you really need to have is to have 2 files in your server or local server (wherever you are working at).

  1. server.php (source code which will respond to all the client's request)

  2. client.php/client.html (source code which will do the requesting stuffs)

So basically, you right the code first on you server.php and start the server. Normally, as I am using windows which adds more of the struggle, I run the server through this command --> php server.php start

Well if you are using xampp. Here's one way to do it. Go to wherever you want to put your files. In our case, we're going to the put the files in

C:/xampp/htdocs/websocket/server.php

C:/xampp/htdocs/websocket/client.php or client.html

Assuming that you already have those files in your local server. Open your Git Bash or Command Line or Terminal or whichever you are using and download the php libraries here.

https://github.com/walkor/Workerman

https://github.com/walkor/phpsocket.io

I usually download it via composer and just autoload those files in my php scripts.

And also check this one. This is really important! You need this javascript libary in order for you client.php or client.html to communicate with the server.php when you run it.

https://github.com/walkor/phpsocket.io/tree/master/examples/chat/public/socket.io-client

I just copy and pasted that socket.io-client folder on the same level as my server.php and my client.php

Here is the server.php sourcecode

<?php
require __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
    $socket->on('send message', function($msg)use($io){
        $io->emit('new message', $msg);
    });
});

Worker::runAll();

And here is the client.php or client.html sourcecode

<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">        
    </head>
    <body>
        <div id="chat-messages" style="overflow-y: scroll; height: 100px; "></div>        
        <input type="text" class="message">
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
    <script src="socket.io-client/socket.io.js"></script>  
    <script>
            var socket = io.connect("ws://127.0.0.1:2021");

            $('.message').on('change', function(){
                socket.emit('send message', $(this).val());
                $(this).val('');
            });

            socket.on('new message', function(data){
                $('#chat-messages').append('<p>' + data +'</p>');
            });
    </script>
</html>

Once again, open your command line or git bash or terminal where you put your server.php file. So in our case, that is C:/xampp/htdocs/websocket/ and typed in php server.php start and press enter.

Then go to you browser and type http://localhost/websocket/client.php to visit your site. Then just type anything to that textbox and you will see a basic php websocket on the go!

You just need to remember. In web socket programming, it just needs a server and a client. Run the server code first and the open the client code. And there you have it! Hope this helps!

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

How to dynamically add a style for text-align using jQuery

Interesting. I got the same problem as you when I wrote a test version.

The solution is to use jquery's ability to chain and do:

$(this).width(500).css("text-align", "center");

Interesting find though.

To expand a bit, the following does not work

$(this).width(500);
$(this).css("text-align", "center");

and results only in the width being set on the style. Chaining the two, as I suggested above, does seem to work.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

  1. running code before Compilation : use controller
  2. running code after Compilation : use Link

Angular convention : write business logic in controller and DOM manipulation in link.

Apart from this you can call one controller function from link function of another directive.For example you have 3 custom directives

<animal>
<panther>
<leopard></leopard>
</panther> 
</animal>

and you want to access animal from inside of "leopard" directive.

http://egghead.io/lessons/angularjs-directive-communication will be helpful to know about inter-directive communication

From milliseconds to hour, minutes, seconds and milliseconds

Just an other java example:

long dayLength = 1000 * 60 * 60 * 24;
long dayMs = System.currentTimeMillis() % dayLength;
double percentOfDay = (double) dayMs / dayLength;
int hour = (int) (percentOfDay * 24);
int minute = (int) (percentOfDay * 24 * 60) % 60;
int second = (int) (percentOfDay * 24 * 60 * 60) % 60;

an advantage is that you can simulate shorter days, if you adjust dayLength

How to change font-size of a tag using inline css?

Strange it doesn't change, as inline styles are most specific, if style sheet has !important declared, it wont over ride, try this and see

<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>

How do I declare a model class in my Angular 2 component using TypeScript?

In your case you are having model on same page, but you have it declared after your Component class, so that's you need to use forwardRef to refer to Class. Don't prefer to do this, always have model object in separate file.

export class testWidget {
    constructor(@Inject(forwardRef(() => Model)) private service: Model) {}
}

Additionally you have to change you view interpolation to refer to correct object

{{model?.param1}}

Better thing you should do is, you can have your Model Class define in different file & then import it as an when you require it by doing. Also have export before you class name, so that you can import it.

import { Model } from './model';

removeEventListener on anonymous functions in JavaScript

A not so anonymous option

element.funky = function() {
    console.log("Click!");
};
element.funky.type = "click";
element.funky.capt = false;
element.addEventListener(element.funky.type, element.funky, element.funky.capt);
// blah blah blah
element.removeEventListener(element.funky.type, element.funky, element.funky.capt);

Since receiving feedback from Andy (quite right, but as with many examples, I wished to show a contextual expansion of the idea), here's a less complicated exposition:

<script id="konami" type="text/javascript" async>
    var konami = {
        ptrn: "38,38,40,40,37,39,37,39,66,65",
        kl: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
    };
    document.body.addEventListener( "keyup", function knm ( evt ) {
        konami.kl = konami.kl.slice( -9 );
        konami.kl.push( evt.keyCode );
        if ( konami.ptrn === konami.kl.join() ) {
            evt.target.removeEventListener( "keyup", knm, false );

            /* Although at this point we wish to remove a listener
               we could easily have had multiple "keyup" listeners
               each triggering different functions, so we MUST
               say which function we no longer wish to trigger
               rather than which listener we wish to remove.

               Normal scoping will apply to where we can mention this function
               and thus, where we can remove the listener set to trigger it. */

            document.body.classList.add( "konami" );
        }
    }, false );
    document.body.removeChild( document.getElementById( "konami" ) );
</script>

This allows an effectively anonymous function structure, avoids the use of the practically deprecated callee, and allows easy removal.

Incidentally: The removal of the script element immediately after setting the listener is a cute trick for hiding code one would prefer wasn't starkly obvious to prying eyes (would spoil the surprise ;-)

So the method (more simply) is:

element.addEventListener( action, function name () {
    doSomething();
    element.removeEventListener( action, name, capture );
}, capture );

jquery to change style attribute of a div class

You can't use $('#Id').attr('style',' color:red'); and $('#Id').css('padding-left','20%');
at the same time.
You can either use attr or css but both only works when they are used alone.

assembly to compare two numbers

As already mentioned, usually the comparison is done through subtraction.
For example, X86 Assembly/Control Flow.

At the hardware level there are special digital circuits for doing the calculations, like adders.

What is "with (nolock)" in SQL Server?

The simplest answer is a simple question - do you need your results to be repeatable? If yes then NOLOCKS is not appropriate under any circumstances

If you don't need repeatability then nolocks may be useful, especially if you don't have control over all processes connecting to the target database.

What is recursion and when should I use it?

1.) A method is recursive if it can call itself; either directly:

void f() {
   ... f() ... 
}

or indirectly:

void f() {
    ... g() ...
}

void g() {
   ... f() ...
}

2.) When to use recursion

Q: Does using recursion usually make your code faster? 
A: No.
Q: Does using recursion usually use less memory? 
A: No.
Q: Then why use recursion? 
A: It sometimes makes your code much simpler!

3.) People use recursion only when it is very complex to write iterative code. For example, tree traversal techniques like preorder, postorder can be made both iterative and recursive. But usually we use recursive because of its simplicity.

How to drop columns using Rails migration

in rails 5 you can use this command in the terminal:

rails generate migration remove_COLUMNNAME_from_TABLENAME COLUMNNAME:DATATYPE

for example to remove the column access_level(string) from table users:

rails generate migration remove_access_level_from_users access_level:string

and then run:

rake db:migrate

Convert string to integer type in Go?

Converting Simple strings

The easiest way is to use the strconv.Atoi() function.

Note that there are many other ways. For example fmt.Sscan() and strconv.ParseInt() which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi():

Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Here's an example using the mentioned functions (try it on the Go Playground):

flag.Parse()
s := flag.Arg(0)

if i, err := strconv.Atoi(s); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

if i, err := strconv.ParseInt(s, 10, 64); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

var i int
if _, err := fmt.Sscan(s, &i); err == nil {
    fmt.Printf("i=%d, type: %T\n", i, i)
}

Output (if called with argument "123"):

i=123, type: int
i=123, type: int64
i=123, type: int

Parsing Custom strings

There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string.

This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123" where you have a prefix "id:" and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:

s := "id:00123"

var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
    fmt.Println(i) // Outputs 123
}

How do I update a formula with Homebrew?

You can update all outdated packages like so:

brew install `brew outdated`

or

brew outdated | xargs brew install

or

brew upgrade

This is from the brew site..

for upgrading individual formula:

brew install formula-name && brew cleanup formula-name

Scanner method to get a char

Console cons = System.console();

The above code line creates cons as a null reference. The code and output are given below:

Console cons = System.console();
if (cons != null) {
    System.out.println("Enter single character: ");
    char c = (char) cons.reader().read();
    System.out.println(c);
}else{
    System.out.println(cons);
}

Output :

null

The code was tested on macbook pro with java version "1.6.0_37"

What is the difference between . (dot) and $ (dollar sign)?

All the other answers are pretty good. But there’s an important usability detail about how ghc treats $, that the ghc type checker allows for instatiarion with higher rank/ quantified types. If you look at the type of $ id for example you’ll find it’s gonna take a function whose argument is itself a polymorphic function. Little things like that aren’t given the same flexibility with an equivalent upset operator. (This actually makes me wonder if $! deserves the same treatment or not )

How do I resolve a TesseractNotFoundError?

This occurs under windows (at least in tesseract version 3.05) when the current directory is on a different drive from where tesseract is installed.

Something in tesseract is expecting data files to be in \Program Files... (rather than C:\Program Files, say). So if you're not on the same drive letter as tesseract, it will fail. It would be great if we could work around it by temporarily changing drives (under windows only) to the tesseract installation drive before executing tesseract, and changing back after. Example in your case: You can copy yourmodule_python.py to "C/Program Files (x86)/Tesseract-OCR/" and RUN!

Are members of a C++ struct initialized to 0 by default?

Move pod members to a base class to shorten your initializer list:

struct foo_pod
{
    int x;
    int y;
    int z;
};

struct foo : foo_pod
{
    std::string name;
    foo(std::string name)
        : foo_pod()
        , name(name)
    {
    }
};

int main()
{
    foo f("bar");
    printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}

Passing parameter using onclick or a click binding with KnockoutJS

Use a binding, like in this example:

<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')">
  Search Manager
</a>
var ViewModelStructure = function () {
    var self = this;
    this.SearchManager = function (search) {
        console.log(search);
    };
}();

Convert a String of Hex into ASCII in Java

To this case, I have a hexadecimal data format into an int array and I want to convert them on String.

int[] encodeHex = new int[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; // Hello encode
for (int i = 0; i < encodeHex.length; i++) {
   System.out.print((char) (encodeHex[i]));
}

Template not provided using create-react-app

This worked for me 1.First uninstall create-react-app globally by this command:

npm uninstall -g create-react-app

If there you still have the previous installation please delete the folder called my app completely.(Make sure no program is using that folder including your terminal or cmd promt)

2.then in your project directory:

npm install create-react-app@latest

3.finally:

npx create-react-app my-app

Why can't Python parse this JSON data?

Your data.json should look like this:

{
 "maps":[
         {"id":"blabla","iscategorical":"0"},
         {"id":"blabla","iscategorical":"0"}
        ],
"masks":
         {"id":"valore"},
"om_points":"value",
"parameters":
         {"id":"valore"}
}

Your code should be:

import json
from pprint import pprint

with open('data.json') as data_file:    
    data = json.load(data_file)
pprint(data)

Note that this only works in Python 2.6 and up, as it depends upon the with-statement. In Python 2.5 use from __future__ import with_statement, in Python <= 2.4, see Justin Peel's answer, which this answer is based upon.

You can now also access single values like this:

data["maps"][0]["id"]  # will return 'blabla'
data["masks"]["id"]    # will return 'valore'
data["om_points"]      # will return 'value'

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

In Preferences -> General -> Web Browser, there is the option "Use internal web browser". Select "Use external web browser" instead and check "Firefox".

What is the maximum value for an int32?

Here's a mnemonic for remembering 2**31, subtract one to get the maximum integer value.

a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9

Boys And Dogs Go Duck Hunting, Come Friday Ducks Hide
2    1   4    7  4    8        3    6      4     8

I've used the powers of two up to 18 often enough to remember them, but even I haven't bothered memorizing 2**31. It's too easy to calculate as needed or use a constant, or estimate as 2G.

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

build.gradle

allprojects {
    repositories {
        google()
        mavenLocal()
        jcenter()
        maven {
            url 'https://maven.google.com'
        }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

Problems with entering Git commit message with Vim

If it is VIM for Windows, you can do the following:

  • enter your message following the presented guidelines
  • press Esc to make sure you are out of the insert mode
  • then type :wqEnter or ZZ.

Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wqEnter always writes the current file before closing it, while ZZ, :xEnter, :xiEnter, :xitEnter, :exiEnter and :exitEnter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.

How to return JSON with ASP.NET & jQuery

Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.

Of course, it's then up to you to do what you need to do on the client side.

I would be thinking something like this:

[WebMethod]
public static List GetProducts()
{
   var products  = context.GetProducts().ToList();   
   return products;
}

There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data

Git Push ERROR: Repository not found

Also be sure to check whether you have desktop client installed. I double checked everything, my permission, SSH, but turns out my repo listed in the client was overriding the one I was inputting via terminal.

Biggest differences of Thrift vs Protocol Buffers?

Another important difference are the languages supported by default.

  • Protocol Buffers: Java, Android Java, C++, Python, Ruby, C#, Go, Objective-C, Node.js
  • Thrift: Java, C++, Python, Ruby, C#, Go, Objective-C, JavaScript, Node.js, Erlang, PHP, Perl, Haskell, Smalltalk, OCaml, Delphi, D, Haxe

Both could be extended to other platforms, but these are the languages bindings available out-of-the-box.

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get

INSERT INTO...SELECT for all MySQL columns

More Examples & Detail

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

Counting the occurrences / frequency of array elements

So here's how I'd do it with some of the newest javascript features:

First, reduce the array to a Map of the counts:

let countMap = array.reduce(
  (map, value) => {map.set(value, (map.get(value) || 0) + 1); return map}, 
  new Map()
)

By using a Map, your starting array can contain any type of object, and the counts will be correct. Without a Map, some types of objects will give you strange counts. See the Map docs for more info on the differences.

This could also be done with an object if all your values are symbols, numbers, or strings:

let countObject = array.reduce(
  (map, value) => { map[value] = (map[value] || 0) + 1; return map },
  {}
)

Or slightly fancier in a functional way without mutation, using destructuring and object spread syntax:

let countObject = array.reduce(
  (value, {[value]: count = 0, ...rest}) => ({ [value]: count + 1, ...rest }),
  {}
)

At this point, you can use the Map or object for your counts (and the map is directly iterable, unlike an object), or convert it to two arrays.

For the Map:

countMap.forEach((count, value) => console.log(`value: ${value}, count: ${count}`)

let values = countMap.keys()
let counts = countMap.values()

Or for the object:

Object
  .entries(countObject) // convert to array of [key, valueAtKey] pairs
  .forEach(([value, count]) => console.log(`value: ${value}, count: ${count}`)

let values = Object.keys(countObject)
let counts = Object.values(countObject)

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

What is the most "pythonic" way to iterate over a list in chunks?

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))
# (in python 2 use xrange() instead of range() to avoid allocating a list)

Works with any sequence:

text = "I am a very, very helpful text"

for group in chunker(text, 7):
   print(repr(group),)
# 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'

print '|'.join(chunker(text, 10))
# I am a ver|y, very he|lpful text

animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']

for group in chunker(animals, 3):
    print(group)
# ['cat', 'dog', 'rabbit']
# ['duck', 'bird', 'cow']
# ['gnu', 'fish']

How to install PHP mbstring on CentOS 6.2

*Make sure you update your linux box first

yum update

In case someone still has this problem, this is a valid solution:

centos-release : rpm -q centos-release

Centos 6.*

wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm

Centos 5.*

wget http://ftp.jaist.ac.jp/pub/Linux/Fedora/epel/5/x86_64/epel-release-5-4.noarch.rpm
rpm -ivh epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
rpm -Uvh remi-release-5*.rpm

Then just do this to update:

yum --enablerepo=remi upgrade php-mbstring

Or this to install:

yum --enablerepo=remi install php-mbstring

jQuery fade out then fade in

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require

Rename multiple files in cmd

I tried pasting Endoro's command (Thanks Endoro) directly into the command prompt to add a prefix to files but encountered an error. Solution was to reduce %% to %, so:

for /f "delims=" %i in ('dir /b /a-d *.*') do ren "%~i" "Service.Enviro.%~ni%~xi"

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

How do I return multiple values from a function in C?

Two different approaches:

  1. Pass in your return values by pointer, and modify them inside the function. You declare your function as void, but it's returning via the values passed in as pointers.
  2. Define a struct that aggregates your return values.

I think that #1 is a little more obvious about what's going on, although it can get tedious if you have too many return values. In that case, option #2 works fairly well, although there's some mental overhead involved in making specialized structs for this purpose.

Best practice to return errors in ASP.NET Web API

For those errors where modelstate.isvalid is false, I generally send the error as it is thrown by the code. Its easy to understand for the developer who is consuming my service. I generally send the result using below code.

     if(!ModelState.IsValid) {
                List<string> errorlist=new List<string>();
                foreach (var value in ModelState.Values)
                {
                    foreach(var error in value.Errors)
                    errorlist.Add( error.Exception.ToString());
                    //errorlist.Add(value.Errors);
                }
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest,errorlist);}

This sends the error to the client in below format which is basically a list of errors:

    [  
    "Newtonsoft.Json.JsonReaderException: **Could not convert string to integer: abc. Path 'Country',** line 6, position 16.\r\n   
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()\r\n   
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter, Boolean inArray)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)",

       "Newtonsoft.Json.JsonReaderException: **Could not convert string to integer: ab. Path 'State'**, line 7, position 13.\r\n   
at Newtonsoft.Json.JsonReader.ReadAsInt32Internal()\r\n   
at Newtonsoft.Json.JsonTextReader.ReadAsInt32()\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter, Boolean inArray)\r\n   
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)"
    ]

Check if instance is of a type

Also, somewhat in the same vein

Type.IsAssignableFrom(Type c)

"True if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c."

From here: http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

How to Sign an Already Compiled Apk

create a key using

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

Import data into Google Colaboratory

The simplest solution I have found so far which works perfectly for small to mid-size CSV files is:

  1. Create a secret gist on gist.github.com and upload (or copy-paste the content of) your file.
  2. Click on the Raw view and copy the raw file URL.
  3. Use the copied URL as the file address when you call pandas.read_csv(URL)

This may or may not work for reading a text file line by line or binary files.

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

Best data type to store money values in MySQL

I prefer to use BIGINT, and store the values in by multiply with 100, so that it will become integer.

For e.g., to represent a currency value of 93.49, the value shall be stored as 9349, while displaying the value we can divide by 100 and display. This will occupy less storage space.

Caution:
Mostly we don't perform currency * currency multiplication, in case if we are doing it then divide the result with 100 and store, so that it returns to proper precision.

Get Filename Without Extension in Python

You can use stem method to get file name.

Here is an example:

from pathlib import Path

p = Path(r"\\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file

Creating a div element inside a div element in javascript

'b' should be in capital letter in document.getElementById modified code jsfiddle

function test()
{

var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
 //document.body.appendChild(element);
 }

What is %timeit in python?

IPython intercepts those, they're called built-in magic commands, here's the list: https://ipython.org/ipython-doc/dev/interactive/magics.html

You can also create your own custom magics, https://ipython.org/ipython-doc/dev/config/custommagics.html

Your timeit is here https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit

How do I find an array item with TypeScript? (a modern, easier way)

For some projects it's easier to set your target to es6 in your tsconfig.json.

{
  "compilerOptions": {
    "target": "es6",
    ...

How to do jquery code AFTER page loading?

Use load instead of ready:

$(document).load(function () {
 // code here
});

Update You need to use .on() since jQuery 1.8. (http://api.jquery.com/on/)

$(window).on('load', function() {
 // code here
});

From this answer:

According to http://blog.jquery.com/2016/06/09/jquery-3-0-final-released/:

Removed deprecated event aliases

.load, .unload, and .error, deprecated since jQuery 1.8, are no more. Use .on() to register listeners.

https://github.com/jquery/jquery/issues/2286

Detecting when user scrolls to bottom of div with jQuery

$(window).on("scroll", function() {
    //get height of the (browser) window aka viewport
    var scrollHeight = $(document).height();
    // get height of the document 
    var scrollPosition = $(window).height() + $(window).scrollTop();
    if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
        // code to run when scroll to bottom of the page
    }
});

This is the code on github.

Is it possible to overwrite a function in PHP

A solution for the related case where you have an include file A that you can edit and want to override some of its functions in an include file B (or the main file):

Main File:

<?php
$Override=true; // An argument used in A.php
include ("A.php");
include ("B.php");
F1();
?>

Include File A:

<?php
if (!@$Override) {
   function F1 () {echo "This is F1() in A";}
}
?>

Include File B:

<?php
   function F1 () {echo "This is F1() in B";}
?>

Browsing to the main file displays "This is F1() in B".

What's the best mock framework for Java?

I like JMock because you are able to set up expectations. This is totally different from checking if a method was called found in some mock libraries. Using JMock you can write very sophisticated expectations. See the jmock cheat-sheat.

String date to xmlgregoriancalendar conversion

Found the solution as below.... posting it as it could help somebody else too :)

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);

XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

System.out.println(xmlGregCal);

Output:

2014-04-24T11:15:00.000+02:00

Rename file with Git

I had a similar problem going through a tutorial.

# git mv README README.markdown

fatal: bad source, source=README, destination=README.markdown

I included the filetype in the source file:

# git mv README.rdoc README.markdown

and it worked perfectly. Don't forget to commit the changes with i.e.:

# git commit -a -m "Improved the README"

Sometimes it is simple little things like that, that piss us off. LOL

Using two values for one switch case statement

The fallthrough answers by others are good ones.

However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.

In the example below, both case 'text1' and case 'text4' behave the same:

switch (name) {
        case text1: {
            method1();
            break;
        }
        case text2: {
            method2();
            break;
        }
        case text3: {
            method3();
            break;
        }
        case text4: {
            method1();
            break;
        }

I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

Thumb Rule: Add a default constructor for each class you used as a mapping class. You missed this and issue arise!
Simply add default constructor and it should work.

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

String to HashMap JAVA

You can to use split to do it:

 String[] elements = s.split(",");
 for(String s1: elements) {
     String[] keyValue = s1.split(":");
     myMap.put(keyValue[0], keyValue[1]);
 }

Nevertheless, myself I will go for guava based solution. https://stackoverflow.com/a/10514513/1356883

Can I get div's background-image url?

I'm using this one

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }

Angular - POST uploaded file

In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.

and the uploader code

let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);

Here is example : https://github.com/wangzilong/angular2-multipartForm

Using sudo with Python script

Many answers focus on how to make your solution work, while very few suggest that your solution is a very bad approach. If you really want to "practice to learn", why not practice using good solutions? Hardcoding your password is learning the wrong approach!

If what you really want is a password-less mount for that volume, maybe sudo isn't needed at all! So may I suggest other approaches?

  • Use /etc/fstab as mensi suggested. Use options user and noauto to let regular users mount that volume.

  • Use Polkit for passwordless actions: Configure a .policy file for your script with <allow_any>yes</allow_any> and drop at /usr/share/polkit-1/actions

  • Edit /etc/sudoers to allow your user to use sudo without typing your password. As @Anders suggested, you can restrict such usage to specific commands, thus avoiding unlimited passwordless root priviledges in your account. See this answer for more details on /etc/sudoers.

All the above allow passwordless root privilege, none require you to hardcode your password. Choose any approach and I can explain it in more detail.

As for why it is a very bad idea to hardcode passwords, here are a few good links for further reading:

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {
}

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.

Update

The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 
    $_POST['postcode']

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
));

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");
}

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

The multi-part identifier could not be bound

Did you forget to join some tables? If not then you probably need to use some aliases.

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

What does the "at" (@) symbol do in Python?

In Python 3.5 you can overload @ as an operator. It is named as __matmul__, because it is designed to do matrix multiplication, but it can be anything you want. See PEP465 for details.

This is a simple implementation of matrix multiplication.

class Mat(list):
    def __matmul__(self, B):
        A = self
        return Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))
                    for j in range(len(B[0])) ] for i in range(len(A))])

A = Mat([[1,3],[7,5]])
B = Mat([[6,8],[4,2]])

print(A @ B)

This code yields:

[[18, 14], [62, 66]]

How do I use a C# Class Library in a project?

  1. Add a reference to your library
  2. Import the namespace
  3. Consume the types in your library

Printing out a number in assembly language?

DOS Print 32 bit value stored in EAX with hexadecimal output (for 80386+)
(on 64 bit OS use DOSBOX)

.code
    mov ax,@DATA        ; get the address of the data segment
    mov ds,ax           ; store the address in the data segment register
;-----------------------
    mov eax,0FFFFFFFFh  ; 32 bit value (0 - FFFFFFFF) for example
;-----------------------
; convert the value in EAX to hexadecimal ASCIIs
;-----------------------
    mov di,OFFSET ASCII ; get the offset address
    mov cl,8            ; number of ASCII
P1: rol eax,4           ; 1 Nibble (start with highest byte)
    mov bl,al
    and bl,0Fh          ; only low-Nibble
    add bl,30h          ; convert to ASCII
    cmp bl,39h          ; above 9?
    jna short P2
    add bl,7            ; "A" to "F"
P2: mov [di],bl         ; store ASCII in buffer
    inc di              ; increase target address
    dec cl              ; decrease loop counter
    jnz P1              ; jump if cl is not equal 0 (zeroflag is not set)
;-----------------------
; Print string
;-----------------------
    mov dx,OFFSET ASCII ; DOS 1+ WRITE STRING TO STANDARD OUTPUT
    mov ah,9            ; DS:DX->'$'-terminated string
    int 21h             ; maybe redirected under DOS 2+ for output to file
                        ; (using pipe character">") or output to printer

  ; terminate program...

.data
ASCII DB "00000000",0Dh,0Ah,"$" ; buffer for ASCII string

Alternative string output directly to the videobuffer without using software interupts:

;-----------------------
; Print string
;-----------------------
    mov ax,0B800h       ; segment address of textmode video buffer
    mov es,ax           ; store address in extra segment register

    mov si,OFFSET ASCII ; get the offset address of the string

; using a fixed target address for example (screen page 0)
; Position`on screen = (Line_number*80*2) + (Row_number*2)

    mov di,(10*80*2)+(10*2)
    mov cl,8            ; number of ASCII
    cld                 ; clear direction flag

P3: lodsb  ; get the ASCII from the address in DS:SI + increase si
    stosb  ; write ASCII directly to the screen using ES:DI + increase di
    inc di ; step over attribut byte
    dec cl ; decrease counter
    jnz P3 ; repeat (print only 8 ASCII, not used bytes are: 0Dh,0Ah,"$")

; Hint: this directly output to the screen do not touch or move the cursor
; but feel free to modify..

What is the difference between Sessions and Cookies in PHP?

A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.

A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

How to populate options of h:selectOneMenu from database?

Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem instances. This is fortunately not needed anymore in JSF 2.x.


Basic example

To answer your question directly, just use <f:selectItems> whose value points to a List<T> property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T actually represents a String.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{bean.names}" />
</h:selectOneMenu>

with

@ManagedBean
@RequestScoped
public class Bean {

    private String name;
    private List<String> names; 

    @EJB
    private NameService nameService;

    @PostConstruct
    public void init() {
        names = nameService.list();
    }

    // ... (getters, setters, etc)
}

Simple as that. Actually, the T's toString() will be used to represent both the dropdown item label and value. So, when you're instead of List<String> using a list of complex objects like List<SomeEntity> and you haven't overridden the class' toString() method, then you would see com.example.SomeEntity@hashcode as item values. See next section how to solve it properly.

Also note that the bean for <f:selectItems> value does not necessarily need to be the same bean as the bean for <h:selectOneMenu> value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{data.names}" />
</h:selectOneMenu>

Complex objects as available items

Whenever T concerns a complex object (a javabean), such as User which has a String property of name, then you could use the var attribute to get hold of the iteration variable which you in turn can use in itemValue and/or itemLabel attribtues (if you omit the itemLabel, then the label becomes the same as the value).

Example #1:

<h:selectOneMenu value="#{bean.userName}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>

with

private String userName;
private List<User> users;

@EJB
private UserService userService;

@PostConstruct
public void init() {
    users = userService.list();
}

// ... (getters, setters, etc)

Or when it has a Long property id which you would rather like to set as item value:

Example #2:

<h:selectOneMenu value="#{bean.userId}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private Long userId;
private List<User> users;

// ... (the same as in previous bean example)

Complex object as selected item

Whenever you would like to set it to a T property in the bean as well and T represents an User, then you would need to bake a custom Converter which converts between User and an unique string representation (which can be the id property). Do note that the itemValue must represent the complex object itself, exactly the type which needs to be set as selection component's value.

<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private User user;
private List<User> users;

// ... (the same as in previous bean example)

and

@ManagedBean
@RequestScoped
public class UserConverter implements Converter {

    @EJB
    private UserService userService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return userService.find(Long.valueOf(submittedValue));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null) {
            return "";
        }

        if (modelValue instanceof User) {
            return String.valueOf(((User) modelValue).getId());
        } else {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
        }
    }

}

(please note that the Converter is a bit hacky in order to be able to inject an @EJB in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class), but that unfortunately doesn't allow @EJB injections)

Don't forget to make sure that the complex object class has equals() and hashCode() properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.

public class User {

    private Long id;

    @Override
    public boolean equals(Object other) {
        return (other != null && getClass() == other.getClass() && id != null)
            ? id.equals(((User) other).id)
            : (other == this);
    }

    @Override
    public int hashCode() {
        return (id != null) 
            ? (getClass().hashCode() + id.hashCode())
            : super.hashCode();
    }

}

Complex objects with a generic converter

Head to this answer: Implement converters for entities with Java Generics.


Complex objects without a custom converter

The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu> without the need to create a custom converter. The SelectItemsConverter will simply do the conversion based on readily available items in <f:selectItem(s)>.

<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

See also:

How to go back (ctrl+z) in vi/vim

On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.

JPA & Criteria API - Select only specific columns

You can do something like this

Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();

where you can change "firstname" with the name of the column you want.

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

change the compiler version to lower value and do apply the changes. The compilation will fail.

Now update the version to required and do apply the changes, the workspace will get rebuild and the issue will get resolved.

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

Just in case of someone has the same problem. I'am using vim with YouCompleteMe, failed to start ycmd with this error message, what I did is: export LC_CTYPE="en_US.UTF-8", the problem is gone.

How do I determine file encoding in OS X?

Synalyze It! allows to compare text or bytes in all encodings the ICU library offers. Using that feature you usually see immediately which code page makes sense for your data.