Programs & Examples On #Media type

How to check file MIME type with javascript before upload?

You can easily determine the file MIME type with JavaScript's FileReader before uploading it to a server. I agree that we should prefer server-side checking over client-side, but client-side checking is still possible. I'll show you how and provide a working demo at the bottom.


Check that your browser supports both File and Blob. All major ones should.

if (window.FileReader && window.Blob) {
    // All the File APIs are supported.
} else {
    // File and Blob are not supported
}

Step 1:

You can retrieve the File information from an <input> element like this (ref):

<input type="file" id="your-files" multiple>
<script>
var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {
    // When the control has changed, there are new files
    var files = control.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }
}, false);
</script>

Here is a drag-and-drop version of the above (ref):

<div id="your-files"></div>
<script>
var target = document.getElementById("your-files");
target.addEventListener("dragover", function(event) {
    event.preventDefault();
}, false);

target.addEventListener("drop", function(event) {
    // Cancel default actions
    event.preventDefault();
    var files = event.dataTransfer.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }
}, false);
</script>

Step 2:

We can now inspect the files and tease out headers and MIME types.

✘ Quick method

You can naïvely ask Blob for the MIME type of whatever file it represents using this pattern:

var blob = files[i]; // See step 1 above
console.log(blob.type);

For images, MIME types come back like the following:

image/jpeg
image/png
...

Caveat: The MIME type is detected from the file extension and can be fooled or spoofed. One can rename a .jpg to a .png and the MIME type will be be reported as image/png.


✓ Proper header-inspecting method

To get the bonafide MIME type of a client-side file we can go a step further and inspect the first few bytes of the given file to compare against so-called magic numbers. Be warned that it's not entirely straightforward because, for instance, JPEG has a few "magic numbers". This is because the format has evolved since 1991. You might get away with checking only the first two bytes, but I prefer checking at least 4 bytes to reduce false positives.

Example file signatures of JPEG (first 4 bytes):

FF D8 FF E0 (SOI + ADD0)
FF D8 FF E1 (SOI + ADD1)
FF D8 FF E2 (SOI + ADD2)

Here is the essential code to retrieve the file header:

var blob = files[i]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
  var header = "";
  for(var i = 0; i < arr.length; i++) {
     header += arr[i].toString(16);
  }
  console.log(header);

  // Check the file signature against known types

};
fileReader.readAsArrayBuffer(blob);

You can then determine the real MIME type like so (more file signatures here and here):

switch (header) {
    case "89504e47":
        type = "image/png";
        break;
    case "47494638":
        type = "image/gif";
        break;
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
    case "ffd8ffe3":
    case "ffd8ffe8":
        type = "image/jpeg";
        break;
    default:
        type = "unknown"; // Or you can use the blob.type as fallback
        break;
}

Accept or reject file uploads as you like based on the MIME types expected.


Demo

Here is a working demo for local files and remote files (I had to bypass CORS just for this demo). Open the snippet, run it, and you should see three remote images of different types displayed. At the top you can select a local image or data file, and the file signature and/or MIME type will be displayed.

Notice that even if an image is renamed, its true MIME type can be determined. See below.

Screenshot

Expected output of demo


_x000D_
_x000D_
// Return the first few bytes of the file as a hex string_x000D_
function getBLOBFileHeader(url, blob, callback) {_x000D_
  var fileReader = new FileReader();_x000D_
  fileReader.onloadend = function(e) {_x000D_
    var arr = (new Uint8Array(e.target.result)).subarray(0, 4);_x000D_
    var header = "";_x000D_
    for (var i = 0; i < arr.length; i++) {_x000D_
      header += arr[i].toString(16);_x000D_
    }_x000D_
    callback(url, header);_x000D_
  };_x000D_
  fileReader.readAsArrayBuffer(blob);_x000D_
}_x000D_
_x000D_
function getRemoteFileHeader(url, callback) {_x000D_
  var xhr = new XMLHttpRequest();_x000D_
  // Bypass CORS for this demo - naughty, Drakes_x000D_
  xhr.open('GET', '//cors-anywhere.herokuapp.com/' + url);_x000D_
  xhr.responseType = "blob";_x000D_
  xhr.onload = function() {_x000D_
    callback(url, xhr.response);_x000D_
  };_x000D_
  xhr.onerror = function() {_x000D_
    alert('A network error occurred!');_x000D_
  };_x000D_
  xhr.send();_x000D_
}_x000D_
_x000D_
function headerCallback(url, headerString) {_x000D_
  printHeaderInfo(url, headerString);_x000D_
}_x000D_
_x000D_
function remoteCallback(url, blob) {_x000D_
  printImage(blob);_x000D_
  getBLOBFileHeader(url, blob, headerCallback);_x000D_
}_x000D_
_x000D_
function printImage(blob) {_x000D_
  // Add this image to the document body for proof of GET success_x000D_
  var fr = new FileReader();_x000D_
  fr.onloadend = function() {_x000D_
    $("hr").after($("<img>").attr("src", fr.result))_x000D_
      .after($("<div>").text("Blob MIME type: " + blob.type));_x000D_
  };_x000D_
  fr.readAsDataURL(blob);_x000D_
}_x000D_
_x000D_
// Add more from http://en.wikipedia.org/wiki/List_of_file_signatures_x000D_
function mimeType(headerString) {_x000D_
  switch (headerString) {_x000D_
    case "89504e47":_x000D_
      type = "image/png";_x000D_
      break;_x000D_
    case "47494638":_x000D_
      type = "image/gif";_x000D_
      break;_x000D_
    case "ffd8ffe0":_x000D_
    case "ffd8ffe1":_x000D_
    case "ffd8ffe2":_x000D_
      type = "image/jpeg";_x000D_
      break;_x000D_
    default:_x000D_
      type = "unknown";_x000D_
      break;_x000D_
  }_x000D_
  return type;_x000D_
}_x000D_
_x000D_
function printHeaderInfo(url, headerString) {_x000D_
  $("hr").after($("<div>").text("Real MIME type: " + mimeType(headerString)))_x000D_
    .after($("<div>").text("File header: 0x" + headerString))_x000D_
    .after($("<div>").text(url));_x000D_
}_x000D_
_x000D_
/* Demo driver code */_x000D_
_x000D_
var imageURLsArray = ["http://media2.giphy.com/media/8KrhxtEsrdhD2/giphy.gif", "http://upload.wikimedia.org/wikipedia/commons/e/e9/Felis_silvestris_silvestris_small_gradual_decrease_of_quality.png", "http://static.giantbomb.com/uploads/scale_small/0/316/520157-apple_logo_dec07.jpg"];_x000D_
_x000D_
// Check for FileReader support_x000D_
if (window.FileReader && window.Blob) {_x000D_
  // Load all the remote images from the urls array_x000D_
  for (var i = 0; i < imageURLsArray.length; i++) {_x000D_
    getRemoteFileHeader(imageURLsArray[i], remoteCallback);_x000D_
  }_x000D_
_x000D_
  /* Handle local files */_x000D_
  $("input").on('change', function(event) {_x000D_
    var file = event.target.files[0];_x000D_
    if (file.size >= 2 * 1024 * 1024) {_x000D_
      alert("File size must be at most 2MB");_x000D_
      return;_x000D_
    }_x000D_
    remoteCallback(escape(file.name), file);_x000D_
  });_x000D_
_x000D_
} else {_x000D_
  // File and Blob are not supported_x000D_
  $("hr").after( $("<div>").text("It seems your browser doesn't support FileReader") );_x000D_
} /* Drakes, 2015 */
_x000D_
img {_x000D_
  max-height: 200px_x000D_
}_x000D_
div {_x000D_
  height: 26px;_x000D_
  font: Arial;_x000D_
  font-size: 12pt_x000D_
}_x000D_
form {_x000D_
  height: 40px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input type="file" />_x000D_
  <div>Choose an image to see its file signature.</div>_x000D_
</form>_x000D_
<hr/>
_x000D_
_x000D_
_x000D_

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

Space between Column's children in Flutter

There are many ways of doing it, I'm listing a few here.

  1. Use Container and give some height:

    Column(
      children: <Widget>[
        Widget1(),
        Container(height: 10), // set height
        Widget2(),
      ],
    )
    
  2. Use Spacer

    Column(
      children: <Widget>[
        Widget1(),
        Spacer(), // use Spacer
        Widget2(),
      ],
    )
    
  3. Use Expanded

    Column(
      children: <Widget>[
        Widget1(),
        Expanded(child: SizedBox()), // use Expanded
        Widget2(),
      ],
    )
    
  4. Use mainAxisAlignment

    Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround, // mainAxisAlignment
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    
  5. Use Wrap

    Wrap(
      direction: Axis.vertical, // make sure to set this
      spacing: 20, // set your spacing
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    

How to remove folders with a certain name

To delete all directories with the name foo, run:

find -type d -name foo -a -prune -exec rm -rf {} \;

The other answers are missing an important thing: the -prune option. Without -prune, GNU find will delete the directory with the matching name and then try to recurse into it to find more directories that match. The -prune option tells it to not recurse into a directory that matched the conditions.

How to get user agent in PHP

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

What are the differences between if, else, and else if?

They mean exactly what they mean in English.

IF a condition is true, do something, ELSE (otherwise) IF another condition is true, do something, ELSE do this when all else fails.

Note that there is no else if construct specifically, just if and else, but the syntax allows you to place else and if together, and the convention is not to nest them deeper when you do. For example:

if( x )
{
    ...
}
else if( y )
{
    ...
}
else
{
    ...
}

Is syntactically identical to:

if( x )
{
    ...
}
else 
{
    if( y )
    {
        ...
    }
    else
    {
        ...
    }
}

The syntax in both cases is:

if *<statment|statment-block>* else *<statment|statment-block>*

and if is itself a statment, so that syntax alone supports the use of else if

Array as session variable

First change the array to a string by using implode() function. E.g $number=array(1,2,3,4,5,...); $stringofnumber=implode("|",$number); then pass the string to a session. e.g $_SESSION['string']=$stringofnumber; so when you go to the page where you want to use the array, just explode your string. e.g $number=explode("|", $_SESSION['string']); finally number is your array but remember to start array on the of each page.

How to select an item from a dropdown list using Selenium WebDriver with java?

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

dropdown.selectByValue("prog");

Happy Coding :)

How to add an action to a UIAlertView button using Swift iOS

Swift 4 Update

        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }

        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)

        // Present the controller
        self.present(alertController, animated: true, completion: nil)

Picking a random element from a set

How about just

public static <A> A getRandomElement(Collection<A> c, Random r) {
  return new ArrayList<A>(c).get(r.nextInt(c.size()));
}

change image opacity using javascript

You can use CSS to set the opacity, and than use javascript to apply the styles to a certain element in the DOM.

.opClass {
    opacity:0.4;
    filter:alpha(opacity=40); /* For IE8 and earlier */
}

Than use (for example) jQuery to change the style:

$('#element_id').addClass('opClass');

Or with plain javascript, like this:

document.getElementById("element_id").className = "opClass";

Am I trying to connect to a TLS-enabled daemon without TLS?

Everything that you need to run Docker on Linux Ubuntu/Mint:

sudo apt-get -y install lxc
sudo gpasswd -a ${USER} docker
newgrp docker
sudo service docker restart

Optionally, you may need to install two additional dependencies if the above doesn't work:

sudo apt-get -y install apparmor cgroup-lite
sudo service docker restart

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

JSON for List of int

Assuming your ints are 0, 375, 668,5 and 6:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [
                       0,
                       375,
                       668,
                       5,
                       6
                   ]
}

I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/

Cannot get a text value from a numeric cell “Poi”

Use that code it definitely works and I modified it.

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
//import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.*;

public class TestApp {

