Programs & Examples On #Icallbackeventhandler

Getting the textarea value of a ckeditor textarea with javascript

you can add the following code : the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.

$().click(function(){
    $('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});

Bundle ID Suffix? What is it?

The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.

It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.

An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:

com.awesomeapps.thebestapp

In this case the suffix is thebestapp.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Honestly though, whether there is a way for it to evaluate to true or not (and as others have shown, there are multiple ways), the answer I'd be looking for, speaking as someone who has conducted hundreds of interviews, would be something along the lines of:

"Well, maybe yes under some weird set of circumstances that aren't immediately obvious to me... but if I encountered this in real code then I would use common debugging techniques to figure out how and why it was doing what it was doing and then immediately refactor the code to avoid that situation... but more importantly: I would absolutely NEVER write that code in the first place because that is the very definition of convoluted code, and I strive to never write convoluted code".

I guess some interviewers would take offense to having what is obviously meant to be a very tricky question called out, but I don't mind developers who have an opinion, especially when they can back it up with reasoned thought and can dovetail my question into a meaningful statement about themselves.

What is the largest TCP/IP network port number allowable for IPv4?

According to RFC 793, the port is a 16 bit unsigned int.

This means the range is 0 - 65535.

However, within that range, ports 0 - 1023 are generally reserved for specific purposes. I say generally because, apart from port 0, there is usually no enforcement of the 0-1023 reservation. TCP/UDP implementations usually don't enforce reservations apart from 0. You can, if you want to, run up a web server's TLS port on port 80, or 25, or 65535 instead of the standard 443. Likewise, even tho it is the standard that SMTP servers listen on port 25, you can run it on 80, 443, or others.

Most implementations reserve 0 for a specific purpose - random port assignment. So in most implementations, saying "listen on port 0" actually means "I don't care what port I use, just give me some random unassigned port to listen on".

So any limitation on using a port in the 0-65535 range, including 0, ephemeral reservation range etc, is implementation (i.e. OS/driver) specific, however all, including 0, are valid ports in the RFC 793.

Set cookies for cross origin requests

Note for Chrome Browser released in 2020.

A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.

So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.

More info https://www.chromium.org/updates/same-site.

Firefox and Edge developers also want to release this feature in the future.

Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8

Direct download from Google Drive using Google Drive API

I simply create a javascript so that it automatically capture the link and download and close the tab with the help of tampermonkey.

// ==UserScript==
// @name         Bypass Google drive virus scan
// @namespace    SmartManoj
// @version      0.1
// @description  Quickly get the download link
// @author       SmartManoj
// @match        https://drive.google.com/uc?id=*&export=download*
// @grant        none
// ==/UserScript==

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function demo() {
        await sleep(5000);
        window.close();
    }

    (function() {
        location.replace(document.getElementById("uc-download-link").href);
        demo();
    })();

Similarly you can get the html source of the url and download in java.

How can I check the size of a file in a Windows batch script?

%~z1 expands to the size of the first argument to the batch file. See

C:\> call /?

and

C:\> if /?

Simple example:

@ECHO OFF
SET SIZELIMIT=1000
SET FILESIZE=%~z1

IF %FILESIZE% GTR %SIZELIMIT% Goto No

ECHO Great! Your filesize is smaller than %SIZELIMIT% kbytes.
PAUSE
GOTO :EOF

:No
ECHO Um ... You have a big filesize.
PAUSE
GOTO :EOF

What's wrong with nullable columns in composite primary keys?

Fundamentally speaking nothing is wrong with a NULL in a multi-column primary key. But having one has implications the designer likely did not intend, which is why many systems throw an error when you try this.

Consider the case of module/package versions stored as a series of fields:

CREATE TABLE module
  (name        varchar(20) PRIMARY KEY,
   description text DEFAULT '' NOT NULL);

CREATE TABLE version
  (module      varchar(20) REFERENCES module,
   major       integer NOT NULL,
   minor       integer DEFAULT 0 NOT NULL,
   patch       integer DEFAULT 0 NOT NULL,
   release     integer DEFAULT 1 NOT NULL,
   ext         varchar(20),
   notes       text DEFAULT '' NOT NULL,
   PRIMARY KEY (module, major, minor, patch, release, ext));

The first 5 elements of the primary key are regularly defined parts of a release version, but some packages have a customized extension that is usually not an integer (like "rc-foo" or "vanilla" or "beta" or whatever else someone for whom four fields is insufficient might dream up). If a package does not have an extension, then it is NULL in the above model, and no harm would be done by leaving things that way.

But what is a NULL? It is supposed to represent a lack of information, an unknown. That said, perhaps this makes more sense:

CREATE TABLE version
  (module      varchar(20) REFERENCES module,
   major       integer NOT NULL,
   minor       integer DEFAULT 0 NOT NULL,
   patch       integer DEFAULT 0 NOT NULL,
   release     integer DEFAULT 1 NOT NULL,
   ext         varchar(20) DEFAULT '' NOT NULL,
   notes       text DEFAULT '' NOT NULL,
   PRIMARY KEY (module, major, minor, patch, release, ext));

In this version the "ext" part of the tuple is NOT NULL but defaults to an empty string -- which is semantically (and practically) different from a NULL. A NULL is an unknown, whereas an empty string is a deliberate record of "something not being present". In other words, "empty" and "null" are different things. Its the difference between "I don't have a value here" and "I don't know what the value here is."

When you register a package that lacks a version extension you know it lacks an extension, so an empty string is actually the correct value. A NULL would only be correct if you didn't know whether it had an extension or not, or you knew that it did but didn't know what it was. This situation is easier to deal with in systems where string values are the norm, because there is no way to represent an "empty integer" other than inserting 0 or 1, which will wind up being rolled up in any comparisons made later (which has its own implications)*.

Incidentally, both ways are valid in Postgres (since we're discussing "enterprise" RDMBSs), but comparison results can vary quite a bit when you throw a NULL into the mix -- because NULL == "don't know" so all results of a comparison involving a NULL wind up being NULL since you can't know something that is unknown. DANGER! Think carefully about that: this means that NULL comparison results propagate through a series of comparisons. This can be a source of subtle bugs when sorting, comparing, etc.

Postgres assumes you're an adult and can make this decision for yourself. Oracle and DB2 assume you didn't realize you were doing something silly and throw an error. This is usually the right thing, but not always -- you might actually not know and have a NULL in some cases and therefore leaving a row with an unknown element against which meaningful comparisons are impossible is correct behavior.

In any case you should strive to eliminate the number of NULL fields you permit across the entire schema and doubly so when it comes to fields that are part of a primary key. In the vast majority of cases the presence of NULL columns is an indication of un-normalized (as opposed to deliberately de-normalized) schema design and should be thought very hard about before being accepted.

[* NOTE: It is possible to create a custom type that is the union of integers and a "bottom" type that would semantically mean "empty" as opposed to "unknown". Unfortunately this introduces a bit of complexity in comparison operations and usually being truly type correct isn't worth the effort in practice as you shouldn't be permitted many NULL values at all in the first place. That said, it would be wonderful if RDBMSs would include a default BOTTOM type in addition to NULL to prevent the habit of casually conflating the semantics of "no value" with "unknown value".]

Difference in days between two dates in Java?

I use this funcion:

DATEDIFF("31/01/2016", "01/03/2016") // me return 30 days

my function:

import java.util.Date;

public long DATEDIFF(String date1, String date2) {
        long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;
        long days = 0l;
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); // "dd/MM/yyyy HH:mm:ss");

        Date dateIni = null;
        Date dateFin = null;        
        try {       
            dateIni = (Date) format.parse(date1);
            dateFin = (Date) format.parse(date2);
            days = (dateFin.getTime() - dateIni.getTime())/MILLISECS_PER_DAY;                        
        } catch (Exception e) {  e.printStackTrace();  }   

        return days; 
     }

How to call controller from the button click in asp.net MVC 4

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

in your code should be,

@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})

How do I create a MongoDB dump of my database?

mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder

mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder.gz

How do I load a file into the python console?

You can just use an import statement:

from file import *

So, for example, if you had a file named my_script.py you'd load it like so:

from my_script import *

Undefined symbols for architecture i386

well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks

i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.

ENJOY

How to Serialize a list in java?

All standard implementations of java.util.List already implement java.io.Serializable.

So even though java.util.List itself is not a subtype of java.io.Serializable, it should be safe to cast the list to Serializable, as long as you know it's one of the standard implementations like ArrayList or LinkedList.

If you're not sure, then copy the list first (using something like new ArrayList(myList)), then you know it's serializable.

Spring Boot REST service exception handling

Solution with dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); and @EnableWebMvc @ControllerAdvice worked for me with Spring Boot 1.3.1, while was not working on 1.2.7

How can I show three columns per row?

Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:

_x000D_
_x000D_
.flex-row-container {_x000D_
    background: #aaa;_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
    flex: 1 1 30%; /*grow | shrink | basis */_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
  background-color: #fff4e6;_x000D_
  border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
  <div class="flex-row-item">1</div>_x000D_
  <div class="flex-row-item">2</div>_x000D_
  <div class="flex-row-item">3</div>_x000D_
  <div class="flex-row-item">4</div>_x000D_
  <div class="flex-row-item">5</div>_x000D_
  <div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone else.

Cannot catch toolbar home button click event

I think the correct solution with support library 21 is the following

// action_bar is def resource of appcompat; 
// if you have not provided your own toolbar I mean  
Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
if (toolbar != null) {
    // change home icon if you wish
    toolbar.setLogo(this.getResValues().homeIconDrawable());
    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //catch here title and home icon click                          
        }                       
    });                 
}

VueJs get url query

In my case I console.log(this.$route) and returned the fullPath:

console.js:
fullPath: "/solicitud/MX/666",
params: {market: "MX", id: "666"},
path: "/solicitud/MX/666"

console.js: /solicitud/MX/666

Python: Assign Value if None Exists

I'm also coming from Ruby so I love the syntax foo ||= 7.

This is the closest thing I can find.

foo = foo if 'foo' in vars() else 7

I've seen people do this for a dict:

try:
    foo['bar']
except KeyError:
    foo['bar'] = 7

Upadate: However, I recently found this gem:

foo['bar'] = foo.get('bar', 7)

If you like that, then for a regular variable you could do something like this:

vars()['foo'] = vars().get('foo', 7)

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

How to get a complete list of ticker symbols from Yahoo Finance?

I have been researching this for a few days, following endless leads that got close, but not quite, to what I was after.

My need is for a simple list of 'symbol, sector, industry'. I'm working in Java and don't want to use any platform native code.

It seems that most other data, like quotes, etc., is readily available.

Finally, followed a suggestion to look at 'finviz.com'. Looks like just the ticket. Try using the following:

http://finviz.com/export.ashx?v=111&t=aapl,cat&o=ticker This comes back as lines, csv style, with a header row, ordered by ticker symbol. You can keep adding tickers. In code, you can read the stream. Or you can let the browser ask you whether to open or save the file.

