Programs & Examples On #Datatemplate

Data templating is a feature of WPF that lets you customize the presentation of data.

Access parent DataContext from DataTemplate

You can use RelativeSource to find the parent element, like this -

Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified, 
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"

See this SO question for more details about RelativeSource.

What's the difference between emulation and simulation?

Both are models of an object that you have some means of controlling inputs and observing outputs. With an emulator, you want the output to be exactly what the object you are emulating would produce. With a simulator, you want certain properties of your output to be similar to what the object would produce.

Let me give an example -- suppose you want to do some system testing to see how adding a new sensor (like a thermometer) to a system would affect the system. You know that the thermometer sends a message 8 time a second containing its measurement.

Simulation -- if you do not have the thermometer yet, but you want to test that this message rate will not overload you system, you can simulate the sensor by attaching a unit that sends a random number 8 times a second. You can run any test that does not rely on the actual value the sensor sends.

Emulation -- suppose you have a very expensive thermometer that measures to 0.001 C, and you want to see if you can get by with a cheaper thermometer that only measures to the nearest 0.5 C. You can emulate the cheaper thermometer using an expensive thermometer by rounding the reading to the nearest 0.5 C and running tests that rely on the temperature values.

Cocoa Autolayout: content hugging vs content compression resistance priority

enter image description here

source: @mokagio

Intrinsic Content Size - Pretty self-explanatory, but views with variable content are aware of how big their content is and describe their content's size through this property. Some obvious examples of views that have intrinsic content sizes are UIImageViews, UILabels, UIButtons.

Content Hugging Priority - The higher this priority is, the more a view resists growing larger than its intrinsic content size.

Content Compression Resistance Priority - The higher this priority is, the more a view resists shrinking smaller than its intrinsic content size.

Check here for more explanation: AUTO LAYOUT MAGIC: CONTENT SIZING PRIORITIES

Cycles in family tree software

Instead of removing all assertions, you should still check for things like a person being his/her own parent or other impossible situations and present an error. Maybe issue a warning if it is unlikely so the user can still detect common input errors, but it will work if everything is correct.

I would store the data in a vector with a permanent integer for each person and store the parents and children in person objects where the said int is the index of the vector. This would be pretty fast to go between generations (but slow for things like name searches). The objects would be in order of when they were created.

How do I display the value of a Django form field in a template?

This seems to work.

{{ form.fields.email.initial }}

Service located in another namespace

To access services in two different namespaces you can use url like this:

HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local

To list out all your namespaces you can use:

kubectl get namespace

And for service in that namespace you can simply use:

kubectl get services -n <namespace-name>

this will help you.

How do I update Node.js?

Today I ran on a Windows Git Bash:

$ npm i node -g

and got the following output:

> [email protected] preinstall C:\Users\X\AppData\Roaming\npm\node_modules\node
> node installArchSpecificPackage

+ [email protected]
added 1 package and audited 1 package in 23.368s
found 0 vulnerabilities

C:\Users\X\AppData\Roaming\npm\node -> C:\Users\X\AppData\Roaming\npm\node_modules\node\bin\node
+ [email protected]
added 2 packages from 1 contributor in 26.089s

Read more about it at https://www.npmjs.com/package/node.

Get number days in a specified month using JavaScript?

// Month here is 1-indexed (January is 1, February is 2, etc). This is
// because we're using 0 as the day so that it returns the last day
// of the last month, so you have to add 1 to the month number 
// so it returns the correct amount of days
function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}

// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29

SQL Server insert if not exists best practice

Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code

Insert Into [Competitors] (cName, cCity, cState)
Select cName, cCity, cState from 
(
    select new.* from 
    (
        select distinct cName, cCity, cState 
        from [Competitors] s, [City] c, [State] s
    ) new
    left join 
    (   
        select distinct cName, cCity, cState 
        from [Competitors] s
    ) existing
    on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
    where existing.Name is null  or existing.City is null or existing.State is null
)

Structure of a PDF file?

Here's the raw reference of PDF 1.7, and here's an article describing the structure of a PDF file. If you use Vim, the pdftk plugin is a good way to explore the document in an ever-so-slightly less raw form, and the pdftk utility itself (and its GPL source) is a great way to tease documents apart.

Eclipse error "ADB server didn't ACK, failed to start daemon"

If you are using a sync application for the device, it could also be because there are other apps using the same 5037 port. Shut down all services running on port 5037 and try starting ADB.

To check if any application is using port 5037, use this:

netstat -a -n -o |findstr "5037"

Get the PID of the application.

Use Process Explorer to find the Process and exit it.

Now use adb start-server or adb get-state to start/check the ADB server status.

I faced the issue when I used the Snappea / Wandoujia Sync application.

ITextSharp insert text to an existing pdf

Here is a method To print over images: taken from here. Use a different layer for your text you're putting over the images, and also make sure to use the GetOverContent() method.

            string oldFile = "FileWithImages.pdf";
            string watermarkedFile = "Layers.pdf";
            // Creating watermark on a separate layer
            // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
            PdfReader reader1 = new PdfReader(oldFile);
            using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
            // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
            using (PdfStamper stamper = new PdfStamper(reader1, fs))
            {
                // Getting total number of pages of the Existing Document
                int pageCount = reader1.NumberOfPages;

                // Create New Layer for Watermark
                PdfLayer layer = new PdfLayer("Layer", stamper.Writer);
                // Loop through each Page
                for (int i = 1; i <= pageCount; i++)
                {
                    // Getting the Page Size
                    Rectangle rect = reader1.GetPageSize(i);

                    // Get the ContentByte object
                    PdfContentByte cb = stamper.GetOverContent(i);

                    // Tell the cb that the next commands should be "bound" to this new layer
                    cb.BeginLayer(layer);
                    
                    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    cb.SetColorFill(BaseColor.RED);
                    cb.SetFontAndSize(bf, 100);

                    cb.BeginText();
                    cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Some random blablablabla...", rect.Width / 2, rect.Height / 2, - 90);
                    cb.EndText();

                    // Close the layer
                    cb.EndLayer();
                }
            }

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

  1. Where I work we have 2 Sprints to an Iteration. The Iteration demo is before the business stakeholders that don't want to meet after every Sprint, but that is our interpretation of the terminology. Some places may have the terms having equally meaning, I'm just pointing out that where I work they aren't the same thing.

  2. No, sprints can have varying lengths. Where I work we had a half a Sprint to align our Sprints with the Iterations that others in the project from another department were using.

Understanding .get() method in Python

I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections library exists to fulfill these purposes.

from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
    letter_counter[letter] += 1

>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})

In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.

As for the dict.get(a_key, default_value), there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.

CSS text-align: center; is not centering things

I assume you want all the items next to each other, and the whole thing to be centered horizontally.

li elements are display: block by default, taking up all the horizontal space.

Add

div#footer ul li { display: inline }

once you've done that, you probably want to get rid of the list's bullets:

div#footer ul { list-style-type: none; padding: 0px; margin: 0px }

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

error_log per Virtual Host?

Yes, you can try,

php_value error_log "/var/log/php_log" 

in .htaccess or you can have users use ini_set() in the beginning of their scripts if they want to have logging.

Another option would be to enable scripts to default to the php.ini in the folder with the script, then go to the user/host's root folder, then to the server's root, or something similar. This would allow hosts to add their own php.ini values and their own error_log locations.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

Here is another one:

http://www.essentialobjects.com/Products/WebBrowser/Default.aspx

This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.

Undefined Reference to

Try to remove the constructor and destructors, it's working for me....

cc1plus: error: unrecognized command line option "-std=c++11" with g++

you should try this

g++-4.4 -std=c++0x or g++-4.7 -std=c++0x

onclick open window and specific size

These are the best practices from Mozilla Developer Network's window.open page :

<script type="text/javascript">
var windowObjectReference = null; // global variable