    public static void main(String[] args) throws Exception {

        try {

            Class forName = Class.forName("com.mysql.jdbc.Driver");
            Connection con = null;
            con = DriverManager.getConnection("jdbc:mysql://localhost/tables", "root", "root");
            con.setAutoCommit(false);
            PreparedStatement pstm = null;
            FileInputStream input = new FileInputStream("C:\\Users\\Desktop\\a1.xls");
            POIFSFileSystem fs = new POIFSFileSystem(input);
            Workbook workbook;
            workbook = WorkbookFactory.create(fs);
            Sheet sheet = workbook.getSheetAt(0);
            Row row;
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                row = (Row) sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String add = row.getCell(1).getStringCellValue();

                int  contact = (int) row.getCell(2).getNumericCellValue();

                String email = row.getCell(3).getStringCellValue();

                String sql = "INSERT INTO employee (name, address, contactNo, email) VALUES('" + name + "','" + add + "'," + contact + ",'" + email + "')";
                pstm = (PreparedStatement) con.prepareStatement(sql);
                pstm.execute();
                System.out.println("Import rows " + i);
            }
            con.commit();
            pstm.close();
            con.close();
            input.close();
            System.out.println("Success import excel to mysql table");
        } catch (IOException e) {
        }
    }

}

Java synchronized block vs. Collections.synchronizedMap

The way you have synchronized is correct. But there is a catch

  1. Synchronized wrapper provided by Collection framework ensures that the method calls I.e add/get/contains will run mutually exclusive.

However in real world you would generally query the map before putting in the value. Hence you would need to do two operations and hence a synchronized block is needed. So the way you have used it is correct. However.

  1. You could have used a concurrent implementation of Map available in Collection framework. 'ConcurrentHashMap' benefit is

a. It has a API 'putIfAbsent' which would do the same stuff but in a more efficient manner.

b. Its Efficient: dThe CocurrentMap just locks keys hence its not blocking the whole map's world. Where as you have blocked keys as well as values.

c. You could have passed the reference of your map object somewhere else in your codebase where you/other dev in your tean may end up using it incorrectly. I.e he may just all add() or get() without locking on the map's object. Hence his call won't run mutually exclusive to your sync block. But using a concurrent implementation gives you a peace of mind that it can never be used/implemented incorrectly.

Java JSON serialization - best practice

Have your tried json-io (https://github.com/jdereg/json-io)?

This library allows you to serialize / deserialize any Java object graph, including object graphs with cycles in them (e.g., A->B, B->A). It does not require your classes to implement any particular interface or inherit from any particular Java class.

In addition to serialization of Java to JSON (and JSON to Java), you can use it to format (pretty print) JSON:

String niceFormattedJson = JsonWriter.formatJson(jsonString)

using mailto to send email with an attachment

If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:.

To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:

var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle);    //not really necessary
mapi.Send(subject, body, true);

How to remove element from an array in JavaScript?

You can also do this with reduce:

let arr = [1, 2, 3]

arr.reduce((xs, x, index) => {
        if (index == 0) {
            return xs
        } else {
            return xs.concat(x)
        }
    }, Array())

// Or if you like a oneliner
arr.reduce((xs, x, index) => index == 0 ? xs : xs.concat(x), Array())

Simple CSS Animation Loop – Fading In & Out "Loading" Text

To make more than one element fade in/out sequentially such as 5 elements fade each 4s,

1- make unique animation for each element with animation-duration equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s

animation-name: anim1 , anim2, anim3 ... 
animation-duration : 20s, 20s, 20s ... 

2- get animation keyframe for each element.

100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)

3- define starting and ending point for each animation:

each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),

@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on

now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,

so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)

enter image description here

http://codepen.io/El-Oz/pen/WwPPZQ

.slide1 {
    animation: fadeInOut1 24s ease reverse forwards infinite
}

.slide2 {
    animation: fadeInOut2 24s ease reverse forwards infinite
}

.slide3 {
    animation: fadeInOut3 24s ease reverse forwards infinite
}

.slide4 {
    animation: fadeInOut4 24s ease reverse forwards infinite
}

.slide5 {
    animation: fadeInOut5 24s ease reverse forwards infinite
}

.slide6 {
    animation: fadeInOut6 24s ease reverse forwards infinite
}

@keyframes fadeInOut1 {
    0% { opacity: 0 }
    1% { opacity: 1 }
    14% {opacity: 1 }
    16% { opacity: 0 }
}

@keyframes fadeInOut2 {
    0% { opacity: 0 }
    14% {opacity: 0 }
    16% { opacity: 1 }
    30% { opacity: 1 }
    33% { opacity: 0 }
}

@keyframes fadeInOut3 {
    0% { opacity: 0 }
    30% {opacity: 0 }
    33% {opacity: 1 }
    46% { opacity: 1 }
    48% { opacity: 0 }
}

@keyframes fadeInOut4 {
    0% { opacity: 0 }
    46% { opacity: 0 }
    48% { opacity: 1 }
    64% { opacity: 1 }
    65% { opacity: 0 }
}

@keyframes fadeInOut5 {
    0% { opacity: 0 }
    64% { opacity: 0 }
    66% { opacity: 1 }
    80% { opacity: 1 }
    83% { opacity: 0 }
}

@keyframes fadeInOut6 {
    80% { opacity: 0 }
    83% { opacity: 1 }
    99% { opacity: 1 }
    100% { opacity: 0 }
}

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

How to create a simple map using JavaScript/JQuery

Just use plain objects:

var map = { key1: "value1", key2: "value2" }
function get(k){
  return map[k];
}

How to call a function in shell Scripting?

Example of using a function() in bash:

#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
    echo "Usage: $0 filename"
    exit 1
}

# define is_file_exists function
# $f -> store argument passed to the script
is_file_exists(){
    local f="$1"
    [[ -f "$f" ]] && return 0 || return 1
}
# invoke  usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage

# Invoke is_file_exits
if ( is_file_exists "$1" )
then
 echo "File found: $1"
else
 echo "File not found: $1"
fi

how to get the current working directory's absolute path from irb

If you want to get the full path of the directory of the current rb file:

File.expand_path('../', __FILE__)

Display / print all rows of a tibble (tbl_df)

i prefer to physically print my tables instead:

CONNECT_SERVER="https://196.168.1.1/"
CONNECT_API_KEY<-"hpphotosmartP9000:8273827"

data.frame = data.frame(1:1000, 1000:2)

connectServer <- Sys.getenv("CONNECT_SERVER")
apiKey <- Sys.getenv("CONNECT_API_KEY")

install.packages('print2print')

print2print::send2printer(connectServer, apiKey, data.frame)

2D arrays in Python

I would suggest that you use a dictionary like so:

arr = {}

arr[1] = (1, 2, 4)
arr[18] = (3, 4, 5)

print(arr[1])
>>> (1, 2, 4)

If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", e.g. try-except.

How to pass the password to su/sudo/ssh without overriding the TTY?

I had the same problem. dialog script to create directory on remote pc. dialog with ssh is easy. I use sshpass (previously installed).

   dialog --inputbox "Enter IP" 8 78 2> /tmp/ip

   IP=$(cat /tmp/ip)


   dialog --inputbox "Please enter username" 8 78 2> /tmp/user

   US=$(cat /tmp/user)


   dialog --passwordbox "enter password for \"$US\" 8 78 2> /tmp/pass

   PASSWORD = $(cat /tmp/pass)


   sshpass -p "$PASSWORD" ssh $US@$IP mkdir -p /home/$US/TARGET-FOLDER


   rm /tmp/ip

   rm /tmp/user

   rm /tmp/pass

greetings from germany

titus

subtract time from date - moment js

There is a simple function subtract which moment library gives us to subtract time from some time. Using it is also very simple.

moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time

//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously

//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time

//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time

Hope this helps!

How to detect duplicate values in PHP array?

You could try turning that array into a associative array with the fruits as keys and the number of occurrences as values. Bit long-winded, but it looks like:

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
   'pear', 'kiwi', 'kiwi', 'kiwi');
$new_array = array();
foreach ($array as $key => $value) {
    if(isset($new_array[$value]))
        $new_array[$value] += 1;
    else
        $new_array[$value] = 1;
}
foreach ($new_array as $fruit => $n) {
    echo $fruit;
    if($n > 1)
        echo "($n)";
    echo "<br />";
}

WCF Service, the type provided as the service attribute values…could not be found

I had this error when I had the current build configuration in Visual Studio set to something other than Debug.

getting error while updating Composer

Problem :

Problem 1
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework (locked at v5.8.38, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.38].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\xampp\php\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Solution :

if you using xampp just remove ' ; ' from

;extension=mbstring

in php.ini , save it, done!

Example to use shared_ptr?

