Programs & Examples On #Help authoring

How exactly does binary code get converted into letters?

Do you mean the conversion 011001100110111101101111 ? foo, for example? You just take the binary stream, split it into separate bytes (01100110, 01101111, 01101111) and look up the ASCII character that corresponds to given number. For example, 01100110 is 102 in decimal and the ASCII character with code 102 is f:

$ perl -E 'say 0b01100110'
102
$ perl -E 'say chr(102)'
f

(See what the chr function does.) You can generalize this algorithm and have a different number of bits per character and different encodings, the point remains the same.

Switching between GCC and Clang/LLVM using CMake

System wide C++ change on Ubuntu:

sudo apt-get install clang
sudo update-alternatives --config c++

Will print something like this:

  Selection    Path              Priority   Status
------------------------------------------------------------
* 0            /usr/bin/g++       20        auto mode
  1            /usr/bin/clang++   10        manual mode
  2            /usr/bin/g++       20        manual mode

Then just select clang++.

Update Eclipse with Android development tools v. 23

If Eclipse gives an error after uninstalling the ADT plugin from your Eclipse installation, try to edit file config.ini in the Eclipse folder ? configuration. Find:

eclipse.application=

And change it to:

eclipse.application=org.eclipse.ui.ide.workbench

I hope it works for you too.

How to select last one week data from today's date

  1. The query is correct

2A. As far as last seven days have much less rows than whole table an index can help

2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

Force an Android activity to always use landscape mode

In my OnCreate(Bundle), I generally do the following:

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

Using Keras & Tensorflow with AMD GPU

One can use AMD GPU via the PlaidML Keras backend.

Fastest: PlaidML is often 10x faster (or more) than popular platforms (like TensorFlow CPU) because it supports all GPUs, independent of make and model. PlaidML accelerates deep learning on AMD, Intel, NVIDIA, ARM, and embedded GPUs.

Easiest: PlaidML is simple to install and supports multiple frontends (Keras and ONNX currently)

Free: PlaidML is completely open source and doesn't rely on any vendor libraries with proprietary and restrictive licenses.

For most platforms, getting started with accelerated deep learning is as easy as running a few commands (assuming you have Python (v2 or v3) installed):

virtualenv plaidml
source plaidml/bin/activate
pip install plaidml-keras plaidbench

Choose which accelerator you'd like to use (many computers, especially laptops, have multiple):

plaidml-setup

Next, try benchmarking MobileNet inference performance:

plaidbench keras mobilenet

Or, try training MobileNet:

plaidbench --batch-size 16 keras --train mobilenet

To use it with keras set

os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"

For more information

https://github.com/plaidml/plaidml

https://github.com/rstudio/keras/issues/205#issuecomment-348336284

Change keystore password from no password to a non blank password

Add -storepass to keytool arguments.

keytool -storepasswd -storepass '' -keystore mykeystore.jks

But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password

$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

Why are there no ++ and --? operators in Python?

I believe it stems from the Python creed that "explicit is better than implicit".

How can I get form data with JavaScript/jQuery?

For those of you who would prefer an Object as opposed to a serialized string (like the one returned by $(form).serialize(), and a slight improvement on $(form).serializeArray()), feel free to use the code below:

var Form = {
    _form: null,
    _validate: function(){
        if(!this._form || this._form.tagName.toLowerCase() !== "form") return false;
        if(!this._form.elements.length) return false;
    }, _loopFields: function(callback){
        var elements = this._form.elements;
        for(var i = 0; i < elements.length; i++){
            var element = form.elements[i];
            if(name !== ""){
                callback(this._valueOfField(element));
            }
        }
    }, _valueOfField: function(element){
        var type = element.type;
        var name = element.name.trim();
        var nodeName = element.nodeName.toLowerCase();
        switch(nodeName){
            case "input":
                if(type === "radio" || type === "checkbox"){
                    if(element.checked){
                        return element.value;
                    }
                }
                return element.value;
                break;
            case "select":
                if(type === "select-multiple"){
                    for(var i = 0; i < element.options.length; i++){
                        if(options[i].selected){
                            return element.value;
                        }
                    }
                }
                return element.value;
                break;
            case "button":
                switch(type){
                    case "reset": 
                    case "submit": 
                    case "button":
                        return element.value;
                        break;
                }
                break;
        } 
    }, serialize: function(form){
        var data = {};
        this._form = form;

        if(this._validate()){
            this._loopFields(function(value){
                if(value !== null) data[name] = value;
            });
        }
        return data;
    }
};

To execute it, just use Form.serialize(form) and the function will return an Object similar to this:

<!-- { username: "username", password: "password" } !-->
<input type="text" value="username">
<input type="password" value="password">

As a bonus, it means you don't have to install the entire bundle of jQuery just for one serialize function.

Difference between h:button and h:commandButton

h:button - clicking on a h:button issues a bookmarkable GET request.

h:commandbutton - Instead of a get request, h:commandbutton issues a POST request which sends the form data back to the server.

What are sessions? How do they work?

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.

Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.

The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.

Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.

In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.

Redirect parent window from an iframe action

window.top.location.href = "http://www.example.com"; 

Will redirect the top most parent Iframe.

window.parent.location.href = "http://www.example.com"; 

Will redirect the parent iframe.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Use ASP.NET MVC validation with jquery ajax?

What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel object( your action method parameter), using MVC model binding feature.

You can validate your form at client side and if everything is fine, send the data to server. The valid() method will come in handy.

$(function () {

    $("#yourSubmitButtonID").click(function (e) {

        e.preventDefault();
        var _this = $(this);
        var _form = _this.closest("form");

        var isvalid = _form .valid();  // Tells whether the form is valid

        if (isvalid)
        {           
           $.post(_form.attr("action"), _form.serialize(), function (data) {
              //check the result and do whatever you want
           })
        }

    });

});

How to pass object with NSNotificationCenter

Swift 5.1 Custom Object/Type

// MARK: - NotificationName
// Extending notification name to avoid string errors.
extension Notification.Name {
    static let yourNotificationName = Notification.Name("yourNotificationName")
}


// MARK: - CustomObject
class YourCustomObject {
    // Any stuffs you would like to set in your custom object as always.
    init() {}
}

// MARK: - Notification Sender Class
class NotificatioSenderClass {

     // Just grab the content of this function and put it to your function responsible for triggering a notification.
    func postNotification(){
        // Note: - This is the important part pass your object instance as object parameter.
        let yourObjectInstance = YourCustomObject()
        NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
    }
}

// MARK: -Notification  Receiver class
class NotificationReceiverClass: UIViewController {
    // MARK: - ViewController Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        // Register your notification listener
        NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
    }

    // MARK: - Helpers
    @objc private func didReceiveNotificationWithCustomObject(notification: Notification){
        // Important: - Grab your custom object here by casting the notification object.
        guard let yourPassedObject = notification.object as? YourCustomObject else {return}
        // That's it now you can use your custom object
        //
        //

    }
      // MARK: - Deinit
  deinit {
      // Save your memory by releasing notification listener
      NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
    }




}

Find if current time falls in a time range

 using System;

 public class Program
 {
    public static void Main()
    {
        TimeSpan t=new TimeSpan(20,00,00);//Time to check

        TimeSpan start = new TimeSpan(20, 0, 0); //8 o'clock evening

        TimeSpan end = new TimeSpan(08, 0, 0); //8 o'clock Morning

        if ((start>=end && (t<end ||t>=start))||(start<end && (t>=start && t<end)))
        {
           Console.WriteLine("Mached");
        }
        else
        {
            Console.WriteLine("Not Mached");
        }

    }
 }

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

change it to 32-bit (true) it works

if you get this Length cannot be less than zero. Parameter name: length issue in iis server configuation do the simple thing change the connection string in web.config file like your sql server name and server name and restart iis then try to load the page it works

Display milliseconds in Excel

Right click on Cell B1 and choose Format Cells. In Custom, put the following in the text box labeled Type:

[h]:mm:ss.000 

To set this in code, you can do something like:

Range("A1").NumberFormat = "[h]:mm:ss.000"

That should give you what you're looking for.

NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######.

Using "-Filter" with a variable

You don't need quotes around the variable, so simply change this:

Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}

into this:

Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}

Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:

Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"

Related. Also related.

And FTR: you're using wildcard matching here (operator -like), not regular expressions (operator -match).

What characters are forbidden in Windows and Linux directory names?

Difficulties with defining, what's legal and not were already adressed and whitelists were suggested. But Windows supports more-than-8-bit characters. Wikipedia states, that (for example) the

modifier letter colon [(See 7. below) is] sometimes used in Windows filenames as it is identical to the colon in the Segoe UI font used for filenames. The [inherited ASCII] colon itself is not permitted.

Therefore, I want to present a much more liberal approach using Unicode characters to replace the "illegal" ones. I found the result in my comparable use-case by far more readable. Plus you can even restore the original content from the replacements. Possible choices and research are provided in the following list:

  1. Instead of * (U+002A * ASTERISK), you can use one of the many listed, for example U+2217 * (ASTERISK OPERATOR) or the Full Width Asterisk U+FF0A *
  2. Instead of ., you can use one of these, for example · U+22C5 dot operator
  3. Instead of ", you can use “ U+201C english leftdoublequotemark (Alternatives see here)
  4. Instead of / (/ SOLIDUS U+002F ), you can use / DIVISION SLASH U+2215 (others here)
  5. Instead of \ (\ U+005C Reverse solidus), you can use ? U+29F5 Reverse solidus operator (more)
  6. Instead of [ (U+005B Left square bracket) and ] (U+005D Right square bracket), you can use for example U+FF3B[ FULLWIDTH LEFT SQUARE BRACKET and U+FF3D ]FULLWIDTH RIGHT SQUARE BRACKET (from here, more possibilities here)
  7. Instead of :, you can use U+2236 : RATIO (for mathematical usage) or U+A789 ? MODIFIER LETTER COLON, (see colon (letter), sometimes used in Windows filenames as it is identical to the colon in the Segoe UI font used for filenames. The colon itself is not permitted) (See here)
  8. Instead of ;, you can use U+037E ; GREEK QUESTION MARK (see here)
  9. For |, there are some good substitutes such as: U+0964 ? DEVANAGARI DANDA, U+2223 | DIVIDES or U+01C0 | LATIN LETTER DENTAL CLICK (Wikipedia). Also the box drawing characters contain various other options.
  10. Instead of , (, U+002C COMMA), you can use for example ‚ U+201A SINGLE LOW-9 QUOTATION MARK (see here)
  11. For ? (U+003F ? QUESTION MARK), these are good candidates: U+FF1F ? FULLWIDTH QUESTION MARK or U+FE56 ? SMALL QUESTION MARK (from here, two more from Dingbats Block, search for "question")