function openFFPromotionPopup() {
  if(windowObjectReference == null || windowObjectReference.closed)
  /* if the pointer to the window object in memory does not exist
     or if such pointer exists but the window was closed */

  {
    windowObjectReference = window.open("http://www.spreadfirefox.com/",
   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
    /* then create it. The new window will be created and
       will be brought on top of any other window. */
  }
  else
  {
    windowObjectReference.focus();
    /* else the window reference must exist and the window
       is not closed; therefore, we can bring it back on top of any other
       window with the focus() method. There would be no need to re-create
       the window or to reload the referenced resource. */
  };
}
</script>

<p><a
 href="http://www.spreadfirefox.com/"
 target="PromoteFirefoxWindowName"
 onclick="openFFPromotionPopup(); return false;" 
 title="This link will create a new window or will re-use an already opened one"
>Promote Firefox adoption</a></p>

How to debug PDO database queries?

Here's a function to see what the effective SQL will be, adpated from a comment by "Mark" at php.net:

function sql_debug($sql_string, array $params = null) {
    if (!empty($params)) {
        $indexed = $params == array_values($params);
        foreach($params as $k=>$v) {
            if (is_object($v)) {
                if ($v instanceof \DateTime) $v = $v->format('Y-m-d H:i:s');
                else continue;
            }
            elseif (is_string($v)) $v="'$v'";
            elseif ($v === null) $v='NULL';
            elseif (is_array($v)) $v = implode(',', $v);

            if ($indexed) {
                $sql_string = preg_replace('/\?/', $v, $sql_string, 1);
            }
            else {
                if ($k[0] != ':') $k = ':'.$k; //add leading colon if it was left out
                $sql_string = str_replace($k,$v,$sql_string);
            }
        }
    }
    return $sql_string;
}

REST vs JSON-RPC?

If you request resources, then RESTful API is better by design. If you request some complicated data with a lot of parameters and complicated methods other than simple CRUD, then RPC is the right way to go.

How to use vim in the terminal?

if you want to open all your .cpp files with one command, and have the window split in as many tiles as opened files, you can use:

vim -o $(find name ".cpp")

if you want to include a template in the place you are, you can use:

:r ~/myHeaderTemplate 

will import the file "myHeaderTemplate in the place the cursor was before starting the command.

you can conversely select visually some code and save it to a file

  1. select visually,
  2. add w ~/myPartialfile.txt

when you select visualy, after type ":" in order to enter a command, you'll see "'<,'>" appear after the ":"

'<,'>w ~/myfile $

^ if you add "~/myfile" to the command, the selected part of the file will be saved to myfile.

if you're editing a file an want to copy it :

:saveas newFileWithNewName 

A child container failed during start java.util.concurrent.ExecutionException

You must have packaged the servlet-api.jar along with the other libraries in your war file. You can verify this by opening up your war file and navigating to the WEB-INF/lib folder.

Ideally, you should not provide the servlet-api jar. The container, in your case Tomcat, is responsible for providing it at deploy time to your application. If you try to provide it as well, then issues arise due to version mismatch etc. Best practise is to just avoid packaging it. Remove it from the WEB-INF/lib.

Additional Information

If you are using maven for your packaging, then simply add the provided tag with the dependency and maven will make sure not to package it in the final war file. Something like

<dependency>
    <artifact>..
    <group> ...
    <version> ...
    <scope>provided</scope>
</<dependency>

Android : How to read file in bytes?

here it's a simple:

File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(bytes, 0, bytes.length);
    buf.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Add permission in manifest.xml:

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

data.frame rows to a list

I was working on this today for a data.frame (really a data.table) with millions of observations and 35 columns. My goal was to return a list of data.frames (data.tables) each with a single row. That is, I wanted to split each row into a separate data.frame and store these in a list.

Here are two methods I came up with that were roughly 3 times faster than split(dat, seq_len(nrow(dat))) for that data set. Below, I benchmark the three methods on a 7500 row, 5 column data set (iris repeated 50 times).

library(data.table)
library(microbenchmark)

microbenchmark(
split={dat1 <- split(dat, seq_len(nrow(dat)))},
setDF={dat2 <- lapply(seq_len(nrow(dat)),
                  function(i) setDF(lapply(dat, "[", i)))},
attrDT={dat3 <- lapply(seq_len(nrow(dat)),
           function(i) {
             tmp <- lapply(dat, "[", i)
             attr(tmp, "class") <- c("data.table", "data.frame")
             setDF(tmp)
           })},
datList = {datL <- lapply(seq_len(nrow(dat)),
                          function(i) lapply(dat, "[", i))},
times=20
) 

This returns

Unit: milliseconds
       expr      min       lq     mean   median        uq       max neval
      split 861.8126 889.1849 973.5294 943.2288 1041.7206 1250.6150    20
      setDF 459.0577 466.3432 511.2656 482.1943  500.6958  750.6635    20
     attrDT 399.1999 409.6316 461.6454 422.5436  490.5620  717.6355    20
    datList 192.1175 201.9896 241.4726 208.4535  246.4299  411.2097    20

While the differences are not as large as in my previous test, the straight setDF method is significantly faster at all levels of the distribution of runs with max(setDF) < min(split) and the attr method is typically more than twice as fast.

A fourth method is the extreme champion, which is a simple nested lapply, returning a nested list. This method exemplifies the cost of constructing a data.frame from a list. Moreover, all methods I tried with the data.frame function were roughly an order of magnitude slower than the data.table techniques.

data

dat <- vector("list", 50)
for(i in 1:50) dat[[i]] <- iris
dat <- setDF(rbindlist(dat))

A simple scenario using wait() and notify() in java

Not a queue example, but extremely simple :)

class MyHouse {
    private boolean pizzaArrived = false;

    public void eatPizza(){
        synchronized(this){
            while(!pizzaArrived){
                wait();
            }
        }
        System.out.println("yumyum..");
    }

    public void pizzaGuy(){
        synchronized(this){
             this.pizzaArrived = true;
             notifyAll();
        }
    }
}

Some important points:
1) NEVER do

 if(!pizzaArrived){
     wait();
 }

Always use while(condition), because

  • a) threads can sporadically awake from waiting state without being notified by anyone. (even when the pizza guy didn't ring the chime, somebody would decide try eating the pizza.).
  • b) You should check for the condition again after acquiring the synchronized lock. Let's say pizza don't last forever. You awake, line-up for the pizza, but it's not enough for everybody. If you don't check, you might eat paper! :) (probably better example would be while(!pizzaExists){ wait(); }.

2) You must hold the lock (synchronized) before invoking wait/nofity. Threads also have to acquire lock before waking.

3) Try to avoid acquiring any lock within your synchronized block and strive to not invoke alien methods (methods you don't know for sure what they are doing). If you have to, make sure to take measures to avoid deadlocks.

4) Be careful with notify(). Stick with notifyAll() until you know what you are doing.

5)Last, but not least, read Java Concurrency in Practice!

How to change the background color of Action Bar's Option Menu in Android 4.2?

If you read this, it's probably because all the previous answers didn't work for your Holo Dark based theme.

Holo Dark uses an additional wrapper for the PopupMenus, so after doing what Jonik suggested you have to add the following style to your 'xml' file:

<style name="PopupWrapper" parent="@android:style/Theme.Holo">
    <item name="android:popupMenuStyle">@style/YourPopupMenu</item>
</style>

Then reference it in your theme block:

<style name="Your.cool.Theme" parent="@android:style/Theme.Holo">
    .
    .
    .
    <item name="android:actionBarWidgetTheme">@style/PopupWrapper</item>
</style>

That's it!

Command copy exited with code 4 when building - Visual Studio restart solves it

While /C may ignore errors, it might not be the real solution as there could be files that MUST be copied in order for the build to be successful.

The most common issue is the missing quotes around the pre-defined command tags (such as $TargetDir). When one creates various branches and paths in code or TFS, there is a very high chance for this to occur.

Sometimes if the file is read only, it will cause issues too. Add the /R option to allow read only files to be copied over. You can find list of available options at:

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true

Another possible issue is that the underlying folder cannot be accessed. If so, trying performing "start xcopy" instead of "xcopy". This will open another command window but with admin priveleges.

How to represent matrices in python

Take a look at this answer:

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

How to check all versions of python installed on osx and centos

we can directly use this to see all the pythons installed both by current user and the root by the following: whereis python

How to set cookies in laravel 5 independently inside controller

You are going right way my friend.Now if you want retrive cookie anywhere in project just put this code $val = Cookie::get('COOKIE_NAME'); That's it! For more information how can this done click here

Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>
</select>

JQuery

var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

how to use "tab space" while writing in text file

You can use \t to create a tab in a file.

Correct way to convert size in bytes to KB, MB, GB in JavaScript

const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

function niceBytes(x){

  let l = 0, n = parseInt(x, 10) || 0;

  while(n >= 1024 && ++l){
      n = n/1024;
  }
  //include a decimal point and a tenths-place digit if presenting 
  //less than ten of KB or greater units
  return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}

Results:

niceBytes(435)                 // 435 bytes
niceBytes(3398)                // 3.3 KB
niceBytes(490398)              // 479 KB
niceBytes(6544528)             // 6.2 MB
niceBytes(23483023)            // 22 MB
niceBytes(3984578493)          // 3.7 GB
niceBytes(30498505889)         // 28 GB
niceBytes(9485039485039445)    // 8.4 PB

CASE .. WHEN expression in Oracle SQL

Following syntax would work :

....
where x.p_NBR =to_number(substr(y.k_str,11,5))
and x.q_nbr = 
 (case 
 when instr(substr(y.m_str,11,9),'_') = 6   then  to_number(substr(y.m_str,11,5))
 when instr(substr(y.m_str,11,9),'_') = 0   then  to_number(substr(y.m_str,11,9))
  else 
       1
  end
)

How do I check if the user is pressing a key?

In java you don't check if a key is pressed, instead you listen to KeyEvents. The right way to achieve your goal is to register a KeyEventDispatcher, and implement it to maintain the state of the desired key:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

Then you can always use:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

You can, of course, use same method to implement isPressing("<some key>") with a map of keys and their state wrapped inside IsKeyPressed.

Named tuple and default values for optional keyword arguments

Python 3.7

Use the defaults parameter.

>>> from collections import namedtuple
>>> fields = ('val', 'left', 'right')
>>> Node = namedtuple('Node', fields, defaults=(None,) * len(fields))
>>> Node()
Node(val=None, left=None, right=None)

Or better yet, use the new dataclasses library, which is much nicer than namedtuple.

>>> from dataclasses import dataclass
>>> from typing import Any
>>> @dataclass
... class Node:
...     val: Any = None
...     left: 'Node' = None
...     right: 'Node' = None
>>> Node()
Node(val=None, left=None, right=None)

Before Python 3.7

Set Node.__new__.__defaults__ to the default values.

>>> from collections import namedtuple
>>> Node = namedtuple('Node', 'val left right')
>>> Node.__new__.__defaults__ = (None,) * len(Node._fields)
>>> Node()
Node(val=None, left=None, right=None)

Before Python 2.6

Set Node.__new__.func_defaults to the default values.

>>> from collections import namedtuple
>>> Node = namedtuple('Node', 'val left right')
>>> Node.__new__.func_defaults = (None,) * len(Node._fields)
>>> Node()
Node(val=None, left=None, right=None)

Order

In all versions of Python, if you set fewer default values than exist in the namedtuple, the defaults are applied to the rightmost parameters. This allows you to keep some arguments as required arguments.

>>> Node.__new__.__defaults__ = (1,2)
>>> Node()
Traceback (most recent call last):
  ...
TypeError: __new__() missing 1 required positional argument: 'val'
>>> Node(3)
Node(val=3, left=1, right=2)

Wrapper for Python 2.6 to 3.6

Here's a wrapper for you, which even lets you (optionally) set the default values to something other than None. This does not support required arguments.

import collections
def namedtuple_with_defaults(typename, field_names, default_values=()):
    T = collections.namedtuple(typename, field_names)
    T.__new__.__defaults__ = (None,) * len(T._fields)
    if isinstance(default_values, collections.Mapping):
        prototype = T(**default_values)
    else:
        prototype = T(*default_values)
    T.__new__.__defaults__ = tuple(prototype)
    return T

Example:

>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None, right=None)
>>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
>>> Node()
Node(val=1, left=2, right=3)
>>> Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
>>> Node()
Node(val=None, left=None, right=7)
>>> Node(4)
Node(val=4, left=None, right=7)

How do I align spans or divs horizontally?

You can use divs with the float: left; attribute which will make them appear horizontally next to each other, but then you may need to use clearing on the following elements to make sure they don't overlap.

CSS Image size, how to fill, but not stretch?

As far as I know, there is a plugin to make this simple.

jQuery Plugin: Auto transform <img> into background style

<img class="fill" src="image.jpg" alt="Fill Image"></img>

<script>
    $("img.fill").img2bg();
</script>

Besides, this way also fulfills the accessibility needs. As this plugin will NOT remove your <img> tag from your codes, the screen reader still tells you the ALT text instead of skipping it.

Initialising a multidimensional array in Java

Try replacing the appropriate lines with:

myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";