The boost documentation provides a pretty good start example: shared_ptr example (it's actually about a vector of smart pointers) or shared_ptr doc The following answer by Johannes Schaub explains the boost smart pointers pretty well: smart pointers explained

The idea behind(in as few words as possible) ptr_vector is that it handles the deallocation of memory behind the stored pointers for you: let's say you have a vector of pointers as in your example. When quitting the application or leaving the scope in which the vector is defined you'll have to clean up after yourself(you've dynamically allocated ANDgate and ORgate) but just clearing the vector won't do it because the vector is storing the pointers and not the actual objects(it won't destroy but what it contains).

 // if you just do
 G.clear() // will clear the vector but you'll be left with 2 memory leaks
 ...
// to properly clean the vector and the objects behind it
for (std::vector<gate*>::iterator it = G.begin(); it != G.end(); it++)
{
  delete (*it);
}

boost::ptr_vector<> will handle the above for you - meaning it will deallocate the memory behind the pointers it stores.

How do I call ::CreateProcess in c++ to launch a Windows executable?

Here is a new example that works on windows 10. When using the windows10 sdk you have to use CreateProcessW instead. This example is commented and hopefully self explanatory.

#ifdef _WIN32
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <string>
#include <algorithm>

class process
{
public:

    static PROCESS_INFORMATION launchProcess(std::string app, std::string arg)
    {

        // Prepare handles.
        STARTUPINFO si;
        PROCESS_INFORMATION pi; // The function returns this
        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        //Prepare CreateProcess args
        std::wstring app_w(app.length(), L' '); // Make room for characters
        std::copy(app.begin(), app.end(), app_w.begin()); // Copy string to wstring.

        std::wstring arg_w(arg.length(), L' '); // Make room for characters
        std::copy(arg.begin(), arg.end(), arg_w.begin()); // Copy string to wstring.

        std::wstring input = app_w + L" " + arg_w;
        wchar_t* arg_concat = const_cast<wchar_t*>( input.c_str() );
        const wchar_t* app_const = app_w.c_str();

        // Start the child process.
        if( !CreateProcessW(
            app_const,      // app path
            arg_concat,     // Command line (needs to include app path as first argument. args seperated by whitepace)
            NULL,           // Process handle not inheritable
            NULL,           // Thread handle not inheritable
            FALSE,          // Set handle inheritance to FALSE
            0,              // No creation flags
            NULL,           // Use parent's environment block
            NULL,           // Use parent's starting directory
            &si,            // Pointer to STARTUPINFO structure
            &pi )           // Pointer to PROCESS_INFORMATION structure
        )
        {
            printf( "CreateProcess failed (%d).\n", GetLastError() );
            throw std::exception("Could not create child process");
        }
        else
        {
            std::cout << "[          ] Successfully launched child process" << std::endl;
        }

        // Return process handle
        return pi;
    }

    static bool checkIfProcessIsActive(PROCESS_INFORMATION pi)
    {
        // Check if handle is closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle is closed or invalid (%d).\n", GetLastError());
                return FALSE;
            }

        // If handle open, check if process is active
        DWORD lpExitCode = 0;
        if( GetExitCodeProcess(pi.hProcess, &lpExitCode) == 0)
        {
            printf( "Cannot return exit code (%d).\n", GetLastError() );
            throw std::exception("Cannot return exit code");
        }
        else
        {
            if (lpExitCode == STILL_ACTIVE)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    }

    static bool stopProcess( PROCESS_INFORMATION &pi)
    {
        // Check if handle is invalid or has allready been closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle invalid. Possibly allready been closed (%d).\n");
                return 0;
            }

        // Terminate Process
            if( !TerminateProcess(pi.hProcess,1))
            {
                printf( "ExitProcess failed (%d).\n", GetLastError() );
                return 0;
            }

        // Wait until child process exits.
            if( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_FAILED)
            {
                printf( "Wait for exit process failed(%d).\n", GetLastError() );
                return 0;
            }

        // Close process and thread handles.
            if( !CloseHandle( pi.hProcess ))
            {
                printf( "Cannot close process handle(%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                pi.hProcess = NULL;
            }

            if( !CloseHandle( pi.hThread ))
            {
                printf( "Cannot close thread handle (%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                 pi.hProcess = NULL;
            }
            return 1;
    }
};//class process
#endif //win32

How to Find Item in Dictionary Collection?

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

The basic solution would be:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

But that requires 2 lookups.

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

How to merge 2 List<T> and removing duplicate values from it in C#

why not simply eg

var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;

oh ... according to the documentation you can leave out the .Distinct()

This method excludes duplicates from the return set

How do I install TensorFlow's tensorboard?

pip install tensorflow.tensorboard  # install tensorboard
pip show tensorflow.tensorboard
# Location: c:\users\<name>\appdata\roaming\python\python35\site-packages
# now just run tensorboard as:
python c:\users\<name>\appdata\roaming\python\python35\site-packages\tensorboard\main.py --logdir=<logidr>

Find the directory part (minus the filename) of a full path in access 97

I always used the FileSystemObject for this sort of thing. Here's a little wrapper function I used. Be sure to reference the Microsoft Scripting Runtime.

Function StripFilename(sPathFile As String) As String

'given a full path and file, strip the filename off the end and return the path

Dim filesystem As New FileSystemObject

StripFilename = filesystem.GetParentFolderName(sPathFile) & "\"

Exit Function

End Function

BLOB to String, SQL Server

Problem was apparently not the SQL server, but the NAV system that updates the field. There is a compression property that can be used on BLOB fields in NAV, that is not a part of SQL Server. So the custom compression made the data unreadable, though the conversion worked.

The solution was to turn off compression through the Object Designer, Table Designer, Properties for the field (Shift+F4 on the field row).

After that the extraction of data can be made with e.g.: select convert(varchar(max), cast(BLOBFIELD as binary)) from Table

Thanks for all answers that were correct in many ways!

What is the default lifetime of a session?

The default in the php.ini for the session.gc_maxlifetime directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:

http://www.php.net/manual/en/session.configuration.php

You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:

php_value session.gc_maxlifetime "3600"

Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation.

The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

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

When you run make, add VERBOSE=1 to see the full command output. For example:

cmake .
make VERBOSE=1

Or you can add -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON to the cmake command for permanent verbose command output from the generated Makefiles.

cmake -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make

To reduce some possibly less-interesting output you might like to use the following options. The option CMAKE_RULE_MESSAGES=OFF removes lines like [ 33%] Building C object..., while --no-print-directory tells make to not print out the current directory filtering out lines like make[1]: Entering directory and make[1]: Leaving directory.

cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make --no-print-directory

What does <T> denote in C#

It is a generic type parameter, see Generics documentation.

T is not a reserved keyword. T, or any given name, means a type parameter. Check the following method (just as a simple example).

T GetDefault<T>()
{
    return default(T);
}

Note that the return type is T. With this method you can get the default value of any type by calling the method as:

GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00

.NET uses generics in collections, ... example:

List<int> integerList = new List<int>();

This way you will have a list that only accepts integers, because the class is instancited with the type T, in this case int, and the method that add elements is written as:

public class List<T> : ...
{
    public void Add(T item);
}

Some more information about generics.

You can limit the scope of the type T.

The following example only allows you to invoke the method with types that are classes:

void Foo<T>(T item) where T: class
{
}

The following example only allows you to invoke the method with types that are Circle or inherit from it.

void Foo<T>(T item) where T: Circle
{
}

And there is new() that says you can create an instance of T if it has a parameterless constructor. In the following example T will be treated as Circle, you get intellisense...

void Foo<T>(T item) where T: Circle, new()
{
    T newCircle = new T();
}

As T is a type parameter, you can get the object Type from it. With the Type you can use reflection...

void Foo<T>(T item) where T: class
{
    Type type = typeof(T);
}

As a more complex example, check the signature of ToDictionary or any other Linq method.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

There isn't a T, however there is TKey and TSource. It is recommended that you always name type parameters with the prefix T as shown above.

You could name TSomethingFoo if you want to.

add image to uitableview cell

Standard UITableViewCell already contains UIImageView that appears to the left to all your labels if its image is set. You can access it using imageView property:

cell.imageView.image = someImage;

If for some reason standard behavior does not suit your needs (note that you can customize properties of that standard image view) then you can add your own UIImageView to the cell as Aman suggested in his answer. But in that approach you'll have to manage cell's layout yourself (e.g. make sure that cell labels do not overlap image). And do not add subviews to the cell directly - add them to cell's contentView:

// DO NOT!
[cell addSubview:imv]; 
// DO:
[cell.contentView addSubview:imv];

Can not change UILabel text color

UIColor's RGB components are scaled between 0 and 1, not up to 255.

Try

categoryTitle.textColor = [UIColor colorWithRed:(188/255.f) green:... blue:... alpha:1.0];

In Swift:

categoryTitle.textColor = UIColor(red: 188/255.0, green: ..., blue: ..., alpha: 1)

Quicksort with Python

def quicksort(array):
 if len(array) < 2:
  return array
 else:
  pivot = array[0]

 less = [i for i in array[1:] if i <= pivot]
 greater = [i for i in array[1:] if i > pivot]
 return quicksort(less) + [pivot] + quicksort(greater)

Remove trailing comma from comma-separated string

Or something like this:

private static String myRemComa(String input) { 
        String[] exploded = input.split(",");
        input="";
        boolean start = true;
        for(String str : exploded) {

         str=str.trim();
         if (str.length()>0) {
             if (start) {
                 input = str;
                    start = false;
                } else {
                    input = input + "," + str;
                }
         }
        }

        return input;
    }

Is Google Play Store supported in avd emulators?

There is no google play store in avd emulator. But you can install it manually.

  1. Install Google APIs System Image, so you will have google services already (without play store)

  2. Create AVD based on Google APIs image

  3. Download smallest archive from http://opengapps.org/ and extract Phonesky.apk from it

  4. Push Phonesky.apk to /system/priv-app/ on avd.

  5. Restart avd. Google play should be there.

Recently I've just tried to do it by myself and you can find detailed tutorial on my blog: http://linuxoidchannel.blogspot.com/2017/01/how-to-install-google-play-store-on.html

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I prefer inline-block, but float are still useful way to put together HTML elemenets, specially when we have elements which one should stick to the left and one to the right, float working better with writing less lines, while inline-block working well in many other cases.

enter image description here

git remote add with other SSH port

For those of you editing the ./.git/config

[remote "external"]                                                                                                                                                                                                                                                            
  url = ssh://[email protected]:11720/aaa/bbb/ccc                                                                                                                                                                                                               
  fetch = +refs/heads/*:refs/remotes/external/* 

Set background color of WPF Textbox in C# code

You can use hex colors:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

How can I bind a background color in WPF/XAML?

Here you've got a copy-paste code:

class NameToBackgroundConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value.ToString() == "System")
            {
                return new SolidColorBrush(System.Windows.Media.Colors.Aqua);
            }else
            {
                return new SolidColorBrush(System.Windows.Media.Colors.Blue);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

Create dynamic URLs in Flask with url_for()

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for, if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Syntax: url_for('name of the function of the route','parameters (if required)')

It can be used as:

@app.route('/index')
@app.route('/')
def index():
    return 'you are in the index page'

Now if you have a link the index page:you can use this:

<a href={{ url_for('index') }}>Index</a>

You can do a lot o stuff with it, for example:

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

For the above we can use:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

Like this you can simply pass the parameters!

asp.net validation to make sure textbox has integer values

If all that you are concerned about is that the field contains an integer (i.e., not concerned with a range), then add a CompareValidator with it's Operator property set to DataTypeCheck:

<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer" 
 ControlToValidate="ValueTextBox" ErrorMessage="Value must be a whole number" />

If there is a specific range of values that are valid (there probably are), then you can use a RangeValidator, like so:

<asp:RangeValidator runat="server" Type="Integer" 
MinimumValue="0" MaximumValue="400" ControlToValidate="ValueTextBox" 
ErrorMessage="Value must be a whole number between 0 and 400" />

These will only validate if there is text in the TextBox, so you will need to keep the RequiredFieldValidator there, too.

As @Mahin said, make sure you check the Page.IsValid property on the server side, otherwise the validator only works for users with JavaScript enabled.

Not equal <> != operator on NULL

<> is Standard SQL-92; != is its equivalent. Both evaluate for values, which NULL is not -- NULL is a placeholder to say there is the absence of a value.

Which is why you can only use IS NULL/IS NOT NULL as predicates for such situations.

This behavior is not specific to SQL Server. All standards-compliant SQL dialects work the same way.

Note: To compare if your value is not null, you use IS NOT NULL, while to compare with not null value, you use <> 'YOUR_VALUE'. I can't say if my value equals or not equals to NULL, but I can say if my value is NULL or NOT NULL. I can compare if my value is something other than NULL.

n-grams in python, four, five, six grams?

You can easily whip up your own function to do this using itertools:

from itertools import izip, islice, tee
s = 'spam and eggs'
N = 3
trigrams = izip(*(islice(seq, index, None) for index, seq in enumerate(tee(s, N))))
list(trigrams)
# [('s', 'p', 'a'), ('p', 'a', 'm'), ('a', 'm', ' '),
# ('m', ' ', 'a'), (' ', 'a', 'n'), ('a', 'n', 'd'),
# ('n', 'd', ' '), ('d', ' ', 'e'), (' ', 'e', 'g'),
# ('e', 'g', 'g'), ('g', 'g', 's')]

Telnet is not recognized as internal or external command

You can also try dism /online /Enable-Feature /FeatureName:TelnetClient

Run this command with "Run as an administrator"

Reference

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

Proper way to use **kwargs in Python

Since **kwargs is used when the number of arguments is unknown, why not doing this?

class Exampleclass(object):
  def __init__(self, **kwargs):
    for k in kwargs.keys():
       if k in [acceptable_keys_list]:
          self.__setattr__(k, kwargs[k])

ComboBox- SelectionChanged event has old value, not new value

I needed to solve this in VB.NET. Here's what I've got that seems to work:

Private Sub ComboBox1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox_AllSites.SelectionChanged
   Dim cr As System.Windows.Controls.ComboBoxItem = ComboBox1.SelectedValue
   Dim currentText = cr.Content
   MessageBox.Show(currentText)
End Sub

Annotation-specified bean name conflicts with existing, non-compatible bean def

Sometimes the problem occurs if you have moved your classes around and it refers to old classes, even if they don't exist.

In this case, just do this :

mvn eclipse:clean

mvn eclipse:eclipse

This worked well for me.

How to make an installer for my C# application?

There are several methods, two of which are as follows. Provide a custom installer or a setup project.

Here is how to create a custom installer

[RunInstaller(true)]
public class MyInstaller : Installer
{
    public HelloInstaller()
        : base()
    {
    }

    public override void Commit(IDictionary mySavedState)
    {
        base.Commit(mySavedState);
        System.IO.File.CreateText("Commit.txt");
    }

    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        System.IO.File.CreateText("Install.txt");
    }

    public override void Uninstall(IDictionary savedState)
    {
        base.Uninstall(savedState);
        File.Delete("Commit.txt");
        File.Delete("Install.txt");
    }

    public override void Rollback(IDictionary savedState)
    {
        base.Rollback(savedState);
        File.Delete("Install.txt");
    }
}

To add a setup project

  • Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment

  • Set properties of the project, using the properties window

The article How to create a Setup package by using Visual Studio .NET provides the details.

Update multiple rows with different values in a single SQL query

There's a couple of ways to accomplish this decently efficiently.

First -
If possible, you can do some sort of bulk insert to a temporary table. This depends somewhat on your RDBMS/host language, but at worst this can be accomplished with a simple dynamic SQL (using a VALUES() clause), and then a standard update-from-another-table. Most systems provide utilities for bulk load, though

Second -
And this is somewhat RDBMS dependent as well, you could construct a dynamic update statement. In this case, where the VALUES(...) clause inside the CTE has been created on-the-fly:

WITH Tmp(id, px, py) AS (VALUES(id1, newsPosX1, newPosY1), 
                               (id2, newsPosX2, newPosY2),
                               ......................... ,
                               (idN, newsPosXN, newPosYN))

UPDATE TableToUpdate SET posX = (SELECT px
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id),
                         posY = (SELECT py
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id)


WHERE id IN (SELECT id
             FROM Tmp)

(According to the documentation, this should be valid SQLite syntax, but I can't get it to work in a fiddle)

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 
ADD NewId INT IDENTITY (1, 1);

Update:

OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

We can also use

return $this->db->count_all('table_name');  

or

$this->db->from('table_name');
return $this->db->count_all_result();

or

return $this->db->count_all_result('table_name');

or

$query = $this->db->query('select * from tab');  
return $query->num_rows();

HashMap - getting First Key value

You can try this:

 Map<String,String> map = new HashMap<>();
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key = entry.getKey();
 String value = entry.getValue();

Keep in mind, HashMap does not guarantee the insertion order. Use a LinkedHashMap to keep the order intact.

Eg:

 Map<String,String> map = new LinkedHashMap<>();
 map.put("Active","33");
 map.put("Renewals Completed","3");
 map.put("Application","15");
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key= entry.getKey();
 String value=entry.getValue();
 System.out.println(key);
 System.out.println(value);

Output:

 Active
 33

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

<context:annotation-config> declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.

<mvc:annotation-driven /> declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping, @Controller, although support for those is the default behaviour), as well as adding support for declarative validation via @Valid and message body marshalling with @RequestBody/ResponseBody.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

Universal way of loading view from xib:

Example:

let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)

Implementation:

extension Bundle {

    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }

        fatalError("Could not load view with type " + String(describing: type))
    }
}

Insert Picture into SQL Server 2005 Image Field using only SQL

For updating a record:

 UPDATE Employees SET [Photo] = (SELECT
 MyImage.* from Openrowset(Bulk
 'C:\photo.bmp', Single_Blob) MyImage)
 where Id = 10

Notes:

  • Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
  • Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!

How to implement a Keyword Search in MySQL?

For a single keyword on VARCHAR fields you can use LIKE:

SELECT id, category, location
FROM table
WHERE
(
    category LIKE '%keyword%'
    OR location LIKE '%keyword%'
)

For a description you're usually better adding a full text index and doing a Full-Text Search (MyISAM only):

SELECT id, description
FROM table
WHERE MATCH (description) AGAINST('keyword1 keyword2')

How to mark a method as obsolete or deprecated?

To mark as obsolete with a warning:

[Obsolete]
private static void SomeMethod()

You get a warning when you use it:

Obsolete warning is shown

And with IntelliSense:

Obsolete warning with IntelliSense

If you want a message:

[Obsolete("My message")]
private static void SomeMethod()

Here's the IntelliSense tool tip:

IntelliSense shows the obsolete message

Finally if you want the usage to be flagged as an error:

[Obsolete("My message", true)]
private static void SomeMethod()

When used this is what you get:

Method usage is displayed as an error

Note: Use the message to tell people what they should use instead, not why it is obsolete.

Convert HTML Character Back to Text Using Java Standard Library

The URL decoder should only be used for decoding strings from the urls generated by html forms which are in the "application/x-www-form-urlencoded" mime type. This does not support html characters.

After a search I found a Translate class within the HTML Parser library.

SELECT max(x) is returning null; how can I make it return 0?

You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:

SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1

How to round up a number to nearest 10?

Try this......pass in the number to be rounded off and it will round off to the nearest tenth.hope it helps....

round($num, 1);

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

You can pass an empty array to unselect all the selection. Here goes an example. From documentation

val() allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like , , and s inside of a . In this case, the inputs and the options having a value that matches one of the elements of the array will be checked or selected while those having a value that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type.

_x000D_
_x000D_
$('.clearAll').on('click', function() {_x000D_
  $('.dropdown').val([]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select class="dropdown" multiple>_x000D_
  <option value="volvo">Volvo</option>_x000D_
  <option value="saab">Saab</option>_x000D_
  <option value="opel">Opel</option>_x000D_
  <option value="audi">Audi</option>_x000D_
</select>_x000D_
_x000D_
<button class='clearAll'>Clear All Selection</button>
_x000D_
_x000D_
_x000D_

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I guess, a column value in a foreign key table should match with the column value of the primary key table. If we are trying to create a foreign key constraint between two tables where the value inside one column(going to be the foreign key) is different from the column value of the primary key table then it will throw the message.

So it is always recommended to insert only those values in the Foreign key column which are present in the Primary key table column.

For ex. If the Primary table column has values 1, 2, 3 and in Foreign key column the values inserted are different, then the query would not be executed as it expects the values to be between 1 & 3.

What are the best JVM settings for Eclipse?

Here's my own setting for my Eclipse running on i7 2630M 16GB RAM laptop, this setting has been using for a week, without a single crashing, and Eclipse 3.7 is running smoothly.

-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms1024m
-Xmx4096m 
-XX:MaxPermSize=256m

Calculations: For Win 7 x64

  • Xms = Physical Memory / 16
  • Xmx = Physical Memory / 4
  • MaxPermSize = Same as default value, which is 256m

How do I convert this list of dictionaries to a csv file?

In python 3 things are a little different, but way simpler and less error prone. It's a good idea to tell the CSV your file should be opened with utf8 encoding, as it makes that data more portable to others (assuming you aren't using a more restrictive encoding, like latin1)

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
with open('people.csv', 'w', encoding='utf8', newline='') as output_file:
    fc = csv.DictWriter(output_file, 
                        fieldnames=toCSV[0].keys(),

                       )
    fc.writeheader()
    fc.writerows(toCSV)
  • Note that csv in python 3 needs the newline='' parameter, otherwise you get blank lines in your CSV when opening in excel/opencalc.

Alternatively: I prefer use to the csv handler in the pandas module. I find it is more tolerant of encoding issues, and pandas will automatically convert string numbers in CSVs into the correct type (int,float,etc) when loading the file.

import pandas
dataframe = pandas.read_csv(filepath)
list_of_dictionaries = dataframe.to_dict('records')
dataframe.to_csv(filepath)

Note:

  • pandas will take care of opening the file for you if you give it a path, and will default to utf8 in python3, and figure out headers too.
  • a dataframe is not the same structure as what CSV gives you, so you add one line upon loading to get the same thing: dataframe.to_dict('records')
  • pandas also makes it much easier to control the order of columns in your csv file. By default, they're alphabetical, but you can specify the column order. With vanilla csv module, you need to feed it an OrderedDict or they'll appear in a random order (if working in python < 3.5). See: Preserving column order in Python Pandas DataFrame for more.

How to stop PHP code execution?

or try

trigger_error('Die', E_ERROR);

Call a React component method from outside

If you are in ES6 just use the "static" keyword on your method from your example would be the following: static alertMessage: function() { ...
},

Hope can help anyone out there :)

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

Referring to @dylanvanw answer. You might still out of luck. I found that you might have a different path that you have installed Python. In my case, I have to move Chromedriver.exe from the cache path (C:\Users\Poom.wdm\drivers\chromedriver\win32\84.0.4147.30) to C:\Python38 then it work!

understanding private setters

I don't understand the need of having private setters which started with C# 2.

Use case example:

I have an instance of an application object 'UserInfo' that contains a property SessionTokenIDV1 that I don't wish to expose to consumers of my class.

I also need the ability to set that value from my class.

My solution was to encapsulate the property as shown and make the setter private so that I can set the value of the session token without allowing instantiating code to also set it (or even see it in my case)

public class UserInfo
{
   public String SessionTokenIDV1 { get; set; }

}


public class Example
{
  // Private vars
  private UserInfo _userInfo = new UserInfo();

  public string SessionValidV1
  {
    get { return ((_userInfo.SessionTokenIDV1 != null) && (_userInfo.SessionTokenIDV1.Length > 0)) ? "set" : "unset"; }
    private set { _userInfo.SessionTokenIDV1 = value; }
  }
}

Edit: Fixed Code Tag Edit: Example had errors which have been corrected

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

We have had the same issue in eclipse or intellij. After trying many alternative solutions, I found simple solution - add this config to your application.properties: spring.main.web-application-type=none

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

Get last field using awk substr

Another option is to use bash parameter substitution.

$ foo="/home/parent/child/filename"
$ echo ${foo##*/}
filename
$ foo="/home/parent/child/child2/filename"
$ echo ${foo##*/}
filename

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

when you have more than one module, you need to specify module name

 ng g c componentName --module=modulename.module 

What is the largest possible heap size with a 64-bit JVM?

For a 64-bit JVM running in a 64-bit OS on a 64-bit machine, is there any limit besides the theoretical limit of 2^64 bytes or 16 exabytes?

You also have to take hardware limits into account. While pointers may be 64bit current CPUs can only address a less than 2^64 bytes worth of virtual memory.

With uncompressed pointers the hotspot JVM needs a continuous chunk of virtual address space for its heap. So the second hurdle after hardware is the operating system providing such a large chunk, not all OSes support this.

And the third one is practicality. Even if you can have that much virtual memory it does not mean the CPUs support that much physical memory, and without physical memory you will end up swapping, which will adversely affect the performance of the JVM because the GCs generally have to touch a large fraction of the heap.

As other answers mention compressed oops: By bumping the object alignment higher than 8 bytes the limits with compressed oops can be increased beyond 32GB

Repeat command automatically in Linux

If the command contains some special characters such as pipes and quotes, the command needs to be padded with quotes. For example, to repeat ls -l | grep "txt", the watch command should be:

watch -n 5 'ls -l | grep "txt"'

Visual Studio keyboard shortcut to display IntelliSense

If you have arrived at this question because IntelliSense has stopped working properly and you are hoping to force it to show you what you need, then most likely none of these solutions are going to work.

Closing and restarting Visual Studio should fix the problem.

What are some resources for getting started in operating system development?

Start hacking away at Minix. It's a lot smaller than Linux (obviously) and it's designed with teaching purposes in mind (some, at least). Not Minix 3 though, that's a whole different story.

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

scrollbars in JTextArea

Simple Way to add JTextArea in JScrollBar with JScrollPan

import javax.swing.*;
public class ScrollingTextArea 
{
     JFrame f;
     JTextArea ta;
     JScrollPane scrolltxt;

     public ScrollingTextArea() 
     {
        // TODO Auto-generated constructor stub

        f=new JFrame();
        f.setLayout(null);
        f.setVisible(true);
        f.setSize(500,500);
        ta=new JTextArea();
        ta.setBounds(5,5,100,200);

        scrolltxt=new JScrollPane(ta);
        scrolltxt.setBounds(3,3,400,400);

         f.add(scrolltxt);

     }

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

Java split string to array

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

String[] array = values.split("\\|", -1);

python pip - install from local dir

You were looking for help on installations with pip. You can find it with the following command:

pip install --help

Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

Does a foreign key automatically create an index?

I notice that Entity Framework 6.1 pointed at MSSQL does automatically add indexes on foreign keys.

How do ACID and database transactions work?

ACID is a set of properties that you would like to apply when modifying a database.

  • Atomicity
  • Consistency
  • Isolation
  • Durability

A transaction is a set of related changes which is used to achieve some of the ACID properties. Transactions are tools to achieve the ACID properties.

Atomicity means that you can guarantee that all of a transaction happens, or none of it does; you can do complex operations as one single unit, all or nothing, and a crash, power failure, error, or anything else won't allow you to be in a state in which only some of the related changes have happened.

Consistency means that you guarantee that your data will be consistent; none of the constraints you have on related data will ever be violated.

Isolation means that one transaction cannot read data from another transaction that is not yet completed. If two transactions are executing concurrently, each one will see the world as if they were executing sequentially, and if one needs to read data that is written by another, it will have to wait until the other is finished.

Durability means that once a transaction is complete, it is guaranteed that all of the changes have been recorded to a durable medium (such as a hard disk), and the fact that the transaction has been completed is likewise recorded.

So, transactions are a mechanism for guaranteeing these properties; they are a way of grouping related actions together such that as a whole, a group of operations can be atomic, produce consistent results, be isolated from other operations, and be durably recorded.

Live Video Streaming with PHP

There are a lot of "off-the-shelf" 'servers' that will run in your environment. Most of these utilize the aforementioned Flex or Silverlight to implement the actual video itself but I'm pretty sure all will run under LAMP/PHP.

The challenges will picking the best software from everything that's available and getting your hosting-provider to let you stream video (it goes without saying that streaming is heavy on bandwidth).

Using Java with Nvidia GPUs (CUDA)

I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/

Quick way to retrieve user information Active Directory

You can call UserPrincipal.FindByIdentity inside System.DirectoryServices.AccountManagement:

using System.DirectoryServices.AccountManagement;

using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
    var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}

How to set bootstrap navbar active class with Angular JS?

I use ng-class directive with $location to achieve it.

<ul class="nav">
<li data-ng-class="{active: ($location.path() == '/') }">
    <a href="#/">Carpeta Amarilla</a>
</li>
<li class="dropdown" data-ng-class="{active: ($location.path() == '/auditoria' || $location.path() == '/auditoria/todos') }">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">
        Auditoria
        <b class="caret"></b>
    </a>
    <ul class="dropdown-menu pull-right">
        <li data-ng-class="{active: ($location.path() == '/auditoria') }">
            <a href="#/auditoria">Por Legajo</a>
        </li>
        <li data-ng-class="{active: ($location.path() == '/auditoria/todos') }">
            <a href="#/auditoria/todos">General</a>
        </li>
    </ul>
</li>
</ul>

It requires the navbar to be inside a main Controller with access to $location service like this:

bajasApp.controller('MenuCntl', ['$scope','$route', '$routeParams', '$location', 
   function MenuCntl($scope, $route, $routeParams, $location) {
   $scope.$route = $route;
   $scope.$location = $location;
   $scope.$routeParams = $routeParams;
}]);

How to split a string of space separated numbers into integers?

l = (int(x) for x in s.split())

If you are sure there are always two integers you could also do:

a,b = (int(x) for x in s.split())

or if you plan on modifying the array after

l = [int(x) for x in s.split()]

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

Fixing pip

For this error:

~/Library/Python/2.7/bin/pip: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory`

The source of this problem is a bad python path hardcoded in pip (which means it won't be fixed by e.g. changing your $PATH). That path is no longer hardcoded in the lastest version of pip, so a solution which should work is:

pip install --upgrade pip

But of course, this command uses pip, so it fails with the same error.

The way to bootstrap yourself out of this mess:

  1. Run which pip
  2. Open that file in a text editor
  3. Change the first line from #!/usr/local/opt/python/bin/python2.7 to e.g. #!/usr/local/opt/python2/bin/python2.7 (note the python2 in the path), or any path to a working python interpreter on your machine.
  4. Now, pip install --upgrade pip (this overwrites your hack and gets pip working at the latest version, where the interpreter issue should be fixed)

Fixing virtualenv

For me, I found this issue by first having the identical issue from virtualenv:

~/Library/Python/2.7/bin/virtualenv: /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory`

The solution here is to run

pip uninstall virtualenv
pip install virtualenv

If running that command gives the same error from pip, see above.

How to change letter spacing in a Textview?

For embedding HTML text in your textview you can use Html.fromHTML() syntax. More information you will get from http://developer.android.com/reference/android/text/Html.html#fromHtml%28java.lang.String%29

How to trigger jQuery change event in code

The parameterless form of the change() method triggers a change event. You can write something like:

$(document).ready(function() {
    $("#yourInitialElementID").change(function() {
        // Do something here...
        $(".yourDropDownClass").change();
    });
});

How to change the sender's name or e-mail address in mutt?

Normally, mutt sets the From: header based on the from configuration variable you set in ~/.muttrc:

set from="Fubar <foo@bar>"

If this is not set, mutt uses the EMAIL environment variable by default. In which case, you can get away with calling mutt like this on the command line (as opposed to how you showed it in your comment):

EMAIL="foo@bar" mutt -s '$MailSubject' -c "abc@def"

However, if you want to be able to edit the From: header while composing, you need to configure mutt to allow you to edit headers first. This involves adding the following line in your ~/.muttrc:

set edit_headers=yes

After that, next time you open up mutt and are composing an E-mail, your chosen text editor will pop up containing the headers as well, so you can edit them. This includes the From: header.

Bootstrap number validation

Well I always use the same easy way and it works for me. In your HTML keep the type as text (like this):

<input type="text" class="textfield" value="" id="onlyNumbers" name="onlyNumbers" onkeypress="return isNumber(event)" onpaste="return false;"/>

After this you only need to add a method on javascript

<script type="text/javascript">     
function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if ( (charCode > 31 && charCode < 48) || charCode > 57) {
            return false;
        }
        return true;
    }
</script>

With this easy validation you will only get positive numbers as you wanted. You can modify the charCodes to add more valid keys to your method.

Here´s the code working: Only numbers validation

Separation of business logic and data access in django

Django employs a slightly modified kind of MVC. There's no concept of a "controller" in Django. The closest proxy is a "view", which tends to cause confusion with MVC converts because in MVC a view is more like Django's "template".

In Django, a "model" is not merely a database abstraction. In some respects, it shares duty with the Django's "view" as the controller of MVC. It holds the entirety of behavior associated with an instance. If that instance needs to interact with an external API as part of it's behavior, then that's still model code. In fact, models aren't required to interact with the database at all, so you could conceivable have models that entirely exist as an interactive layer to an external API. It's a much more free concept of a "model".

Unable to begin a distributed transaction

My last adventure with MSDTC and this error today turned out to be a DNS issue. You're on the right track asking if the machines are on the same domain, EBarr. Terrific list for this issue, by the way!

My situation: I needed a server in a child domain to be able to run distributed transactions against a server in the parent domain through a firewall. I've used linked servers quite a bit over the years, so I had all the usual settings in SQL for a linked server and in MSDTC that Ian documented so nicely above. I set up MSDTC with a range of TCP ports (5000-5200) to use on both servers, and arranged for a firewall hole between the boxes for ports 1433 and 5000-5200. That should have worked. The linked server tested OK and I could query the remote SQL server via the linked server nicely, but I couldn't get it to allow a distributed transaction. I could even see a connection on the QA server from the DEV server, but something wasn't making the trip back.

I could PING the DEV server from QA using a FQDN like: PING DEVSQL.dev.domain.com

I could not PING the DEV server with just the machine name: PING DEVSQL

The DEVSQL server was supposed to be a member of both domains, but the name wasn't resolving in the parent domain's DNS... something had happened to the machine account for DEVSQL in the parent domain. Once we added DEVSQL to the DNS for the parent domain, and "PING DEVSQL" worked from the remote QA server, this issue was resolved for us.

I hope this helps!

Web scraping with Python

If we think of getting name of items from any specific category then we can do that by specifying the class name of that category using css selector:

import requests ; from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get('https://www.flipkart.com/').text, "lxml")
for link in soup.select('div._2kSfQ4'):
    print(link.text)

This is the partial search results:

Puma, USPA, Adidas & moreUp to 70% OffMen's Shoes
Shirts, T-Shirts...Under ?599For Men
Nike, UCB, Adidas & moreUnder ?999Men's Sandals, Slippers
Philips & moreStarting ?99LED Bulbs & Emergency Lights

How do you convert epoch time in C#?

Use the method DateTimeOffset.ToUnixTimeMilliseconds() It returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.

This is only supported with Framework 4.6 or higher

var EPOCH = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

It's well documented here DateTimeOffset.ToUnixTimeMilliseconds

The other way out is to use the following

long EPOCH = DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1,0,0,0,0).Ticks;

To get the EPOCH with seconds only you may use

 var Epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

and convert the Epoch to DateTime with the following method

private DateTime Epoch2UTCNow(int epoch) 
{
    return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch); 
}

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