For additional ideas, you can also look for example into this block. In Windows, these special characters should theoretically be able to be typed by using an alt-code, but I only found a solution to insert it in Microsoft Office in this Microsoft article using ALT + X. It can of course still be copied instead of typed.

How to upgrade PowerShell version from 2.0 to 3.0

Just run this in a console.

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
cinst powershell

It installs the latest version using a Chocolatey repository.

Originally I was using command cinst powershell 3.0.20121027, but it looks like it later stopped working. Since this question is related to PowerShell 3.0 this was the right way. At this moment (June 26, 2014) cinst powershell refers to version 3.0 of PowerShell, and that may change in future.

See the Chocolatey PowerShell package page for details on what version will be installed.

Getting HTTP headers with Node.js

Try to look at http.get and response headers.

var http = require("http");

var options = {
  host: 'stackoverflow.com',
  port: 80,
  path: '/'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  for(var item in res.headers) {
    console.log(item + ": " + res.headers[item]);
  }
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

Download Excel file via AJAX MVC

I used the solution posted by CSL but I would recommend you dont store the file data in Session during the whole session. By using TempData the file data is automatically removed after the next request (which is the GET request for the file). You could also manage removal of the file data in Session in download action.

Session could consume much memory/space depending on SessionState storage and how many files are exported during the session and if you have many users.

I've updated the serer side code from CSL to use TempData instead.

public ActionResult PostReportPartial(ReportVM model){

   // Validate the Model is correct and contains valid data
   // Generate your report output based on the model parameters
   // This can be an Excel, PDF, Word file - whatever you need.

   // As an example lets assume we've generated an EPPlus ExcelPackage

   ExcelPackage workbook = new ExcelPackage();
   // Do something to populate your workbook

   // Generate a new unique identifier against which the file can be stored
   string handle = Guid.NewGuid().ToString()

   using(MemoryStream memoryStream = new MemoryStream()){
        workbook.SaveAs(memoryStream);
        memoryStream.Position = 0;
        TempData[handle] = memoryStream.ToArray();
   }      

   // Note we are returning a filename as well as the handle
   return new JsonResult() { 
         Data = new { FileGuid = handle, FileName = "TestReportOutput.xlsx" }
   };

}

[HttpGet]
public virtual ActionResult Download(string fileGuid, string fileName)
{   
   if(TempData[fileGuid] != null){
        byte[] data = TempData[fileGuid] as byte[];
        return File(data, "application/vnd.ms-excel", fileName);
   }   
   else{
        // Problem - Log the error, generate a blank file,
        //           redirect to another controller action - whatever fits with your application
        return new EmptyResult();
   }
}

Awaiting multiple Tasks with different results

Given three tasks - FeedCat(), SellHouse() and BuyCar(), there are two interesting cases: either they all complete synchronously (for some reason, perhaps caching or an error), or they don't.

Let's say we have, from the question:

Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();
    // what here?
}

Now, a simple approach would be:

Task.WhenAll(x, y, z);

but ... that isn't convenient for processing the results; we'd typically want to await that:

async Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    await Task.WhenAll(x, y, z);
    // presumably we want to do something with the results...
    return DoWhatever(x.Result, y.Result, z.Result);
}

but this does lots of overhead and allocates various arrays (including the params Task[] array) and lists (internally). It works, but it isn't great IMO. In many ways it is simpler to use an async operation and just await each in turn:

async Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    // do something with the results...
    return DoWhatever(await x, await y, await z);
}

Contrary to some of the comments above, using await instead of Task.WhenAll makes no difference to how the tasks run (concurrently, sequentially, etc). At the highest level, Task.WhenAll predates good compiler support for async/await, and was useful when those things didn't exist. It is also useful when you have an arbitrary array of tasks, rather than 3 discreet tasks.

But: we still have the problem that async/await generates a lot of compiler noise for the continuation. If it is likely that the tasks might actually complete synchronously, then we can optimize this by building in a synchronous path with an asynchronous fallback:

Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    if(x.Status == TaskStatus.RanToCompletion &&
       y.Status == TaskStatus.RanToCompletion &&
       z.Status == TaskStatus.RanToCompletion)
        return Task.FromResult(
          DoWhatever(a.Result, b.Result, c.Result));
       // we can safely access .Result, as they are known
       // to be ran-to-completion

    return Awaited(x, y, z);
}

async Task Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
    return DoWhatever(await x, await y, await z);
}

This "sync path with async fallback" approach is increasingly common especially in high performance code where synchronous completions are relatively frequent. Note it won't help at all if the completion is always genuinely asynchronous.

Additional things that apply here:

  1. with recent C#, a common pattern is for the async fallback method is commonly implemented as a local function:

    Task<string> DoTheThings() {
        async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
            return DoWhatever(await a, await b, await c);
        }
        Task<Cat> x = FeedCat();
        Task<House> y = SellHouse();
        Task<Tesla> z = BuyCar();
    
        if(x.Status == TaskStatus.RanToCompletion &&
           y.Status == TaskStatus.RanToCompletion &&
           z.Status == TaskStatus.RanToCompletion)
            return Task.FromResult(
              DoWhatever(a.Result, b.Result, c.Result));
           // we can safely access .Result, as they are known
           // to be ran-to-completion
    
        return Awaited(x, y, z);
    }
    
  2. prefer ValueTask<T> to Task<T> if there is a good chance of things ever completely synchronously with many different return values:

    ValueTask<string> DoTheThings() {
        async ValueTask<string> Awaited(ValueTask<Cat> a, Task<House> b, Task<Tesla> c) {
            return DoWhatever(await a, await b, await c);
        }
        ValueTask<Cat> x = FeedCat();
        ValueTask<House> y = SellHouse();
        ValueTask<Tesla> z = BuyCar();
    
        if(x.IsCompletedSuccessfully &&
           y.IsCompletedSuccessfully &&
           z.IsCompletedSuccessfully)
            return new ValueTask<string>(
              DoWhatever(a.Result, b.Result, c.Result));
           // we can safely access .Result, as they are known
           // to be ran-to-completion
    
        return Awaited(x, y, z);
    }
    
  3. if possible, prefer IsCompletedSuccessfully to Status == TaskStatus.RanToCompletion; this now exists in .NET Core for Task, and everywhere for ValueTask<T>

java.lang.Exception: No runnable methods exception in running JUnits

in my case i just disabled //@RunWith(SpringRunner.class)

and there is no exception

jQuery add class .active on menu

I am guessing you are trying to mix Asp code and JS code and at some point it's breaking or not excusing the binding calls correctly.

Perhaps you can try using a delegate instead. It will cut out the complexity of when to bind the click event.

An example would be:

$('body').delegate('.menu li','click',function(){
   var $li = $(this);

   var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;

   if(shouldAddClass){
       $li.addClass('active');
   }
});

See if that helps, it uses the Attribute Starts With Selector from jQuery.

Chi

Add php variable inside echo statement as href link address?

You can use one and more echo statement inside href

<a href="profile.php?usr=<?php echo $_SESSION['firstname']."&email=". $_SESSION['email']; ?> ">Link</a>

link : "/profile.php?usr=firstname&email=email"

What does a lazy val do?

scala> lazy val lazyEight = {
     |   println("I am lazy !")
     |   8
     | }
lazyEight: Int = <lazy>

scala> lazyEight
I am lazy !
res1: Int = 8
  • All vals are initialized during object construction
  • Use lazy keyword to defer initialization until first usage
  • Attention: Lazy vals are not final and therefore might show performance drawbacks

Does Java have an exponential operator?

you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)

System.out.println(Math.pow(2, 3));

Copy map values to vector in STL

#include <algorithm> // std::transform
#include <iterator>  // std::back_inserter
std::transform( 
    your_map.begin(), 
    your_map.end(),
    std::back_inserter(your_values_vector),
    [](auto &kv){ return kv.second;} 
);

Sorry that I didn't add any explanation - I thought that code is so simple that is doesn't require any explanation. So:

transform( beginInputRange, endInputRange, outputIterator, unaryOperation)

this function calls unaryOperation on every item from inputIterator range (beginInputRange-endInputRange). The value of operation is stored into outputIterator.

If we want to operate through whole map - we use map.begin() and map.end() as our input range. We want to store our map values into vector - so we have to use back_inserter on our vector: back_inserter(your_values_vector). The back_inserter is special outputIterator that pushes new elements at the end of given (as paremeter) collection. The last parameter is unaryOperation - it takes only one parameter - inputIterator's value. So we can use lambda: [](auto &kv) { [...] }, where &kv is just a reference to map item's pair. So if we want to return only values of map's items we can simply return kv.second:

[](auto &kv) { return kv.second; }

I think this explains any doubts.

Failed to start mongod.service: Unit mongod.service not found

For those that run into this and end up on this answer, as I did, where they got this error during uninstall orupgrade and Ubuntu keeps failing to uninstall the previous because the service doesn't exist this one line will get you past that and allow the uninstall or upgrade to continue.

sudo touch /lib/systemd/system/mongod.service

How to create nested directories using Mkdir in Golang?

This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

package main

import (
    "fmt"
    "os"
)

func main()  {
    if err := ensureDir("/test-dir"); err != nil {
        fmt.Println("Directory creation failed with error: " + err.Error())
        os.Exit(1)
    }
    // Proceed forward
}

func ensureDir(dirName string) error {

    err := os.MkdirAll(dirName, os.ModeDir)

    if err == nil || os.IsExist(err) {
        return nil
    } else {
        return err
    }
}

Javascript close alert box

Appears you can somewhat accomplish something similar with the Notification API. You can't control how long it stays visible (probably an OS preference of some kind--unless you specify requireInteraction true, then it stays up forever or until dismissed or until you close it), and it requires the user to click "allow notifications" (unfortunately) first, but here it is:

If you want it to close after 1s (all OS's leave it open 1s at least):

var notification = new Notification("Hi there!", {body: "some text"});
setTimeout(function() {notification.close()}, 1000);

If you wanted to show it longer than the "default" you could bind to the onclose callback and show another repeat notification I suppose, to replace it.

Ref: inspired by this answer, though that answer doesn't work in modern Chrome anymore, but the Notification API does.

Express: How to pass app-instance to routes from a different file?

If you want to pass an app-instance to others in Node-Typescript :

Option 1: With the help of import (when importing)

//routes.ts
import { Application } from "express";
import { categoryRoute } from './routes/admin/category.route'
import { courseRoute } from './routes/admin/course.route';

const routing = (app: Application) => {
    app.use('/api/admin/category', categoryRoute)
    app.use('/api/admin/course', courseRoute)
}
export { routing }

Then import it and pass app:

import express, { Application } from 'express';

const app: Application = express();
import('./routes').then(m => m.routing(app))

Option 2: With the help of class

// index.ts
import express, { Application } from 'express';
import { Routes } from './routes';


const app: Application = express();
const rotues = new Routes(app)
...

Here we will access the app in the constructor of Routes Class

// routes.ts
import { Application } from 'express'
import { categoryRoute } from '../routes/admin/category.route'
import { courseRoute } from '../routes/admin/course.route';

class Routes {
    constructor(private app: Application) {
        this.apply();
    }

    private apply(): void {
       this.app.use('/api/admin/category', categoryRoute)
       this.app.use('/api/admin/course', courseRoute)
    }
}

export { Routes }

How do I use the new computeIfAbsent function?

Recently I was playing with this method too. I wrote a memoized algorithm to calcualte Fibonacci numbers which could serve as another illustration on how to use the method.

We can start by defining a map and putting the values in it for the base cases, namely, fibonnaci(0) and fibonacci(1):

private static Map<Integer,Long> memo = new HashMap<>();
static {
   memo.put(0,0L); //fibonacci(0)
   memo.put(1,1L); //fibonacci(1)
}

And for the inductive step all we have to do is redefine our Fibonacci function as follows:

public static long fibonacci(int x) {
   return memo.computeIfAbsent(x, n -> fibonacci(n-2) + fibonacci(n-1));
}

As you can see, the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map. This represents a significant improvement over the traditional, tree recursive algorithm.

Remove empty array elements

I had to do this in order to keep an array value of (string) 0

$url = array_filter($data, function ($value) {
  return (!empty($value) || $value === 0 || $value==='0');
});

AngularJS event on window innerWidth size change

If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout to not update the attribute until it has been unchanged for 500ms.

var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
    var newWidth = window.innerWidth,
        updateStuffTimer;

    if (newWidth !== oldWidth) {
        $timeout.cancel(updateStuffTimer);
    }

    updateStuffTimer = $timeout(function() {
         updateStuff(newWidth); // Update the attribute based on window.innerWidth
    }, 500);
});

$scope.$on('$destroy',function (){
    $(window).off('resize.doResize'); // remove the handler added earlier
});

Reference: https://gist.github.com/tommaitland/7579618

Apache and IIS side by side (both listening to port 80) on windows2003

You will need to use different IP addresses. The server, whether Apache or IIS, grabs the traffic based on the IP and Port, which ever they are bound to listen to. Once it starts listening, then it uses the headers, such as the server name to filter and determine what site is being accessed. You can't do it will simply changing the server name in the request

Basic HTTP authentication with Node and Express 4

function auth (req, res, next) {
  console.log(req.headers);
  var authHeader = req.headers.authorization;
  if (!authHeader) {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');
      err.status = 401;
      next(err);
      return;
  }
  var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
  var user = auth[0];
  var pass = auth[1];
  if (user == 'admin' && pass == 'password') {
      next(); // authorized
  } else {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');      
      err.status = 401;
      next(err);
  }
}
app.use(auth);

Multiple lines of input in <input type="text" />

Use <div contenteditable="true"> (supported well) with storing to <input type="hidden">.

HTML:

<div id="multilineinput" contenteditable="true"></div>
<input type="hidden" id="detailsfield" name="detailsfield">

js (using jQuery)

$("#multilineinput").on('keyup',function(e) {   
    $("#detailsfield").val($(this).text()); //store content to input[type=hidden]
});
//optional - one line but wrap it
$("#multilineinput").on('keypress',function(e) {    
    if(e.which == 13) { //on enter
        e.preventDefault(); //disallow newlines     
        // here comes your code to submit
    }
});

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

How to find where gem files are installed

You can check it from your command prompt by running gem help commands and then selecting the proper command:

kirti@kirti-Aspire-5733Z:~$  gem help commands
GEM commands are:

    build                  Build a gem from a gemspec
    cert                   Manage RubyGems certificates and signing settings
    check                  Check a gem repository for added or missing files
    cleanup                Clean up old versions of installed gems in the local
                           repository
    contents               Display the contents of the installed gems
    dependency             Show the dependencies of an installed gem
    environment            Display information about the RubyGems environment
    fetch                  Download a gem and place it in the current directory
    generate_index         Generates the index files for a gem server directory
    help                   Provide help on the 'gem' command
    install                Install a gem into the local repository
    list                   Display gems whose name starts with STRING
    lock                   Generate a lockdown list of gems
    mirror                 Mirror all gem files (requires rubygems-mirror)
    outdated               Display all gems that need updates
    owner                  Manage gem owners on RubyGems.org.
    pristine               Restores installed gems to pristine condition from
                           files located in the gem cache
    push                   Push a gem up to RubyGems.org
    query                  Query gem information in local or remote repositories
    rdoc                   Generates RDoc for pre-installed gems
    regenerate_binstubs    Re run generation of executable wrappers for gems.
    search                 Display all gems whose name contains STRING
    server                 Documentation and gem repository HTTP server
    sources                Manage the sources and cache file RubyGems uses to
                           search for gems
    specification          Display gem specification (in yaml)
    stale                  List gems along with access times
    uninstall              Uninstall gems from the local repository
    unpack                 Unpack an installed gem to the current directory
    update                 Update installed gems to the latest version
    which                  Find the location of a library file you can require
    yank                   Remove a specific gem version release from
                           RubyGems.org

For help on a particular command, use 'gem help COMMAND'.

Commands may be abbreviated, so long as they are unambiguous.
e.g. 'gem i rake' is short for 'gem install rake'.
kirti@kirti-Aspire-5733Z:~$ 

Now from the above I can see the command environment is helpful. So I would do:

kirti@kirti-Aspire-5733Z:~$ gem help environment
Usage: gem environment [arg] [options]


  Common Options:
    -h, --help                       Get help on this command
    -V, --[no-]verbose               Set the verbose level of output
    -q, --quiet                      Silence commands
        --config-file FILE           Use this config file instead of default
        --backtrace                  Show stack backtrace on errors
        --debug                      Turn on Ruby debugging


  Arguments:
    packageversion  display the package version
    gemdir          display the path where gems are installed
    gempath         display path used to search for gems
    version         display the gem format version
    remotesources   display the remote gem servers
    platform        display the supported gem platforms
    <omitted>       display everything

  Summary:
    Display information about the RubyGems environment

  Description:
    The RubyGems environment can be controlled through command line arguments,
    gemrc files, environment variables and built-in defaults.

    Command line argument defaults and some RubyGems defaults can be set in a
    ~/.gemrc file for individual users and a /etc/gemrc for all users. These
    files are YAML files with the following YAML keys:

      :sources: A YAML array of remote gem repositories to install gems from
      :verbose: Verbosity of the gem command. false, true, and :really are the
                levels
      :update_sources: Enable/disable automatic updating of repository metadata
      :backtrace: Print backtrace when RubyGems encounters an error
      :gempath: The paths in which to look for gems
      :disable_default_gem_server: Force specification of gem server host on
    push
      <gem_command>: A string containing arguments for the specified gem command

    Example:

      :verbose: false
      install: --no-wrappers
      update: --no-wrappers
      :disable_default_gem_server: true

    RubyGems' default local repository can be overridden with the GEM_PATH and
    GEM_HOME environment variables. GEM_HOME sets the default repository to
    install into. GEM_PATH allows multiple local repositories to be searched for
    gems.

    If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
    HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
    proxy server.

    If you would like to push gems to a private gem server the RUBYGEMS_HOST
    environment variable can be set to the URI for that server.

    If you are packaging RubyGems all of RubyGems' defaults are in
    lib/rubygems/defaults.rb.  You may override these in
    lib/rubygems/defaults/operating_system.rb
kirti@kirti-Aspire-5733Z:~$ 

Finally to show you what you asked, I would do:

kirti@kirti-Aspire-5733Z:~$ gem environment gemdir
/home/kirti/.rvm/gems/ruby-2.0.0-p0
kirti@kirti-Aspire-5733Z:~$ gem environment gempath
/home/kirti/.rvm/gems/ruby-2.0.0-p0:/home/kirti/.rvm/gems/ruby-2.0.0-p0@global
kirti@kirti-Aspire-5733Z:~$ 

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

What is the LDF file in SQL Server?

LDF holds the transaction log. If you set your backups correctly - it will be small. It it grows - you have a very common problem of setting database recovery mode to FULL and then forgetting to backup the transaction log (LDF file). Let me explain how to fix it.

  1. If your business can afford to lose a little data between backups, just set the database recovery mode to SIMPLE, then forget about LDF - it will be small. This is the recommended solution for most of the cases.
  2. If you have to be able to restore to the exact point in time - use FULL recovery mode. In this case you have to take regular Transaction Log backups. The simplest way to do it is to use a tool like SqlBackupAndFTP (disclosure - I am a developer). The log file will be truncated at this time and would not grow beyond certain limits.

Some would suggest to use SHRINKFILE to trim you log. Note that this is OK only as an exception. If you do it regularly, it defeats the purpose of FULL recovery model: first you go into trouble of saving every single change in the log, then you just dump it. Set recovery mode to SIMPLE instead.

Constructors in Go

There are no default constructors in Go, but you can declare methods for any type. You could make it a habit to declare a method called "Init". Not sure if how this relates to best practices, but it helps keep names short without loosing clarity.

package main

import "fmt"

type Thing struct {
    Name string
    Num int
}

func (t *Thing) Init(name string, num int) {
    t.Name = name
    t.Num = num
}

func main() {
    t := new(Thing)
    t.Init("Hello", 5)
    fmt.Printf("%s: %d\n", t.Name, t.Num)
}

The result is:

Hello: 5

Open new Terminal Tab from command line (Mac OS X)

when you are in a terminal window, command + n => opens a new terminal and command + t => opens a new tab in current terminal window

Is there a way to force npm to generate package-lock.json?

As several answer explained the you should run:

npm i

BUT if it does not solve...

Check the version of your npm executable. (For me it was 3.x.x which doesn't uses the package-lock.json (at all))

npm -v

It should be at least 5.x.x (which introduced the package-lock.json file.)

To update npm on Linux, follow these instructions.

For more details about package files, please read this medium story.

create array from mysql query php

THE CORRECT WAY ************************ THE CORRECT WAY

while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows);  // pop the last row off, which is an empty row

Getting output of system() calls in Ruby

Another way is:

f = open("|ls")
foo = f.read()

Note that's the "pipe" character before "ls" in open. This can also be used to feed data into the programs standard input as well as reading its standard output.

jQuery count number of divs with a certain class?

For better performance you should use:

var numItems = $('div.item').length;

Since it will only look for the div elements in DOM and will be quick.

Suggestion: using size() instead of length property means one extra step in the processing since SIZE() uses length property in the function definition and returns the result.

Adding rows dynamically with jQuery

This will get you close, the add button has been removed out of the table so you might want to consider this...

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
          $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
          return false;
        });
    });
</script>

HTML markup looks like this

  <a  id="add">+</a></td>
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    </tbody>
  </table>

EDIT To empty a value of a textbox after insert..

    $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
    $('#mytable tbody>tr:last #name').val('');
    return false;

EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this