Your code is incorrect because the sub-arrays have a length of y, and indexing starts at 0. So setting to myStringArray[0][y] or myStringArray[0][x] will fail because the indices x and y are out of bounds.

String[][] myStringArray = new String [x][y]; is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.

jQuery 'if .change() or .keyup()'

Do this.

$(function(){
    var myFunction = function()
    {
        alert("myFunction called");
    }

    jQuery(':input').change(myFunction).keyup(myFunction);
});

Route.get() requires callback functions but got a "object Undefined"

I got the same error. After debugging, I found that I misspelled the method name that I imported from the controller into the route file. Please check the method name.

hadoop copy a local file system folder to HDFS

To copy a folder file from local to hdfs, you can the below command

hadoop fs -put /path/localpath  /path/hdfspath

or

hadoop fs -copyFromLocal /path/localpath  /path/hdfspath

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

For my case, I made sure that Fragment class is imported from

android.support.v4.app.Fragment

Not from

android.app.Fragment

Then I have used

getActivity().getSupportFragmentManager();

And now its working. If I use activity instance which I got in onAttach() is not working also.

php search array key and get value

Here is an example straight from PHP.net

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

in the foreach you can do a comparison of each key to something that you are looking for

Taking pictures with camera on Android programmatically

Look at following demo code.

Here is your XML file for UI,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnCapture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Camera" />

</LinearLayout>

And here is your Java class file,

public class CameraDemoActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Here, we are making a folder named picFolder to store
        // pics taken by the camera using this application.
        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);
        newdir.mkdirs();

        Button capture = (Button) findViewById(R.id.btnCapture);
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Here, the counter will be incremented each time, and the
                // picture taken by camera will be stored as 1.jpg,2.jpg
                // and likewise.
                count++;
                String file = dir+count+".jpg";
                File newfile = new File(file);
                try {
                    newfile.createNewFile();
                }
                catch (IOException e)
                {
                }

                Uri outputFileUri = Uri.fromFile(newfile);

                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");
        }
    }
}

Note:

Specify the following permissions in your manifest file,

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

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

How to obtain image size using standard Python class (without using external library)?

That code does accomplish 2 things:

  • Getting the image dimension

  • Find the real EOF of a jpg file

Well when googling I was more interest in the later one. The task was to cut out a jpg file from a datastream. Since I I didn't find any way to use Pythons 'image' to a way to get the EOF of so jpg-File I made up this.

Interesting things /changes/notes in this sample:

  • extending the normal Python file class with the method uInt16 making source code better readable and maintainable. Messing around with struct.unpack() quickly makes code to look ugly

  • Replaced read over'uninteresting' areas/chunk with seek

  • Incase you just like to get the dimensions you may remove the line:

    hasChunk = ord(byte) not in range( 0xD0, 0xDA) + [0x00] 
    

    ->since that only get's important when reading over the image data chunk and comment in

    #break
    

    to stop reading as soon as the dimension were found. ...but smile what I'm telling - you're the Coder ;)

      import struct
      import io,os
    
      class myFile(file):
    
          def byte( self ):
               return file.read( self,  1);
    
          def uInt16( self ):
               tmp = file.read( self,  2)
               return struct.unpack( ">H", tmp )[0];
    
      jpeg = myFile('grafx_ui.s00_\\08521678_Unknown.jpg', 'rb')
    
      try:
          height = -1
          width  = -1
          EOI    = -1
    
          type_check = jpeg.read(2)
          if type_check != b'\xff\xd8':
            print("Not a JPG")
    
          else:
    
            byte = jpeg.byte()
    
            while byte != b"":
    
              while byte != b'\xff': byte = jpeg.byte()
              while byte == b'\xff': byte = jpeg.byte()
    
    
              # FF D8       SOI Start of Image
              # FF D0..7  RST DRI Define Restart Interval inside CompressedData
              # FF 00           Masked FF inside CompressedData
              # FF D9       EOI End of Image
              # http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure
              hasChunk = ord(byte) not in range( 0xD0, 0xDA) + [0x00]
              if hasChunk:
                   ChunkSize   =  jpeg.uInt16()  - 2
                   ChunkOffset =  jpeg.tell()
                   Next_ChunkOffset = ChunkOffset + ChunkSize
    
    
              # Find bytes \xFF \xC0..C3 That marks the Start of Frame
              if (byte >= b'\xC0' and byte <= b'\xC3'):
    
                # Found  SOF1..3 data chunk - Read it and quit
                jpeg.seek(1, os.SEEK_CUR)
                h = jpeg.uInt16()
                w = jpeg.uInt16()
    
    
                #break
    
    
              elif (byte == b'\xD9'):
                   # Found End of Image
                   EOI = jpeg.tell()
                   break
              else:
                  # Seek to next data chunk
                 print "Pos: %.4x %x" % (jpeg.tell(), ChunkSize)
    
              if hasChunk:       
                 jpeg.seek(Next_ChunkOffset)
    
              byte = jpeg.byte()
    
            width  = int(w)
            height = int(h)
    
            print("Width: %s, Height: %s  JpgFileDataSize: %x" % (width, height, EOI))
      finally:
          jpeg.close()
    

A good Sorted List for Java

SortedList decorator from Java Happy Libraries can be used to decorate TreeList from Apache Collections. That would produce a new list which performance is compareable to TreeSet. https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/

Where is debug.keystore in Android Studio

On Windows, if the debug.keystore file is not in the location (C:\Users\username\.android), the debug.keystore file may also be found in the location where you have installed Android Studio.

SQL Server : check if variable is Empty or NULL for WHERE clause

Just use

If @searchType is null means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType is NULL

If @searchType is an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR @SearchType = ''

If @searchType is null or an empty string means 'return the whole table' then use

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

Show hide div using codebehind

RegisteredClientScriptBlock adds the script at the top of the page on the post-back with no assurance about the order, meaning that either the call is being injected after the function declaration (your js file with the function is inlined after your call) or when the script tries to execute the div is probably not there yet 'cause the page is still rendering. A good idea is probably to simulate the two scenarios I described above on firebug and see if you get similar errors.

My guess is this would work if you append the script at the bottom of the page with RegisterStartupScript - worth a shot at least.

Anyway, as an alternative solution if you add the runat="server" attribute to the div you will be able to access it by its id in the codebehind (without reverting to js - how cool that might be), and make it disappear like this:

data.visible = false

hadoop No FileSystem for scheme: file

For SBT use below mergeStrategy in build.sbt

mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => {
    case PathList("META-INF", "services", "org.apache.hadoop.fs.FileSystem") => MergeStrategy.filterDistinctLines
    case s => old(s)
  }
}

how to change the default positioning of modal in bootstrap?

If you need to change the bottom position of the modal, you need to modify the max-height of the modal-body:

.modal-body {
  max-height: 75vh;
}

As other answers have said, you can adjust the right and top on the modal-dialog :

.modal-dialog {
  top: 10vh;
  right: 5vw;
}
  • "vh" means "% of view height"
  • "vw" means "% of view width"

ASP.NET file download from server

Try this set of code to download a CSV file from the server.

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();

CSS media query to target only iOS devices

I don't know about targeting iOS as a whole, but to target iOS Safari specifically:

@supports (-webkit-touch-callout: none) {
   /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
   /* CSS for other than iOS devices */ 
}

Apparently as of iOS 13 -webkit-overflow-scrolling no longer responds to @supports, but -webkit-touch-callout still does. Of course that could change in the future...

Django set field value after a form is initialized

Another way to do this, if you have already initialised a form (with or without data), and you need to add further data before displaying it:

form = Form(request.POST.form)
form.data['Email'] = GetEmailString()

How to name Dockerfiles

I have created two Dockerfiles in same directory,

# vi one.Dockerfile
# vi two.Dockerfile

to build both Dockerfiles use,

# docker build . -f one.Dockerfile
# docker build . -f two.Dockerfile

Note: you should be in present working directory..

Get first word of string

In modern JS, this is simplified, and you can write something like this:

_x000D_
_x000D_
const firstWords = str =>_x000D_
  str .split (/\|/) .map (s => s .split (/\s+/) [0])_x000D_
_x000D_
const str = "Hello m|sss sss|mmm ss"_x000D_
_x000D_
console .log (firstWords (str))
_x000D_
_x000D_
_x000D_

We first split the string on the | and then split each string in the resulting array on any white space, keeping only the first one.

File path to resource in our war/WEB-INF folder?

I know this is late, but this is how I normally do it,

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();           
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

You can use Configuration to resolve this.

Ex (Startup.cs):

You can pass by DI to the controllers after this implementation.

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        Configuration = builder.Build();

    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        var microserviceName = Configuration["microserviceName"];

       services.AddSingleton(Configuration);

       ...
    }

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

Try this:

XmlDocument bodyDoc = new XmlDocument();
bodyDoc.XMLResolver = null;
bodyDoc.Load(body);

How do you determine the ideal buffer size when using FileInputStream?

As already mentioned in other answers, use BufferedInputStreams.

After that, I guess the buffer size does not really matter. Either the program is I/O bound, and growing buffer size over BIS default, will not make any big impact on performance.

Or the program is CPU bound inside the MessageDigest.update(), and majority of the time is not spent in the application code, so tweaking it will not help.

(Hmm... with multiple cores, threads might help.)

How to encode the filename parameter of Content-Disposition header in HTTP?

There is discussion of this, including links to browser testing and backwards compatibility, in the proposed RFC 5987, "Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters."

RFC 2183 indicates that such headers should be encoded according to RFC 2184, which was obsoleted by RFC 2231, covered by the draft RFC above.

Bubble Sort Homework

You've got a couple of errors in there. The first is in length, and the second is in your use of unsorted (as stated by McWafflestix). You probably also want to return the list if you're going to print it:

mylist = [12, 5, 13, 8, 9, 65]

def bubble(badList):
    length = len(badList) - 2
    unsorted = True

    while unsorted:
        for element in range(0,length):
            unsorted = False

            if badList[element] > badList[element + 1]:
                hold = badList[element + 1]
                badList[element + 1] = badList[element]
                badList[element] = hold
                print badList
                unsorted = True

    return badList

print bubble(mylist)

eta: You're right, the above is buggy as hell. My bad for not testing through some more examples.

def bubble2(badList):
    swapped = True
    length = len(badList) - 2

    while swapped:
        swapped = False
        for i in range(0, length):
            if badList[i] > badList[i + 1]:

                # swap
                hold = badList[i + 1]
                badList[i + 1] = badList[i]
                badList[i] = hold

                swapped = True

    return badList