http://finviz.com/export.ashx?v=111&&o=ticker Same csv style, but pulls all available symbols (a lot, across global exchanges)

Replace 'export' with 'screener' and the data will show up in the browser.

There are many more options you can use, one for every screener element on the site.

So far, this is the most powerful and convenient programmatic way to get the few pieces of data I couldn't otherwise seem to easily get. And, it looks like this site could well be a single source for most of what you might need other than real- or near-real-time quotes.

How do I run Python script using arguments in windows command line

  • import sys out of hello function.
  • arguments should be converted to int.
  • String literal that contain ' should be escaped or should be surrouned by ".
  • Did you invoke the program with python hello.py <some-number> <some-number> in command line?

import sys

def hello(a,b):
    print "hello and that's your sum:", a + b

if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    hello(a, b)

How do I create the small icon next to the website tab for my site?

It is called favicon.ico and you can generate it from this site.

http://www.favicon.cc/

How to change python version in anaconda spyder

First, you have to run below codes in Anaconda prompt,

conda create -n py27 python=2.7  #for version 2.7
activate py27

conda create -n py36 python=3.6  #for version 3.6
activate py36

Then, you have to open Anaconda navigator and, enter image description here The button might say "install" instead of Launch. After the installation, which takes a few moments, It will be ready to launch.

Thank you, @cloudscomputes and @Francisco Camargo.

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

How to use a client certificate to authenticate and authorize in a Web API

Looking at the source code I also think there must be some issue with the private key.

What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.

If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.

(see source code from class SecureChannnel, method EnsurePrivateKey)

So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.

You can activate Network Tracing to try to debug this. It will give you output like this:

  • Trying to find a matching certificate in the certificate store
  • Cannot find the certificate in either the LocalMachine store or the CurrentUser store.

How can I get column names from a table in SQL Server?

One other option which is arguably more intuitive is:

SELECT [name] 
FROM sys.columns 
WHERE object_id = OBJECT_ID('[yourSchemaType].[yourTableName]') 

This gives you all your column names in a single column. If you care about other metadata, you can change edit the SELECT STATEMENT TO SELECT *.

Making a div vertically scrollable using CSS

You can use overflow-y: scroll for vertical scrolling.

_x000D_
_x000D_
<div  style="overflow-y:scroll; height:400px; background:gray">_x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
 </div>
_x000D_
_x000D_
_x000D_

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

Adding quotes to a string in VBScript

You can escape by doubling the quotes