There actually IS a way to do this. Think about how you might use Newtonsoft JSON to deserialize an object from json. It will (or at least can) ignore missing elements and populate all the elements that it does know about.

So here's how I did it. A small code sample will follow my explanation.

  1. Create an instance of your object from the base class and populate it accordingly.

  2. Using the "jsonconvert" class of Newtonsoft json, serialize that object into a json string.

  3. Now create your sub class object by deserializing with the json string created in step 2. This will create an instance of your sub class with all the properties of the base class.

This works like a charm! So.. when is this useful? Some people asked when this would make sense and suggested changing the OP's schema to accommodate the fact that you can't natively do this with class inheritance (in .Net).

In my case, I have a settings class that contains all the "base" settings for a service. Specific services have more options and those come from a different DB table, so those classes inherit the base class. They all have a different set of options. So when retrieving the data for a service, it's much easier to FIRST populate the values using an instance of the base object. One method to do this with a single DB query. Right after that, I create the sub class object using the method outlined above. I then make a second query and populate all the dynamic values on the sub class object.

The final output is a derived class with all the options set. Repeating this for additional new sub classes takes just a few lines of code. It's simple, and it uses a very tried and tested package (Newtonsoft) to make the magic work.

This example code is vb.Net, but you can easily convert to c#.

' First, create the base settings object.
    Dim basePMSettngs As gtmaPayMethodSettings = gtmaPayments.getBasePayMethodSetting(payTypeId, account_id)
    Dim basePMSettingsJson As String = JsonConvert.SerializeObject(basePMSettngs, Formatting.Indented)

    ' Create a pmSettings object of this specific type of payment and inherit from the base class object
    Dim pmSettings As gtmaPayMethodAimACHSettings = JsonConvert.DeserializeObject(Of gtmaPayMethodAimACHSettings)(basePMSettingsJson)