$("#mytable tbody>tr:last").each(function() {this.reset();});           

I will leave the rest to you!

The character encoding of the HTML document was not declared

You have to change the file from .html to .php.

and add this following line

header('Content-Type: text/html; charset=utf-8');

Generate a sequence of numbers in Python

using numpy and list comprehension you can do the

import numpy as np
[num for num in np.arange(1,101) if (num%4 == 1 or num%4 == 2)]

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

There is a single quote in $submitsubject or $submit_message

Why is this a problem?

The single quote char terminates the string in MySQL and everything past that is treated as a sql command. You REALLY don't want to write your sql like that. At best, your application will break intermittently (as you're observing) and at worst, you have just introduced a huge security vulnerability.

Imagine if someone submitted '); DROP TABLE private_messages; in submit message.

Your SQL Command would be:

INSERT INTO private_messages (to_id, from_id, time_sent, subject, message) 
        VALUES('sender_id', 'id', now(),'subjet','');

DROP TABLE private_messages;

Instead you need to properly sanitize your values.

AT A MINIMUM you must run each value through mysql_real_escape_string() but you should really be using prepared statements.

If you were using mysql_real_escape_string() your code would look like this:

if($_POST['submit_message']){

if($_POST['form_subject']==""){
    $submit_subject="(no subject)";
}else{
    $submit_subject=mysql_real_escape_string($_POST['form_subject']); 
}
$submit_message=mysql_real_escape_string($_POST['form_message']);
$sender_id = mysql_real_escape_string($_POST['sender_id']);

Here is a great article on prepared statements and PDO.

How to pass data from Javascript to PHP and vice versa?

I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.

How do I restore a dump file from mysqldump?

If you want to view the progress of the dump try this:

pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME

You'll of course need 'pv' installed. This command works only on *nix.

What's the point of the X-Requested-With header?

Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.

Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.

Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html

Container is running beyond memory limits

I can't comment on the accepted answer, due to low reputation. However, I would like to add, this behavior is by design. The NodeManager is killing your container. It sounds like you are trying to use hadoop streaming which is running as a child process of the map-reduce task. The NodeManager monitors the entire process tree of the task and if it eats up more memory than the maximum set in mapreduce.map.memory.mb or mapreduce.reduce.memory.mb respectively, we would expect the Nodemanager to kill the task, otherwise your task is stealing memory belonging to other containers, which you don't want.

android pinch zoom

Updated Answer

Code can be found here : official-doc

Answer Outdated

Check out the following links which may help you

Best examples are provided in the below links, which you can refactor to meet your requirements.

  1. implementing-the-pinch-zoom-gestur

  2. Android-pinch

  3. GestureDetector.SimpleOnGestureListener

Connect to SQL Server database from Node.js

//start the program
var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'datapullman',
        password: 'system',
        server: 'localhost', 
        database: 'chat6' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records

        request.query("select * From emp", function (err, recordset) {            
            if  (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

//create a table as emp in a database (i have created as chat6)

// programs ends here

//save it as app.js and run as node app.js //open in you browser as localhost:5000

Order by multiple columns with Doctrine

The orderBy method requires either two strings or an Expr\OrderBy object. If you want to add multiple order declarations, the correct thing is to use addOrderBy method, or instantiate an OrderBy object and populate it accordingly:

   # Inside a Repository method:
   $myResults = $this->createQueryBuilder('a')
       ->addOrderBy('a.column1', 'ASC')
       ->addOrderBy('a.column2', 'ASC')
       ->addOrderBy('a.column3', 'DESC')
   ;

   # Or, using a OrderBy object:
   $orderBy = new OrderBy('a.column1', 'ASC');
   $orderBy->add('a.column2', 'ASC');
   $orderBy->add('a.column3', 'DESC');

   $myResults = $this->createQueryBuilder('a')
       ->orderBy($orderBy)
   ;

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Instead of mocking concrete class you should mock that class interface. Extract interface from XmlCupboardAccess class

public interface IXmlCupboardAccess
{
    bool IsDataEntityInXmlCupboard(string dataId, out string nameInCupboard, out string refTypeInCupboard, string nameTemplate = null);
}

And instead of

private Mock<XmlCupboardAccess> _xmlCupboardAccess = new Mock<XmlCupboardAccess>();

change to

private Mock<IXmlCupboardAccess> _xmlCupboardAccess = new Mock<IXmlCupboardAccess>();

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

Use the createFromFormat method:

$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);

UPDATE

I now recommend the use of Carbon

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

Error converting data types when importing from Excel to SQL Server 2008

SSIS doesn't implicitly convert data types, so you need to do it explicitly. The Excel connection manager can only handle a few data types and it tries to make a best guess based on the first few rows of the file. This is fully documented in the SSIS documentation.

You have several options:

  • Change your destination data type to float
  • Load to a 'staging' table with data type float using the Import Wizard and then INSERT into the real destination table using CAST or CONVERT to convert the data
  • Create an SSIS package and use the Data Conversion transformation to convert the data

You might also want to note the comments in the Import Wizard documentation about data type mappings.

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

if you want to use parentheses in laravel 4 and don't forget return
In Laravel 4 (at least) you need to use $a, $b in parentheses as in the example

$a = 1;
$b = 1;
$c = 1;
$d = 1;
Model::where(function ($query) use ($a, $b) {
    return $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    return $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});

This is my result: enter image description here

Java swing application, close one window and open another when button is clicked

Use this.dispose for current window to close and next_window.setVisible(true) to show next window behind button property ActionPerformed , Example is shown below in pic for your help.

enter image description here

Different names of JSON property during serialization and deserialization

This was not what I was expecting as a solution (though it is a legitimate use case). My requirement was to allow an existing buggy client (a mobile app which already released) to use alternate names.

The solution lies in providing a separate setter method like this:

@JsonSetter( "r" )
public void alternateSetRed( byte red ) {
    this.red = red;
}

Text in HTML Field to disappear when clicked?

To accomplish that, you can use the two events onfocus and onblur:

<input type="text" name="theName" value="DefaultValue"
  onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
  onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
  style="color:#BBB;" />

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

How to run an application as "run as administrator" from the command prompt?

See this TechNet article: Runas command documentation

From a command prompt:

C:\> runas /user:<localmachinename>\administrator cmd

Or, if you're connected to a domain:

C:\> runas /user:<DomainName>\<AdministratorAccountName> cmd

How to call javascript from a href?

Using JQuery would be good;

<a href="#" id="youLink">Call JavaScript </a>



$("#yourLink").click(function(e){
//do what ever you want...
});

How to use Google App Engine with my own naked domain (not subdomain)?

Just managed to sort this finally after hours. The www subdomain was pointing to Sites, but the front end wasn't showing me that.

After taking the plunge and setting the CNAME to gwh.google.com, and enabling / disabling Sites a couple of times (see the comment from Rodrigo Moraes on http://groups.google.com/group/google-appengine/web/deleting-existing-www-mapping-from-google-apps) I was able to set the Sites address to use the www subdomain.

I was then able to change it away from using the www subdomain, at which point the appengine app allowed me to specify the www subdomain.

That is one dirty fix - basically turning on and off Sites until it works!

jquery - Check for file extension before uploading

        function yourfunctionName() {
            var yourFileName = $("#yourinputfieldis").val();

            var yourFileExtension = yourFileName .replace(/^.*\./, '');
            switch (yourFileExtension ) {
                case 'pdf':
                case 'jpg':
                case 'doc':
                    $("#formId").submit();// your condition what you want to do
                    break;
                default:
                    alert('your File extension is wrong.');
                    this.value = '';
            }    
        }

What is the difference between an interface and abstract class?

In an interface all methods must be only definitions, not single one should be implemented.

But in an abstract class there must an abstract method with only definition, but other methods can be also in the abstract class with implementation...

how to change onclick event with jquery?

$('#id').attr('onclick', 'function()');

Right now (11 Jul 2015) this solution is still working (jquery 2.1.4); in my opinion, it is the best one to pick up.

Adding three months to a date in PHP

You need to convert the date into a readable value. You may use strftime() or date().

Try this:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
$effectiveDate = strftime ( '%Y-%m-%d' , $effectiveDate );
echo $effectiveDate;

This should work. I like using strftime better as it can be used for localization you might want to try it.

git ahead/behind info between master and branch?

With Git 2.5+, you now have another option to see ahead/behind for all branches which are configured to push to a branch.

git for-each-ref --format="%(push:track)" refs/heads

See more at "Viewing Unpushed Git Commits"

Java sending and receiving file (byte[]) over sockets

Adding up on EJP's answer; use this for more fluidity. Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:

int count;
byte[] bytes = new byte[4096];
try {
    while ((count = is.read(bytes)) > 0) {
        System.out.println(count);
        bos.write(bytes, 0, count);
    }
} catch ( Exception e )
{
    //It will land here....
}
// Then continue from here

EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!

Hope this post solves any of your issues

css3 text-shadow in IE9

Try CSS Generator.

You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:

text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);

How to Customize the time format for Python logging?

if using logging.config.fileConfig with a configuration file use something like:

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

A simple solution:

original = [1,2,3]
cloned = original.map(x=>x)

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

How to cache data in a MVC application

Extending @Hrvoje Hudo's answer...

Code:

using System;
using System.Runtime.Caching;

public class InMemoryCache : ICacheService
{
    public TValue Get<TValue>(string cacheKey, int durationInMinutes, Func<TValue> getItemCallback) where TValue : class
    {
        TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
        }
        return item;
    }

    public TValue Get<TValue, TId>(string cacheKeyFormat, TId id, int durationInMinutes, Func<TId, TValue> getItemCallback) where TValue : class
    {
        string cacheKey = string.Format(cacheKeyFormat, id);
        TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
        if (item == null)
        {
            item = getItemCallback(id);
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
        }
        return item;
    }
}

interface ICacheService
{
    TValue Get<TValue>(string cacheKey, Func<TValue> getItemCallback) where TValue : class;
    TValue Get<TValue, TId>(string cacheKeyFormat, TId id, Func<TId, TValue> getItemCallback) where TValue : class;
}

Examples

Single item caching (when each item is cached based on its ID because caching the entire catalog for the item type would be too intensive).

Product product = cache.Get("product_{0}", productId, 10, productData.getProductById);

Caching all of something

IEnumerable<Categories> categories = cache.Get("categories", 20, categoryData.getCategories);

Why TId

The second helper is especially nice because most data keys are not composite. Additional methods could be added if you use composite keys often. In this way you avoid doing all sorts of string concatenation or string.Formats to get the key to pass to the cache helper. It also makes passing the data access method easier because you don't have to pass the ID into the wrapper method... the whole thing becomes very terse and consistant for the majority of use cases.

How to read AppSettings values from a .json file in ASP.NET Core

With .NET Core 2.2, and in the simplest way possible...

public IActionResult Index([FromServices] IConfiguration config)
{
    var myValue = config.GetValue<string>("MyKey");
}

appsettings.json is automatically loaded and available through either constructor or action injection, and there's a GetSection method on IConfiguration as well. There isn't any need to alter Startup.cs or Program.cs if all you need is appsettings.json.

Get second child using jQuery

It's surprising to see that nobody mentioned the native JS way to do this..

Without jQuery:

Just access the children property of the parent element. It will return a live HTMLCollection of children elements which can be accessed by an index. If you want to get the second child:

parentElement.children[1];

In your case, something like this could work: (example)

var secondChild = document.querySelector('.parent').children[1];

console.log(secondChild); // <td>element two</td>
<table>
    <tr class="parent">
        <td>element one</td>
        <td>element two</td>
    </tr>
</table>

You can also use a combination of CSS3 selectors / querySelector() and utilize :nth-of-type(). This method may work better in some cases, because you can also specifiy the element type, in this case td:nth-of-type(2) (example)

var secondChild = document.querySelector('.parent > td:nth-of-type(2)');

console.log(secondChild); // <td>element two</td>

Filter Extensions in HTML form upload

The accept attribute specifies a comma-separated list of content types (MIME types) that the target of the form will process correctly. Unfortunately this attribute is ignored by all the major browsers, so it does not affect the browser's file dialog in any way.

How to list active / open connections in Oracle?

select
  username,
  osuser,
  terminal,
  utl_inaddr.get_host_address(terminal) IP_ADDRESS
from
  v$session
where
  username is not null
order by
  username,
  osuser;

Scrolling a div with jQuery

jCarousel is a Jquery Plugin , it have same functionality already implemented , which might want to archive. it's nice and easy. here is the link

and complete documentation can be found here

how to implement a long click listener on a listview

I think this above code will work on LongClicking the listview, not the individual items.

why not use registerForContextMenu(listView). and then get the callback in OnCreateContextMenu.

For most use cases this will work same.

Jquery show/hide table rows

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
  <tr class="black">
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
  </tr>
</thead>
<tbody>
  <tr id="white">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
  <tr class="black" style="background-color:black;">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
   $("#black_only").click(function(){
    $("#white").hide();
    $(".black").show();

   });
   $("#white_only").click(function(){
    $(".black").hide();
    $("#white").show();

   });
   $("#all").click(function(){
    $("#white").show();
    $(".black").show();

   });

});
</script>