How to get JSON objects value if its name contains dots?

in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]

this should do the trick

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

How to get All input of POST in Laravel

For those who came here looking for "how to get All input of POST" only

class Illuminate\Http\Request extends from Symfony\Component\HttpFoundation\Request which has two class variables that store request parameters.

public $query - for GET parameters

public $request - for POST parameters

Usage: To get a post data only

$request = Request::instance();
$request->request->all(); //Get all post requests
$request->request->get('my_param'); //Get a post parameter

Source here

EDIT

For Laravel >= 5.5, you can simply call $request->post() or $request->post('my_param') which internally calls $request->request->all() or $request->request->get('my_param') respectively.

javac is not recognized as an internal or external command, operable program or batch file

Run the following from the command prompt: set Path="C:\Program Files\Java\jdk1.7.0_09\bin" or set PATH="C:\Program Files\Java\jdk1.7.0_09\bin"

I have tried this and it works well.

call javascript function onchange event of dropdown list

You just try this, Its so easy

 <script>

  $("#YourDropDownId").change(function () {
            alert($("#YourDropDownId").val());
        });

</script>

'Java' is not recognized as an internal or external command

Assume, Java/JDK is installed to the folder: C:\Program Files\Java:

Java/JDK installation path

Follow the steps:

  1. Goto Control Panel ? System ? Advanced system settings ? Advanced ? Environment variables (Win+Pause/Break for System in Control Panel)
  2. In the System variables section click on New…
  3. In Variable name write: JAVA_HOME
  4. In Variable value write: C:\Program Files\Java\bin, press OK: Add JAVA_HOME
  5. In the System variables section double click on Path
  6. Press New and write C:\Program Files\Java\bin, press OK: Add Java Path
  7. In Environment variables window press OK
  8. Restart/Run cmd.exe and write: java --version: Java version CMD

How can I hide a checkbox in html?

You need to add the element type to the class, otherwise it will not work.

_x000D_
_x000D_
.hide-checkbox { display: none }        /* This will not work! */_x000D_
input.hide-checkbox { display: none }   /* But this will. */ 
_x000D_
<input class="hide-checkbox" id="checkbox" />_x000D_
<label for="checkbox">Checkbox</label>
_x000D_
_x000D_
_x000D_

It looks too simple, but try it out!

How to replace a string in a SQL Server Table Column

You can use this query

update table_name set column_name = replace (column_name , 'oldstring' ,'newstring') where column_name like 'oldstring%'

401 Unauthorized: Access is denied due to invalid credentials

I realize its an old question, but this came up in my searches. Had a similar issue for an MVC application recently built, deployed for the first time, and Authentication mechanism wasn't completely hashed out.

It wasn't an IIS setting in my case, it was a Controller that was not [AllowAnonymous] decorated. I was using a Render.Action/Html.Action in a Layout.cshtml and the User was unauthenticated. So the Layout tried to load an Authenticated Action in an UnAuthenticated context.

Once I updated the action to AllowAnonymous, the problem went away, and this is what led me to it.

Hope this helps someone.

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

try my code In JavaScript

 var settings = {
              "url": "https://myinboxhub.co.in/example",
              "method": "GET",
              "timeout": 0,
              "headers": {},
            };
        $.ajax(settings).done(function (response) {
          console.log(response);
            if (response.auth) { 
                console.log('on success');
            } 
        }).fail(function (jqXHR, exception) { 
                var msg = '';
                if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
                    
                        msg = 'Uncaught Error.\n' + jqXHR.responseText; 
                }
                if (jqXHR.status === 0) {
                        msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 413) {
                        msg = 'Image size is too large.'; 
                }  else if (jqXHR.status == 404) {
                        msg = 'Requested page not found. [404]'; 
                } else if (jqXHR.status == 405) {
                        msg = 'Image size is too large.'; 
                } else if (jqXHR.status == 500) {
                        msg = 'Internal Server Error [500].'; 
                } else if (exception === 'parsererror') {
                        msg = 'Requested JSON parse failed.'; 
                } else if (exception === 'timeout') {
                        msg = 'Time out error.'; 
                } else if (exception === 'abort') {
                        msg = 'Ajax request aborted.'; 
                } else {
                        msg = 'Uncaught Error.\n' + jqXHR.responseText; 
                }
                console.log(msg);
        });;

In PHP

header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");

run main class of Maven project

Try the maven-exec-plugin. From there:

mvn exec:java -Dexec.mainClass="com.example.Main"

This will run your class in the JVM. You can use -Dexec.args="arg0 arg1" to pass arguments.

If you're on Windows, apply quotes for exec.mainClass and exec.args:

mvn exec:java -D"exec.mainClass"="com.example.Main"

If you're doing this regularly, you can add the parameters into the pom.xml as well:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.2.1</version>
  <executions>
    <execution>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>com.example.Main</mainClass>
    <arguments>
      <argument>foo</argument>
      <argument>bar</argument>
    </arguments>
  </configuration>
</plugin>

Tell Ruby Program to Wait some amount of time

sleep 6 will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes) or sleep(6.hours).

Access properties file programmatically with Spring?

This is the finest way I got it to work:

package your.package;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class ApplicationProperties {

    private Properties properties;

    public ApplicationProperties() {
        // application.properties located at src/main/resource
        Resource resource = new ClassPathResource("/application.properties");
        try {
            this.properties = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException ex) {
            Logger.getLogger(ApplicationProperties.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getProperty(String propertyName) {
        return this.properties.getProperty(propertyName);
    }
}

Android Fragment onClick button Method

Your activity must have

public void insertIntoDb(View v) {
...
} 

not Fragment .

If you don't want the above in activity. initialize button in fragment and set listener to the same.

<Button
    android:id="@+id/btn_conferma" // + missing

Then

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

   View view = inflater.inflate(R.layout.fragment_rssitem_detail,
    container, false);
   Button button = (Button) view.findViewById(R.id.btn_conferma);
   button.setOnClickListener(new OnClickListener()
   {
             @Override
             public void onClick(View v)
             {
                // do something
             } 
   }); 
   return view;
}

Querying a linked sql server

SELECT * FROM [server].[database].[schema].[table]

This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

How to match hyphens with Regular Expression?

Is this what you are after?

MatchCollection matches = Regex.Matches(mystring, "-");

Can Javascript read the source of any web page?

<script>
    $.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('hhttps://example.com/') + '&callback=?', function (data) {
        alert(data.contents);
    });

</script>

Include jQuery and use this code to get HTML of other website. Replace example.com with your website.

This method involves an external server fetching the sites HTML & sending it to you. :)

How do I remove my IntelliJ license in 2019.3?

I think there are more solutions!

You can start the app, and here are 3 things you can do:

  1. If the app shows for the first time the "import settings" dialog and then the "create/open a project" dialog, you can click on Settings > Manage License... > Remove License, and that removes for all Jetbrains products*.
  2. If you open products like IntelliJ IDEA and have projects currently active (like the app open automatically the all IDE without prompt), then click on File > Close Project, and follow the first step.
  3. Inside any app of IntelliJ, click on Help > Register... > Remove license.

*In case you have a license for a pack of products. If not, you have to remove the license per product individually. Check the 3rd step.

Graphical user interface Tutorial in C

My favourite UI tutorials all come from zetcode.com:

These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.

How do I trap ctrl-c (SIGINT) in a C# console app

This question is very similar to:

Capture console exit C#

Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.

namespace CancelSample
{
    using System;
    using System.Threading;
    using System.Runtime.InteropServices;

    internal class Program
    {
        /// <summary>
        /// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
        /// </summary>
        /// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
        /// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);

        /// <summary>
        /// The console close handler delegate.
        /// </summary>
        /// <param name="closeReason">
        /// The close reason.
        /// </param>
        /// <returns>
        /// True if cleanup is complete, false to run other registered close handlers.
        /// </returns>
        private delegate bool ConsoleCloseHandler(int closeReason);

        /// <summary>
        ///  Event set when the process is terminated.
        /// </summary>
        private static readonly ManualResetEvent TerminationRequestedEvent;

        /// <summary>
        /// Event set when the process terminates.
        /// </summary>
        private static readonly ManualResetEvent TerminationCompletedEvent;

        /// <summary>
        /// Static constructor
        /// </summary>
        static Program()
        {
            // Do this initialization here to avoid polluting Main() with it
            // also this is a great place to initialize multiple static
            // variables.
            TerminationRequestedEvent = new ManualResetEvent(false);
            TerminationCompletedEvent = new ManualResetEvent(false);
            SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
        }

        /// <summary>
        /// The main console entry point.
        /// </summary>
        /// <param name="args">The commandline arguments.</param>
        private static void Main(string[] args)
        {
            // Wait for the termination event
            while (!TerminationRequestedEvent.WaitOne(0))
            {
                // Something to do while waiting
                Console.WriteLine("Work");
            }

            // Sleep until termination
            TerminationRequestedEvent.WaitOne();

            // Print a message which represents the operation
            Console.WriteLine("Cleanup");

            // Set this to terminate immediately (if not set, the OS will
            // eventually kill the process)
            TerminationCompletedEvent.Set();
        }

        /// <summary>
        /// Method called when the user presses Ctrl-C
        /// </summary>
        /// <param name="reason">The close reason</param>
        private static bool OnConsoleCloseEvent(int reason)
        {
            // Signal termination
            TerminationRequestedEvent.Set();

            // Wait for cleanup
            TerminationCompletedEvent.WaitOne();

            // Don't run other handlers, just exit.
            return true;
        }
    }
}

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Java finished with non-zero exit value 2 - Android Gradle

Mine got solved by enabling multiDex for debug builds.

defaultConfig {
multiDexEnabled true
}

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

CSS selector for "foo that contains bar"?

Is there any way you could programatically apply a class to the object?

<object class="hasparams">

then do

object.hasparams

Selecting with complex criteria from pandas.DataFrame

You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)

df[['A']][df.B.gt(50) & df.C.ne(900)]

df[['A']] will give you back column A in DataFrame format.

pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.

How to print like printf in Python3?

Other words printf absent in python... I'm surprised! Best code is

def printf(format, *args):
    sys.stdout.write(format % args)

Because of this form allows not to print \n. All others no. That's why print is bad operator. And also you need write args in special form. There is no disadvantages in function above. It's a standard usual form of printf function.

Reading CSV files using C#

I'd highly suggest using CsvHelper.

Here's a quick example:

public class csvExampleClass
{
    public string Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

var items = DeserializeCsvFile<List<csvExampleClass>>( csvText );

public static List<T> DeserializeCsvFile<T>(string text)
{
    CsvReader csv = new CsvReader( new StringReader( text ) );
    csv.Configuration.Delimiter = ",";
    csv.Configuration.HeaderValidated = null;
    csv.Configuration.MissingFieldFound = null;
    return (List<T>)csv.GetRecords<T>();
}

Full documentation can be found at: https://joshclose.github.io/CsvHelper

How to find the port for MS SQL Server 2008?

Here are 5 methodes i found:

  • Method 1: SQL Server Configuration Manager
  • Method 2: Windows Event Viewer
  • Method 3: SQL Server Error Logs
  • Method 4: sys.dm_exec_connections DMV
  • Method 5: Reading registry using xp_instance_regread

Method 4: sys.dm_exec_connections DMV
I think this is almost the easiest way...
DMVs return server state that can be used to monitor SQL Server Instance. We can use sys.dm_exec_connections DMV to identify the port number SQL Server Instance is listening on using below T-SQL code:

SELECT local_tcp_port
FROM   sys.dm_exec_connections
WHERE  session_id = @@SPID
GO

Result Set:
local_tcp_port
61499

(1 row(s) affected)

Method 1: SQL Server Configuration Manager

Step 1. Click Start > All Programs > Microsoft SQL Server 2012 > Configuration Tools > SQL Server Configuration Manager

Step 2. Go to SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for

Step 3. Right Click on TCP/IP and select Properties

enter image description here

Step 4. In TCP/IP Properties dialog box, go to IP Addresses tab and scroll down to IPAll group.

enter image description here

If SQL Server if configured to run on a static port it will be available in TCP Port textbox, and if it is configured on dynamic port then current port will be available in TCP Dynamic Ports textbox. Here my instance is listening on port number 61499.

The other methods you can find here: http://sqlandme.com/2013/05/01/sql-server-finding-tcp-port-number-sql-instance-is-listening-on/

How to insert a character in a string at a certain position?

If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:

    for (int i = 1; i < 100000; i *= 2) {
        String s = "00" + i;
        System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
    }

Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)

How can I debug a HTTP POST in Chrome?

Another option that may be useful is a dedicated HTTP debugging tool. There's a few available, I'd suggest HTTP Toolkit: an open-source project I've been working on (yeah, I might be biased) to solve this same problem for myself.

The main difference is usability & power. The Chrome dev tools are good for simple things, and I'd recommend starting there, but if you're struggling to understand the information there, and you need either more explanation or more power then proper focused tools can be useful!

For this case, it'll show you the full POST body you're looking for, with a friendly editor and highlighting (all powered by VS Code) so you can dig around. It'll give you the request & response headers of course, but with extra info like docs from MDN (the Mozilla Developer Network) for every standard header and status code you can see.

A picture is worth a thousand StackOverflow answers:

A screenshot of HTTP Toolkit showing a POST request and its body

How to put sshpass command inside a bash script?

1 - You can script sshpass's ssh command like this:

#!/bin/bash

export SSHPASS=password
sshpass -e ssh -oBatchMode=no user@host

2 - You can script sshpass's sftp commandlike this:

#!/bin/bash

export SSHPASS=password

sshpass -e sftp -oBatchMode=no -b - user@host << !
   put someFile
   get anotherFile
   bye
!

When should the xlsm or xlsb formats be used?

The XLSB format is also dedicated to the macros embeded in an hidden workbook file located in excel startup folder (XLSTART).

A quick & dirty test with a xlsm or xlsb in XLSTART folder:

Measure-Command { $x = New-Object -com Excel.Application ;$x.Visible = $True ; $x.Quit() }

0,89s with a xlsb (binary) versus 1,3s with the same content in xlsm format (xml in a zip file) ... :)

GROUP_CONCAT ORDER BY

In IMPALA, not having order in the GROUP_CONCAT can be problematic, over at Coders'Co. we have some sort of a workaround for that (we need it for Rax/Impala). If you need the GROUP_CONCAT result with an ORDER BY clause in IMPALA, take a look at this blog post: http://raxdb.com/blog/sorting-by-regex/

How can I scroll a web page using selenium webdriver in python?

This code scrolls to the bottom but doesn't require that you wait each time. It'll continually scroll, and then stop at the bottom (or timeout)

from selenium import webdriver
import time

driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://example.com')

pre_scroll_height = driver.execute_script('return document.body.scrollHeight;')
run_time, max_run_time = 0, 1
while True:
    iteration_start = time.time()
    # Scroll webpage, the 100 allows for a more 'aggressive' scroll
    driver.execute_script('window.scrollTo(0, 100*document.body.scrollHeight);')

    post_scroll_height = driver.execute_script('return document.body.scrollHeight;')

    scrolled = post_scroll_height != pre_scroll_height
    timed_out = run_time >= max_run_time

    if scrolled:
        run_time = 0
        pre_scroll_height = post_scroll_height
    elif not scrolled and not timed_out:
        run_time += time.time() - iteration_start
    elif not scrolled and timed_out:
        break

# closing the driver is optional 
driver.close()

This is much faster than waiting 0.5-3 seconds each time for a response, when that response could take 0.1 seconds

Making a POST call instead of GET using urllib2

Try this instead:

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
req = urllib2.Request(url=url,data=data)
content = urllib2.urlopen(req).read()
print content

Get value from input (AngularJS)

If your markup is bound to a controller, directive or anything else with a $scope:

console.log($scope.movie);

Find a file by name in Visual Studio Code

It is CMD + P (or CTRL + P) by default. However the keyboard bindings may differ according to your preferences.

To know your bindings go to the "Keyboard Shortcuts" settings and search for "Go to File"

How to define static constant in a class in swift

If I understand your question correctly, you are asking how you can create class level constants (static - in C++ parlance) such that you don't a) replicate the overhead in every instance, and b have to recompute what is otherwise constant.

The language has evolved - as every reader knows, but as I test this in Xcode 6.3.1, the solution is:

import Swift

class MyClass {
    static let testStr = "test"
    static let testStrLen = count(testStr)

    init() {
        println("There are \(MyClass.testStrLen) characters in \(MyClass.testStr)")
    }
}

let a = MyClass()

// -> There are 4 characters in test

I don't know if the static is strictly necessary as the compiler surely only adds only one entry per const variable into the static section of the binary, but it does affect syntax and access. By using static, you can refer to it even when you don't have an instance: MyClass.testStrLen.

Pandas - How to flatten a hierarchical index in columns

And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:

In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
 'WBAN',
 'day',
 'month',
 's_CDsum',
 's_CLsum',
 's_CNTsum',
 's_PCsum',
 'tempfamax',
 'tempfamin',
 'year']

In [2]: df.columns = new_cols

How to insert current datetime in postgresql insert query

For current datetime, you can use now() function in postgresql insert query.

You can also refer following link.

insert statement in postgres for data type timestamp without time zone NOT NULL,.

How to recover deleted rows from SQL server table?

What is gone is gone. The only protection I know of is regular backup.

How to close IPython Notebook properly?

Option 1

Open a different console and run

jupyter notebook stop [PORT]

The default [PORT] is 8888, so, assuming that Jupyter Notebooks is running on port 8888, just run

jupyter notebook stop

If it is on port 9000, then

jupyter notebook stop 9000

Option 2 (Source)

  1. Check runtime folder location

    jupyter --paths
    
  2. Remove all files in the runtime folder

    rm -r [RUNTIME FOLDER PATH]/*
    
  3. Use top to find any Jupyter Notebook running processes left and if so kill their PID.

    top | grep jupyter &
    kill [PID]
    

One can boilt it down to

TARGET_PORT=8888
kill -9 $(lsof -n -i4TCP:$TARGET_PORT | cut -f 2 -d " ")

Note: If one wants to launch one's Notebook on a specific IP/Port

jupyter notebook --ip=[ADD_IP] --port=[ADD_PORT] --allow-root &

Foreach with JSONArray and JSONObject

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

Automatically accept all SDK licences

Turns out if you didn't install any SDK, Android Studio also shown "you haven't accept the license"...Such deceiving message, normal people would assume it implied SDK were already installed but anyway. In the Studio's SDK manager, you can just manually select the missing sdk to download and install and it handles license too. You just need to restart the Android Studio.

Here is a YT video showing your where SDK manager is.

How can I create a product key for my C# application?

Whether it's trivial or hard to crack, I'm not sure that it really makes much of a difference.

The likelihood of your app being cracked is far more proportional to its usefulness rather than the strength of the product key handling.

Personally, I think there are two classes of user. Those who pay. Those who don't. The ones that do will likely do so with even the most trivial protection. Those who don't will wait for a crack or look elsewhere. Either way, it won't get you any more money.

Change font-weight of FontAwesome icons?

Another solution I've used to create lighter fontawesome icons, similar to the webkit-text-stroke approach but more portable, is to set the color of the icon to the same as the background (or transparent) and use text-shadow to create an outline:

.fa-outline-dark-gray {
    color: #fff;
    text-shadow: -1px -1px 0 #999,
            1px -1px 0 #999,
           -1px 1px 0 #999,
            1px 1px 0 #999;
}

It doesn't work in ie <10, but at least it's not restricted to webkit browsers.

How to open generated pdf using jspdf in new window

I have to use this to load the PDF directly. Using doc.output('dataurlnewwindow'); produces an ugly iframe for me. Mac/Chrome.

  var string = doc.output('datauristring');
  var x = window.open();
  x.document.open();
  x.document.location=string;

Add borders to cells in POI generated Excel File

a Helper function:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);

Disable Tensorflow debugging information

I have had this problem as well (on tensorflow-0.10.0rc0), but could not fix the excessive nose tests logging problem via the suggested answers.

I managed to solve this by probing directly into the tensorflow logger. Not the most correct of fixes, but works great and only pollutes the test files which directly or indirectly import tensorflow:

# Place this before directly or indirectly importing tensorflow
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)

PHP - count specific array values

$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

Execute and get the output of a shell command in node.js

Thanks to Renato answer, I have created a really basic example:

const exec = require('child_process').exec

exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))

It will just print your global git username :)

PL/SQL block problem: No data found error

Might be worth checking online for the errata section for your book.

There's an example of handling this exception here http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm

git cherry-pick says "...38c74d is a merge but no -m option was given"

The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.

So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?

You're trying to cherry pick fd9f578, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m option. For example, git cherry-pick -m 1 fd9f578 to use parent 1 as the base.

I can't say for sure for your particular situation, but using git merge instead of git cherry-pick is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

Excel VBA - select a dynamic cell range

So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

How can I call a WordPress shortcode within a template?

Make sure to enable the use of shortcodes in text widgets.

// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );

// and then you can use it in any PHP file:  
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>

Check the documentation for more.

How to communicate between Docker containers via "hostname"

As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.

If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address.

Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:

wordpress:                                                                         
  image: wordpress:4.1                                                             
  stateful: true                                                                   
  ports:                                                                           
    - 80:80                                                                      
  links:                                                                           
    - mysql:wordpress-mysql                                                        
  environment:                                                                     
    - WORDPRESS_DB_HOST=wordpress-mysql.kontena.local                              
    - WORDPRESS_DB_PASSWORD=secret                                                 
mysql:                                                                             
  image: mariadb:5.5                                                               
  stateful: true                                                                   
  environment:                                                                     
    - MYSQL_ROOT_PASSWORD=secret

Move to next item using Java 8 foreach loop in stream

The lambda you are passing to forEach() is evaluated for each element received from the stream. The iteration itself is not visible from within the scope of the lambda, so you cannot continue it as if forEach() were a C preprocessor macro. Instead, you can conditionally skip the rest of the statements in it.

How to `wget` a list of URLs in a text file?

Run it in parallel with

cat text_file.txt | parallel --gnu "wget {}"

Routing for custom ASP.NET MVC 404 Error page

I will talk about some specific cases,

if you are using 'PageNotFound method' in HomeController like below

[Route("~/404")]
public ActionResult PageNotFound()
{
  return MyView();
}

it wouldn't work this. But you must clear Route tags like below,

//[Route("~/404")]
public ActionResult PageNotFound()
{
  return MyView();
}

And if you change it as method Name in web.config it works. However don't forget to do code like below in web.config

<customErrors mode="On">
  <error statusCode="404" redirect="~/PageNotFound" /> 
 *// it is not "~/404" because it is not accepted url in Route Tag like [Route("404")]*