With CSS, how do I make an image span the full width of the page as a background image?

You set the CSS to :

#elementID {
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
    height: 200px;
}

It centers the image, but does not scale it.

FIDDLE

In newer browsers you can use the background-size property and do:

#elementID {
    height: 200px; 
    width: 100%;
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
    background-size: 100% 100%;
}

FIDDLE

Other than that, a regular image is one way to do it, but then it's not really a background image.

?

Mapping list in Yaml to list of objects in Spring Boot

for me the fix was to add the injected class as inner class in the one annotated with @ConfigurationProperites, because I think you need @Component to inject properties.

python selenium click on button

Remove space between classes in css selector:

driver.find_element_by_css_selector('.button .c_button .s_button').click()
#                                           ^         ^

=>

driver.find_element_by_css_selector('.button.c_button.s_button').click()

Failed to build gem native extension (installing Compass)

For macOS 10.14 Mojave, make sure you have already installed command line tools via xcode-select --install and the run the following command to install std headers.

sudo open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Now try your command again.

Where's the DateTime 'Z' format specifier?

When you use DateTime you are able to store a date and a time inside a variable.

The date can be a local time or a UTC time, it depend on you.

For example, I'm in Italy (+2 UTC)

var dt1 = new DateTime(2011, 6, 27, 12, 0, 0); // store 2011-06-27 12:00:00
var dt2 = dt1.ToUniversalTime()  // store 2011-06-27 10:00:00

So, what happen when I print dt1 and dt2 including the timezone?

dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 12:00:00 +2

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 10:00:00 +2

dt1 and dt2 contain only a date and a time information. dt1 and dt2 don't contain the timezone offset.

So where the "+2" come from if it's not contained in the dt1 and dt2 variable?