Databound drop down list - initial value

I know this already has a chosen answer - but I wanted to toss in my two cents. I have a databound dropdown list:

<asp:DropDownList 
  id="country" 
  runat="server" 
  CssClass="selectOne" 
  DataSourceID="country_code" 
  DataTextField="Name" 
  DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource 
  id="country_code" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
  SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>

In the codebehind, I have this - (which selects United States by default):

if (this.IsPostBack)
{
  //handle posted data
}
else 
{
  country.SelectedValue = "US";
}

The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)

How to put a UserControl into Visual Studio toolBox

Recompiling did the trick for me!

How to find the mysql data directory from command line in windows

You can try this-

mysql> select @@datadir;

PS- It works on every platform.

How do you detect Credit card type based on number?

The first numbers of the credit card can be used to approximate the vendor:

  • Visa: 49,44 or 47
  • Visa electron: 42, 45, 48, 49
  • MasterCard: 51
  • Amex:34
  • Diners: 30, 36, 38
  • JCB: 35

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Just make sure you've downloaded Binary zip archive(apache-maven-3.5.0-bin.zip) instead of Source zip archive. Then add the bin directory of the created directory apache-maven-3.5.0 to the PATH environment variable.

How to decrypt Hash Password in Laravel

Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).

The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.

Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).

For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.

How can I convert a .py to .exe for Python?

Steps to convert .py to .exe in Python 3.6

  1. Install Python 3.6.
  2. Install cx_Freeze, (open your command prompt and type pip install cx_Freeze.
  3. Install idna, (open your command prompt and type pip install idna.
  4. Write a .py program named myfirstprog.py.
  5. Create a new python file named setup.py on the current directory of your script.
  6. In the setup.py file, copy the code below and save it.
  7. With shift pressed right click on the same directory, so you are able to open a command prompt window.
  8. In the prompt, type python setup.py build
  9. If your script is error free, then there will be no problem on creating application.
  10. Check the newly created folder build. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.

See the original script in my blog.

setup.py:

from cx_Freeze import setup, Executable

base = None    

executables = [Executable("myfirstprog.py", base=base)]

packages = ["idna"]
options = {
    'build_exe': {    
        'packages':packages,
    },    
}

setup(
    name = "<any name>",
    options = options,
    version = "<any number>",
    description = '<any description>',
    executables = executables
)

EDIT:

  • be sure that instead of myfirstprog.py you should put your .pyextension file name as created in step 4;
  • you should include each imported package in your .py into packages list (ex: packages = ["idna", "os","sys"])
  • any name, any number, any description in setup.py file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = '' )
  • the imported packages must be installed before you start step 8.

What should every programmer know about security?

Also be sure to check out the OWASP Top 10 List for a categorization of all the main attack vectors/vulnerabilities.

These things are fascinating to read about. Learning to think like an attacker will train you of what to think about as you're writing your own code.

Remove xticks in a matplotlib plot?

There is a better, and simpler, solution than the one given by John Vinyard. Use NullLocator:

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.show()
plt.savefig('plot')

Hope that helps.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Loading existing .html file with android WebView

paste your .html file in assets folder of your project folder. and create an xml file in layout folder with the fol code: my.xml:

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/webview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
    />

add fol code in activity

setContentView(R.layout.my);
    WebView mWebView = null;
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl("file:///android_asset/new.html"); //new.html is html file name.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.

Java: How to read a text file

Use Apache Commons (IO and Lang) for simple/common things like this.

Imports:

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;

Code:

String contents = FileUtils.readFileToString(new File("path/to/your/file.txt"));
String[] array = ArrayUtils.toArray(contents.split(" "));

Done.

Generating a random hex color code with PHP

$color = sprintf("#%06x",rand(0,16777215));

How to Display Selected Item in Bootstrap Button Dropdown Title

I was able to slightly improve Jai's answer to work in the case of you having more than one button dropdown with a pretty good presentation that works with bootstrap 3:

Code for The Button

<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Option: <span class="selection">Option 1</span><span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">Option 1</a></li>
    <li><a href="#">Option 2</a></li>
    <li><a href="#">Option 3</a></li>
  </ul>
</div>

JQuery Snippet

$(".dropdown-menu li a").click(function(){

  $(this).parents(".btn-group").find('.selection').text($(this).text());
  $(this).parents(".btn-group").find('.selection').val($(this).text());

});

I also added a 5px margin-right to the "selection" class.

Fiddler not capturing traffic from browsers

For me i tried everything on here and eventually it boiled down to a corporate proxy that kept on resetting the INET Settings.

I worked my way down the list of suggestions but in the end turned out to be the proxy settings. I had hunch about it but i wanted to be thorogh about it before going to 'IT' and saying can i have local bindows proxy settings override please?

I asked for the proxy management software to be removed and then within a second fiddler started working. If you cannot override the proxy settings in Internet Properties then fiddler will never work.

Bootstrap 3 - set height of modal window according to screen size

I assume you want to make modal use as much screen space as possible on phones. I've made a plugin to fix this UX problem of Bootstrap modals on mobile phones, you can check it out here - https://github.com/keaukraine/bootstrap-fs-modal

All you will need to do is to apply modal-fullscreen class and it will act similar to native screens of iOS/Android.

How to Git stash pop specific stash in 1.8.3?

I have 2.22 installed and this worked..

git stash pop --index 1

Div table-cell vertical align not working

This is how I do it:

CSS:

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}
#content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

HTML:

<div id="content">
    Content goes here
</div>

See

Example of vertical centering

and

CSS: centering things.

How do I print debug messages in the Google Chrome JavaScript Console?

In addition to Delan Azabani's answer, I like to share my console.js, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log function, but no console.debug:

// Create a noop console object if the browser doesn't provide one...
if (!window.console){
  window.console = {};
}

// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
  if (!window.console.debug && typeof window.console.log !== 'undefined') {
    window.console.debug = window.console.log;
  }
}

// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

for (var i = 0; i < names.length; ++i){
  if(!window.console[names[i]]){
    window.console[names[i]] = function() {};
  }
}

How to subtract date/time in JavaScript?

Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:

subtractDates: function(date1, date2) {
    return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
    return moment().subtract(dateSince).milliseconds();
},

Why would an Enum implement an Interface?

When creating constants in a jar file, it is often helpful to let users extend enum values. We used enums for PropertyFile keys and got stuck because nobody could add any new ones! Below would have worked much better.

Given:

public interface Color {
  String fetchName();
}

and:

public class MarkTest {

  public static void main(String[] args) {
    MarkTest.showColor(Colors.BLUE);
    MarkTest.showColor(MyColors.BROWN);
  }

  private static void showColor(Color c) {
    System.out.println(c.fetchName());
  }
}

one could have one enum in the jar:

public enum Colors implements Color {
  BLUE, RED, GREEN;
  @Override
  public String fetchName() {
    return this.name();
  }
}

and a user could extend it to add his own colors:

public enum MyColors implements Color {
  BROWN, GREEN, YELLOW;
  @Override
  public String fetchName() {
    return this.name();
  }
}

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I had the same error. Resizing the images resolved the issue. However, I used online tools to resize the images because using pillow to resize them did not solve my problem.

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

How do I detect "shift+enter" and generate a new line in Textarea?

Another Solution for detecting Shift+Enter Key with Angular2+

Inside Component.html

<input type="text" (keydown.shift.enter)="newLine($event)">

Inside Component.ts

newLine(event){
      if(event.keyCode==13 && event.shiftKey){
        alert('Shift+Enter key Pressed');
      }
  }

Reading large text files with streams in C#

If you read the performance and benchmark stats on this website, you'll see that the fastest way to read (because reading, writing, and processing are all different) a text file is the following snippet of code:

using (StreamReader sr = File.OpenText(fileName))
{
    string s = String.Empty;
    while ((s = sr.ReadLine()) != null)
    {
        //do your stuff here
    }
}

All up about 9 different methods were bench marked, but that one seem to come out ahead the majority of the time, even out performing the buffered reader as other readers have mentioned.

Factory Pattern. When to use factory methods?

They're also useful when you need several "constructors" with the same parameter type but with different behavior.

Label word wrapping

If you open the dropdown for the Text property in Visual Studio, you can use the enter key to split lines. This will obviously only work for static text unless you know the maximum dimensions of dynamic text.

Inserting a string into a list without getting split into characters

I suggest to add the '+' operator as follows:

list = list + ['foo']

Hope it helps!

Select unique or distinct values from a list in UNIX shell script

./script.sh | sort -u

This is the same as monoxide's answer, but a bit more concise.