</customErrors>

Right way to split an std::string into a vector<string>

std::vector<std::string> split(std::string text, char delim) {
    std::string line;
    std::vector<std::string> vec;
    std::stringstream ss(text);
    while(std::getline(ss, line, delim)) {
        vec.push_back(line);
    }
    return vec;
}

split("String will be split", ' ') -> {"String", "will", "be", "split"}

split("Hello, how are you?", ',') -> {"Hello", "how are you?"}

EDIT: Here's a thing I made, this can use multi-char delimiters, albeit I'm not 100% sure if it always works:

std::vector<std::string> split(std::string text, std::string delim) {
    std::vector<std::string> vec;
    size_t pos = 0, prevPos = 0;
    while (1) {
        pos = text.find(delim, prevPos);
        if (pos == std::string::npos) {
            vec.push_back(text.substr(prevPos));
            return vec;
        }

        vec.push_back(text.substr(prevPos, pos - prevPos));
        prevPos = pos + delim.length();
    }
}

Auto-increment primary key in SQL tables

  1. Presumably you are in the design of the table. If not: right click the table name - "Design".
  2. Click the required column.
  3. In "Column properties" (at the bottom), scroll to the "Identity Specification" section, expand it, then toggle "(Is Identity)" to "Yes".

enter image description here

Run-time error '1004' - Method 'Range' of object'_Global' failed

Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.

http://www.bettersolutions.com/excel/EED883/YI416010881.htm

Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales

This should fix your problem.

How do I send a cross-domain POST request via JavaScript?

If you have access to the cross domain server and don't want to make any code changes on server side, you can use a library called - 'xdomain'.

How it works:

Step 1: server 1: include the xdomain library and configure the cross domain as a slave:

<script src="js/xdomain.min.js" slave="https://crossdomain_server/proxy.html"></script>

Step 2: on cross domain server, create a proxy.html file and include server 1 as a master:

proxy.html:
<!DOCTYPE HTML>
<script src="js/xdomain.min.js"></script>
<script>
  xdomain.masters({
    "https://server1" : '*'
  });
</script>

Step 3:

Now, you can make an AJAX call to the proxy.html as endpoint from server1. This is bypass the CORS request. The library internally uses iframe solution which works with Credentials and all possible methods: GET, POST etc.

Query ajax code:

$.ajax({
        url: 'https://crossdomain_server/proxy.html',
        type: "POST",
        data: JSON.stringify(_data),
        dataType: "json",
        contentType: "application/json; charset=utf-8"
    })
    .done(_success)
    .fail(_failed)

ES6 Map in Typescript

See comment in: https://github.com/Microsoft/TypeScript/issues/3069#issuecomment-99964139

TypeScript does not come with built in pollyfills. it is up to you to decide which pollyfill to use, if any. you can use something like es6Collection, es6-shims, corejs..etc. All the Typescript compiler needs is a declaration for the ES6 constructs you want to use. you can find them all in this lib file.

here is the relevant portion:

interface Map<K, V> {
    clear(): void;
    delete(key: K): boolean;
    entries(): IterableIterator<[K, V]>;
    forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
    get(key: K): V;
    has(key: K): boolean;
    keys(): IterableIterator<K>;
    set(key: K, value?: V): Map<K, V>;
    size: number;
    values(): IterableIterator<V>;
    [Symbol.iterator]():IterableIterator<[K,V]>;
    [Symbol.toStringTag]: string;
}

interface MapConstructor {
    new <K, V>(): Map<K, V>;
    new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
    prototype: Map<any, any>;
}
declare var Map: MapConstructor;

Dependent DLL is not getting copied to the build output folder in Visual Studio

Not sure if this helps but for me, many times I reference a DLL (which automatically adds it to the bin folder of course). However that DLL might need additional DLLs (depending on what functions I'm using). I do NOT want to reference those in my Project because they just simply need to end up in the same folder as the DLL I am actually using.

I accomplish this in Visual Studio by "Adding an existing file". You should be able to add it anywhere except the Add_data folder. personally I just add it to the root.

Then change the properties of that file to ...

Build Action = None (having this set to something like Content actually copies the "root" version to the root, plus a copy in the Bin).

Copy to output folder = Copy if Newer (Basically puts it in the BIN folder only if it is missing, but doesn't do it after that)

When I publish.. my added DLL's only exists in the BIN folder and nowhere else in the Publish location (which is what I want).

Listing only directories using ls in Bash?

Here is a variation using tree which outputs directory names only on separate lines, yes it's ugly, but hey, it works.

tree -d | grep -E '^[+|+]' | cut -d ' ' -f2

or with awk

tree -d | grep -E '^[+|+]' | awk '{print $2}'

This is probably better however and will retain the / after directory name.

ls -l | grep "^d" | awk '{print $9}'

How to test whether a service is running from the command line

Thinking a little bit outside the box here I'm going to propose that powershell may be an answer on up-to-date XP/2003 machines and certainly on Vista/2008 and newer (instead of .bat/.cmd). Anyone who has some Perl in their background should feel at-home pretty quickly.


$serviceName = "ServiceName";
$serviceStatus = (get-service "$serviceName").Status;

if ($serviceStatus -eq "Running") {
    echo "Service is Running";
}
else {
    #Could be Stopped, Stopping, Paused, or even Starting...
    echo "Service is $serviceStatus";
}

Another way, if you have significant investment in batch is to run the PS script as a one-liner, returning an exit code.


@ECHO off
SET PS=powershell -nologo -command
%PS% "& {if((get-service SvcName).Status -eq 'Running'){exit 1}}"

ECHO.%ERRORLEVEL%

Running as a one-liner also gets around the default PS code signing policy at the expense of messiness. To put the PS commands in a .ps1 file and run like powershell myCode.ps1 you may find signing your powershell scripts is neccessary to run them in an automated way (depends on your environment). See http://www.hanselman.com/blog/SigningPowerShellScripts.aspx for details

Interactive shell using Docker Compose

You can do docker-compose exec SERVICE_NAME sh on the command line. The SERVICE_NAME is defined in your docker-compose.yml. For example,

services:
    zookeeper:
        image: wurstmeister/zookeeper
        ports:
          - "2181:2181"

The SERVICE_NAME would be "zookeeper".

Create an enum with string values

TypeScript 2.1 +

Lookup types, introduced in TypeScript 2.1 allow another pattern for simulating string enums:

// String enums in TypeScript 2.1
const EntityType = {
    Foo: 'Foo' as 'Foo',
    Bar: 'Bar' as 'Bar'
};

function doIt(entity: keyof typeof EntityType) {
    // ...
}

EntityType.Foo          // 'Foo'
doIt(EntityType.Foo);   // 
doIt(EntityType.Bar);   // 
doIt('Foo');            // 
doIt('Bad');            //  

TypeScript 2.4 +

With version 2.4, TypeScript introduced native support for string enums, so the solution above is not needed. From the TS docs:

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}

How to Update/Drop a Hive Partition?

You may also need to make database containing table active

use [dbname]

otherwise you may get error (even if you specify database i.e. dbname.table )

FAILED Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter partition. Unable to alter partitions because table or database does not exist.

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

How to discover number of *logical* cores on Mac OS X?

This should be cross platform. At least for Linux and Mac OS X.

python -c 'import multiprocessing as mp; print(mp.cpu_count())'

A little bit slow but works.

What is callback in Android?

CallBack Interface are used for Fragment to Fragment communication in android.

Refer here for your understanding.

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

Get current directory name (without full path) in a Bash script

You can use a combination of pwd and basename. E.g.

#!/bin/bash

CURRENT=`pwd`
BASENAME=`basename "$CURRENT"`

echo "$BASENAME"

exit;

How to trigger a phone call when clicking a link in a web page on mobile phone

Essentially, use an <a> element with an href attr pointing to the phone number prefixed by tel:. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.

MDN Web Docs

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link

The HTML <a> element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

[…]

Offering phone links is helpful for users viewing web documents and laptops connected to phones.

<a href="tel:+491570156">+49 157 0156</a>

IETF Documents

https://tools.ietf.org/html/rfc3966

The tel URI for Telephone Numbers

The "tel" URI has the following syntax:

telephone-uri = "tel:" telephone-subscriber

[…]

Examples

tel:+1-201-555-0123: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.

tel:7042;phone-context=example.com: The URI describes a local phone number valid within the context "example.com".

tel:863-1234;phone-context=+1-914-555: The URI describes a local phone number that is valid within a particular phone prefix.

Class Not Found Exception when running JUnit test

1- mvn eclipse:eclipse

2- project clean all projects

3- restart

Listing only directories in UNIX

Try this ls -d */ to list directories within the current directory

Playing .mp3 and .wav in Java?

It's been a while since I used it, but JavaLayer is great for MP3 playback

MySQL - Using COUNT(*) in the WHERE clause

I'm not sure about what you're trying to do... maybe something like

SELECT gid, COUNT(*) AS num FROM gd GROUP BY gid HAVING num > 10 ORDER BY lastupdated DESC

Multiline editing in Visual Studio Code

On Windows, you hold Ctrl+Alt while pressing the up ? or down ? arrow keys to add cursors.

Mac: ? Opt+? Cmd+?/?

Linux: Shift+Alt+?/?

Note that third-party software may interfere with these shortcuts, preventing them from working as intended (particularly Intel's HD Graphics software on Windows; see comments for more details).

If you experience this issue, you can either disable the Intel/other software hotkeys, or modify the VS Code shortcuts (described below).

Press Esc to reset to a single cursor.

Multiline cursors in Visual Studio Code

Or, as Isidor Nikolic points out, you can hold Alt and left click to place cursors arbitrarily.

Arbitrarily placed multiline cursors in Visual Studio Code

You can view and edit keyboard shortcuts via:

File ? Preferences ? Keyboard Shortcuts

Documentation:

https://code.visualstudio.com/docs/customization/keybindings

Official VS Code Keyboard shortcut cheat sheets:

https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf
https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf
https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Jquery open popup on button click for bootstrap

Below mentioned link gives the clear explanation with example.

http://www.aspsnippets.com/Articles/Open-Show-jQuery-UI-Dialog-Modal-Popup-on-Button-Click.aspx

Code from the same link

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
    rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("#dialog").dialog({
            modal: true,
            autoOpen: false,
            title: "jQuery Dialog",
            width: 300,
            height: 150
        });
        $("#btnShow").click(function () {
            $('#dialog').dialog('open');
        });
    });