It come from your machine clock setting.

The compiler is telling you that when you use the 'zzz' format you are writing a string that combine "DATE + TIME" (that are store in dt1 and dt2) + "TIMEZONE OFFSET" (that is not contained in dt1 and dt2 because they are DateTyme type) and it will use the offset of the server machine that it's executing the code.

The compiler tell you "Warning: the output of your code is dependent on the machine clock offset"

If i run this code on a server that is positioned in London (+1 UTC) the result will be completly different: instead of "+2" it will write "+1"

...
dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 12:00:00 +1

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 10:00:00 +1

The right solution is to use DateTimeOffset data type in place of DateTime. It's available in sql Server starting from the 2008 version and in the .Net framework starting from the 3.5 version

How can I programmatically get the MAC address of an iphone

@Grantland This "pretty clean solution" looks similar to my own improvement over iPhoneDeveloperTips solution.

You can see my step here: https://gist.github.com/1409855/

/* Original source code courtesy John from iOSDeveloperTips.com */

#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

+ (NSString *)getMacAddress
{
    int                 mgmtInfoBase[6];
    char                *msgBuffer = NULL;
    NSString            *errorFlag = NULL;
    size_t              length;

    // Setup the management Information Base (mib)
    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
    mgmtInfoBase[2] = 0;              
    mgmtInfoBase[3] = AF_LINK;        // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces

    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0) 
        errorFlag = @"if_nametoindex failure";
    // Get the size of the data available (store in len)
    else if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0) 
        errorFlag = @"sysctl mgmtInfoBase failure";
    // Alloc memory based on above call
    else if ((msgBuffer = malloc(length)) == NULL)
        errorFlag = @"buffer allocation failure";
    // Get system information, store in buffer
    else if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
    {
        free(msgBuffer);
        errorFlag = @"sysctl msgBuffer failure";
    }
    else
    {
        // Map msgbuffer to interface message structure
        struct if_msghdr *interfaceMsgStruct = (struct if_msghdr *) msgBuffer;

        // Map to link-level socket structure
        struct sockaddr_dl *socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);

        // Copy link layer address data in socket structure to an array
        unsigned char macAddress[6];
        memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);

        // Read from char array into a string object, into traditional Mac address format
        NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                      macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]];
        NSLog(@"Mac Address: %@", macAddressString);

        // Release the buffer memory
        free(msgBuffer);

        return macAddressString;
    }

    // Error...
    NSLog(@"Error: %@", errorFlag);

    return nil;
}

"git rebase origin" vs."git rebase origin/master"

git rebase origin means "rebase from the tracking branch of origin", while git rebase origin/master means "rebase from the branch master of origin"

You must have a tracking branch in ~/Desktop/test, which means that git rebase origin knows which branch of origin to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie), git doesn't know which branch of origin it must take, and fails.

To fix this, you can make the branch track origin/master with:

git branch --set-upstream-to=origin/master 

Or, if master isn't the currently checked-out branch:

git branch --set-upstream-to=origin/master master

How do you pass a function as a parameter in C?

Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,

std::function<bool (int)>

where bool is the return type here of a one-argument function whose first argument is of type int.

I have included an example program below:

// g++ test.cpp --std=c++11
#include <functional>

double Combiner(double a, double b, std::function<double (double,double)> func){
  return func(a,b);
}

double Add(double a, double b){
  return a+b;
}

double Mult(double a, double b){
  return a*b;
}

int main(){
  Combiner(12,13,Add);
  Combiner(12,13,Mult);
}

Sometimes, though, it is more convenient to use a template function:

// g++ test.cpp --std=c++11

template<class T>
double Combiner(double a, double b, T func){
  return func(a,b);
}

double Add(double a, double b){
  return a+b;
}

double Mult(double a, double b){
  return a*b;
}

int main(){
  Combiner(12,13,Add);
  Combiner(12,13,Mult);
}

Switch statement for greater-than/less-than

Untested and unsure if this will work, but why not do a few if statements before, to set variables for the switch statement.

var small, big;

if(scrollLeft < 1000){
    //add some token to the page
    //call it small
}


switch (//reference token/) {
  case (small):
   //do stuff
   break;
  case (big):
   //do stuff;
   break;
}

How do I access the HTTP request header fields via JavaScript?

This can be accessed through Javascript because it's a property of the loaded document, not of its parent.

Here's a quick example:

<script type="text/javascript">
document.write(document.referrer);
</script>

The same thing in PHP would be:

<?php echo $_SERVER["HTTP_REFERER"]; ?>

installing urllib in Python3.6

The corrected code is

import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand: 
    words = line.decode().split() 
for word in words: 
    counts[word] = counts.get(word, 0) + 1 
print(counts) 

running the code above produces

{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}

Namespace not recognized (even though it is there)

In my case, the referenced dll was build in higher version of .Net Framework. After I added the reference, I could use it. But as soon as I did a build, the 'missing reference' error will pop up. I refresh the dll the error will go but it would never build. This post made me check the framework version and thus I could resolve it by building the referenced project in same version.

how to get data from selected row from datagridview

I was having the same issue and this works excellently.

Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting  
  'Display complete contents in tooltip even though column display cuts off part of it.   
  DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
End Sub

String comparison technique used by Python

Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.

How do I create a user account for basic authentication?

I know this is a really old question but I wanted to add a bit of explanation that I discovered the hard way (this is n00b information).

"Basic Authentication" shares the same accounts that you have on your local computer or network. If you leave the domain and realm empty, local accounts are what are actually being used. So to add a new account you follow the exact process you would for adding a normal new user account to your local computer (as answered by JoshM or shown here). If you enter a domain and realm you can create network accounts in your local active directory and these are what will be used to log the user in and out.

Because it has been around for so long, basic authentication is generally compatible with any browser/system out there but it does have to major flaws:

  • user and password are sent in the clear (except over SSL)
  • you need to have a user account for each user or client

For more information about basic authentication or user accounts see the following MSDN page.

How can I style an Android Switch?

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Sqlite or MySql? How to decide?

The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.

Java regex to extract text between tags

    String s = "<B><G>Test</G></B><C>Test1</C>";

    String pattern ="\\<(.+)\\>([^\\<\\>]+)\\<\\/\\1\\>";

       int count = 0;

        Pattern p = Pattern.compile(pattern);
        Matcher m =  p.matcher(s);
        while(m.find())
        {
            System.out.println(m.group(2));
            count++;
        }

.htaccess mod_rewrite - how to exclude directory from rewrite rule

If you want to remove a particular directory from the rule (meaning, you want to remove the directory foo) ,you can use :

RewriteEngine on

RewriteCond %{REQUEST_URI} !^/foo/$
RewriteRule !index\.php$ /index.php [L]

The rewriteRule above will rewrite all requestes to /index.php excluding requests for /foo/ .

To exclude all existent directries, you will need to use the following condition above your rule :

RewriteCond %{REQUEST_FILENAME} !-d

the following rule

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !index\.php$ /index.php [L]

rewrites everything (except directries) to /index.php .

How do I pass multiple attributes into an Angular.js attribute directive?

This worked for me and I think is more HTML5 compliant. You should change your html to use 'data-' prefix

<div data-example-directive data-number="99"></div>

And within the directive read the variable's value:

scope: {
        number : "=",
        ....
    },

How to generate a random string in Ruby

My favorite is (:A..:Z).to_a.shuffle[0,8].join. Note that shuffle requires Ruby > 1.9.

Getting the ID of the element that fired an event

this works with most types of elements:

$('selector').on('click',function(e){
    log(e.currentTarget.id);
    });

Getting title and meta tags from external website

Your best bet is to bite the bullet use the DOM Parser - it's the 'right way' to do it. In the long run it'll save you more time than it takes to learn how. Parsing HTML with Regex is known to be unreliable and intolerant of special cases.

Simplest JQuery validation rules example

$("#commentForm").validate({
    rules: {
     cname : { required : true, minlength: 2 }
    }
});

Should be something like that, I've just typed this up in the editor here so might be a syntax error or two, but you should be able to follow the pattern and the documentation

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

You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.

_x000D_
_x000D_
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const {
    stdout,
    stderr
  } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
_x000D_
_x000D_
_x000D_

UINavigationBar custom back button without title

To add to Thomas C's answer above, sometimes putting a single space doesn't work and you have to keep adding spaces.

empty bar button

You'll know you succeeded when you see "Bar Button Item - " under the "Navigation Item". That's in the Document Outline (Editor->Show Document Outline). Once you see the above picture, you can delete a few spaces and see if it still works.

Explanation of BASE terminology

To add to the other answers, I think the acronyms were derived to show a scale between the two terms to distinguish how reliable transactions or requests where between RDMS versus Big Data.

From this article acid vs base

In Chemistry, pH measures the relative basicity and acidity of an aqueous (solvent in water) solution. The pH scale extends from 0 (highly acidic substances such as battery acid) to 14 (highly alkaline substances like lie); pure water at 77° F (25° C) has a pH of 7 and is neutral.

Data engineers have cleverly borrowed acid vs base from chemists and created acronyms that while not exact in their meanings, are still apt representations of what is happening within a given database system when discussing the reliability of transaction processing.

One other point, since I work with Big Data using Elasticsearch. To clarify, an instance of Elasticsearch is a node and a group of nodes form a cluster.

To me from a practical standpoint, BA (Basically Available), in this context, has the idea of multiple master nodes to handle the Elasticsearch cluster and it's operations.

If you have 3 master nodes and the currently directing master node goes down, the system stays up, albeit in a less efficient state, and another master node takes its place as the main directing master node. If two master nodes go down, the system still stays up and the last master node takes over.

Regular expression for a hexadecimal number?

This will match with or without 0x prefix

(?:0[xX])?[0-9a-fA-F]+

Display date/time in user's locale format and time offset

Here's what I've used in past projects:

var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set.  again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');

Build query string for System.Net.HttpClient get

Along the same lines as Rostov's post, if you do not want to include a reference to System.Web in your project, you can use FormDataCollection from System.Net.Http.Formatting and do something like the following:

Using System.Net.Http.Formatting.FormDataCollection

var parameters = new Dictionary<string, string>()
{
    { "ham", "Glaced?" },
    { "x-men", "Wolverine + Logan" },
    { "Time", DateTime.UtcNow.ToString() },
}; 
var query = new FormDataCollection(parameters).ReadAsNameValueCollection().ToString();

In PHP how can you clear a WSDL cache?

You can safely delete the WSDL cache files. If you wish to prevent future caching, use:

ini_set("soap.wsdl_cache_enabled", 0);

or dynamically:

$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

    <LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">

        Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Good luck!!!!

How do I make a branch point at a specific commit?

git branch -f <branchname> <commit>

I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on

git branch -f <branchname> <commit>

Here is a scenario where I have needed to do this.

Scenario

Develop on the wrong branch and hence need to reset it.

Start Okay

Cleanly develop and release some software.

So far so good

Develop on wrong branch

Mistake: Accidentally stay on the release branch while developing further.

After a mistake

Realize the mistake

"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.

Create a branch for the development that is up to date holding the work committed so far and switch to it.

git branch development
git checkout development 

Changed to another branch

Correct the branch

Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.

Correct the release branch to point back to the last real release.

git branch -f release release2

The release branch is now correct again, like this ...

Corrected

What if I pushed the mistake to a remote?

git push -f <remote> <branch> is well described in another thread, though the word "overwrite" in the title is misleading. Force "git push" to overwrite remote files

Apk location in New Android Studio

The .apk file is located at [your project]\out\production\[your project name]

Calling one Bash script from another Script passing it arguments with quotes and spaces

Quote your args in Testscript 1:

echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"

Change hash without reload in jQuery

You can set your hash directly to URL too.

window.location.hash = "YourHash";

The result : http://url#YourHash

How to convert an NSString into an NSNumber

I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?

All I pretty much did was:

double myDouble = [myString doubleValue];

How to set Toolbar text and back arrow color