jquery data selector

At the moment I'm selecting like this:

$('a[data-attribute=true]')

Which seems to work just fine, but it would be nice if jQuery was able to select by that attribute without the 'data-' prefix.

I haven't tested this with data added to elements via jQuery dynamically, so that could be the downfall of this method.

Change navbar text color Bootstrap

If you need to change the background colour of the navbar, you can do the following:

<nav class="navbar navbar-expand-lg navbar-light" style="background-color=#e3f2fd">

And to change the text:

<a class="nav-link" href="#" style="color:#ccc">

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

This Kotlin state machine library has PlantUML export feature, it is not integrated with Android Studio but it is easy to visualize state machine structure on PlantUML web site.

https://github.com/nsk90/kstatemachine

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

That’s probably everyone’s first thought. But it’s a little bit more difficult. See Chris Shiflett’s article SERVER_NAME Versus HTTP_HOST.

It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME.

So you either go with that or you check the host name against a white list:

$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}

Embed an External Page Without an Iframe?

You could load the external page with jquery:

<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script>
<div id="testLoad"></div>
//would this help

What is an HttpHandler in ASP.NET

An HttpHandler (or IHttpHandler) is basically anything that is responsible for serving content. An ASP.NET page (aspx) is a type of handler.

You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)

Change HTML email body font type and size in VBA

Set texts with different sizes and styles, and size and style for texts from cells ( with Range)

Sub EmailManuellAbsenden()

Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String

Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
.GetInspector.Display
 ghOldBody = .htmlBody

 ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
 "<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
 Range("B5") & "<br>" & _
 Range("B6") & "<br>" & _
 "<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
 Range("B5")
 .htmlBody = ghNewBody & ghOldBody

 End With

End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts

Get properties of a class

There is another answer here that also fits the authors request: 'compile-time' way to get all property names defined interface

If you use the plugin ts-transformer-keys and an Interface to your class you can get all the keys for the class.

But if you're using Angular or React then in some scenarios there is additional configuration necessary (webpack and typescript) to get it working: https://github.com/kimamula/ts-transformer-keys/issues/4

Oracle: Import CSV file

I would like to share 2 tips: (tip 1) create a csv file (tip 2) Load rows from a csv file into a table.

====[ (tip 1) SQLPLUS to create a csv file form an Oracle table ]====

I use SQLPLUS with the following commands:

set markup csv on
set lines 1000
set pagesize 100000 linesize 1000
set feedback off 
set trimspool on
spool /MyFolderAndFilename.csv
Select *  from MYschema.MYTABLE  where MyWhereConditions ;
spool off
exit

====[tip 2 SQLLDR to load a csv file into a table ]====

I use SQLLDR and a csv ( comma separated ) file to add (APPEND) rows form the csv file to a table. the file has , between fields text fields have " before and after the text CRITICAL: if last column is null there is a , at the end of the line

Example of data lines in the csv file:

11,"aa",1001
22,"bb',2002
33,"cc",
44,"dd",4004
55,"ee',

This is the control file:

LOAD DATA
APPEND 
INTO TABLE MYSCHEMA.MYTABLE
fields terminated by ',' optionally enclosed by '"'
TRAILING NULLCOLS
(
CoulmnName1,
CoulmnName2,
CoulmnName3
)

This is the command to execute sqlldr in Linux. If you run in Windows use \ instead of / c:

sqlldr userid=MyOracleUser/MyOraclePassword@MyOracleServerIPaddress:port/MyOracleSIDorService  DATA=datafile.csv  CONTROL=controlfile.ctl  LOG=logfile.log  BAD=notloadedrows.bad

Good luck !

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

Are PostgreSQL column names case-sensitive?

To quote the documentation:

Key words and unquoted identifiers are case insensitive. Therefore:

UPDATE MY_TABLE SET A = 5;

can equivalently be written as:

uPDaTE my_TabLE SeT a = 5;

You could also write it using quoted identifiers:

UPDATE "my_table" SET "a" = 5;

Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other.

If you want to write portable applications you are advised to always quote a particular name or never quote it.

#pragma once vs include guards?

I don't think it will make a significant difference in compile time but #pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent.

#pragma once is less prone to making mistakes and it is less code to type.

To speed up compile time more just forward declare instead of including in .h files when you can.

I prefer to use #pragma once.

See this wikipedia article about the possibility of using both.

Why can't I reference my class library?

If using TFS, performing a Get latest (recursive) doesn't always work. Instead, I force a get latest by clicking Source control => Get specific version then clicking both boxes. This tends to work.

enter image description here

If it still doesn't work then deleting the suo file (usually found in the same place as the solution) forces visual studio to get all the files from the source (and subsequently rebuild the suo file).

If that doesn't work then try closing all your open files and closing Visual studio. When you next open Visual studio it should be fixed. There is a resharper bug that is resolved this way.

How to convert string to XML using C#

xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>                    
                    </body></head>");

How to check if a symlink exists

How about using readlink?

# if symlink, readlink returns not empty string (the symlink target)
# if string is not empty, test exits w/ 0 (normal)
#
# if non symlink, readlink returns empty string
# if string is empty, test exits w/ 1 (error)
simlink? () {
  test "$(readlink "${1}")";
}

FILE=/usr/mda

if simlink? "${FILE}"; then
  echo $FILE is a symlink
else
  echo $FILE is not a symlink
fi

Drawing Circle with OpenGL

#include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define window_width  1080  
#define window_height 720 
void drawFilledSun(){
    //static float angle;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0, 0, -10);
    int i, x, y;
    double radius = 0.30;
    //glColor3ub(253, 184, 19);     
    glColor3ub(255, 0, 0);
    double twicePi = 2.0 * 3.142;
    x = 0, y = 0;
    glBegin(GL_TRIANGLE_FAN); //BEGIN CIRCLE
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= 20; i++)   {
        glVertex2f (
            (x + (radius * cos(i * twicePi / 20))), (y + (radius * sin(i * twicePi / 20)))
            );
    }
    glEnd(); //END
}
void DrawCircle(float cx, float cy, float r, int num_segments) {
    glBegin(GL_LINE_LOOP);
    for (int ii = 0; ii < num_segments; ii++)   {
        float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle 
        float x = r * cosf(theta);//calculate the x component 
        float y = r * sinf(theta);//calculate the y component 
        glVertex2f(x + cx, y + cy);//output vertex 
    }
    glEnd();
}
void main_loop_function() {
    int c;
    drawFilledSun();
    DrawCircle(0, 0, 0.7, 100);
    glutSwapBuffers();
    c = getchar();
}
void GL_Setup(int width, int height) {
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glEnable(GL_DEPTH_TEST);
    gluPerspective(45, (float)width / height, .1, 100);
    glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitWindowSize(window_width, window_height);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutCreateWindow("GLUT Example!!!");
    glutIdleFunc(main_loop_function);
    GL_Setup(window_width, window_height);
    glutMainLoop();
}

This is what I did. I hope this helps. Two types of circle are here. Filled and unfilled.

How to convert list data into json in java

i wrote my own function to return list of object for populate combo box :

public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
        try {
            Object[] args={};
            Class cl = Class.forName(kelas);
            Method getName = cl.getMethod(name, null);
            Method getLabel = cl.getMethod(label, null);
            String json="[";
            for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if(i>0){
                json+=",";
            }
            json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
            //System.out.println("Object = " + i+" -> "+o.getNumber());
            }
            json+="]";
            return json;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            System.out.println("Error in get JSON List");
            ex.printStackTrace();
        }
        return "";
    }

and call it from anywhere like :

String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();

This is probably a more "correct" way of getting it.

Is there an easy way to strike through text in an app widget?

try this code

textview.setText((Html.fromHtml("<strike>hello world!</strike>")));

AssertNull should be used or AssertNotNull

Use assertNotNull(obj). assert means must be.

how to open .mat file without using MATLAB?

You don't need to download any new software. You can use Octave Online to open .m files.

Disabling radio buttons with jQuery

I've refactored your code a bit, this should work:

jQuery("#loadActive").click(writeData);

function writeData() {
    jQuery("#chatTickets input:radio").attr('disabled',true);
}

If there are more than two radio buttons on your form, you'll have to modify the selector, for example, you can use the starts with attribute filter to pick out the radios whose ID starts with ticketID:

function writeData() {
    jQuery("#chatTickets input[id^=ticketID]:radio").attr('disabled',true);
}

How to round up with excel VBA round()?

I got a workaround myself:

    'G = Maximum amount of characters for width of comment cell
    G = 100
    'CommentX
    If THISWB.Sheets("Source").Cells(i, CommentColumn).Value = "" Then
        CommentX = ""
     Else
        CommentArray = Split(THISWB.Sheets("Source").Cells(i, CommentColumn).Value, Chr(10)) 'splits on alt + enter
        DeliverableComment = "Available"
    End If
                        If CommentX <> "" Then

                            'this loops for each newline in a cell (alt+enter in cell)
                            For CommentPart = 0 To UBound(CommentArray)
                            'format comment to max G characters long
                                LASTSPACE = 0
                                LASTSPACE2 = 0
                                    If Len(CommentArray(CommentPart)) > G Then

                                        'find last space in G length character string to make sure the line ends with a whole word and the new line starts with a whole word
                                        Do Until LASTSPACE2 >= Len(CommentArray(CommentPart))
                                            If CommentPart = 0 And LASTSPACE2 = 0 And LASTSPACE = 0 Then
                                                LASTSPACE = WorksheetFunction.Find("þ", WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "þ", (Len(Left(CommentArray(CommentPart), G)) - Len(WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "")))))
                                                ActiveCell.AddComment Left(CommentArray(CommentPart), LASTSPACE)
                                            Else
                                                If LASTSPACE2 = 0 Then
                                                   LASTSPACE = WorksheetFunction.Find("þ", WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "þ", (Len(Left(CommentArray(CommentPart), G)) - Len(WorksheetFunction.Substitute(Left(CommentArray(CommentPart), G), " ", "")))))
                                                   ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & Left(CommentArray(CommentPart), LASTSPACE)
                                                Else
                                                   If Len(Mid(CommentArray(CommentPart), LASTSPACE2)) < G Then
                                                       LASTSPACE = Len(Mid(CommentArray(CommentPart), LASTSPACE2))
                                                       ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & Mid(CommentArray(CommentPart), LASTSPACE2 - 1, LASTSPACE)
                                                   Else
                                                       LASTSPACE = WorksheetFunction.Find("þ", WorksheetFunction.Substitute(Mid(CommentArray(CommentPart), LASTSPACE2, G), " ", "þ", (Len(Mid(CommentArray(CommentPart), LASTSPACE2, G)) - Len(WorksheetFunction.Substitute(Mid(CommentArray(CommentPart), LASTSPACE2, G), " ", "")))))
                                                       ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & Mid(CommentArray(CommentPart), LASTSPACE2 - 1, LASTSPACE)
                                                   End If
                                                End If
                                            End If
                                            LASTSPACE2 = LASTSPACE + LASTSPACE2 + 1
                                        Loop
                                    Else
                                        If CommentPart = 0 And LASTSPACE2 = 0 And LASTSPACE = 0 Then
                                          ActiveCell.AddComment CommentArray(CommentPart)
                                        Else
                                          ActiveCell.Comment.Text Text:=ActiveCell.Comment.Text & vbNewLine & CommentArray(CommentPart)
                                        End If
                                    End If

                            Next CommentPart
                            ActiveCell.Comment.Shape.TextFrame.AutoSize = True

                        End If