</script>
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
    This is a jQuery Dialog.
</div>

Rails 3 execute custom sql query without a model

Maybe try this:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

How to find patterns across multiple lines using grep?

With silver searcher:

ag 'abc.*(\n|.)*efg'

similar to ring bearer's answer, but with ag instead. Speed advantages of silver searcher could possibly shine here.

node.js Error: connect ECONNREFUSED; response from server

I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

First letter capitalization for EditText

Set input type in XML as well as in JAVA file like this,

In XML,

android:inputType="textMultiLine|textCapSentences"

It will also allow multiline and in JAVA file,

edittext.setRawInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

make sure your keyboard's Auto-Capitalization setting is Enabled.

Change onclick action with a Javascript function

var Foo = function(){
    document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}

var Boo = function(){
    alert("test");
}

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

Can you use a trailing comma in a JSON object?

Unfortunately the JSON specification does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.

In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:

s.append("[");
for (i = 0; i < 5; ++i) {
  if (i) s.append(","); // add the comma only if this isn't the first entry
  s.appendF("\"%d\"", i);
}
s.append("]");

That extra one line of code in your for loop is hardly expensive...

Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).

Doesn't work well with an array unfortunately.

How to replace NaNs by preceding values in pandas DataFrame?

You can use fillna to remove or replace NaN values.

NaN Remove

import pandas as pd

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])

df.fillna(method='ffill')
     0    1    2
0  1.0  2.0  3.0
1  4.0  2.0  3.0
2  4.0  2.0  9.0

NaN Replace

df.fillna(0) # 0 means What Value you want to replace 
     0    1    2
0  1.0  2.0  3.0
1  4.0  0.0  0.0
2  0.0  0.0  9.0

Reference pandas.DataFrame.fillna

How do I get console input in javascript?

You can try something like process.argv, that is if you are using node.js to run the program.
console.log(process.argv) => Would print an array containing

[                                                                                                                                                                                          
  '/usr/bin/node',                                                                                                                                                                         
  '/home/user/path/filename.js',                                                                                                                                            
  'your_input'                                                                                                                                                                                   
]

You get the user provided input via array index, i.e., console.log(process.argv[3]) This should provide you with the input which you can store.


Example:

var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two

console.log(somevariable);
console.log(somevariable2);

If you are building a command-line program then the npm package yargs would be really helpful.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How to deploy a war file in Tomcat 7

You can access your application from: http://localhost:8080/sample

Deploying or redeploying of war files is automatic by default - after copying/overwriting the file sample.war, check your webapps folder for an extracted folder sample.

If it doesn't open properly, check the log files (e.g. tomcat/logs/catalina.out) for problems with deployment.

Adding Buttons To Google Sheets and Set value to Cells on clicking

It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.

You can use following code to insert an image through script.

  function insertImageOnSpreadsheet() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'https://developers.google.com/adwords/scripts/images/reports.png');
  var binaryData = response.getContent();

  // Insert the image in cell A1.
  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1);
}

Above example has been copied from this link. Check noogui's reply for details.

In case you need to insert image from Google Drive, please check this link for current updates.

Pandas aggregate count distinct

'nunique' is an option for .agg() since pandas 0.20.0, so:

df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})

Calculate distance between 2 GPS coordinates

This is version from "Henry Vilinskiy" adapted for MySQL and Kilometers:

CREATE FUNCTION `CalculateDistanceInKm`(
  fromLatitude float,
  fromLongitude float,
  toLatitude float, 
  toLongitude float
) RETURNS float
BEGIN
  declare distance float;

  select 
    6367 * ACOS(
            round(
              COS(RADIANS(90-fromLatitude)) *
                COS(RADIANS(90-toLatitude)) +
                SIN(RADIANS(90-fromLatitude)) *
                SIN(RADIANS(90-toLatitude)) *
                COS(RADIANS(fromLongitude-toLongitude))
              ,15)
            )
    into distance;

  return  round(distance,3);
END;

What is cURL in PHP?

cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

You can make HTTP requests without cURL, too, though it requires allow_url_fopen to be enabled in your php.ini file.

// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

It is working for me.

Get in Timestamp type:

public static Timestamp getCurrentTimestamp() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    final Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    Timestamp ts = new Timestamp(date.getTime());
    return ts;
}

Get in String type:

    public static String getCurrentTimestamp() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    final Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    Timestamp ts = new Timestamp(date.getTime());
    return ts.toString();
}

Adding a new value to an existing ENUM Type

If you are using Postgres 12 you can just run ALTER TYPE ... ADD VALUE inside of transaction (documentation).

If ALTER TYPE ... ADD VALUE (the form that adds a new value to an enum type) is executed inside a transaction block, the new value cannot be used until after the transaction has been committed.

So no hacks needed in migrations.

UPD: here is an example (thanks to Nick for it)

ALTER TYPE enum_type ADD VALUE 'new_value';

Is there a way to run Bash scripts on Windows?

You can always install Cygwin to run a Unix shell under Windows. I used Cygwin extensively with Window XP.

How can I use querySelector on to pick an input element by name?

So ... you need to change some things in your code

<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>

<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;

function checkForm() {
  alert(pwd.value);
}
</script>

Try this way.

String is immutable. What exactly is the meaning?

see here

class ImmutableStrings {

    public static void main(String[] args) {
        testmethod();
    }

    private static void testmethod() {
    String a="a";
    System.out.println("a 1-->"+a);
    System.out.println("a 1 address-->"+a.hashCode());

    a = "ty";
    System.out.println("a 2-->"+a);

       System.out.println("a 2 address-->"+a.hashCode());
    }
}

output:

a 1-->a
a 1 address-->97
a 2-->ty
a 2 address-->3717

This indicates that whenever you are modifying the content of immutable string object a a new object will be created. i.e you are not allowed to change the content of immutable object. that's why the address are different for both the object.

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

On the documentation:

http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat

It says:

(...) if you know the matrix element type, e.g. it is float, then you can use at<>() method

That is, you can use:

Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);

Maybe it is easier to use the Mat_ class. It is a template wrapper for Mat. Mat_ has the operator() overloaded in order to access the elements.

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

Have you tried just using the mysql command line client directly?

mysql -u username -p -h hostname databasename < dump.sql

If you can't do that, there are any number of utilities you can find by Googling that help you import a large dump into MySQL, like BigDump

GIT vs. Perforce- Two VCS will enter... one will leave

The one important difference between Perforce and git (and the one most commonly mentioned) is their respective handling of huge binary files.

Like, for example, in this blog of an employee at a video game development company: http://corearchitecture.blogspot.com/2011/09/git-vs-perforce-from-game-development.html

However, the important thing is that, the speed difference between git and perforce, when you have a huge 6gb repository, containing everything from documentation to every binary ever built (and finally, oh yes! the actual source history), usually comes from the fact that huge companies tend to run Perforce, and so they set it up to offload all significant operations to the huge server bank in the basement.

This important advantage on Perforce's part comes only from a factor that has nothing whatsoever to do with Perforce, the fact that the company running it can afford said server bank.