g="abcd """ & a & """"

or write an explicit chr() call

g="abcd " & chr(34) & a & chr(34)

In Angular, how to pass JSON object/array into directive?

If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

app.factory('locations', function($http) {
  var promise = null;

  return function() {
    if (promise) {
      // If we've already asked for this data once,
      // return the promise that already exists.
      return promise;
    } else {
      promise = $http.get('locations/locations.json');
      return promise;
    }
  };
});

As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

- The 80/20 Guide to Writing AngularJS Directives

In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

app.controller('SomeController', function($scope, locations) {
  locations().success(function(data) {
    $scope.locations = data;
  });
});
<ul class="list">
   <li ng-repeat="location in locations">
      <a href="#">{{location.id}}. {{location.name}}</a>
   </li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
      // creates a scope variable in your directive
      // called `locations` bound to whatever was passed
      // in via the `locations` attribute in the DOM
      locations: '=locations'
    },
    link: function(scope, element, attrs) {
      scope.$watch('locations', function(locations) {
        angular.forEach(locations, function(location, key) {
          // do something
        });
      });
    }
  };
});

In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

How does one target IE7 and IE8 with valid CSS?

I did it using Javascript. I add three css classes to the html element:

ie<version>
lte-ie<version>
lt-ie<version + 1>

So for IE7, it adds ie7, lte-ie7 ..., lt-ie8 ...

Here is the javascript code:

(function () {
    function getIEVersion() {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf('MSIE ');
        var trident = ua.indexOf('Trident/');

        if (msie > 0) {
            // IE 10 or older => return version number
            return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        } else if (trident > 0) {
            // IE 11 (or newer) => return version number
            var rv = ua.indexOf('rv:');
            return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
        } else {
            return NaN;
        }
    };

    var ieVersion = getIEVersion();

    if (!isNaN(ieVersion)) { // if it is IE
        var minVersion = 6;
        var maxVersion = 13; // adjust this appropriately

        if (ieVersion >= minVersion && ieVersion <= maxVersion) {
            var htmlElem = document.getElementsByTagName('html').item(0);

            var addHtmlClass = function (className) { // define function to add class to 'html' element
                htmlElem.className += ' ' + className;
            };

            addHtmlClass('ie' + ieVersion); // add current version
            addHtmlClass('lte-ie' + ieVersion);

            if (ieVersion < maxVersion) {
                for (var i = ieVersion + 1; i <= maxVersion; ++i) {
                    addHtmlClass('lte-ie' + i);
                    addHtmlClass('lt-ie' + i);
                }
            }
        }
    }
})();

Thereafter, you use the .ie<version> css class in your stylesheet as described by potench.

(Used Mario's detectIE function in Check if user is using IE with jQuery)

The benefit of having lte-ie8 and lt-ie8 etc is that it you can target all browser less than or equal to IE9, that is IE7 - IE9.

How to update a record using sequelize for node?

This solution is deprecated

failure|fail|error() is deprecated and will be removed in 2.1, please use promise-style instead.

so you have to use

Project.update(

    // Set Attribute values 
    {
        title: 'a very different title now'
    },

    // Where clause / criteria 
    {
        _id: 1
    }

).then(function() {

    console.log("Project with id =1 updated successfully!");

}).catch(function(e) {
    console.log("Project update failed !");
})

And you can use .complete() as well

Regards

Filter Pyspark dataframe column with None value

None/Null is a data type of the class NoneType in pyspark/python so, Below will not work as you are trying to compare NoneType object with string object

Wrong way of filreting

df[df.dt_mvmt == None].count() 0 df[df.dt_mvmt != None].count() 0

correct

df=df.where(col("dt_mvmt").isNotNull()) returns all records with dt_mvmt as None/Null

Necessary to add link tag for favicon.ico?

<link rel="icon" type="image/x-icon" href="http://example.com/favicon.ico" />
<link rel="icon" type="image/png" href="http://example.com/favicon.png" />
<link rel="icon" type="image/gif" href="http://example.com/favicon.gif" />
<link rel="icon" type="image/jpeg" href="http://example.com/favicon.jpeg" />
<link rel="icon" type="image/webp" href="http://example.com/favicon.webp" />

It all depends on which format of image you like to use!
if you have an icon of your website, it will be much better for UX!

demo

show logo in the browser tab

enter image description here

How to run a javascript function during a mouseover on a div

the prototype way

<div id="sub1" title="some text on mouse over">some text</div>


<script type="text/javascript">//<![CDATA[
  $("sub1").observe("mouseover", function() {
    alert(this.readAttribute("title"));
  });
//]]></script>

include Prototype Lib for testing

<script type="text/javascript" 
  src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>

How to run an external program, e.g. notepad, using hyperlink?

Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.

The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.

*ngIf else if in template

You can also use this old trick for converting complex if/then/else blocks into a slightly cleaner switch statement:

<div [ngSwitch]="true">
    <button (click)="foo=(++foo%3)+1">Switch!</button>

    <div *ngSwitchCase="foo === 1">one</div>
    <div *ngSwitchCase="foo === 2">two</div>
    <div *ngSwitchCase="foo === 3">three</div>
</div>

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Renaming files using node.js

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');

How can I use std::maps with user-defined types as key?

Keys must be comparable, but you haven't defined a suitable operator< for your custom class.

How can I get Docker Linux container information from within the container itself?

You can communicate with docker from inside of a container using unix socket via Docker Remote API:

https://docs.docker.com/engine/reference/api/docker_remote_api/

In a container, you can find out a shortedned docker id by examining $HOSTNAME env var. According to doc, there is a small chance of collision, I think that for small number of container, you do not have to worry about it. I don't know how to get full id directly.

You can inspect container similar way as outlined in banyan answer:

GET /containers/4abbef615af7/json HTTP/1.1

Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
         "Id": "4abbef615af7......  ",
         "Created": "2013.....",
         ...
}

Alternatively, you can transfer docker id to the container in a file. The file is located on "mounted volume" so it is transfered to container:

docker run -t -i -cidfile /mydir/host1.txt -v /mydir:/mydir ubuntu /bin/bash

The docker id (shortened) will be in file /mydir/host1.txt in the container.

How can I represent a range in Java?

You could use java.time.temporal.ValueRange which accepts long and would also work with int:

int a = 2147;

//Use java 8 java.time.temporal.ValueRange. The range defined
//is inclusive of both min and max 
ValueRange range = ValueRange.of(0, 2147483647);

if(range.isValidValue(a)) {
    System.out.println("in range");
}else {
    System.out.println("not in range");
}

Python: avoiding pylint warnings about too many arguments

I do not like referring to the number, the sybolic name is much more expressive and avoid having to add a comment that could become obsolete over time.

So I'd rather do:

#pylint: disable-msg=too-many-arguments

And I would also recommend to not leave it dangling there: it will stay active until the file ends or it is disabled, whichever comes first.

So better doing:

#pylint: disable-msg=too-many-arguments
code_which_would_trigger_the_msg
#pylint: enable-msg=too-many-arguments    

I would also recommend enabling/disabling one single warning/error per line.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)

Use:

System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);

From the docs:

public static class EnvironmentVariablesExample
{
    [FunctionName("GetEnvironmentVariables")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
        log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
    }

    public static string GetEnvironmentVariable(string name)
    {
        return name + ": " +
            System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
    }
}

App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.

The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.

What's the console.log() of java?

Use the Android logging utility.

http://developer.android.com/reference/android/util/Log.html

Log has a bunch of static methods for accessing the different log levels. The common thread is that they always accept at least a tag and a log message.

Tags are a way of filtering output in your log messages. You can use them to wade through the thousands of log messages you'll see and find the ones you're specifically looking for.

You use the Log functions in Android by accessing the Log.x objects (where the x method is the log level). For example:

Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Log.e("MyTagGoesHere", "This is my log message at the error level here");

I usually make it a point to make the tag my class name so I know where the log message was generated too. Saves a lot of time later on in the game.

You can see your log messages using the logcat tool for android:

adb logcat

Or by opening the eclipse Logcat view by going to the menu bar

Window->Show View->Other then select the Android menu and the LogCat view

How do I view cookies in Internet Explorer 11 using Developer Tools

  1. Click on the Network button
  2. Enable capture of network traffic by clicking on the green triangular button in top toolbar
  3. Capture some network traffic by interacting with the page
  4. Click on DETAILS/Cookies
  5. Step through each captured traffic segment; detailed information about cookies will be displayed

Python: download a file from an FTP server

If you want to take advantage of recent Python versions' async features, you can use aioftp (from the same family of libraries and developers as the more popular aiohttp library). Here is a code example taken from their client tutorial:

client = aioftp.Client()
await client.connect("ftp.server.com")
await client.login("user", "pass")
await client.download("tmp/test.py", "foo.py", write_into=True)

The I/O operation has been aborted because of either a thread exit or an application request

What I do when it happens is Disable the COM port into the Device Manager and Enable it again.

It stop the communications with another program or thread and become free for you.

I hope this works for you. Regards.

x86 Assembly on a Mac

Running assembly Code on Mac is just 3 steps away from you. It could be done using XCODE but better is to use NASM Command Line Tool. For My Ease I have already installed Xcode, if you have Xcode installed its good.

But You can do it without XCode as well.

Just Follow:

  1. First Install NASM using Homebrew brew install nasm
  2. convert .asm file into Obj File using this command nasm -f macho64 myFile.asm
  3. Run Obj File to see OutPut using command ld -macosx_version_min 10.7.0 -lSystem -o OutPutFile myFile.o && ./64

Simple Text File named myFile.asm is written below for your convenience.

global start
section .text

start:
    mov     rax, 0x2000004 ; write
    mov     rdi, 1 ; stdout
    mov     rsi, msg
    mov     rdx, msg.len
    syscall

    mov     rax, 0x2000001 ; exit
    mov     rdi, 0
    syscall

section .data

msg:    db      "Assalam O Alaikum Dear", 10
.len:   equ     $ - msg

eval command in Bash and its typical uses

You asked about typical uses.

One common complaint about shell scripting is that you (allegedly) can't pass by reference to get values back out of functions.

But actually, via "eval", you can pass by reference. The callee can pass back a list of variable assignments to be evaluated by the caller. It is pass by reference because the caller can allowed to specify the name(s) of the result variable(s) - see example below. Error results can be passed back standard names like errno and errstr.

Here is an example of passing by reference in bash:

#!/bin/bash
isint()
{
    re='^[-]?[0-9]+$'
    [[ $1 =~ $re ]]
}

#args 1: name of result variable, 2: first addend, 3: second addend 
iadd()
{
    if isint ${2} && isint ${3} ; then
        echo "$1=$((${2}+${3}));errno=0"
        return 0
    else
        echo "errstr=\"Error: non-integer argument to iadd $*\" ; errno=329"
        return 1
    fi
}

var=1
echo "[1] var=$var"

eval $(iadd var A B)
if [[ $errno -ne 0 ]]; then
    echo "errstr=$errstr"
    echo "errno=$errno"
fi
echo "[2] var=$var (unchanged after error)"

eval $(iadd var $var 1)
if [[ $errno -ne 0 ]]; then
    echo "errstr=$errstr"
    echo "errno=$errno"
fi  
echo "[3] var=$var (successfully changed)"

The output looks like this:

[1] var=1
errstr=Error: non-integer argument to iadd var A B
errno=329
[2] var=1 (unchanged after error)
[3] var=2 (successfully changed)

There is almost unlimited band width in that text output! And there are more possibilities if the multiple output lines are used: e.g., the first line could be used for variable assignments, the second for continuous 'stream of thought', but that's beyond the scope of this post.

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

A bit late, and not a complete solution either, but for everyone who gets hit by this error without any obvious reason (having all the references defined, etc.) This thread put me on the correct track though. The issue seems to originate from some caching related bug in MS Office VBA Editor.

After making some changes to a project including about 40 forms with code modules plus 40 classes and some global modules in MS Access 2016 the compilation failed.

Commenting out code was obviously not an option, nor did exporting and re-importing all the 80+ files seem reasonable. Concentrating on what had recently been changed, my suspicions focused on removal of one class module.

Having no better ideas I re-cereated an empty class module with the same name that had previously been removed. And voliá the error was gone! It was even possible to remove the unused class module again without the error reappearing, until any changes were saved to a form module which previously had contained a WithEvents declaration involving the now removed class.

Not completely sure if WithEvents declaration really is what triggers the error even after the declaration has been removed. And no clues how to actually find out (without having information about the development history) which Form might be the culprit...

But what finally solved the issue was:

  1. In VBE - Copy all code from Form code module
  2. In Access open Form in Design view and set Has Module property to No
  3. Save the project (this removes any code associated with Form)
  4. (Not sure if need to close and re-open Access, but I did it)
  5. Open Form in Design view and set Has Module property back to Yes
  6. In VBE paste back the copied out module code
  7. Save

How to get number of rows inserted by a transaction

I found the answer to may previous post. Here it is.

CREATE TABLE #TempTable (id int) 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 1,2 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 3,4 

SELECT * FROM #TempTable --this select will chage @@ROWCOUNT value

In Chrome 55, prevent showing Download button for HTML 5 video

Hey I found a permanent solution that should work in every case!

For normal webdevelopment

<script type="text/javascript"> 
$("video").each(function(){jQuery(this).append('controlsList="nodownload"')}); 
</script>

HTML5 videos that has preload on false

$( document ).ready(function() {
  $("video").each(function(){
    $(this).attr('controlsList','nodownload');
    $(this).load();
  });
});

$ undevinded? --> Debug modus!

<script type="text/javascript"> 
jQuery("video").each(function(){jQuery(this).append('controlsList="nodownload"')}); 
</script>

HTML5 videos that has preload on false

jQuery( document ).ready(function() {
  jQuery("video").each(function(){
    jQuery(this).attr('controlsList','nodownload');
    jQuery(this).load();
  });
});

Let me know if it helped you out!

How to normalize a signal to zero mean and unit variance?

To avoid division by zero!

function x = normalize(x, eps)
    % Normalize vector `x` (zero mean, unit variance)

    % default values
    if (~exist('eps', 'var'))
        eps = 1e-6;
    end

    mu = mean(x(:));

    sigma = std(x(:));
    if sigma < eps
        sigma = 1;
    end

    x = (x - mu) / sigma;
end

Python convert set to string and vice versa

Use repr and eval:

>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])

Note that eval is not safe if the source of string is unknown, prefer ast.literal_eval for safer conversion:

>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])

help on repr:

repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.

Ways to implement data versioning in MongoDB

Another option is to use mongoose-history plugin.

let mongoose = require('mongoose');
let mongooseHistory = require('mongoose-history');
let Schema = mongoose.Schema;

let MySchema = Post = new Schema({
    title: String,
    status: Boolean
});

MySchema.plugin(mongooseHistory);
// The plugin will automatically create a new collection with the schema name + "_history".
// In this case, collection with name "my_schema_history" will be created.

Python Pandas Replacing Header with Top Row

--another way to do this


df.columns = df.iloc[0]
df = df.reindex(df.index.drop(0)).reset_index(drop=True)
df.columns.name = None

    Sample Number  Group Number  Sample Name  Group Name
0             1.0           1.0          s_1         g_1
1             2.0           1.0          s_2         g_1
2             3.0           1.0          s_3         g_1
3             4.0           2.0          s_4         g_2

If you like it hit up arrow. Thanks

Wordpress plugin install: Could not create directory

The user that is running your web server does not have permissions to write to the directory that Wordpress is intending to create the plugin directory in. You should chown the directory in question to the user that is running Wordpress. It is most likely not root.

In short, this is a permissions issue. Your touch command is working because you're using it as root, and root has global permissions to write wherever it wants.

Is there a "not equal" operator in Python?

Use !=. See comparison operators. For comparing object identities, you can use the keyword is and its negation is not.

e.g.

1 == 1 #  -> True
1 != 1 #  -> False
[] is [] #-> False (distinct objects)
a = b = []; a is b # -> True (same object)

Undo git update-index --assume-unchanged <file>

None of the solutions worked for me in Windows - it seems to use capital H rather than h for the file status and the grep command requires an extra caret as ^ also represents the start of line as well as negating the next character.

Windows solution

  1. Open Git Bash and change to the relevant top level directory.
  2. git ls-files -v | grep '^^H' to list all the uncached files
  3. git ls-files -v | grep '^^H' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-skip-worktree to undo the files skipping of all files that was done via update-index --skip-worktree
  4. git ls-files -v | grep '^^H]' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-assume-unchanged to undo the files skipping of all files that was done via update-index --assume-unchanged
  5. git ls-files -v | grep '^^H' to again list all the uncached files and check whether the above commands have worked - this should now not return anything

JQuery Redirect to URL after specified time

Use setTimeout function with either of the following

// simulates similar behavior as an HTTP redirect
window.location.replace("http://www.google.com");

// simulates similar behavior as clicking on a link
window.location.href = "http://www.google.com";

setTimeout(function(){
   window.location.replace("http://www.google.com");
}, 1000) 

source: https://www.sitepoint.com/jquery-redirect-web-page/

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

  1. what's happening? you haven' shown much of the output to be able to decide. if you are using netbeans 7.4, try disabling Compile on Save.

  2. to enable debug output, either run Custom > Goals... action from project popup or after running a regular build, click the Rerun with options action from the output's toolbar

Modify tick label text

I noticed that all the solutions posted here that use set_xticklabels() are not preserving the offset, which is a scaling factor applied to the ticks values to create better-looking tick labels. For instance, if the ticks are on the order of 0.00001 (1e-5), matplotlib will automatically add a scaling factor (or offset) of 1e-5, so the resultant tick labels may end up as 1 2 3 4, rather than 1e-5 2e-5 3e-5 4e-5.

Below gives an example:

The x array is np.array([1, 2, 3, 4])/1e6, and y is y=x**2. So both are very small values.

Left column: manually change the 1st and 3rd labels, as suggested by @Joe Kington. Note that the offset is lost.

Mid column: similar as @iipr suggested, using a FuncFormatter.

Right column: My suggested offset-preserving solution.

Figure here: enter image description here

Complete code here:

import matplotlib.pyplot as plt
import numpy as np

# create some *small* data to plot
x = np.arange(5)/1e6
y = x**2

fig, axes = plt.subplots(1, 3, figsize=(10,6))

#------------------The set_xticklabels() solution------------------
ax1 = axes[0]
ax1.plot(x, y)
fig.canvas.draw()
labels = [item.get_text() for item in ax1.get_xticklabels()]

# Modify specific labels
labels[1] = 'Testing'
labels[3] = 'Testing2'
ax1.set_xticklabels(labels)
ax1.set_title('set_xticklabels()')

#--------------FuncFormatter solution--------------
import matplotlib.ticker as mticker

def update_ticks(x, pos):
    if pos==1:
        return 'testing'
    elif pos==3:
        return 'testing2'
    else:
        return x

ax2=axes[1]
ax2.plot(x,y)
ax2.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
ax2.set_title('Func Formatter')

#-------------------My solution-------------------
def changeLabels(axis, pos, newlabels):
    '''Change specific x/y tick labels

    Args:
        axis (Axis): .xaxis or .yaxis obj.
        pos (list): indices for labels to change.
        newlabels (list): new labels corresponding to indices in <pos>.
    '''

    if len(pos) != len(newlabels):
        raise Exception("Length of <pos> doesn't equal that of <newlabels>.")

    ticks = axis.get_majorticklocs()
    # get the default tick formatter
    formatter = axis.get_major_formatter()
    # format the ticks into strings
    labels = formatter.format_ticks(ticks)

    # Modify specific labels
    for pii, lii in zip(pos, newlabels):
        labels[pii] = lii

    # Update the ticks and ticklabels. Order is important here.
    # Need to first get the offset (1e-6 in this case):
    offset = formatter.get_offset()
    # Then set the modified labels:
    axis.set_ticklabels(labels)
    # In doing so, matplotlib creates a new FixedFormatter and sets it to the xaxis
    # and the new FixedFormatter has no offset. So we need to query the
    # formatter again and re-assign the offset:
    axis.get_major_formatter().set_offset_string(offset)

    return

ax3 = axes[2]
ax3.plot(x, y)

changeLabels(ax3.xaxis, [1, 3], ['Testing', 'Testing2'])
ax3.set_title('With offset')

fig.show()
plt.savefig('tick_labels.png')

Caveat: it appears that solutions that use set_xticklabels(), including my own, relies on FixedFormatter, which is static and doesn't respond to figure resizing. To observe the effect, change the figure to a smaller size, e.g. fig, axes = plt.subplots(1, 3, figsize=(6,6)) and enlarge the figure window. You will notice that that only the mid column responds to resizing and adds more ticks as the figure gets larger. The left and right column will have empty tick labels (see figure below).

Caveat 2: I also noticed that if your tick values are floats, calling set_xticklabels(ticks) directly might give you ugly-looking strings, like 1.499999999998 instead of 1.5.

enter image description here

How is a tag different from a branch in Git? Which should I use, here?

Branches are made of wood and grow from the trunk of the tree. Tags are made of paper (derivative of wood) and hang like Christmas Ornaments from various places in the tree.

Your project is the tree, and your feature that will be added to the project will grow on a branch. The answer is branch.

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

Between matplotlib+pylab and NumPy I don't think there's much actual difference between Matlab and python other than cultural inertia as suggested by @Adam Bellaire.

What does "zend_mm_heap corrupted" mean

This option has already been written above, but I want to walk you through the steps how I reproduced this error.

Briefly. It helped me:

opcache.fast_shutdown = 0

My legacy configuration:

  1. CentOS release 6.9 (Final)
  2. PHP 5.6.24 (fpm-fcgi) with Zend OPcache v7.0.6-dev
  3. Bitrix CMS

Step by step:

  1. Run phpinfo()
  2. Find "OPcache" in output. It should be enabled. If not, then this solution will definitely not help you.
  3. Execute opcache_reset() in any place (thanks to bug report, comment [2015-05-15 09:23 UTC] nax_hh at hotmail dot com). Load multiple pages on your site. If OPcache is to blame, then in the nginx logs will appear line with text

104: Connection reset by peer

and in the php-fpm logs

zend_mm_heap corrupted

and on the next line

fpm_children_bury()

  1. Set opcache.fast_shutdown=0 (for me in /etc/php.d/opcache.ini file)
  2. Restart php-fpm (e.g. service php-fpm restart)
  3. Load some pages of your site again. Execute opcache_reset() and load some pages again. Now there should be no mistakes.

By the way. In the output of phpinfo(), you can find the statistics of OPcache and then optimize the parameters (for example, increase the memory limit). Good instructions for tuning opcache (russian language, but you can use a translator)

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

Copy Local = True was solve for one of my projects. But in another project, I get the same error, tried to set Copy Local = true, but it not solve my problem. Changing the Target framework from 4.5.1 to 4.5 in Project Properties Helped with this.

How can I select records ONLY from yesterday?

trunc(tran_date) = trunc(sysdate -1)

Converting <br /> into a new line for use in a text area

The answer by @Mobilpadde is nice. But this is my solution with regex using preg_replace which might be faster according to my tests.

echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");

function function_one() {
    preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}

function function_two() {
    str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}

function benchmark() {
    $count = 10000000;
    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_one();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function one\n";



    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_two();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();

Results:

1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)

Is there any difference between GROUP BY and DISTINCT

If you are using a GROUP BY without any aggregate function then internally it will treated as DISTINCT, so in this case there is no difference between GROUP BY and DISTINCT.

But when you are provided with DISTINCT clause better to use it for finding your unique records because the objective of GROUP BY is to achieve aggregation.

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.

From the comments:

/* =======================
 * HASHED PASSWORD FORMATS
 * =======================
 * 
 * Version 2:
 * PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
 * (See also: SDL crypto guidelines v5.1, Part III)
 * Format: { 0x00, salt, subkey }
 *
 * Version 3:
 * PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
 * Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
 * (All UInt32s are stored big-endian.)
 */

How to get datas from List<Object> (Java)?

Thanks All for your responses. Good solution was to use 'brain`s' method:

List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
Object[] row = (Object[]) list.get(i);
System.out.println("Element "+i+Arrays.toString(row));
}

Problem solved. Thanks again.

Array Length in Java

If you want the logical size of the array, you can traverse all the values in the array and check them against zero. Increment the value if it is not zero and that would be the logical size. Because array size is fixed, you do not have any inbuilt method, may be you should have a look at collections.

In Django, how do I check if a user is in a certain group?

If you don't need the user instance on site (as I did), you can do it with

User.objects.filter(pk=userId, groups__name='Editor').exists()

This will produce only one request to the database and return a boolean.

Wait 5 seconds before executing next line

This solution comes from React Native's documentation for a refresh control:

function wait(timeout) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
}

To apply this to the OP's question, you could use this function in coordination with await:

await wait(5000);
if (newState == -1) {
    alert('Done');
}

Removing a non empty directory programmatically in C or C++

You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty and you can remove it via the syscall.

To enumerate directories on Unix, you can use opendir(), readdir(), and closedir(). To remove you use rmdir() on an empty directory (i.e. at the end of your function, after deleting the children) and unlink() on a file. Note that on many systems the d_type member in struct dirent is not supported; on these platforms, you will have to use stat() and S_ISDIR(stat.st_mode) to determine if a given path is a directory.

On Windows, you will use FindFirstFile()/FindNextFile() to enumerate, RemoveDirectory() on empty directories, and DeleteFile() to remove files.

Here's an example that might work on Unix (completely untested):

int remove_directory(const char *path) {
   DIR *d = opendir(path);
   size_t path_len = strlen(path);
   int r = -1;

   if (d) {
      struct dirent *p;

      r = 0;
      while (!r && (p=readdir(d))) {
          int r2 = -1;
          char *buf;
          size_t len;

          /* Skip the names "." and ".." as we don't want to recurse on them. */
          if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
             continue;

          len = path_len + strlen(p->d_name) + 2; 
          buf = malloc(len);

          if (buf) {
             struct stat statbuf;

             snprintf(buf, len, "%s/%s", path, p->d_name);
             if (!stat(buf, &statbuf)) {
                if (S_ISDIR(statbuf.st_mode))
                   r2 = remove_directory(buf);
                else
                   r2 = unlink(buf);
             }
             free(buf);
          }
          r = r2;
      }
      closedir(d);
   }

   if (!r)
      r = rmdir(path);

   return r;
}

How to do jquery code AFTER page loading?

You can avoid get undefined in '$' this way

window.addEventListener("DOMContentLoaded", function(){
    // Your code
});

EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure

How to print to stderr in Python?

I would say that your first approach:

print >> sys.stderr, 'spam' 

is the "One . . . obvious way to do it" The others don't satisfy rule #1 ("Beautiful is better than ugly.")

-- Edit for 2020 --

Above was my answer for Python 2.7 in 2011. Now that Python 3 is the standard, I think the "right" answer is:

print("spam", file=sys.stderr) 

ReflectionException: Class ClassName does not exist - Laravel

When it is looking for the seeder class file, you can run composer dump-autoload. When you run it again and it's looking for the Model, you can reference it on the seeder file itself. Like so,

use App\{Model};

Get refresh token google api

For those using the Google API Client Library for PHP and seeking offline access and refresh tokens beware as of the time of this writing the docs are showing incorrect examples.

currently it's showing:

$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true);   // incremental auth

source: https://developers.google.com/identity/protocols/OAuth2WebServer#offline

All of this works great - except ONE piece

$client->setApprovalPrompt("consent");

After a bit of reasoning I changed this line to the following and EVERYTHING WORKED

$client->setPrompt("consent");

It makes sense since using the HTTP requests it was changed from approval_prompt=force to prompt=consent. So changing the setter method from setApprovalPrompt to setPrompt follows natural convention - BUT IT'S NOT IN THE DOCS!!! That I found at least.

How to make <label> and <input> appear on the same line on an HTML form?

Wrap the label and the input within a bootstraps div

<div class ="row">
  <div class="col-md-4">Name:</div>
  <div class="col-md-8"><input type="text"></div>
</div>

Why docker container exits immediately

I would like to extend or dare I say, improve answer mentioned by camposer

When you run

docker run -dit ubuntu

you are basically running the container in background in interactive mode.

When you attach and exit the container by CTRL+D (most common way to do it), you stop the container because you just killed the main process which you started your container with the above command.

Making advantage of an already running container, I would just fork another process of bash and get a pseudo TTY by running:

docker exec -it <container ID> /bin/bash

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

LINQ extension methods - Any() vs. Where() vs. Exists()

Where returns a new sequence of items matching the predicate.

Any returns a Boolean value; there's a version with a predicate (in which case it returns whether or not any items match) and a version without (in which case it returns whether the query-so-far contains any items).

I'm not sure about Exists - it's not a LINQ standard query operator. If there's a version for the Entity Framework, perhaps it checks for existence based on a key - a sort of specialized form of Any? (There's an Exists method in List<T> which is similar to Any(predicate) but that predates LINQ.)

Add image in pdf using jspdf

In TypeScript, you can do:

private getImage(imagePath): ng.IPromise<any> {
    var defer = this.q.defer<any>();
    var img = new Image();
    img.src = imagePath;
    img.addEventListener('load',()=>{
       defer.resolve(img);
    });


    return defer.promise;
} 

Use the above function to getimage object. Then the following to add to pdf file:

pdf.addImage(getImage(url), 'png', x, y, imagewidth, imageheight);

In plain JavaScript, the function looks like this:

function (imagePath) {
        var defer = this.q.defer();
        var img = new Image();
        img.src = imagePath;
        img.addEventListener('load', function () {
            defer.resolve(img);
        });
        return defer.promise;
    };

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Simply try running npm install / yarn etc first before running npm start / yarn start as @only4 mentioned, if you see this problem, as it means your .env is not in sync with your package.json, i.e. you installed a package but not quite configured it or other way around

How can I check if my Element ID has focus?

Compare document.activeElement with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn't.

// dummy element
var dummyEl = document.getElementById('myID');

// check for focus
var isFocused = (document.activeElement === dummyEl);

hasFocus is part of the document; there's no such method for DOM elements.

Also, document.getElementById doesn't use a # at the beginning of myID. Change this:

var dummyEl = document.getElementById('#myID');

to this:

var dummyEl = document.getElementById('myID');

If you'd like to use a CSS query instead you can use querySelector (and querySelectorAll).

Creating PHP class instance with a string

You can simply use the following syntax to create a new class (this is handy if you're creating a factory):

$className = $whatever;
$object = new $className;

As an (exceptionally crude) example factory method:

public function &factory($className) {

    require_once($className . '.php');
    if(class_exists($className)) return new $className;

    die('Cannot create new "' . $className . '" class - includes not found or class unavailable.');
}

How to insert &nbsp; in XSLT

XSLT stylesheets must be well-formed XML. Since "&nbsp;" is not one of the five predefined XML entities, it cannot be directly included in the stylesheet. So coming back to your solution "&#160;" is a perfect replacement of "&nbsp;" you should use.

Example:

<xsl:value-of select="$txtFName"/>&#160;<xsl:value-of select="$txtLName"/>

How to install both Python 2.x and Python 3.x in Windows

I just had to install them. Then I used the free (and portable) soft at http://defaultprogramseditor.com/ under "File type settings"/"Context menu"/search:"py", chose .py file and added an 'open' command for the 2 IDLE by copying the existant command named 'open with IDLE, changing names to IDLE 3.4.1/2.7.8, and remplacing the files numbers of their respective versions in the program path. Now I have just to right click the .py file and chose which IDLE I want to use. Can do the same with direct interpreters if you prefer.

jquery how to use multiple ajax calls one after the end of the other

Haven't tried it yet but this is the best way I can think of if there umpteen number of ajax calls.

Method1:

let ajax1= $.ajax({url:'', type:'', . . .});
let ajax2= $.ajax({url:'', type:'', . . .});
.
.
.
let ajaxList = [ajax1, ajax2, . . .]

let count = 0;
let executeAjax = (i) => {
   $.when(ajaxList[i]).done((data) => {
      //  dataOperations goes here
      return i++
   })
}
while (count< ajaxList.length) {
   count = executeAjax(count)
}

If there are only a handful you can always nest them like this.

Method2:

$.when(ajax1).done((data1) => {
      //  dataOperations goes here on data1
      $.when(ajax2).done((data2) => {
         //  Here you can utilize data1 and data 2 simultaneously 
         . . . and so on
      })
   })

Note: If it is repetitive task go for method1, And if each data is to be treated differently, nesting in method2 makes more sense.

Proper way to use **kwargs in Python

Here's another approach:

def my_func(arg1, arg2, arg3):
    ... so something ...

kwargs = {'arg1': 'Value One', 'arg2': 'Value Two', 'arg3': 'Value Three'}
# Now you can call the function with kwargs like this:

my_func(**kwargs)

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

After wasting so much time i got to know that there was mistake in my syntax to connect with DB. I was using colon ":" instead of slash "/".

(1) if you use sid below is the syntax to get connection:

**"jdbc:oracle:thin:@{hostname}:{port}:{SID}"**

(2) if you use service name, below is the syntax to get connection:

"**jdbc:oracle:thin:@//{hostname}:{port}/{servicename}**"

Biggest advantage to using ASP.Net MVC vs web forms

Biggest single advantage for me would be the clear-cut separation between your Model, View, and Controller layers. It helps promote good design from the start.

C++ compile time error: expected identifier before numeric constant

You cannot do this:

vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);

in a class outside of a method.

You can initialize the data members at the point of declaration, but not with () brackets:

class Foo {
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5,0)};
};

Before C++11, you need to declare them first, then initialize them e.g in a contructor

class Foo {
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5,0) {}
};

Why dict.get(key) instead of dict[key]?

For what purpose is this function useful?

One particular usage is counting with a dictionary. Let's assume you want to count the number of occurrences of each element in a given list. The common way to do so is to make a dictionary where keys are elements and values are the number of occurrences.

fruits = ['apple', 'banana', 'peach', 'apple', 'pear']
d = {}
for fruit in fruits:
    if fruit not in d:
        d[fruit] = 0
    d[fruit] += 1

Using the .get() method, you can make this code more compact and clear:

for fruit in fruits:
    d[fruit] = d.get(fruit, 0) + 1

PHPMyAdmin Default login password

I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )

Anyway, coming to the solution, this is what I was required to do:

su -
gedit /etc/phpMyAdmin/config.inc.php

if not found... try phpmyadmin - all small caps.

gedit /etc/phpmyadmin/config.inc.php

Locate

$cfg['Servers'][$i]['AllowNoPassword']

and set it to:

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Save it.

How do I update the password for Git?

I would try to delete my account in Keychain Access and then run git clone again. Git will ask me for a new password.

There is already an object named in the database

In the database, query __MigrationHistory table and copy [ContextKey].

Paste it into the DbMigrationsConfiguration ConextKey as below

internal sealed class DbConfiguration: DbMigrationsConfiguration<DbContext>
    {
        public DbConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = "<contextKey from above>";
        }

How can I check file size in Python?

we have two options Both include importing os module

1) import os, as os.stat() function returns an object which contains so many headers including file created time and last modified time etc.. among them st_size gives the exact size of the file.

os.stat("filename").st_size

2) import os In this, we have to provide the exact file path(absolute path), not a relative path.

os.path.getsize("path of file")

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.

I don't know if my approach is the best, but is so easy and simple.

I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
[request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];

NSURLResponse *response;

NSError *error;

[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

At the server side, I receive the photo using the code:

InputStream is = request.inputStream

def receivedPhotoFile = (IOUtils.toByteArray(is))

def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"    

if (photo.save()) {    

    File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
    saveLocation.mkdirs()

    File tempFile = File.createTempFile("photo", ".jpg", saveLocation)

    photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()

    tempFile.append(photo.photoFile);

} else {

    println("Error")

}

I don't know if I have problems in future, but now is working fine in production environment.

Getting an "ambiguous redirect" error

This might be the case too.

you have not specified the file in a variable and redirecting output to it, then bash will throw this error.

files=`ls`
out_file = /path/to/output_file.t
for i in `echo "$files"`;
do
    content=`cat $i` 
    echo "${content}  ${i}" >> ${out_file}
done

out_file variable is not set up correctly so keep an eye on this too. BTW this code is printing all the content and its filename on the console.

Best way to implement keyboard shortcuts in a Windows Forms application?

You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.F)) {
    MessageBox.Show("What the Ctrl+F?");
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

Setting PATH environment variable in OSX permanently

You could also add this

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

to ~/.bash_profile, then create ~/.bashrc where you can just add more paths to PATH. An example with .

export PATH=$PATH:.

How to set TextView textStyle such as bold, italic

Use textView.setTypeface(Typeface tf, int style); to set style property of the TextView. See the developer documentation for more info.

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I had the same problem when I created application in Visual Studio, and then in properties created virtual directory for use with local IIS. If someone has this error it is because VS creates application under wrong AppPool, i.e. under AppPool which doesn't suit your needs.
If this is the case, go to IIS Manager, select App, Go to Basic settings and change AppPool for App and you are good to go.

How can I setup & run PhantomJS on Ubuntu?

Here are the build steps I used (note these instructions are for version 1.3. See comments to this answer for the installation instructions of the latest PhantomJS):

sudo apt-get update
sudo apt-get install git-core
sudo apt-get install build-essential
sudo apt-get install libqt4-dev libqtwebkit-dev qt4-qmake
git clone git://github.com/ariya/phantomjs.git && cd phantomjs
git checkout 1.3
qmake-qt4 && make

Now install Xvfb

sudo apt-get install xvfb xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic

Launch Xvfb:
Xvfb :23 -screen 0 1024x768x24 &

Now run phantom:
DISPLAY=:23 ./phantomjs hello.js

Assignment makes pointer from integer without cast

You are returning char, and not char*, which is the pointer to the first character of an array.

If you want to return a new character array instead of doing in-place modification, you can ask for an already allocated pointer (char*) as parameter or an uninitialized pointer. In this last case you must allocate the proper number of characters for new string and remember that in C parameters as passed by value ALWAYS, so you must use char** as parameter in the case of array allocated internally by function. Of course, the caller must free that pointer later.

How can I change all input values to uppercase using Jquery?

You can use each()

$('#id-submit').click(function () {
      $(":input").each(function(){
          this.value = this.value.toUpperCase();          
      });
});

How to avoid 'undefined index' errors?

Set each index in the array at the beginning (or before the $output array is used) would probably be the easiest solution for your case.

Example

$output['admin_link'] = ""
$output['alternate_title'] = ""
$output['access_info'] = ""
$output['description'] = ""
$output['url'] = ""

Also not really relevant for your case but where you said you were new to PHP and this is not really immediately obvious isset() can take multiple arguments. So in stead of this:

if(isset($var1) && isset($var2) && isset($var3) ...){
    // all are set
}

You can do:

if(isset($var1, $var2, $var3)){
   // all are set 
}

Select N random elements from a List<T> in C#

Extending from @ers's answer, if one is worried about possible different implementations of OrderBy, this should be safe:

// Instead of this
YourList.OrderBy(x => rnd.Next()).Take(5)

// Temporarily transform 
YourList
    .Select(v => new {v, i = rnd.Next()}) // Associate a random index to each entry
    .OrderBy(x => x.i).Take(5) // Sort by (at this point fixed) random index 
    .Select(x => x.v); // Go back to enumerable of entry

Detect and exclude outliers in Pandas data frame

My function for dropping outliers

def drop_outliers(df, field_name):
    distance = 1.5 * (np.percentile(df[field_name], 75) - np.percentile(df[field_name], 25))
    df.drop(df[df[field_name] > distance + np.percentile(df[field_name], 75)].index, inplace=True)
    df.drop(df[df[field_name] < np.percentile(df[field_name], 25) - distance].index, inplace=True)

Make column fixed position in bootstrap

in Bootstrap 3 class="affix" works, but in Bootstrap 4 it does not. I solved this problem in Bootstrap 4 with class="sticky-top" (using position: fixed in CSS has its own problems)

code will be something like this:

<div class="row">
    <div class="col-lg-3">
        <div class="sticky-top">
            Fixed content
        </div>
    </div>
    <div class="col-lg-9">
        Normal scrollable content
    </div>
</div>

Using an image caption in Markdown Jekyll

There are two semantically correct solutions to this question:

  1. Using a plugin
  2. Creating a custom include

1. Using a plugin

I've tried a couple of plugins doing this and my favourite is jekyll-figure.

1.1. Install jekyll-figure

One way to install jekyll-figure is to add gem "jekyll-figure" to your Gemfile in your plugins group.

Then run bundle install from your terminal window.

1.2. Use jekyll-figure

Simply wrap your markdown in {% figure %} and {% endfigure %} tags.

You caption goes in the opening {% figure %} tag, and you can even style it with markdown!

Example:

{% figure caption:"Le logo de **Jekyll** et son clin d'oeil à Robert Louis Stevenson" %}
    ![Le logo de Jekyll](/assets/images/2018-08-07-jekyll-logo.png)
{% endfigure %}

1.3. Style it

Now that your images and captions are semantically correct, you can apply CSS as you wish to:

  • figure (for both image and caption)
  • figure img (for image only)
  • figcaption (for caption only)

2. Creating a custom include

You'll need to create an image.html file in your _includes folder, and include it using Liquid in Markdown.

2.1. Create _includes/image.html

Create the image.html document in your _includes folder :

<!-- _includes/image.html -->
<figure>
    {% if include.url %}
    <a href="{{ include.url }}">
    {% endif %}
    <img
        {% if include.srcabs %}
            src="{{ include.srcabs }}"
        {% else %}
            src="{{ site.baseurl }}/assets/images/{{ include.src }}"
        {% endif %}
    alt="{{ include.alt }}">
    {% if include.url %}
    </a>
    {% endif %}
    {% if include.caption %}
        <figcaption>{{ include.caption }}</figcaption>
    {% endif %}
</figure>

2.2. In Markdown, include an image using Liquid

An image in /assets/images with a caption:

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="jekyll-logo.png" <!-- image filename (placed in /assets/images) -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

An (external) image using an absolute URL: (change src="" to srcabs="")

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    srcabs="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

A clickable image: (add url="" argument)

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    url="https://jekyllrb.com" <!-- destination url -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

An image without a caption:

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    alt="Jekyll's logo" <!-- alt text -->
%}

2.3. Style it

Now that your images and captions are semantically correct, you can apply CSS as you wish to:

  • figure (for both image and caption)
  • figure img (for image only)
  • figcaption (for caption only)

Get first key in a (possibly) associative array?

A one-liner:

$array = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
echo key( array_slice( $array, 0, 1, true ) );

# echos 'key1'

how to concatenate two dictionaries to create a new one in Python?

You can use the update() method to build a new dictionary containing all the items:

dall = {}
dall.update(d1)
dall.update(d2)
dall.update(d3)

Or, in a loop:

dall = {}
for d in [d1, d2, d3]:
  dall.update(d)

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

How to rotate the background image in the container?

CSS:

.reverse {
  transform: rotate(180deg);
}

.rotate {
  animation-duration: .5s;
  animation-iteration-count: 1;
  animation-name: yoyo;
  animation-timing-function: linear;
}

@keyframes yoyo {
  from { transform: rotate(  0deg); }
  to   { transform: rotate(360deg); }
}

Javascript:

$(buttonElement).click(function () {
  $(".arrow").toggleClass("reverse")

  return false
})

$(buttonElement).hover(function () {
  $(".arrow").addClass("rotate")
}, function() {
  $(".arrow").removeClass("rotate")
})

PS: I've found this somewhere else but don't remember the source

SQL to Query text in access with an apostrophe in it

When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.

SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";

If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.

SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';

Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.

It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.

SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";

error C2065: 'cout' : undeclared identifier

is normally stored in the C:\Program Files\Microsoft Visual Studio 8\VC\include folder. First check if it is still there. Then choose Tools + Options, Projects and Solutions, VC++ Directories, choose "Include files" in the "Show Directories for" combobox and double-check that $(VCInstallDir)include is on top of the list.

What is the difference between a Relational and Non-Relational Database?

The relational database uses a formal system of predicates to address data. The underlying physical implementation is of no substance and can vary to optimize for certain operations, but it must always assume the relational model. In layman's terms, that's just saying I know exactly how many values (attributes) each row (tuple) in my table (relation) has and now I want to exploit the fact accordingly, thoroughly and to it's extreme. That's the true nature of the beast. 

Since we're obviously the generation that has had a relational upbringing, if you look at NoSQL database models from the perspective of the relational model, again in layman's terms, the first obvious difference is that no assumptions about the number of values a row can contain is ever made. This is really oversimplifying the matter and does not cleanly apply to the intricacies of the physical models of every NoSQL database, but it's the pinnacle of the relational model and the first assumption we have to leave behind or, if you'd rather, the biggest leap we have to make.

We can agree to two things that are true for every DBMS: it can store any kind of data and has enough mathematical underpinnings to make it possible to manage the data in any way imaginable. The reality is that you'll never want to make the mistake of putting any of the two points to the test, but rather just stick with what the actual DBMS was really made for. In layman's terms: respect the beast within!

(Please note that I've avoided comparing the (obviously) well founded standards revolving around the relational model against the many flavors provided by NoSQL databases. If you'd like, consider NoSQL databases as an umbrella term for any DBMS that does not completely assume the relational model, in exclusion to everything else. The differences are too many, but that's the principal difference and the one I think would be of most use to you to understand the two.)

How can I suppress column header output for a single SQL statement?

Invoke mysql with the -N (the alias for -N is --skip-column-names) option:

mysql -N ...
use testdb;
select * from names;

+------+-------+
|    1 | pete  |
|    2 | john  |
|    3 | mike  |
+------+-------+
3 rows in set (0.00 sec)

Credit to ErichBSchulz for pointing out the -N alias.

To remove the grid (the vertical and horizontal lines) around the results use -s (--silent). Columns are separated with a TAB character.

mysql -s ...
use testdb;
select * from names;

id  name
1   pete
2   john
3   mike

To output the data with no headers and no grid just use both -s and -N.

mysql -sN ...

Read from file in eclipse

You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

If you whish to read the file in a given directory, you have to says so :

File file = new File(System.getProperty("user.dir")+"/"+"file.txt");

You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

Note that there is also a property for the separator (hard-coded to "/" in my exemple)

regards Guillaume

What does the question mark in Java generics' type parameter mean?

Perhaps a contrived "real world" example would help.

At my place of work we have rubbish bins that come in different flavours. All bins contain rubbish, but some bins are specialist and do not take all types of rubbish. So we have Bin<CupRubbish> and Bin<RecylcableRubbish>. The type system needs to make sure I can't put my HalfEatenSandwichRubbish into either of these types, but it can go into a general rubbish bin Bin<Rubbish>. If I wanted to talk about a Bin of Rubbish which may be specialised so I can't put in incompatible rubbish, then that would be Bin<? extends Rubbish>.

(Note: ? extends does not mean read-only. For instance, I can with proper precautions take out a piece of rubbish from a bin of unknown speciality and later put it back in a different place.)

Not sure how much that helps. Pointer-to-pointer in presence of polymorphism isn't entirely obvious.

JavaScript URL Decode function

decodeURIComponent(mystring);

you can get passed parameters by using this bit of code:

//parse URL to get values: var i = getUrlVars()["i"];
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Or this one-liner to get the parameters:

location.search.split("your_parameter=")[1]

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.

The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.

Makefile If-Then Else and Loops

Conditional Forms

Simple

conditional-directive
text-if-true
endif

Moderately Complex

conditional-directive
text-if-true
else
text-if-false
endif

More Complex

conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif

Conditional Directives

If Equal Syntax

ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"

If Not Equal Syntax

ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"

If Defined Syntax

ifdef variable-name

If Not Defined Syntax

ifndef variable-name  

foreach Function

foreach Function Syntax

$(foreach var, list, text)  

foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

How can I get last characters of a string

Following script shows the result for get last 5 characters and last 1 character in a string using JavaScript:

var testword='ctl03_Tabs1';
var last5=testword.substr(-5); //Get 5 characters
var last1=testword.substr(-1); //Get 1 character

Output :

Tabs1 // Got 5 characters

1 // Got 1 character

Can I safely delete contents of Xcode Derived data folder?

Yes, you can delete all files from DerivedData sub-folder (Not DerivedData Folder) directly.

That will not affect your project work. Contents of DerivedData folder is generated during the build time and you can delete them if you want. It's not an issue.

The contents of DerivedData will be recreated when you build your projects again.

Xcode8+ Update

From the Xcode8 that removed project option from the window tab so you can still use first way:

Xcode -> Preferences -> location -> click on small arrow button as i explain in my first answer.

Xcode7.3 Update For remove particular project's DeriveData you just need to follow the following steps:

Go to Window -> Project:

enter image description here

You can find the list of project and you can either go the DerivedData Folder or you can direct delete individual Project's DerivedData

enter image description here


I am not working on Xcode5 but in 4.6.3 you can find DerivedData folder as found in the below image:

enter image description here

After clicking on Preferences..

enter image description here

You get this window

enter image description here

Exposing a port on a live Docker container

Read Ricardo's response first. This worked for me.

However, there exists a scenario where this won't work if the running container was kicked off using docker-compose. This is because docker-compose (I'm running docker 1.17) creates a new network. The way to address this scenario would be

docker network ls

Then append the following docker run -d --name sqlplus --link db:db -p 1521:1521 sqlplus --net network_name

Opening port 80 EC2 Amazon web services

This is actually really easy:

  • Go to the "Network & Security" -> Security Group settings in the left hand navigation
  • Find the Security Group that your instance is apart of
  • Click on Inbound Rules
  • Use the drop down and add HTTP (port 80)
  • Click Apply and enjoy

How do you add a Dictionary of items into another Dictionary

Swift 2.2

func + <K,V>(left: [K : V], right: [K : V]) -> [K : V] {
    var result = [K:V]()

    for (key,value) in left {
        result[key] = value
    }

    for (key,value) in right {
        result[key] = value
    }
    return result
}

Description Box using "onmouseover"

This an old question but for people still looking. In JS you can now use the title property.

button.title = ("Popup text here");

Best way to handle list.index(might-not-exist) in python?

I have the same issue with the ".index()" method on lists. I have no issue with the fact that it throws an exception but I strongly disagree with the fact that it's a non-descriptive ValueError. I could understand if it would've been an IndexError, though.

I can see why returning "-1" would be an issue too because it's a valid index in Python. But realistically, I never expect a ".index()" method to return a negative number.

Here goes a one liner (ok, it's a rather long line ...), goes through the list exactly once and returns "None" if the item isn't found. It would be trivial to rewrite it to return -1, should you so desire.

indexOf = lambda list, thing: \
            reduce(lambda acc, (idx, elem): \
                   idx if (acc is None) and elem == thing else acc, list, None)

How to use:

>>> indexOf([1,2,3], 4)
>>>
>>> indexOf([1,2,3], 1)
0
>>>

What is the difference between Jupyter Notebook and JupyterLab?

(I am using JupyterLab with Julia)

First thing is that Jupyter lab from my previous use offers more 'themes' which is great on the eyes, and also fontsize changes independent of the browser, so that makes it closer to that of an IDE. There are some specifics I like such as changing the 'code font size' and leaving the interface font size to be the same.

Major features that are great is

  • the drag and drop of cells so that you can easily rearrange the code
  • collapsing cells with a single mouse click and a small mark to remind of their placement

What is paramount though is the ability to have split views of the tabs and the terminal. If you use Emacs, then you probably enjoyed having multiple buffers with horizontal and vertical arrangements with one of them running a shell (terminal), and with jupyterlab this can be done, and the arrangement is made with drags and drops which in Emacs is typically done with sets of commands.

(I do not believe that there is a learning curve added to those that have not used the 'notebook' original version first. You can dive straight into this IDE experience)

How to create an array from a CSV file using PHP and the fgetcsv function

$arrayFromCSV =  array_map('str_getcsv', file('/path/to/file.csv'));

What is the best method to merge two PHP objects?

A very simple solution considering you have object A and B:

foreach($objB AS $var=>$value){
    $objA->$var = $value;
}

That's all. You now have objA with all values from objB.

Rollback transaction after @Test

Just add @Transactional annotation on top of your test:

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class StudentSystemTest {

By default Spring will start a new transaction surrounding your test method and @Before/@After callbacks, rolling back at the end. It works by default, it's enough to have some transaction manager in the context.

From: 10.3.5.4 Transaction management (bold mine):

In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that TransactionalTestExecutionListener is configured by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must provide a PlatformTransactionManager bean in the application context loaded by @ContextConfiguration semantics. In addition, you must declare @Transactional either at the class or method level for your tests.

Where's my invalid character (ORA-00911)

If you use the string literal exactly as you have shown us, the problem is the ; character at the end. You may not include that in the query string in the JDBC calls.

As you are inserting only a single row, a regular INSERT should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):

String query1 = "select substr(to_char(max_data),1,4) as year, " + 
  "substr(to_char(max_data),5,6) as month, max_data " +
  "from dss_fin_user.acq_dashboard_src_load_success " + 
  "where source = 'CHQ PeopleSoft FS'";

String query2 = ".....";

String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();

reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();

pstmt.executeBatch();   
con.commit();

How do I use 3DES encryption/decryption in Java?

Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64:

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

public class TrippleDes {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public TrippleDes() throws Exception {
        myEncryptionKey = "ThisIsSpartaThisIsSparta";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }


    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedText = Base64.decodeBase64(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }


    public static void main(String args []) throws Exception
    {
        TrippleDes td= new TrippleDes();

        String target="imparator";
        String encrypted=td.encrypt(target);
        String decrypted=td.decrypt(encrypted);

        System.out.println("String To Encrypt: "+ target);
        System.out.println("Encrypted String:" + encrypted);
        System.out.println("Decrypted String:" + decrypted);

    }

}

Running the above program results with the following output:

String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator

How to convert .pem into .key?

openssl rsa -in privkey.pem -out private.key does the job.

Numpy: Divide each row by a vector element

Adding to the answer of stackoverflowuser2010, in the general case you can just use

data = np.array([[1,1,1],[2,2,2],[3,3,3]])

vector = np.array([1,2,3])

data / vector.reshape(-1,1)

This will turn your vector into a column matrix/vector. Allowing you to do the elementwise operations as you wish. At least to me, this is the most intuitive way going about it and since (in most cases) numpy will just use a view of the same internal memory for the reshaping it's efficient too.

Why is setTimeout(fn, 0) sometimes useful?

Some other cases where setTimeout is useful:

You want to break a long-running loop or calculation into smaller components so that the browser doesn't appear to 'freeze' or say "Script on page is busy".

You want to disable a form submit button when clicked, but if you disable the button in the onClick handler the form will not be submitted. setTimeout with a time of zero does the trick, allowing the event to end, the form to begin submitting, then your button can be disabled.

Sqlite convert string to date

This is for fecha(TEXT) format date YYYY-MM-dd HH:mm:ss for instance I want all the records of Ene-05-2014 (2014-01-05):

SELECT 
 fecha 
FROM 
 Mytable 
WHERE 
 DATE(substr(fecha ,1,4) ||substr(fecha ,6,2)||substr(fecha ,9,2))
BETWEEN 
 DATE(20140105) 
AND 
 DATE(20140105);

How to properly set Column Width upon creating Excel file? (Column properties)

I have change all columns width in my case as

            worksheet.Columns[1].ColumnWidth = 7;
            worksheet.Columns[2].ColumnWidth = 15;
            worksheet.Columns[3].ColumnWidth = 15;
            worksheet.Columns[4].ColumnWidth = 15;
            worksheet.Columns[5].ColumnWidth = 18;
            worksheet.Columns[6].ColumnWidth = 8;
            worksheet.Columns[7].ColumnWidth = 13;
            worksheet.Columns[8].ColumnWidth = 17;
            worksheet.Columns[9].ColumnWidth = 17;

Note: Columns in worksheet start with 1 not from 0 as in Arrary.

How to check if a float value is a whole number

You could use this:

if k == int(k):
    print(str(k) + " is a whole number!")

How can I find a specific element in a List<T>?

Use a lambda expression

MyClass result = list.Find(x => x.GetId() == "xy");

Note: C# has a built-in syntax for properties. Instead of writing getter and setter methods (as you might be used to from Java), write

private string _id;
public string Id
{
    get
    {
        return _id;
    }
    set
    {
        _id = value;
    }
}

value is a contextual keyword known only in the set accessor. It represents the value assigned to the property.

Since this pattern is often used, C# provides auto-implemented properties. They are a short version of the code above; however, the backing variable is hidden and not accessible (it is accessible from within the class in VB, however).

public string Id { get; set; }

You can simply use properties as if you were accessing a field:

var obj = new MyClass();
obj.Id = "xy";       // Calls the setter with "xy" assigned to the value parameter.
string id = obj.Id;  // Calls the getter.

Using properties, you would search for items in the list like this

MyClass result = list.Find(x => x.Id == "xy"); 

You can also use auto-implemented properties if you need a read-only property:

public string Id { get; private set; }

This enables you to set the Id within the class but not from outside. If you need to set it in derived classes as well you can also protect the setter

public string Id { get; protected set; }

And finally, you can declare properties as virtual and override them in deriving classes, allowing you to provide different implementations for getters and setters; just as for ordinary virtual methods.


Since C# 6.0 (Visual Studio 2015, Roslyn) you can write getter-only auto-properties with an inline initializer

public string Id { get; } = "A07"; // Evaluated once when object is initialized.

You can also initialize getter-only properties within the constructor instead. Getter-only auto-properties are true read-only properties, unlike auto-implemented properties with a private setter.

This works also with read-write auto-properties:

public string Id { get; set; } = "A07";

Beginning with C# 6.0 you can also write properties as expression-bodied members

public DateTime Yesterday => DateTime.Date.AddDays(-1); // Evaluated at each call.
// Instead of
public DateTime Yesterday { get { return DateTime.Date.AddDays(-1); } }

See: .NET Compiler Platform ("Roslyn")
         New Language Features in C# 6

Starting with C# 7.0, both, getter and setter, can be written with expression bodies:

public string Name
{
    get => _name;                                // getter
    set => _name = value;                        // setter
}

Note that in this case the setter must be an expression. It cannot be a statement. The example above works, because in C# an assignment can be used as an expression or as a statement. The value of an assignment expression is the assigned value where the assignment itself is a side effect. This allows you to assign a value to more than one variable at once: x = y = z = 0 is equivalent to x = (y = (z = 0)) and has the same effect as the statements x = 0; y = 0; z = 0;.

The next version of the language, C# 9.0, probably available in November 2020, will allow read-only (or better initialize-once) properties that you can initialize in an object initializer. This is currently not possible with getter-only properties.

public string Name { get; init; }

var c = new C { Name = "c-sharp" };

Reload content in modal (twitter bootstrap)

A little more compressed than the above accepted example. Grabs the target from the data-target of the current clicked anything with data-toggle=modal on. This makes it so you don't have to know what the id of the target modal is, just reuse the same one! less code = win! You could also modify this to load title, labels and buttons for your modal should you want to.

 $("[data-toggle=modal]").click(function(ev) {
    ev.preventDefault();
    // load the url and show modal on success
    $( $(this).attr('data-target') + " .modal-body").load($(this).attr("href"), function() { 
         $($(this).attr('data-target')).modal("show"); 
    });
});

Example Links:

<a data-toggle="modal" href="/page/api?package=herp" data-target="#modal">click me</a>
<a data-toggle="modal" href="/page/api?package=derp" data-target="#modal">click me2</a>
<a data-toggle="modal" href="/page/api?package=merp" data-target="#modal">click me3</a>

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.

You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.

Ruby capitalize every word first letter

"hello world".split.each{|i| i.capitalize!}.join(' ')

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

Be careful with rebase. If you're sharing your develop branch with anybody, rebase can make a mess of things. Rebase is good only for your own local branches.

Rule of thumb, if you've pushed the branch to origin, don't use rebase. Instead, use merge.

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I faced the same issue with grpc module and in my case, I was using electron and have set a wrong electron version in the env variable "export npm_config_target=1.2.3", setting it to the electron version I am using resolved the issue on my end. Hope this helps someone who set env variables as given here (https://electronjs.org/docs/tutorial/using-native-node-modules#the-npm-way)

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

What is exactly the base pointer and stack pointer? To what do they point?

You have it right. The stack pointer points to the top item on the stack and the base pointer points to the "previous" top of the stack before the function was called.

When you call a function, any local variable will be stored on the stack and the stack pointer will be incremented. When you return from the function, all the local variables on the stack go out of scope. You do this by setting the stack pointer back to the base pointer (which was the "previous" top before the function call).

Doing memory allocation this way is very, very fast and efficient.

Is it not possible to define multiple constructors in Python?

The easiest way is through keyword arguments:

class City():
  def __init__(self, city=None):
    pass

someCity = City(city="Berlin")

This is pretty basic stuff. Maybe look at the Python documentation?

How to change the value of ${user} variable used in Eclipse templates

Rather than changing ${user} in eclipse, it is advisable to introduce

-Duser.name=Whateverpleaseyou

in eclipse.ini which is present in your eclipse folder.

SQL: Select columns with NULL values only

You can do:

select 
  count(<columnName>)
from
  <tableName>

If the count returns 0 that means that all rows in that column all NULL (or there is no rows at all in the table)

can be changed to

select 
    case(count(<columnName>)) when 0 then 'Nulls Only' else 'Some Values' end
from 
    <tableName>

If you want to automate it you can use system tables to iterate the column names in the table you are interested in

Function pointer to member function

int (*x)() is not a pointer to member function. A pointer to member function is written like this: int (A::*x)(void) = &A::f;.

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

How do I "break" out of an if statement?

Nested ifs:

if (condition)
{
    // half-massive amount of code here

    if (!breakOutCondition)
    {
        //half-massive amount of code here
    }
}

At the risk of being downvoted -- it's happened to me in the past -- I'll mention that another (unpopular) option would of course be the dreaded goto; a break statement is just a goto in disguise.

And finally, I'll echo the common sentiment that your design could probably be improved so that the massive if statement is not necessary, let alone breaking out of it. At least you should be able to extract a couple of methods, and use a return:

if (condition)
{
    ExtractedMethod1();

    if (breakOutCondition)
        return;

    ExtractedMethod2();
}

How to programmatically set the SSLContext of a JAX-WS client?

By combining Radek and l0co's answers you can access the WSDL behind https:

SSLContext sc = SSLContext.getInstance("TLS");

KeyManagerFactory kmf = KeyManagerFactory
        .getInstance(KeyManagerFactory.getDefaultAlgorithm());

KeyStore ks = KeyStore.getInstance("JKS");
ks.load(getClass().getResourceAsStream(keystore),
        password.toCharArray());

kmf.init(ks, password.toCharArray());

sc.init(kmf.getKeyManagers(), null, null);

HttpsURLConnection
        .setDefaultSSLSocketFactory(sc.getSocketFactory());

yourService = new YourService(url); //Handshake should succeed

Convert string to nullable type (int, double, etc...)

What about this:


double? amount = string.IsNullOrEmpty(strAmount) ? (double?)null : Convert.ToDouble(strAmount);

Of course, this doesn't take into account the convert failing.

How to echo shell commands as they are executed

For zsh, echo

setopt VERBOSE

And for debugging,

setopt XTRACE

What is the syntax for Typescript arrow functions with generics?

The full example explaining the syntax referenced by Robin... brought it home for me:

Generic functions

Something like the following works fine:

function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:

const foo = <T extends unknown>(x: T) => x;

INNER JOIN ON vs WHERE clause

I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

Addressing localhost from a VirtualBox virtual machine

On Windows with a virtual Windows 7 the only thing that worked for me was using NAT and port-forwarding (couldn't get bridged connection running). I found a tutorial here: http://www.howtogeek.com/122641/how-to-forward-ports-to-a-virtual-machine-and-use-it-as-a-server/ (scroll down to the part with "Forwarding Ports to a Virtual Machine").

With this changes I could reach the xampp website with "http://192.168.xx.x:8888/mywebsite" in internet explorer 10 on my virtual machine.

I found the IP in XAMPP Control Panel > Netstat ("System").

Convert Dictionary<string,string> to semicolon separated string in c#

using System.Linq;

string s = string.Join(";", myDict.Select(x => x.Key + "=" + x.Value).ToArray());

(And if you're using .NET 4, or newer, then you can omit the final ToArray call.)

async await return Task

This is a Task that is returning a Task of type String (C# anonymous function or in other word a delegation is used 'Func')

    public static async Task<string> MyTask()
    {
        //C# anonymous AsyncTask
        return await Task.FromResult<string>(((Func<string>)(() =>
        {
            // your code here
            return  "string result here";

        }))());
    }

Checking on a thread / remove from list

The answer has been covered, but for simplicity...

# To filter out finished threads
threads = [t for t in threads if t.is_alive()]

# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]

How to append rows to an R data frame

A more generic solution for might be the following.

    extendDf <- function (df, n) {
    withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
    nr          <- nrow (df)
    colNames    <- names(df)
    for (c in 1:length(colNames)) {
        if (is.factor(df[,c])) {
            col         <- vector (mode='character', length = nr+n) 
            col[1:nr]   <- as.character(df[,c])
            col[(nr+1):(n+nr)]<- rep(col[1], n)  # to avoid extra levels
            col         <- as.factor(col)
        } else {
            col         <- vector (mode=mode(df[1,c]), length = nr+n)
            class(col)  <- class (df[1,c])
            col[1:nr]   <- df[,c] 
        }
        if (c==1) {
            newDf       <- data.frame (col ,stringsAsFactors=withFactors)
        } else {
            newDf[,c]   <- col 
        }
    }
    names(newDf) <- colNames
    newDf
}

The function extendDf() extends a data frame with n rows.

As an example:

aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
#      l i n c                   t
# 1  TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00

system.time (eDf <- extendDf (aDf, 100000))
#    user  system elapsed 
#   0.009   0.002   0.010
system.time (eDf <- extendDf (eDf, 100000))
#    user  system elapsed 
#   0.068   0.002   0.070

Difference between abstract class and interface in Python

In general, interfaces are used only in languages that use the single-inheritance class model. In these single-inheritance languages, interfaces are typically used if any class could use a particular method or set of methods. Also in these single-inheritance languages, abstract classes are used to either have defined class variables in addition to none or more methods, or to exploit the single-inheritance model to limit the range of classes that could use a set of methods.

Languages that support the multiple-inheritance model tend to use only classes or abstract base classes and not interfaces. Since Python supports multiple inheritance, it does not use interfaces and you would want to use base classes or abstract base classes.

http://docs.python.org/library/abc.html

Calculate distance between two points in google maps V3

If you want to calculate it yourself, then you can use the Haversine formula:

var rad = function(x) {
  return x * Math.PI / 180;
};

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s mean radius in meter
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d; // returns the distance in meter
};

How to generate a random string in Ruby

I just write a small gem random_token to generate random tokens for most use case, enjoy ~

https://github.com/sibevin/random_token

Uninstall / remove a Homebrew package including all its dependencies

A More-Complete Bourne Shell Function

There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time.

Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies.

unbrew () {
    local formula
    for formula in "$@"; do
        brew deps "$formula" |
        xargs brew uninstall --ignore-dependencies --force
        brew uninstall --force "$formula"
    done
    brew missing | cut -f2 -d: | sort -u | xargs brew install
}

It was tested on Homebrew 1.7.4.

Caveats

This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim).

jQuery - trapping tab select event

Simply:

$("#tabs_div").tabs();
$("#tabs_div").on("click", "a.tab_a", function(){
    console.log("selected tab id: " + $(this).attr("href"));
    console.log("selected tab name: " + $(this).find("span").text());
});

But you have to add class name to your anchors named "tab_a":

<div id="tabs">
<UL>
    <LI><A class="tab_a" href="#fragment-1"><SPAN>Tab1</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-2"><SPAN>Tab2</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-3"><SPAN>Tab3</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-4"><SPAN>Tab4</SPAN></A></LI>
</UL>

<DIV id=fragment-1>
<UL>
    <LI><A class="tab_a" href="#fragment-1a"><SPAN>Sub-Tab1</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-1b"><SPAN>Sub-Tab2</SPAN></A></LI>
    <LI><A class="tab_a" href="#fragment-1c"><SPAN>Sub-Tab3</SPAN></A></LI>
</UL>
</DIV>
.
.
</DIV>

Action Bar's onClick listener for the Home button

You need to explicitly enable the home action if running on ICS. From the docs:

Note: If you're using the icon to navigate to the home activity, beware that beginning with Android 4.0 (API level 14), you must explicitly enable the icon as an action item by calling setHomeButtonEnabled(true) (in previous versions, the icon was enabled as an action item by default).

Vue.js get selected option on @change

Use v-model to bind the value of selected option's value. Here is an example.

<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
   <option value="1">Annual Leave/ Off-Day</option>
   <option value="2">On Demand Leave</option>
</select>
<script>
var vm = new Vue({
    data: {
        key: ""
    },
    methods: {
        onChange(event) {
            console.log(event.target.value)
        }
    }
}
</script>

More reference can been seen from here.

Android and setting width and height programmatically in dp units

Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:

final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);

And your dimens.xml will have:

<dimen name="dimen_entry_in_dp">72dp</dimen>

Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Perhaps the error message is somewhat misleading, but the gist is that X_train is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:

out_images = np.array(X_train)[indices.astype(int)]

Selecting non-blank cells in Excel with VBA

This might be completely off base, but can't you just copy the whole column into a new spreadsheet and then sort the column? I'm assuming that you don't need to maintain the order integrity.

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

node.js Error: connect ECONNREFUSED; response from server

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

Create local maven repository

Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.

To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source

Add a file to your repository like this:

mvn install:install-file \
  -Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID 
  -DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
  -Dpackaging=jar \
  -DlocalRepositoryPath=/var/www/html/mavenRepository

If your domain is example.com and the root directory of the web server is located at /var/www/html/, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>.

Get webpage contents with Python?

Suppose you want to GET a webpage's content. The following code does it:

# -*- coding: utf-8 -*-
# python

# example of getting a web page

from urllib import urlopen
print urlopen("http://xahlee.info/python/python_index.html").read()

Select query with date condition

Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".

Put # signs around the date, like this #1/09/2008#

How to get milliseconds from LocalDateTime in Java 8

Since Java 8 you can call java.time.Instant.toEpochMilli().

For example the call

final long currentTimeJava8 = Instant.now().toEpochMilli();

gives you the same results as

final long currentTimeJava1 = System.currentTimeMillis();

What is "pom" packaging in maven?

pom packaging is simply a specification that states the primary artifact is not a war or jar, but the pom.xml itself.

Often it is used in conjunction with "modules" which are typically contained in sub-directories of the project in question; however, it may also be used in certain scenarios where no primary binary was meant to be built, all the other important artifacts have been declared as secondary artifacts

Think of a "documentation" project, the primary artifact might be a PDF, but it's already built, and the work to declare it as a secondary artifact might be desired over the configuration to tell maven how to build a PDF that doesn't need compiled.

Equivalent of .bat in mac os

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

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

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

Selenium wait until document is ready

This is a working Java version of the example you gave :

void waitForLoad(WebDriver driver) {
    new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd ->
            ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
}

Example For c#:

public static void WaitForLoad(IWebDriver driver, int timeoutSec = 15)
{
    IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
    WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, timeoutSec));
    wait.Until(wd => js.ExecuteScript("return document.readyState").ToString() == "complete");
}

Example for PHP:

final public function waitUntilDomReadyState(RemoteWebDriver $webDriver): void
{
    $webDriver->wait()->until(function () {
        return $webDriver->executeScript('return document.readyState') === 'complete';
    });
}

In LaTeX, how can one add a header/footer in the document class Letter?

This code works to insert both header and footer on the first page with header center aligned and footer left aligned

\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
  % for the first page
  \def\ps@IEEEtitlepagestyle{%
    \old@ps@IEEEtitlepagestyle%
    \def\@oddhead{\strut\hfill#1\hfill\strut}%
    \def\@evenhead{\strut\hfill#1\hfill\strut}%
 \def\@oddfoot{\mycopyrightnotice}
  \def\@evenfoot{}
  }%
  \ps@headings%
}
\makeatother

\confheader{%
  5$^{th}$  IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}

\def\mycopyrightnotice{
  {\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
  \gdef\mycopyrightnotice{}

}

\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}


\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```

make *** no targets specified and no makefile found. stop

If you create Makefile in the VSCode, your makefile doesnt run. I don't know the cause of this issue. Maybe the configuration of the file is not added to system. But I solved this way. delete created makefile, then go to project directory and right click mouse later create a file and named Makefile. After fill the Makefile and run it. It will work.

Class Diagrams in VS 2017

Noticed this in the beta and thought I had a bad install. The UI elements to add new Class Diagrams were missing and I was unable to open existing *.cd Class Diagram files in my solutions. Just upgraded to 2017 and found the problem remains. After some investigation it seems the Class Designer component is no longer installed by default.

Re-running the VS Installer and adding the Class Designer component restores both my ability to open and edit Class Diagrams as well as the UI elements needed to create new ones

VS Installer > Individual Components > Class Designer

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());