Feel free to thank me. Works like a charm to me and the autosize function also works!

How to change maven logging level to display only warning and errors?

Go to simplelogger.properties in ${MAVEN_HOME}/conf/logging/ and set the following properties:

org.slf4j.simpleLogger.defaultLogLevel=warn
org.slf4j.simpleLogger.log.Sisu=warn
org.slf4j.simpleLogger.warnLevelString=warn

And beware: warn, not warning

Pointers in Python?

It's not a bug, it's a feature :-)

When you look at the '=' operator in Python, don't think in terms of assignment. You don't assign things, you bind them. = is a binding operator.

So in your code, you are giving the value 1 a name: a. Then, you are giving the value in 'a' a name: b. Then you are binding the value 2 to the name 'a'. The value bound to b doesn't change in this operation.

Coming from C-like languages, this can be confusing, but once you become accustomed to it, you find that it helps you to read and reason about your code more clearly: the value which has the name 'b' will not change unless you explicitly change it. And if you do an 'import this', you'll find that the Zen of Python states that Explicit is better than implicit.

Note as well that functional languages such as Haskell also use this paradigm, with great value in terms of robustness.

Java: how to convert HashMap<String, Object> to array

Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");

Object[][] twoDarray = new Object[map.size()][2];

Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();

for (int row = 0; row < twoDarray.length; row++) {
    twoDarray[row][0] = keys[row];
    twoDarray[row][1] = values[row];
}

// Print out the new 2D array
for (int i = 0; i < twoDarray.length; i++) {
    for (int j = 0; j < twoDarray[i].length; j++) {
        System.out.println(twoDarray[i][j]);
    }
}

How can I clear the content of a file?

Try using something like

File.Create

Creates or overwrites a file in the specified path.

How do you make a LinearLayout scrollable?

This can be done using the tag <ScrollView>. For ScrollView, one thing you have to remind that, ScrollView must have a single child.

If you want your full layout to be scrollable then add <ScrollView> at the top. Check the example given below.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout 
        android:id="@+id/container" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
            <!-- Content here -->
    </LinearLayout>

</ScrollView>

But if you want some part of your layout to be scrollable then add <ScrollView> within that part. Check the example given below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="400dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
                <!-- Content here -->
        </LinearLayout>

    </ScrollView>

</LinearLayout>

Java error - "invalid method declaration; return type required"

Every method (other than a constructor) must have a return type.

public double diameter(){...

oracle SQL how to remove time from date

If your column with DATE datatype has value like below : -

value in column : 10-NOV-2005 06:31:00

Then, You can Use TRUNC function in select query to convert your date-time value to only date like - DD/MM/YYYY or DD-MON-YYYY

select TRUNC(column_1) from table1;

result : 10-NOV-2005

You will see above result - Provided that NLS_DATE_FORMAT is set as like below :-

Alter session NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

What's the difference between git reset --mixed, --soft, and --hard?

When you modify a file in your repository, the change is initially unstaged. In order to commit it, you must stage it—that is, add it to the index—using git add. When you make a commit, the changes that are committed are those that have been added to the index.

git reset changes, at minimum, where the current branch (HEAD) is pointing. The difference between --mixed and --soft is whether or not your index is also modified. So, if we're on branch master with this series of commits:

- A - B - C (master)

HEADpoints to C and the index matches C.

When we run git reset --soft B, master (and thus HEAD) now points to B, but the index still has the changes from C; git status will show them as staged. So if we run git commit at this point, we'll get a new commit with the same changes as C.


Okay, so starting from here again:

- A - B - C (master)

Now let's do git reset --mixed B. (Note: --mixed is the default option). Once again, master and HEAD point to B, but this time the index is also modified to match B. If we run git commit at this point, nothing will happen since the index matches HEAD. We still have the changes in the working directory, but since they're not in the index, git status shows them as unstaged. To commit them, you would git add and then commit as usual.


And finally, --hard is the same as --mixed (it changes your HEAD and index), except that --hard also modifies your working directory. If we're at C and run git reset --hard B, then the changes added in C, as well as any uncommitted changes you have, will be removed, and the files in your working copy will match commit B. Since you can permanently lose changes this way, you should always run git status before doing a hard reset to make sure your working directory is clean or that you're okay with losing your uncommitted changes.


And finally, a visualization: enter image description here

How to wait until an element exists?

If you want it to stop looking after a while (timeout) then the following jQuery will work. It will time out after 10sec. I needed to use this code rather than pure JS because I needed to select an input via name and was having trouble implementing some of the other solutions.

 // Wait for element to exist.

    function imageLoaded(el, cb,time) {

        if ($(el).length) {
            // Element is now loaded.

            cb($(el));

            var imageInput =  $('input[name=product\\[image_location\\]]');
            console.log(imageInput);

        } else if(time < 10000) {
            // Repeat every 500ms.
            setTimeout(function() {
               time = time+500;

                imageLoaded(el, cb, time)
            }, 500);
        }
    };

    var time = 500;

    imageLoaded('input[name=product\\[image_location\\]]', function(el) {

     //do stuff here 

     },time);

List comprehension vs. lambda + filter

Filter is just that. It filters out the elements of a list. You can see the definition mentions the same(in the official docs link I mentioned before). Whereas, list comprehension is something that produces a new list after acting upon something on the previous list.(Both filter and list comprehension creates new list and not perform operation in place of the older list. A new list here is something like a list with, say, an entirely new data type. Like converting integers to string ,etc)

In your example, it is better to use filter than list comprehension, as per the definition. However, if you want, say other_attribute from the list elements, in your example is to be retrieved as a new list, then you can use list comprehension.

return [item.other_attribute for item in my_list if item.attribute==value]

This is how I actually remember about filter and list comprehension. Remove a few things within a list and keep the other elements intact, use filter. Use some logic on your own at the elements and create a watered down list suitable for some purpose, use list comprehension.

conversion from string to json object android

Remove the slashes:

String json = {"phonetype":"N95","cat":"WP"};

try {

    JSONObject obj = new JSONObject(json);

    Log.d("My App", obj.toString());

} catch (Throwable t) {
    Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

With Spring can I make an optional path variable?

Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.

Fixed footer in Bootstrap

Add this:

<div class="footer navbar-fixed-bottom">

https://stackoverflow.com/a/21604189

EDIT: class navbar-fixed-bottom has been changed to fixed-bottom as of Bootstrap v4-alpha.6.

http://v4-alpha.getbootstrap.com/components/navbar/#placement

PHP cURL HTTP CODE return 0

What is the exact contents you are passing into $html_brand?

If it is has an invalid URL syntax, you will very likely get the HTTP code 0.

How to set custom favicon in Express?

No need for custom middleware?! In express:

 //you probably have something like this already    
app.use("/public", express.static('public')); 

Then put your favicon in public and add the following line in your html's head:

<link rel="icon" href="/public/favicon.ico">

Any reason to prefer getClass() over instanceof when generating .equals()?

If you want to ensure only that class will match then use getClass() ==. If you want to match subclasses then instanceof is needed.

Also, instanceof will not match against a null but is safe to compare against a null. So you don't have to null check it.

if ( ! (obj instanceof MyClass) ) { return false; }

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

Hibernate error: ids for this class must be manually assigned before calling save():

Here is what I did to solve just by 2 ways:

  1. make ID column as int type

  2. if you are using autogenerate in ID dont assing value in the setter of ID. If your mapping the some then sometimes autogenetated ID is not concedered. (I dont know why)

  3. try using @GeneratedValue(strategy=GenerationType.SEQUENCE) if possible

Why is it important to override GetHashCode when Equals method is overridden?

As of .NET 4.7 the preferred method of overriding GetHashCode() is shown below. If targeting older .NET versions, include the System.ValueTuple nuget package.

// C# 7.0+
public override int GetHashCode() => (FooId, FooName).GetHashCode();

In terms of performance, this method will outperform most composite hash code implementations. The ValueTuple is a struct so there won't be any garbage, and the underlying algorithm is as fast as it gets.

How does one parse XML files?

If you're using .NET 2.0, try XmlReader and its subclasses XmlTextReader, and XmlValidatingReader. They provide a fast, lightweight (memory usage, etc.), forward-only way to parse an XML file.

If you need XPath capabilities, try the XPathNavigator. If you need the entire document in memory try XmlDocument.

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

Difference between `constexpr` and `const`

Overview

  • const guarantees that a program does not change an object’s value. However, const does not guarantee which type of initialization the object undergoes.

    Consider:

    const int mx = numeric_limits<int>::max();  // OK: runtime initialization
    

    The function max() merely returns a literal value. However, because the initializer is a function call, mx undergoes runtime initialization. Therefore, you cannot use it as a constant expression:

    int arr[mx];  // error: “constant expression required”
    
  • constexpr is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization. It controls the evaluation time of an expression. By enforcing compile-time evaluation of its expression, constexpr lets you define true constant expressions that are crucial for time-critical applications, system programming, templates, and generally speaking, in any code that relies on compile-time constants.

Constant-expression functions

A constant-expression function is a function declared constexpr. Its body must be non-virtual and consist of a single return statement only, apart from typedefs and static asserts. Its arguments and return value must have literal types. It can be used with non-constant-expression arguments, but when that is done the result is not a constant expression.

A constant-expression function is meant to replace macros and hardcoded literals without sacrificing performance or type safety.

constexpr int max() { return INT_MAX; }           // OK
constexpr long long_max() { return 2147483647; }  // OK
constexpr bool get_val()
{
    bool res = false;
    return res;
}  // error: body is not just a return statement

constexpr int square(int x)
{ return x * x; }  // OK: compile-time evaluation only if x is a constant expression
const int res = square(5);  // OK: compile-time evaluation of square(5)
int y = getval();
int n = square(y);          // OK: runtime evaluation of square(y)

Constant-expression objects

A constant-expression object is an object declared constexpr. It must be initialized with a constant expression or an rvalue constructed by a constant-expression constructor with constant-expression arguments.

A constant-expression object behaves as if it was declared const, except that it requires initialization before use and its initializer must be a constant expression. Consequently, a constant-expression object can always be used as part of another constant expression.

struct S
{
    constexpr int two();      // constant-expression function
private:
    static constexpr int sz;  // constant-expression object
};
constexpr int S::sz = 256;
enum DataPacket
{
    Small = S::two(),  // error: S::two() called before it was defined
    Big = 1024
};
constexpr int S::two() { return sz*2; }
constexpr S s;
int arr[s.two()];  // OK: s.two() called after its definition

Constant-expression constructors

A constant-expression constructor is a constructor declared constexpr. It can have a member initialization list but its body must be empty, apart from typedefs and static asserts. Its arguments must have literal types.

A constant-expression constructor allows the compiler to initialize the object at compile-time, provided that the constructor’s arguments are all constant expressions.

struct complex
{
    // constant-expression constructor
    constexpr complex(double r, double i) : re(r), im(i) { }  // OK: empty body
    // constant-expression functions
    constexpr double real() { return re; }
    constexpr double imag() { return im; }
private:
    double re;
    double im;
};
constexpr complex COMP(0.0, 1.0);         // creates a literal complex
double x = 1.0;
constexpr complex cx1(x, 0);              // error: x is not a constant expression
const complex cx2(x, 1);                  // OK: runtime initialization
constexpr double xx = COMP.real();        // OK: compile-time initialization
constexpr double imaglval = COMP.imag();  // OK: compile-time initialization
complex cx3(2, 4.6);                      // OK: runtime initialization

Tips from the book Effective Modern C++ by Scott Meyers about constexpr:

  • constexpr objects are const and are initialized with values known during compilation;
  • constexpr functions produce compile-time results when called with arguments whose values are known during compilation;
  • constexpr objects and functions may be used in a wider range of contexts than non-constexpr objects and functions;
  • constexpr is part of an object’s or function’s interface.

Source: Using constexpr to Improve Security, Performance and Encapsulation in C++.

Setting a minimum/maximum character count for any character using a regular expression

It's usually the metacharacter . when not inside a character class.

So use ^.{1,35}$. However, dot does not include newlines unless the dot-all modifier is applied against it.

You can use ^[\S\s]{1,35}$ without any modifiers, and this includes newlines as well.

Fatal error: Call to undefined function pg_connect()

Uncommenting extension=php_pgsql.dll in the php.ini configuration files does work but, you may have to also restart your XAMPP server to finally get it working. I had to do this.

Magento - How to add/remove links on my account navigation?

Its work 100% i am Sure.

Step 1: Go To ( YourTemplate/customer/account/navigation.phtml )

Step 2: Replace This Line: <?php $_count = count($_links); ?> With:

<?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
unset($_links['account']); /* Account Info */     
unset($_links['account_edit']); /* Account Info */            
unset($_links['tags']); /* My Tags */
unset($_links['invitations']); /* My Invitations */
unset($_links['reviews']);  /* Reviews */
unset($_links['wishlist']); /* Wishlist */
unset($_links['newsletter']); /* Newsletter */
unset($_links['orders']); /* My Orders */
unset($_links['address_book']); /* Address */
unset($_links['enterprise_customerbalance']); /* Store Credit */
unset($_links['OAuth Customer Tokens']); /* My Applications */
unset($_links['enterprise_reward']); /* Reward Points */
unset($_links['giftregistry']); /* Gift Registry */
unset($_links['downloadable_products']); /* My Downloadable Products */
unset($_links['recurring_profiles']); /* Recurring Profiles */
unset($_links['billing_agreements']); /* Billing Agreements */
unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */

?>

How should I escape strings in JSON?

If you are using fastexml jackson, you can use the following: com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)

If you are using codehaus jackson, you can use the following: org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)