And, anyway, in the end, Perforce and git are different products. Git was designed to be solely a VCS, and it does this far better than Perforce (in that it has more features, which are generally easier to use, in particular, in the words of another, branching in Perforce is like performing open-heart surgery, it should only be done by experts :P ) ( http://stevehanov.ca/blog/index.php?id=50 )

Any other benefits which companies that use Perforce gain have come merely because Perforce is not solely a VCS, it's also a fileserver, as well as having a host of other features for testing the performance of builds, etc.

Finally: Git being open-source and far more flexible to boot, it would not be so hard to patch git to offload important operations to a central server, running mounds of expensive hardware.

What is the curl error 52 "empty reply from server"?

It happens when you are trying to access secure Website like Https.

I hope you missed 's'

Try Changing URL to curl -sS -u "username:password" https://www.example.com/backup.php

Hiding the address bar of a browser (popup)

Looking for the same, the only thing I'm able to do is

Launch Google Chrome in app mode

Chrome.exe --app="<address>"

From the run prompt. Example:

Chrome.exe --app="http://www.google.com"

Hide the address bar in Mozilla Firefox

Type about:config in the address bar, the search for:

dom.disable_window_open_feature.location

And set it to false

So, when you open a popup window, it will launch with the address bar hidden. For example:

window.open("http://www.google.com",'','postwindow');

Firefox without location bar

Chrome in app mode

Now, I'm looking to do something similar with Microsoft Edge, I have not found anything yet for this browser.

Control the size of points in an R scatterplot?

Try the cex argument:

?par

  • cex
    A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points accept a vector of values which are recycled. Other uses will take just the first value if a vector of length greater than one is supplied.

Android background music service

@Synxmax's answer is correct when using a Service and the MediaPlayer class, however you also need to declare the Service in the Manifest for this to work, like so:

<service
    android:enabled="true"
    android:name="com.package.name.BackgroundSoundService" />

Print "hello world" every X seconds

For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs.

See tutorials for Quartz scheduling.

How do I disable a Button in Flutter?

For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its ignoring property is set to true, the sub-widget (actually, the entire subtree) is not clickable.

IgnorePointer(
    ignoring: true, // or false
    child: RaisedButton(
        onPressed: _logInWithFacebook,
        child: Text("Facebook sign-in"),
        ),
),

Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().

Adding external library in Android studio

Turn any github project into a single line gradle implementation with this website

https://jitpack.io/

Example, I needed this project: https://github.com/mik3y/usb-serial-for-android

All I did was paste this into my gradle file:

implementation 'com.github.mik3y:usb-serial-for-android:master-SNAPSHOT'

Offline Speech Recognition In Android (JellyBean)

In short, I don't have the implementation, but the explanation.

Google did not make offline speech recognition available to third party apps. Offline recognition is only accessable via the keyboard. Ben Randall (the developer of utter!) explains his workaround in an article at Android Police:

I had implemented my own keyboard and was switching between Google Voice Typing and the users default keyboard with an invisible edit text field and transparent Activity to get the input. Dirty hack!

This was the only way to do it, as offline Voice Typing could only be triggered by an IME or a system application (that was my root hack) . The other type of recognition API … didn't trigger it and just failed with a server error. … A lot of work wasted for me on the workaround! But at least I was ready for the implementation...

From Utter! Claims To Be The First Non-IME App To Utilize Offline Voice Recognition In Jelly Bean

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

In addition to the answers above, you could encounter this error if your client is running the wrong TLS version, for example if the server is only running TLS 1.2.

You can fix it by using:

// tested in .NET 4.5:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

How to override toString() properly in Java?

Following code is a sample. Question based on the same, instead of using IDE based conversion, is there a faster way to implement so that in future the changes occur, we do not need to modify the values over and over again?

@Override
    public String toString() {
        return "ContractDTO{" +
                "contractId='" + contractId + '\'' +
                ", contractTemplateId='" + contractTemplateId + '\'' +
                '}';
    }

Edit In Place Content Editing

I was looking for a inline editing solution and I found a plunker that seemed promising, but it didn't work for me out of the box. After some tinkering with the code I got it working. Kudos to the person who made the initial effort to code this piece.

The example is available here http://plnkr.co/edit/EsW7mV?p=preview

Here goes the code:

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

  $scope.updateTodo = function(indx) {
    console.log(indx);
  };

  $scope.cancelEdit = function(value) {
    console.log('Canceled editing', value);
  };

  $scope.todos = [
    {id:123, title: 'Lord of the things'},
    {id:321, title: 'Hoovering heights'},
    {id:231, title: 'Watership brown'}
  ];
});

// On esc event
app.directive('onEsc', function() {
  return function(scope, elm, attr) {
    elm.bind('keydown', function(e) {
      if (e.keyCode === 27) {
        scope.$apply(attr.onEsc);
      }
    });
  };
});

// On enter event
app.directive('onEnter', function() {
  return function(scope, elm, attr) {
    elm.bind('keypress', function(e) {
      if (e.keyCode === 13) {
        scope.$apply(attr.onEnter);
      }
    });
  };
});

// Inline edit directive
app.directive('inlineEdit', function($timeout) {
  return {
    scope: {
      model: '=inlineEdit',
      handleSave: '&onSave',
      handleCancel: '&onCancel'
    },
    link: function(scope, elm, attr) {
      var previousValue;

      scope.edit = function() {
        scope.editMode = true;
        previousValue = scope.model;

        $timeout(function() {
          elm.find('input')[0].focus();
        }, 0, false);
      };
      scope.save = function() {
        scope.editMode = false;
        scope.handleSave({value: scope.model});
      };
      scope.cancel = function() {
        scope.editMode = false;
        scope.model = previousValue;
        scope.handleCancel({value: scope.model});
      };
    },
    templateUrl: 'inline-edit.html'
  };
});

Directive template:

<div>
  <input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
  <button ng-click="cancel()" ng-show="editMode">cancel</button>
  <button ng-click="save()" ng-show="editMode">save</button>
  <span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
    <span ng-hide="editMode" ng-click="edit()">{{model}}</span>
    <a ng-show="showEdit" ng-click="edit()">edit</a>
  </span>
</div>

To use it just add water:

<div ng-repeat="todo in todos" 
     inline-edit="todo.title" 
     on-save="updateTodo($index)" 
     on-cancel="cancelEdit(todo.title)"></div>

UPDATE:

Another option is to use the readymade Xeditable for AngularJS:

http://vitalets.github.io/angular-xeditable/

MySQL Multiple Joins in one query?

Just add another join:

SELECT dashboard_data.headline,
       dashboard_data.message,
       dashboard_messages.image_id,
       images.filename 
FROM dashboard_data 
    INNER JOIN dashboard_messages
            ON dashboard_message_id = dashboard_messages.id 
    INNER JOIN images
            ON dashboard_messages.image_id = images.image_id

How to define an enum with string value?

I created a base class for creating string-valued enums in .NET. It is just one C# file that you can copy & paste into your projects, or install via NuGet package named StringEnum.

Usage:

///<completionlist cref="HexColor"/> 
class HexColor : StringEnum<HexColor>
{
    public static readonly HexColor Blue = New("#FF0000");
    public static readonly HexColor Green = New("#00FF00");
    public static readonly HexColor Red = New("#000FF");
}

Features

  • Your StringEnum looks somewhat similar to a regular enum:
    // Static Parse Method
    HexColor.Parse("#FF0000") // => HexColor.Red
    HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
    HexColor.Parse("invalid") // => throws InvalidOperationException

    // Static TryParse method.
    HexColor.TryParse("#FF0000") // => HexColor.Red
    HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
    HexColor.TryParse("invalid") // => null

    // Parse and TryParse returns the preexistent instances
    object.ReferenceEquals(HexColor.Parse("#FF0000"), HexColor.Red) // => true

    // Conversion from your `StringEnum` to `string`
    string myString1 = HexColor.Red.ToString(); // => "#FF0000"
    string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
  • Intellisense will suggest the enum name if the class is annotated with the xml comment <completitionlist>. (Works in both C# and VB): i.e.

Intellisense demo

Instalation

Either:

  • Install latest StringEnum NuGet package, which is based on .Net Standard 1.0 so it runs on .Net Core >= 1.0, .Net Framework >= 4.5, Mono >= 4.6, etc.
  • Or paste the following StringEnum base class to your project. (latest version)
    public abstract class StringEnum<T> : IEquatable<T> where T : StringEnum<T>, new()
    {
        protected string Value;
        private static IList<T> valueList = new List<T>();
        protected static T New(string value)
        {
            if (value == null)
                return null; // the null-valued instance is null.

            var result = new T() { Value = value };
            valueList.Add(result);
            return result;
        }

        public static implicit operator string(StringEnum<T> enumValue) => enumValue.Value;
        public override string ToString() => Value;

        public static bool operator !=(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value != o2?.Value;
        public static bool operator ==(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value == o2?.Value;

        public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
        bool IEquatable<T>.Equals(T other) => this.Value.Equals(other.Value);
        public override int GetHashCode() => Value.GetHashCode();

        /// <summary>
        /// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else throws InvalidOperationException.
        /// </summary>
        /// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
        /// <param name="caseSensitive">If true, the strings must match case sensitivity.</param>
        public static T Parse(string value, bool caseSensitive = false)
        {
            var result = TryParse(value, caseSensitive);
            if (result == null)
                throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");

            return result;
        }

        /// <summary>
        /// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else returns null.
        /// </summary>
        /// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
        /// <param name="caseSensitive">If true, the strings must match case sensitivity.</param>
        public static T TryParse(string value, bool caseSensitive = false)
        {
            if (value == null) return null;
            if (valueList.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
            var field = valueList.FirstOrDefault(f => f.Value.Equals(value,
                    caseSensitive ? StringComparison.Ordinal
                                  : StringComparison.OrdinalIgnoreCase));
            // Not using InvariantCulture because it's only supported in NETStandard >= 2.0

            if (field == null)
                return null;

            return field;
        }
    }
  • For Newtonsoft.Json serialization support, copy this extended version instead. StringEnum.cs

I realized after the fact that this code is similar to Ben's answer. I sincerely wrote it from scratch. However I think it has a few extras, like the <completitionlist> hack, the resulting class looks more like an Enum, no use of reflection on Parse(), the NuGet package and repo where I will hopefully address incoming issues and feedback.

How can I check if a value is a json object?

Since it's just false and json object, why don't you check whether it's false, otherwise it must be json.

if(ret == false || ret == "false") {
    // json
}

Update statement with inner join on Oracle

UPDATE (SELECT T.FIELD A, S.FIELD B
FROM TABLE_T T INNER JOIN TABLE_S S
ON T.ID = S.ID)
SET B = A;

A and B are alias fields, you do not need to point the table.

Creating a Zoom Effect on an image on hover using CSS?

Simply:

.grow { transition: all .2s ease-in-out; }

This will allow the element to assign an animation via css.

.grow:hover { transform: scale(1.1); }

This will make it grow!

Error: Unable to run mksdcard SDK tool

Here's what you need to do to fix the issue on Arch Linux :

  1. Enable the multilib repository on your system if you have not already done so by uncommenting the [multilib] section in /etc/pacman.conf :

    [multilib]
    Include = /etc/pacman.d/mirrorlist
    
  2. Update pacman :

    # pacman -Suy
    
  3. Install the 32 bit version of libstdc++5 :

    # pacman -S lib32-libstdc++5
    

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

i think lodash _.get() can help here, as in _.get(user, 'name'), and more complex tasks like _.get(o, 'a[0].b.c', 'default-value')

SVG: text inside rect

This is not possible. If you want to display text inside a rect element you should put them both in a group with the text element coming after the rect element ( so it appears on top ).

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
  <g>_x000D_
    <rect x="0" y="0" width="100" height="100" fill="red"></rect>_x000D_
    <text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>_x000D_
  </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

sudo psql --host=localhost --dbname=database-name --username=postgres

This solved my issue

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I had a similar issue and searched all the internet for this problem

if you have this problem just copy your HTML code in a new HTML file and use the normal <meta charset="UTF-8"> and it will work....

just create a new HTML file in the same location and use a different name