To change the Toolbar's back icon drawable you can use this:
Add the <item name="toolbarStyle">@style/ToolbarStyle</item> into your Theme.
And here is the ToolbarStyle itself:

<style name="ToolbarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="navigationIcon">@drawable/ic_up_indicator</item>
</style>

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

I think the confusing aspect of this is the fact that BootStrap 3 is a mobile first responsive system and fails to explain how this affects the col-xx-n hierarchy in that part of the Bootstrap documentation. This makes you wonder what happens on smaller devices if you choose a value for larger devices and makes you wonder if there is a need to specify multiple values. (You don't)

I would attempt to clarify this by stating that... Lower grain types (xs, sm) attempt retain layout appearance on smaller screens and larger types (md,lg) will display correctly only on larger screens but will wrap columns on smaller devices. The values quoted in previous examples refer to the threshold as which bootstrap degrades the appearance to fit the available screen estate.

What this means in practice is that if you make the columns col-xs-n then they will retain correct appearance even on very small screens, until the window drops to a size that is so restrictive that the page cannot be displayed correctly. This should mean that devices that have a width of 768px or less should show your table as you designed it rather than in degraded (single or wrapped column form). Obviously this still depends on the content of the columns and that's the whole point. If the page attempts to display multiple columns of large data, side by side on a small screen then the columns will naturally wrap in a horrible way if you did not account for it. Therefore, depending on the data within the columns you can decide the point at which the layout is sacificed to display the content adequately.

e.g. If your page contains three col-sm-n columns bootstrap would wrap the columns into rows when the page width drops below 992px. This means that the data is still visible but will require vertical scrolling to view it. If you do not want your layout to degrade, choose xs (as long as your data can be adequately displayed on a lower resolution device in three columns)

If the horizontal position of the data is important then you should try to choose lower granularity values to retain the visual nature. If the position is less important but the page must be visible on all devices then a higher value should be used.

If you choose col-lg-n then the columns will display correctly until the screen width drops below the xs threshold of 1200px.

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

Note that HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

As others have noted, the two also differ when using IPv6:

$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'

decimal vs double! - Which one should I use and when?

For money, always decimal. It's why it was created.

If numbers must add up correctly or balance, use decimal. This includes any financial storage or calculations, scores, or other numbers that people might do by hand.

If the exact value of numbers is not important, use double for speed. This includes graphics, physics or other physical sciences computations where there is already a "number of significant digits".

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
{
public :
    PetStore()
    : Farm()     // <---- Call base-class constructor in initialision list
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

JOptionPane YES/No Options Confirm Dialog Box Issue

int opcion = JOptionPane.showConfirmDialog(null, "Realmente deseas salir?", "Aviso", JOptionPane.YES_NO_OPTION);

if (opcion == 0) { //The ISSUE is here
   System.out.print("si");
} else {
   System.out.print("no");
}

Remove property for all objects in array

ES6:

const newArray = array.map(({keepAttr1, keepAttr2}) => ({keepAttr1, newPropName: keepAttr2}))

What does "#pragma comment" mean?

The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment to send a command to the linker at link time for example

#pragma comment(linker,"/ENTRY:Entry")

tell the linker to change the entry point form WinMain() to Entry() after that the CRTStartup going to transfer controll to Entry()

Owl Carousel, making custom navigation

If you want to use your own custom navigation elements,

For Owl Carousel 1

var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
    owl.trigger('owl.prev');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
    owl.trigger('owl.next');
})

For Owl Carousel 2

var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
    owl.trigger('next.owl.carousel');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
    // With optional speed parameter
    // Parameters has to be in square bracket '[]'
    owl.trigger('prev.owl.carousel', [300]);
})

How do I center a Bootstrap div with a 'spanX' class?

If anyone wants the true solution for centering BOTH images and text within a span using bootstrap row-fluid, here it is (how to implement this and explanation follows my example):

css

div.row-fluid [class*="span"] .center-in-span { 
   float: none; 
   margin: 0 auto; 
   text-align: center; 
   display: block; 
   width: auto; 
   height: auto;
}

html

<div class="row-fluid">
   <div class="span12">
      <img class="center-in-span" alt="MyExample" src="/path/to/example.jpg"/>
   </div>
</div>

<div class="row-fluid">
   <div class="span12">
      <p class="center-in-span">this is text</p>
   </div>
</div>

USAGE: To use this css to center an image within a span, simply apply the .center-in-span class to the img element, as shown above.

To use this css to center text within a span, simply apply the .center-in-span class to the p element, as shown above.

EXPLANATION: This css works because we are overriding specific bootstrap styling. The notable differences from the other answers that were posted are that the width and height are set to auto, so you don't have to used a fixed with (good for a dynamic webpage). also, the combination of setting the margin to auto, text-align:center and display:block, takes care of both images and paragraphs.

Let me know if this is thorough enough for easy implementation.

How to send a GET request from PHP?

Unless you need more than just the contents of the file, you could use file_get_contents.

$xml = file_get_contents("http://www.example.com/file.xml");

For anything more complex, I'd use cURL.

MySQL Fire Trigger for both Insert and Update

In response to @Zxaos request, since we can not have AND/OR operators for MySQL triggers, starting with your code, below is a complete example to achieve the same.

1. Define the INSERT trigger:

DELIMITER //
DROP TRIGGER IF EXISTS my_insert_trigger//
CREATE DEFINER=root@localhost TRIGGER my_insert_trigger
    AFTER INSERT ON `table`
    FOR EACH ROW

BEGIN
    -- Call the common procedure ran if there is an INSERT or UPDATE on `table`
    -- NEW.id is an example parameter passed to the procedure but is not required
    -- if you do not need to pass anything to your procedure.
    CALL procedure_to_run_processes_due_to_changes_on_table(NEW.id);
END//
DELIMITER ;

2. Define the UPDATE trigger

DELIMITER //
DROP TRIGGER IF EXISTS my_update_trigger//

CREATE DEFINER=root@localhost TRIGGER my_update_trigger
    AFTER UPDATE ON `table`
    FOR EACH ROW
BEGIN
    -- Call the common procedure ran if there is an INSERT or UPDATE on `table`
    CALL procedure_to_run_processes_due_to_changes_on_table(NEW.id);
END//
DELIMITER ;

3. Define the common PROCEDURE used by both these triggers:

DELIMITER //
DROP PROCEDURE IF EXISTS procedure_to_run_processes_due_to_changes_on_table//

CREATE DEFINER=root@localhost PROCEDURE procedure_to_run_processes_due_to_changes_on_table(IN table_row_id VARCHAR(255))
READS SQL DATA
BEGIN

    -- Write your MySQL code to perform when a `table` row is inserted or updated here

END//
DELIMITER ;

You note that I take care to restore the delimiter when I am done with my business defining the triggers and procedure.

Unicode characters in URLs

Use percent encoding. Modern browsers will take care of display & paste issues and make it human-readable. E. g. http://ko.wikipedia.org/wiki/????:??

Edit: when you copy such an url in Firefox, the clipboard will hold the percent-encoded form (which is usually a good thing), but if you copy only a part of it, it will remain unencoded.

Increasing (or decreasing) the memory available to R processes

For linux/unix, I can suggest unix package.

To increase the memory limit in linux:

install.packages("unix") 
library(unix)
rlimit_as(1e12)  #increases to ~12GB

You can also check the memory with this:

rlimit_all()

for detailed information: https://rdrr.io/cran/unix/man/rlimit.html

also you can find further info here: limiting memory usage in R under linux

Creating layout constraints programmatically

When using Auto Layout in code, setting the frame does nothing. So the fact that you specified a width of 200 on the view above, doesn't mean anything when you set constraints on it. In order for a view's constraint set to be unambiguous, it needs four things: an x-position, a y-position, a width, and a height for any given state.

Currently in the code above, you only have two (height, relative to the superview, and y-position, relative to the superview). In addition to this, you have two required constraints that could conflict depending on how the view's superview's constraints are setup. If the superview were to have a required constraint that specifies it's height be some value less than 748, you will get an "unsatisfiable constraints" exception.

The fact that you've set the width of the view before setting constraints means nothing. It will not even take the old frame into account and will calculate a new frame based on all of the constraints that it has specified for those views. When dealing with autolayout in code, I typically just create a new view using initWithFrame:CGRectZero or simply init.