Concatenating string and integer in python

String formatting, using the new-style .format() method (with the defaults .format() provides):

 '{}{}'.format(s, i)

Or the older, but "still sticking around", %-formatting:

 '%s%d' %(s, i)

In both examples above there's no space between the two items concatenated. If space is needed, it can simply be added in the format strings.

These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

Is it possible to serialize and deserialize a class in C++?

C++14 (C++17 recommended) boost prf

  • no macros
  • no code to be explicitly written

demo

Regular vs Context Free Grammars

Regular grammar:- grammar containing production as follows is RG:

V->TV or VT
V->T

where V=variable and T=terminal

RG may be Left Linear Grammar or Right Liner Grammar, but not Middle linear Grammar.

As we know all RG are Linear Grammar but only Left Linear or Right Linear Grammar are RG.

A regular grammar can be ambiguous.

S->aA|aB
A->a
B->a

Ambiguous Grammar:- for a string x their exist more than one LMD or More than RMD or More than one Parse tree or One LMD and One RMD but both Produce different Parse tree.

                S                   S

              /   \               /   \
             a     A             a     B
                    \                   \
                     a                   a

this Grammar is ambiguous Grammar because two parse tree.

CFG:- A grammar said to be CFG if its Production is in form:

   V->@   where @ belongs to (V+T)*

DCFL:- as we know all DCFL are LL(1) Grammar and all LL(1) is LR(1) so it is Never be ambiguous. so DCFG is Never be ambiguous.

We also know all RL are DCFL so RL never be ambiguous. Note that RG may be ambiguous but RL not.

CFL: CFl May or may not ambiguous.

Note: RL never be Inherently ambiguous.

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get an access token: facebook Graph API Explorer

You can customize specific access permissions, basic permissions are included by default.

New lines (\r\n) are not working in email body

Using <BR> is not allways enough. MS Outlook 2007 will ignore this if you dont tell outlook that it is a selfclosing html tag by using

 <BR />

What is the difference between `throw new Error` and `throw someObject`?

You first mention this code:

throw new Error('sample')

and then in your first example you write:

throw new Error({'hehe':'haha'}) 

The first Error object would actually be useful, because it is expecting a string value, in this case 'sample'. The second would not because you are trying to pass an object in, and it is expecting a string, and would not display a helpful error.

The error object would have the "message" property, which would be 'sample'.

rmagick gem install "Can't find Magick-config"

I had to specify version 6

brew install imagemagick@6
brew link --overwrite --force imagemagick@6

Why is my xlabel cut off in my matplotlib plot?

In case you want to store it to a file, you solve it using bbox_inches="tight" argument:

plt.savefig('myfile.png', bbox_inches = "tight")

TypeError: 'float' object is not callable

You have forgotten a * between -3.7 and (prof[x]).

Thus:

for x in range(len(prof)):
    PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))

Also, there seems to be missing an ( as I count 6 times ( and 7 times ), and I think (math.e, (0/2.25)) is missing a function call (probably math.pow, but thats just a wild guess).

How to set a bitmap from resource

Using this function you can get Image Bitmap. Just pass image url

 public Bitmap getBitmapFromURL(String strURL) {
      try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
 }

How to add option to select list in jQuery

$.each(data,function(index,itemData){
    $('#dropListBuilding').append($("<option></option>")
        .attr("value",key)
        .text(value)); 
});

Reportviewer tool missing in visual studio 2017 RC

Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:

  1. If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:

    • Microsoft.DataTools.ReportingServices.vsix, and
    • Microsoft.RdlcDesigner.vsix
  2. Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:

    • Microsoft.ReportViewer.Common.dll
    • Microsoft.ReportViewer.DataVisualization.dll
    • Microsoft.ReportViewer.Design.dll
    • Microsoft.ReportViewer.ProcessingObjectModel.dll
    • Microsoft.ReportViewer.WinForms.dll
  3. Install the 2 components from 1 above

  4. Add the dlls from 2 above as references (Project>References>Add...)
  5. (Optional) Add Reporting tab to the toolbar
  6. Add Items to Reporting tab
  7. Browse to the bin folder or where you have the above dlls and add them

You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project

NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!

How to convert color code into media.brush?

What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
        <Rectangle.Fill>
            <SolidColorBrush Color="#FF00AE00" />
        </Rectangle.Fill>
    </Rectangle>
</Grid>

Deserialize a JSON array in C#

[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

and Remove a "{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

DeserializeObject..,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

Vue.js data-bind style backgroundImage not working

Binding background image style using a dynamic value from v-for loop could be done like this.

<div v-for="i in items" :key="n" 
  :style="{backgroundImage: 'url('+require('./assets/cars/'+i.src+'.jpg')+')'}">
</div>

if (boolean condition) in Java

Assuming state is having a valid boolean value set in your actual code, then the following condition will succeed

if(state)

when state is boolean value is TRUE

If condition checks for the expression whether it is evaluated to TRUE/FALSE. If the expression is simple true then the condition will succeed.

How to add colored border on cardview?

Start From the material design update, it support app:strokeColor and also app:strokeWidth. see more

to use material design update. add following code to build.gradle(:app)

dependencies {
    // ...
    implementation 'com.google.android.material:material:1.0.0'
    // ...
  }

and Change CardView to MaterialCardView

Is using 'var' to declare variables optional?

I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:

// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;

// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);

This triggers the visual cue fading in and out.

Using prepared statements with JDBCTemplate

class Main {
    public static void main(String args[]) throws Exception {
        ApplicationContext ac = new
          ClassPathXmlApplicationContext("context.xml", Main.class);
        DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String prasobhName = 
        jdbcTemplate.query(
           "select first_name from customer where last_name like ?",
            new PreparedStatementSetter() {
              public void setValues(PreparedStatement preparedStatement) throws
                SQLException {
                  preparedStatement.setString(1, "nair%");
              }
            }, 
            new ResultSetExtractor<Long>() {
              public Long extractData(ResultSet resultSet) throws SQLException,
                DataAccessException {
                  if (resultSet.next()) {
                      return resultSet.getLong(1);
                  }
                  return null;
              }
            }
        );
        System.out.println(machaceksName);
    }
}

How to Install Font Awesome in Laravel Mix

the path you are using is not correct you could just open the node_module and find the path of font-awesome. use could use js or svg font but i prefer the css style.

at first use this command to install font-awesome-free npm install --save-dev @fortawesome/fontawesome-free

after that you can do this

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";

and I copy the font path like below this is optional

.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/fonts');

and finally just run the script npm run dev or npm run watch in laravel

Facebook user url by id

Accepted answer didn't work for me, this does:

https://www.facebook.com/app_scoped_user_id/10152384781676191

How to convert a color integer to a hex String in Android?

Integer value of ARGB color to hexadecimal string:

String hex = Integer.toHexString(color); // example for green color FF00FF00

Hexadecimal string to integer value of ARGB color:

int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

In case anyone is as dopey as me, double check the year of your date. I was converting a date from a text file in YYMMDD format so was creating a date with a year of 0020, not 2020. Obvious error but I spent more time looking at it but not seeing it than I should have!

Error: Execution failed for task ':app:clean'. Unable to delete file

I had the same problem and this worked for me:

  1. close Android Studio.
  2. delete intermediates directory (as long as Android Studio is opened, this directory can't be deleted)
  3. open Android Studio again

How to format a duration in java? (e.g format H:MM:SS)

If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:

  String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));