To create the constraint set required for the layout you verbally described in your question, you would need to add some horizontal constraints to bound the width and x-position in order to give a fully-specified layout:

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"V:|-[myView(>=748)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"H:[myView(==200)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

Verbally describing this layout reads as follows starting with the vertical constraint:

myView will fill its superview's height with a top and bottom padding equal to the standard space. myView's superview has a minimum height of 748pts. myView's width is 200pts and has a right padding equal to the standard space against its superview.

If you would simply like the view to fill the entire superview's height without constraining the superview's height, then you would just omit the (>=748) parameter in the visual format text. If you think that the (>=748) parameter is required to give it a height - you don't in this instance: pinning the view to the superview's edges using the bar (|) or bar with space (|-, -|) syntax, you are giving your view a y-position (pinning the view on a single-edge), and a y-position with height (pinning the view on both edges), thus satisfying your constraint set for the view.

In regards to your second question:

Using NSDictionaryOfVariableBindings(self.myView) (if you had an property setup for myView) and feeding that into your VFL to use self.myView in your VFL text, you will probably get an exception when autolayout tries to parse your VFL text. It has to do with the dot notation in dictionary keys and the system trying to use valueForKeyPath:. See here for a similar question and answer.

How to allow only one radio button to be checked?

All the radio buttons options must have the same name for you to be able to select one option at a time.

References with text in LaTeX

Using the hyperref package, you could also declare a new command by using \newcommand{\secref}[1]{\autoref{#1}. \nameref{#1}} in the pre-amble. Placing \secref{section:my} in the text generates: 1. My section.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

For self-containing Maven project I usually installing all external jar dependencies into project's repository. For SQL Server JDBC driver you can do:

  • download JDBC driver from https://www.microsoft.com/en-us/download/confirmation.aspx?id=11774
  • create folder local-repo in your Maven project
  • temporary copy sqljdbc42.jar into local-repo folder
  • in local-repo folder run mvn deploy:deploy-file -Dfile=sqljdbc42.jar -DartifactId=sqljdbc42 -DgroupId=com.microsoft.sqlserver -DgeneratePom=true -Dpackaging=jar -Dversion=6.0.7507.100 -Durl=file://. to deploy JAR into local repository (stored together with your code in SCM)
  • sqljdbc42.jar and downloaded files can be deleted
  • modify your's pom.xml and add reference to project's local repository: xml <repositories> <repository> <id>parent-local-repository</id> <name>Parent Local repository</name> <layout>default</layout> <url>file://${basedir}/local-repo</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> Now you can run your project everywhere without any additional configurations or installations.

Controlling fps with requestAnimationFrame?

A simple solution to this problem is to return from the render loop if the frame is not required to render:

const FPS = 60;
let prevTick = 0;    

function render() 
{
    requestAnimationFrame(render);

    // clamp to fixed framerate
    let now = Math.round(FPS * Date.now() / 1000);
    if (now == prevTick) return;
    prevTick = now;

    // otherwise, do your stuff ...
}

It's important to know that requestAnimationFrame depends on the users monitor refresh rate (vsync). So, relying on requestAnimationFrame for game speed for example will make it unplayable on 200Hz monitors if you're not using a separate timer mechanism in your simulation.

CSS3 selector to find the 2nd div of the same class

My original answer regarding :nth-of-type is simply wrong. Thanks to Paul for pointing this out.

The word "type" there refers only to the "element type" (like div). It turns out that the selectors div.bar:nth-of-type(2) and div:nth-of-type(2).bar mean the same thing. Both select elements that [a] are the second div of their parent, and [b] have class bar.

So the only pure CSS solution left that I'm aware of, if you want to select all elements of a certain selector except the first, is the general sibling selector:

.bar ~ .bar

http://www.w3schools.com/cssref/sel_gen_sibling.asp


My original (wrong) answer follows:

With the arrival of CSS3, there is another option. It may not have been available when the question was first asked:

.bar:nth-of-type(2)

http://www.w3schools.com/cssref/sel_nth-of-type.asp

This selects the second element that satisfies the .bar selector.

If you want the second and last of a specific kind of element (or all of them except the first), the general sibling selector would also work fine:

.bar ~ .bar

http://www.w3schools.com/cssref/sel_gen_sibling.asp

It's shorter. But of course, we don't like to duplicate code, right? :-)

How to get an HTML element's style values in javascript?

In jQuery, you can do alert($("#theid").css("width")).

-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.

Update

for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.

If Python is interpreted, what are .pyc files?

These are created by the Python interpreter when a .py file is imported, and they contain the "compiled bytecode" of the imported module/program, the idea being that the "translation" from source code to bytecode (which only needs to be done once) can be skipped on subsequent imports if the .pyc is newer than the corresponding .py file, thus speeding startup a little. But it's still interpreted.

Get value of multiselect box using jQuery or pure JS

This got me the value and text of the selected options for the jQuery multiselect.js plugin:

$("#selectBox").multiSelect({
    afterSelect: function(){
        var selections = [];
        $("#selectBox option:selected").each(function(){
            var optionValue = $(this).val();
            var optionText = $(this).text();
            console.log("optionText",optionText);                
            // collect all values
            selections.push(optionValue);
        });

        // use array "selections" here.. 
    }
});   

very usefull if you need it for your "onChange" event ;)

ImportError: No module named request

You can do that using Python 2.

  1. Remove request
  2. Make that line: from urllib2 import urlopen

You cannot have request in Python 2, you need to have Python 3 or above.

Defining static const integer members in class definition

Here's another way to work around the problem:

std::min(9, int(test::N));

(I think Crazy Eddie's answer correctly describes why the problem exists.)

How can I delay a method call for 1 second?

You can do this

[self performSelector:@selector(MethodToExecute) withObject:nil afterDelay:1.0 ];

failed to load ad : 3

Option 1: Go to Settings-> search Reset advertising ID -> click on Reset advertising ID -> OK. You should start receiving Ads now

No search option? Try Option 2

Option 2: Go to Settings->Google->Ads->Reset advertising ID->OK

No Google options in Settings? Try Option 3

Option 3:Look for Google Settings (NOT THE SETTINGS)->Ads->Reset advertising ID

Spring Boot REST service exception handling

By default Spring Boot gives json with error details.

curl -v localhost:8080/greet | json_pp
[...]
< HTTP/1.1 400 Bad Request
[...]
{
   "timestamp" : 1413313361387,
   "exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
   "status" : 400,
   "error" : "Bad Request",
   "path" : "/greet",
   "message" : "Required String parameter 'name' is not present"
}

It also works for all kind of request mapping errors. Check this article http://www.jayway.com/2014/10/19/spring-boot-error-responses/

If you want to create log it to NoSQL. You can create @ControllerAdvice where you would log it and then re-throw the exception. There is example in documentation https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

Could not obtain information about Windows NT group user

Active Directory is refusing access to your SQL Agent. The Agent should be running under an account that is recognized by STAR domain controller.

Printing *s as triangles in Java?

Question:

      *
     ***
    *****

Answer:

    int i,a,j;
    i=5;
    while (i>=3)
    {
        a=1;
        while (a<=i)
        {

            System.out.print(" ");
            a++;
        }
        j=10;
        while (j/2>=i)
        {
            System.out.print("*");
            --j;
        }
        System.out.println("");
        i--;
    }   

Enjoy!!

LOAD DATA INFILE Error Code : 13

If you're using cPanel or phpmyadmin to import the CSV using LOAD DATA then be sure to Enable Use LOCAL keyword. This worked for me in a shared server environment.

excel VBA run macro automatically whenever a cell is changed

Another option is

Private Sub Worksheet_Change(ByVal Target As Range)
    IF Target.Address = "$D$2" Then
        MsgBox("Cell D2 Has Changed.")
    End If
End Sub

I believe this uses fewer resources than Intersect, which will be helpful if your worksheet changes a lot.

img tag displays wrong orientation

An easy way to the fix the problem, sans coding, is to use Photoshop's Save for Web export function. In the dialog box one can chose to remove all or most of an image's EXIF data. I usually just keep copyright and contact info. Also, since images coming directly from a digital camera are greatly oversized for web display it is a good idea to downsize them via Save for the Web anyway. For those that are not Photoshop savvy, I have no doubt that there are online resources for resizing an image and stripping it of any unnecessary EXIF data.

How to get current language code with Swift?

Swift 5.3:

let languagePrefix = Locale.preferredLanguages[0]
print(languagePrefix)

Better way to set distance between flexbox items

Eventually they will add the gap property to flexbox. Until then you could use CSS grid instead which already has the gap property, and just have a single row. Nicer than dealing with margins.

How to check a string for a special character?

You will need to define "special characters", but it's likely that for some string s you mean:

import re
if re.match(r'^\w+$', s):
    # s is good-to-go

data.map is not a function

this.$http.get('https://pokeapi.co/api/v2/pokemon')
.then(response => {
   if(response.status === 200)
   {
      this.usuarios = response.data.results.map(usuario => {
      return { name: usuario.name, url: usuario.url, captched: false } })
          }
    })
.catch( error => { console.log("Error al Cargar los Datos: " + error ) } )

How do I call an Angular 2 pipe with multiple arguments?

Extended from : user3777549

Multi-value filter on one set of data(reference to title key only)

HTML

<div *ngFor='let item of items | filtermulti: [{title:["mr","ms"]},{first:["john"]}]' >
 Hello {{item.first}} !
</div>

filterMultiple

args.forEach(function (filterobj) {
    console.log(filterobj)
    let filterkey = Object.keys(filterobj)[0];
    let filtervalue = filterobj[filterkey];
    myobjects.forEach(function (objectToFilter) {

      if (!filtervalue.some(x=>x==objectToFilter[filterkey]) && filtervalue != "") {
        // object didn't match a filter value so remove it from array via filter
        returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
      }
    })
  });

Spring Boot Rest Controller how to return different HTTP status codes?

Try this code:

@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
    int numberHTTPDesired = 400;
    ErrorBean responseBean = new ErrorBean();
    responseBean.setError("ERROR");
    responseBean.setMensaje("Error in validation!");

    return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}

Keep only first n characters in a string?

var myString = "Hello, how are you?";
myString.slice(0,8);

How can I loop through a C++ map of maps?

As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:

int main() {
    std::map<std::string, std::map<std::string, std::string>> m {
        {"name1", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name2", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name3", {{"value1", "data1"}, {"value2", "data2"}}}
    };

    for (const auto& [k1, v1] : m)
        for (const auto& [k2, v2] : v1)
            std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;

    return 0;
}

Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.

Note 2: If you want to modify the map m within the loops, you have to remove the const keywords.

Code on Coliru

C++ program converts fahrenheit to celsius

Best way would be

#include <iostream>                        
using namespace std;                       

int main() {                               
    float celsius;                         
    float fahrenheit;

    cout << "Enter Celsius temperature: "; 
    cin >> celsius;
    fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
    cout << "Fahrenheit = " << fahrenheit << endl;

    return 0;                             
}

:)

How to show an empty view with a RecyclerView?

On the same layout where is defined the RecyclerView, add the TextView:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical" />

<TextView
    android:id="@+id/empty_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:visibility="gone"
    android:text="@string/no_data_available" />

At the onCreate or the appropriate callback you check if the dataset that feeds your RecyclerView is empty. If the dataset is empty, the RecyclerView is empty too. In that case, the message appears on the screen. If not, change its visibility:

private RecyclerView recyclerView;
private TextView emptyView;

// ...

recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
emptyView = (TextView) rootView.findViewById(R.id.empty_view);

// ...

if (dataset.isEmpty()) {
    recyclerView.setVisibility(View.GONE);
    emptyView.setVisibility(View.VISIBLE);
}
else {
    recyclerView.setVisibility(View.VISIBLE);
    emptyView.setVisibility(View.GONE);
}

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

In my case just run the command and worked like charm.

php artisan route:clear

Referring to a Column Alias in a WHERE Clause

You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;

DBFiddle Demo

Pros:

  • single definition of expression(easier to maintain/no need of copying-paste)
  • no need for wrapping entire query with CTE/outerquery
  • possibility to refer in WHERE/GROUP BY/ORDER BY
  • possible better performance(single execution)

Looping through a Scripting.Dictionary using index/item number

According to the documentation of the Item property:

Sets or returns an item for a specified key in a Dictionary object.

In your case, you don't have an item whose key is 1 so doing:

s = d.Item(i)

actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

The Dictionary also has the Items method which allows looping over the indices:

a = d.Items
For i = 0 To d.Count - 1
    s = a(i)
Next i

Cycles in family tree software

Another mock serious answer for a silly question:

The real answer is, use an appropriate data structure. Human genealogy cannot fully be expressed using a pure tree with no cycles. You should use some sort of graph. Also, talk to an anthropologist before going any further with this, because there are plenty of other places similar errors could be made trying to model genealogy, even in the most simple case of "Western patriarchal monogamous marriage."

Even if we want to ignore locally taboo relationships as discussed here, there are plenty of perfectly legal and completely unexpected ways to introduce cycles into a family tree.

For example: http://en.wikipedia.org/wiki/Cousin_marriage

Basically, cousin marriage is not only common and expected, it is the reason humans have gone from thousands of small family groups to a worldwide population of 6 billion. It can't work any other way.

There really are very few universals when it comes to genealogy, family and lineage. Almost any strict assumption about norms suggesting who an aunt can be, or who can marry who, or how children are legitimized for the purpose of inheritance, can be upset by some exception somewhere in the world or history.

How to style readonly attribute with CSS?

To be safe you may want to use both...

input[readonly], input[readonly="readonly"] {
    /*styling info here*/
}

The readonly attribute is a "boolean attribute", which can be either blank or "readonly" (the only valid values). http://www.whatwg.org/specs/web-apps/current-work/#boolean-attribute

If you are using something like jQuery's .prop('readonly', true) function, you'll end up needing [readonly], whereas if you are using .attr("readonly", "readonly") then you'll need [readonly="readonly"].


Correction: You only need to use input[readonly]. Including input[readonly="readonly"] is redundant. See https://stackoverflow.com/a/19645203/1766230

How can prepared statements protect from SQL injection attacks?

In SQL Server, using a prepared statement is definitely injection-proof because the input parameters don't form the query. It means that the executed query is not a dynamic query. Example of an SQL injection vulnerable statement.

string sqlquery = "select * from table where username='" + inputusername +"' and password='" + pass + "'";

Now if the value in the inoutusername variable is something like a' or 1=1 --, this query now becomes:

select * from table where username='a' or 1=1 -- and password=asda

And the rest is commented after --, so it never gets executed and bypassed as using the prepared statement example as below.

Sqlcommand command = new sqlcommand("select * from table where username = @userinput and password=@pass");
command.Parameters.Add(new SqlParameter("@userinput", 100));
command.Parameters.Add(new SqlParameter("@pass", 100));
command.prepare();

So in effect you cannot send another parameter in, thus avoiding SQL injection...

How to vertical align an inline-block in a line of text?

display: inline-block is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:

Working Example

(it looks like your picture anyway ;))

CSS:

p, div {
  display: inline-block; 
  vertical-align: middle;
}
p, div {
  display: inline !ie7; /* hack for IE7 and below */
}

table {
  background: #000; 
  color: #fff; 
  font-size: 16px; 
  font-weight: bold; margin: 0 10px;
}

td {
  padding: 5px; 
  text-align: center;
}

HTML:

<p>some text</p> 
<div>
  <table summary="">
  <tr><td>A</td></tr>
  <tr><td>B</td></tr>
  <tr><td>C</td></tr>
  <tr><td>D</td></tr>
  </table>
</div> 
<p>continues afterwards</p>