Programs & Examples On #Valuestack

The ValueStack is a context for the beans evaluated via the EL expressions.

Get JSON Data from URL Using Android?

Don't know about android but in POJ I use

public final class MyJSONObject extends JSONObject {
    public MyJSONObject(URL url) throws IOException {
        super(getServerData(url));
    }
    static String getServerData(URL url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String text = ir.lines().collect(Collectors.joining("\n"));
        return (text);
    }
}

Add new column with foreign key constraint in one command

You can do it like below in SQL Server

ALTER TABLE one
ADD two_id int foreign key
REFERENCES two(id)

JavaScript DOM: Find Element Index In Container

A modern native approach could make use of 'Array.from()' - for example: `

_x000D_
_x000D_
const el = document.getElementById('get-this-index')_x000D_
const index = Array.from(document.querySelectorAll('li')).indexOf(el)_x000D_
document.querySelector('h2').textContent = `index = ${index}`
_x000D_
<ul>_x000D_
  <li>zero_x000D_
  <li>one_x000D_
  <li id='get-this-index'>two_x000D_
  <li>three_x000D_
</ul>_x000D_
<h2></h2>
_x000D_
_x000D_
_x000D_

`

How do I remove a MySQL database?

If your database cannot be dropped, even though you have no typos in the statement and do not miss the ; at the end, enclose the database name in between backticks:

mysql> drop database `my-database`;

Backticks are for databases or columns, apostrophes are for data within these.

For more information, see this answer to Stack Overflow question When to use single quotes, double quotes, and backticks?.

How do you create a yes/no boolean field in SQL server?

You can use the BIT field

To create new table:

CREATE TABLE Tb_Table1
(
ID              INT,
BitColumn       BIT DEFAULT 1
)

Adding Column in existing Table:

ALTER TABLE Tb_Table1 ADD BitColumn  BIT DEFAULT 1

To Insert record:

INSERT Tb_Table1 VALUES(11,0)

Disabling swap files creation in vim

If you are using git, you can add *.swp to .gitignore.

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

Print: Entry, ":CFBundleIdentifier", Does Not Exist

the 0.44 is ok to run,but 0.45 can not,maybe is the version problem i solved this by the following command: rninit init TaxiApp --source [email protected];

Python math module

You need to say math.sqrt when you use it. Or, do from math import sqrt.

Hmm, I just read your question more thoroughly.... How are you importing math? I just tried import math and then math.sqrt which worked perfectly. Are you doing something like import math as m? If so, then you have to prefix the function with m (or whatever name you used after as).

pow is working because there are two versions: an always available version in __builtin__, and another version in math.

Remove padding from columns in Bootstrap 3

Specifically for SASS mixin:

@mixin no-padding($side) {
    @if $side == 'all' {
        .no-padding {
            padding: 0 !important;
        }
    } @else {
        .no-padding-#{$side} {
            padding-#{$side}: 0 !important;
        }
    }
}

@include no-padding("left");
@include no-padding("right");
@include no-padding("top");
@include no-padding("bottom");
@include no-padding("all");

Then in HTML, you can use

.no-padding-left
.no-padding-right
.no-padding-bottom
.no-padding-top
.no-padding - to remove padding from all sides

Sure, you can @include only those declarations, which you need.

How to position two elements side by side using CSS

None of these solutions seem to work if you increase the amount of text so it is larger than the width of the parent container, the element to the right still gets moved below the one to the left instead of remaining next to it. To fix this, you can apply this style to the left element:

position: absolute;
width: 50px;

And apply this style to the right element:

margin-left: 50px;

Just make sure that the margin-left for the right element is greater than or equal to the width of the left element. No floating or other attributes are necessary. I would suggest wrapping these elements in a div with the style:

display: inline-block;

Applying this style may not be necessary depending on surrounding elements

Fiddle: http://jsfiddle.net/2b0bqqse/

You can see the text to the right is taller than the element to the left outlined in black. If you remove the absolute positioning and margin and instead use float as others have suggested, the text to the right will drop down below the element to the left

Fiddle: http://jsfiddle.net/qrx78u20/

How to set ssh timeout?

You could also connect with flag

-o ServerAliveInterval=<secs>
so the SSH client will send a null packet to the server each <secs> seconds, just to keep the connection alive. In Linux this could be also set globally in /etc/ssh/ssh_config or per-user in ~/.ssh/config.

Instant run in Android Studio 2.0 (how to turn off)

Using Android Studio newest version and update Android Plugin to 'newest alpha version`, I can disable Instant Run: Android studio Instant Run view with Version highlighted Android studio Project view with Android Plugin Version highlighted

Try to update Android Studio.

jQuery get values of checked checkboxes into array

I refactored your code a bit and believe I came with the solution for which you were looking. Basically instead of setting searchIDs to be the result of the .map() I just pushed the values into an array.

$("#merge_button").click(function(event){
  event.preventDefault();

  var searchIDs = [];

  $("#find-table input:checkbox:checked").map(function(){
    searchIDs.push($(this).val());
  });

  console.log(searchIDs);
});

I created a fiddle with the code running.

How do you keep parents of floated elements from collapsing?

One of the most well known solutions is a variation of your solution number 3 that uses a pseudo element instead of a non-semantic html element.

It goes something like this...

.cf:after {
    content: " ";
    display: block;
    visibility: hidden;
    height: 0;
    clear: both;
}

You place that in your stylesheet, and all you need is to add the class 'cf' to the element containing the floats.

What I use is another variation which comes from Nicolas Gallagher.

It does the same thing, but it's shorter, looks neater, and maybe used to accomplish another thing that's pretty useful - preventing the child elements' margins from collapsing with it's parents' (but for that you do need something else - read more about it here http://nicolasgallagher.com/micro-clearfix-hack/ ).

.cf:after {
    content: " ";
    display: table;
    clear: float;
}

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

If you have problem getting the latest, just create a new Spring Starter Project. Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.

ASP.NET Core Get Json Array using IConfiguration

Add a level in your appsettings.json :

{
  "MySettings": {
    "MyArray": [
      "str1",
      "str2",
      "str3"
    ]
  }
}

Create a class representing your section :

public class MySettings
{
     public List<string> MyArray {get; set;}
}

In your application startup class, bind your model an inject it in the DI service :

services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));

And in your controller, get your configuration data from the DI service :

public class HomeController : Controller
{
    private readonly List<string> _myArray;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _myArray = mySettings.Value.MyArray;
    }

    public IActionResult Index()
    {
        return Json(_myArray);
    }
}

You can also store your entire configuration model in a property in your controller, if you need all the data :

public class HomeController : Controller
{
    private readonly MySettings _mySettings;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        return Json(_mySettings.MyArray);
    }
}

The ASP.NET Core's dependency injection service works just like a charm :)

Array of arrays (Python/NumPy)

a=np.array([[1,2,3],[4,5,6]])

a.tolist()

tolist method mentioned above will return the nested Python list

Replace values in list using Python

In case you want to replace values in place, you can update your original list with values from a list comprehension by assigning to the whole slice of the original.

data = [*range(11)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
id_before = id(data)
data[:] = [x if x % 2 else None for x in data]
data
# Out: [None, 1, None, 3, None, 5, None, 7, None, 9, None]
id_before == id(data)  # check if list is still the same
# Out: True

If you have multiple names pointing to the original list, for example you wrote data2=data before changing the list and you skip the slice notation for assigning to data, data will rebind to point to the newly created list while data2 still points to the original unchanged list.

data = [*range(11)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
data2 = data
id_before = id(data)
data = [x if x % 2 else None for x in data]  # no [:] here
data
# Out: [None, 1, None, 3, None, 5, None, 7, None, 9, None]
id_before == id(data)  # check if list is still the same
# Out: False
data2
# Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note: This is no recommendation for generally preferring one over the other (changing list in place or not), but behavior you should be aware of.

How do I create a batch file timer to execute / call another batch throughout the day

I did it by writing a little C# app that just wakes up to launch periodic tasks -- don't know if it is doable from a batch file without downloading extensions to support a sleep command. (For my purposes the Windows scheduler didn't work because the apps launched had no graphics context available.)

Function in JavaScript that can be called only once

This one is useful for preventing infinite loops (using jQuery):

<script>
var doIt = true;
if(doIt){
  // do stuff
  $('body').html(String($('body').html()).replace("var doIt = true;", 
                                                  "var doIt = false;"));
} 
</script>

If you're worried about namespace pollution, subsitute a long, random string for "doIt".

Allowed memory size of 536870912 bytes exhausted in Laravel

I had this problem when trying to resize a CMYK jpeg using the Intervention / gd library. I had to increase the memory_limit.

installing vmware tools: location of GCC binary?

Found the answer. What I did was was first

sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y

and tried it but it didn't work so I continued and did

sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`

after doing these two steps and trying again, it worked.

How to display a gif fullscreen for a webpage background?

You can set up a background with your GIF file and set the body this way:

body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}

Change background image URL with your GIF. With background-position: center you can put the image to the center and with background-size: cover you set the picture to fit all the screen. You can also set background-size: contain if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.

Here's more info about the property:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

Hope it helps :)

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

Sometimes there is some error in the local Maven repo. So please close your eclipse and delete the jar spring-webmvc from your local .m2 then open Eclipse and on the project press Update Maven Dependencies.

Then Eclipse will download the dependency again for you. That how I fixed the same problem.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

use jQuery to get values of selected checkboxes

var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
     SlectedList.push($(this).val());
});

Select All checkboxes using jQuery

$(document).ready(function() {
    $('#ckbCheckAll').click(function() {
        $('.checkBoxClass').each(function() {
            $(this).attr('checked',!$(this).attr('checked'));
        });
    });
});

OR

$(function () {
    $('#ckbCheckAll').toggle(
        function() {
            $('.checkBoxClass').prop('checked', true);
        },
        function() {
            $('.checkBoxClass').prop('checked', false);
        }
    );
});

Where IN clause in LINQ

This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.

Problem:

Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate) composite Keys : name,version

So we need to get latest versions of all documents.

soloution

 var result = (from t in Context.document
                          where ((from tt in Context.document where t.Name == tt.Name
                                orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
                          select t).ToList();

How to Make Laravel Eloquent "IN" Query?

If you are using Query builder then you may use a blow

DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()

If you are working with Eloquent then you can use as below

$sendUsersList = Newsletter Subscription:: select ('*')
                ->whereIn('id', $send_users_list)
                ->get();

How can I display a JavaScript object?

Simply use

JSON.stringify(obj)

Example

var args_string = JSON.stringify(obj);
console.log(args_string);

Or

alert(args_string);

Also, note in javascript functions are considered as objects.

As an extra note :

Actually you can assign new property like this and access it console.log or display it in alert

foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);

Can I create a One-Time-Use Function in a Script or Stored Procedure?

Common Table Expressions let you define what are essentially views that last only within the scope of your select, insert, update and delete statements. Depending on what you need to do they can be terribly useful.

C#: How to access an Excel cell?

Simple.

To open a workbook. Use xlapp.workbooks.Open()

where you have previously declared and instanitated xlapp as so.. Excel.Application xlapp = new Excel.Applicaton();

parameters are correct.

Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.

Overriding !important style

Building on @Premasagar's excellent answer; if you don't want to remove all the other inline styles use this

//accepts the hyphenated versions (i.e. not 'cssFloat')
addStyle(element, property, value, important) {
    //remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    //insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

Can't use removeProperty() because it wont remove !important rules in Chrome.
Can't use element.style[property] = '' because it only accepts camelCase in FireFox.

Variables declared outside function

The local names for a function are decided when the function is defined:

>>> x = 1
>>> def inc():
...     x += 5
...     
>>> inc.__code__.co_varnames
('x',)

In this case, x exists in the local namespace. Execution of x += 5 requires a pre-existing value for x (for integers, it's like x = x + 5), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError is named as such.

Compare the other version, where x is not a local variable, so it can be resolved at the global scope instead:

>>> def incg():
...    print(x)
...    
>>> incg.__code__.co_varnames
()

Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Getter and Setter declaration in .NET

Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).

In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.

how to access iFrame parent page using jquery?

yeah it works for me as well.

Note : we need to use window.parent.document

    $("button", window.parent.document).click(function()
    {
        alert("Functionality defined by def");
    });

How to get distinct values from an array of objects in JavaScript?

The forEach version of @travis-j's answer (helpful on modern browsers and Node JS world):

var unique = {};
var distinct = [];
array.forEach(function (x) {
  if (!unique[x.age]) {
    distinct.push(x.age);
    unique[x.age] = true;
  }
});

34% faster on Chrome v29.0.1547: http://jsperf.com/filter-versus-dictionary/3

And a generic solution that takes a mapper function (tad slower than direct map, but that's expected):

function uniqueBy(arr, fn) {
  var unique = {};
  var distinct = [];
  arr.forEach(function (x) {
    var key = fn(x);
    if (!unique[key]) {
      distinct.push(key);
      unique[key] = true;
    }
  });
  return distinct;
}

// usage
uniqueBy(array, function(x){return x.age;}); // outputs [17, 35]

Rerender view on browser resize with React

As of React 16.8 you can use Hooks!

/* globals window */
import React, { useState, useEffect } from 'react'
import _debounce from 'lodash.debounce'

const Example = () => {
  const [width, setWidth] = useState(window.innerWidth)

  useEffect(() => {
    const handleResize = _debounce(() => setWidth(window.innerWidth), 100)

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    }
  }, [])

  return <>Width: {width}</>
}

Efficient way to add spaces between characters in a string

A very pythonic and practical way to do it is by using the string join() method:

str.join(iterable)

The official Python documentations says:

Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.

How to use it?

Remember: this is a string method.

This method will be applied to the str above, which reflects the string that will be used as separator of the items in the iterable.

Let's have some practical example!

iterable = "BINGO"
separator = " " # A whitespace character.
                # The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'

In practice you would do it like this:

iterable = "BINGO"    
" ".join(iterable)
> 'B I N G O'

But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.

iterable = ['B', 'I', 'N', 'G', 'O']    
" ".join(iterable)
> 'B I N G O'

What happens if you use a hyphen as a string instead?

iterable = ['B', 'I', 'N', 'G', 'O']    
"-".join(iterable)
> 'B-I-N-G-O'

Mongoose: findOneAndUpdate doesn't return updated document

By default findOneAndUpdate returns the original document. If you want it to return the modified document pass an options object { new: true } to the function:

Cat.findOneAndUpdate({ age: 17 }, { $set: { name: "Naomi" } }, { new: true }, function(err, doc) {

});

Regex in JavaScript for validating decimal numbers

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of custom filter of input of an float number with decimal pointer and limitation to 2 digit after decimal pointer:

_x000D_
_x000D_
<!doctype html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" >_x000D_
<head>_x000D_
    <title>Input Key Filter Test</title>_x000D_
 <meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>_x000D_
 _x000D_
 <!-- For compatibility of IE browser with audio element in the beep() function._x000D_
 https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->_x000D_
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>_x000D_
 _x000D_
 <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">  _x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>_x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>_x000D_
 _x000D_
</head>_x000D_
<body>_x000D_
 <h1>Float field</h1>_x000D_
<input id="Float" _x000D_
 onchange="javascript: onChangeFloat(this)"_x000D_
 onblur="inputKeyFilter.isNaN(parseFloat(this.value), this);"_x000D_
/>_x000D_
<script>_x000D_
 function CreateFloatFilterCustom(elementID, onChange, onblur){_x000D_
  try{_x000D_
   inputKeyFilter.Create(elementID_x000D_
    , onChange_x000D_
    , function(elementInput, value){//customFilter_x000D_
     if(value.match(/^(-?\d*)((\.(\d{0,2})?)?)$/i) == null){_x000D_
      inputKeyFilter.TextAdd(isRussian() ?_x000D_
        "?????????? ??????: -[0...9].[0...9] ??? -[0...9]e-[0...9]. ????????: -12.34 1234"_x000D_
        : "Acceptable formats: -[0...9].[0...9] or -[0...9]e-[0...9]. Examples: -12.34 1234"_x000D_
       , elementInput);_x000D_
      return false;_x000D_
     }_x000D_
     return true;_x000D_
    }_x000D_
    , onblur_x000D_
   )_x000D_
  } catch(e) {_x000D_
   consoleError("Create float filter failed. " + e);_x000D_
  }_x000D_
 }_x000D_
 _x000D_
 CreateFloatFilterCustom("Float");_x000D_
 _x000D_
 function onChangeFloat(input){_x000D_
  inputKeyFilter.RemoveMyTooltip();_x000D_
  var elementNewFloat = document.getElementById("NewFloat");_x000D_
  var float = parseFloat(input.value);_x000D_
  if(inputKeyFilter.isNaN(float, input)){_x000D_
   elementNewFloat.innerHTML = "";_x000D_
   return;_x000D_
  }_x000D_
  elementNewFloat.innerHTML = float;_x000D_
 }_x000D_
</script>_x000D_
 New float: <span id="NewFloat"></span>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Also see my page example of the input key filter

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

How to create text file and insert data to that file on Android

I'm using Kotlin here

Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example

var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
 strwrt=FileWriter(File("sdcard/${NamaFile}"))
            strwrt.write(teks)
            strwrt.close()

after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.

Android Studio: Module won't show up in "Edit Configuration"

Make sure your build.gradle is

apply plugin: 'com.android.application'

not

apply plugin: 'com.android.library'

After you have changed, please sync your gradle again.

enter image description here

How to quickly test some javascript code?

If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:

javascript:alert("hello world");

And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.

How to insert programmatically a new line in an Excel cell in C#?

If anyone is interested in the Infragistics solution, here it is.

  1. Use

    Environment.NewLine

  2. Make sure your cell is wrapped

    dataSheet.Rows[i].Cells[j].CellFormat.WrapText = ExcelDefaultableBoolean.True;

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Best way to store data locally in .NET (C#)

Without knowing what your data looks like, i.e. the complexity, size, etc...XML is easy to maintain and easily accessible. I would NOT use an Access database, and flat files are more difficult to maintain over the long haul, particularly if you are dealing with more than one data field/element in your file.

I deal with large flat-file data feeds in good quantities daily, and even though an extreme example, flat-file data is much more difficult to maintain than the XML data feeds I process.

A simple example of loading XML data into a dataset using C#:

DataSet reportData = new DataSet();

reportData.ReadXml(fi.FullName);

You can also check out LINQ to XML as an option for querying the XML data...

HTH...

Difference between object and class in Scala

Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.

more information check this article class and object keyword in scala programming

cleanup php session files

In case someone want's to do this with a cronjob, please keep in mind that this:

find .session/ -atime +7  -exec rm {} \;

is really slow, when having a lot of files.

Consider using this instead:

find .session/ -atime +7 | xargs -r rm

In Case you have spaces in you file names use this:

find .session/ -atime +7 -print0 | xargs -0 -r rm

xargs will fill up the commandline with files to be deleted, then run the rm command a lot lesser than -exec rm {} \;, which will call the rm command for each file.

Just my two cents

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

How find out which process is using a file in Linux?

You can use the fuser command, like:

fuser file_name

You will receive a list of processes using the file.

You can use different flags with it, in order to receive a more detailed output.

You can find more info in the fuser's Wikipedia article, or in the man pages.

Difference between except: and except Exception as e: in Python

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

How do I see the current encoding of a file in Sublime Text?

plugin ConverToUTF8 also has the functionality.

How to rsync only a specific list of files?

I got similar task: to rsync all files modified after given date, but excluding some directories. It was difficult to build one liner all-in-one style, so I dived problem into smaller pieces. Final solution:

find  ~/sourceDIR -type f -newermt "DD MMM YYYY HH:MM:SS" | egrep -v "/\..|Downloads|FOO" > FileList.txt
rsync -v --files-from=FileList.txt ~/sourceDIR /Destination

First I use find -L ~/sourceDIR -type f -newermt "DD MMM YYYY HH:MM:SS". I tried to add regex to find line to exclude name patterns, however my flavor of Linux (Mint) seams not to understand negate regex in find. Tried number of regex flavors - non work as desired. So I end up with egrep -v - option that excludes pattern easy way. My rsync is not copying directories like /.cache or /.config plus some other I explicitly named.

Is there a Pattern Matching Utility like GREP in Windows?

TL;DR: ripgrep

Since 2009, a lot happened. Rust delivered many CLI utilities, among them ripgrep. It is advertised as a recursively searches directories for a regex pattern, supports Windows, MacOSX and Linux.

It is fast. Look at this performance comparison with similar tools. It also has many explanations on the design of the tool. Quite informative and geeky. =)

Supports a wide range of features that the POSIX grep tools support. Look at the comparison by ack author here.

If you have Scoop, you can install it with scoop install ripgrep. Else head over to the installation section of the doc.

Script to get the HTTP status code of a list of urls?

wget --spider -S "http://url/to/be/checked" 2>&1 | grep "HTTP/" | awk '{print $2}'

prints only the status code for you

Best way to call a JSON WebService from a .NET Console

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
{
    return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}

How to create a CPU spike with a bash command

Utilizing ideas here, created code which exits automatically after a set duration, don't have to kill processes --

#!/bin/bash
echo "Usage : ./killproc_ds.sh 6 60  (6 threads for 60 secs)"

# Define variables
NUM_PROCS=${1:-6} #How much scaling you want to do
duration=${2:-20}    # seconds

function infinite_loop {
endtime=$(($(date +%s) + $duration))
while (($(date +%s) < $endtime)); do
    #echo $(date +%s)
    echo $((13**99)) 1>/dev/null 2>&1
    $(dd if=/dev/urandom count=10000 status=none| bzip2 -9 >> /dev/null) 2>&1 >&/dev/null
done
echo "Done Stressing the system - for thread $1"
}


echo Running for duration $duration secs, spawning $NUM_PROCS threads in background
for i in `seq ${NUM_PROCS}` ;
do
# Put an infinite loop
    infinite_loop $i  &
done

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

How does String.Index work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

startIndex and endIndex

  • startIndex is the index of the first character
  • endIndex is the index after the last character.

Example

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex..<str.endIndex
str[range]  // "Hello, playground"

With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

let range = str.startIndex...
let range = ..<str.endIndex

I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

after

As in: index(after: String.Index)

  • after refers to the index of the character directly after the given index.

Examples

// character
let index = str.index(after: str.startIndex)
str[index]  // "e"

// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range]  // "ello, playground"

before

As in: index(before: String.Index)

  • before refers to the index of the character directly before the given index.

Examples

// character
let index = str.index(before: str.endIndex)
str[index]  // d

// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range]  // Hello, playgroun

offsetBy

As in: index(String.Index, offsetBy: String.IndexDistance)

  • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

Examples

// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index]  // p

// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range]  // play

limitedBy

As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

  • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

Example

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

If the offset had been 77 instead of 7, then the if statement would have been skipped.

Why is String.Index needed?

It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

How do I use WPF bindings with RelativeSource?

This is an example of the use of this pattern that worked for me on empty datagrids.

<Style.Triggers>
    <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
        <Setter Property="Background">
            <Setter.Value>
                <VisualBrush Stretch="None">
                    <VisualBrush.Visual>
                        <TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Setter.Value>
        </Setter>
    </DataTrigger>
</Style.Triggers>

How can I export Excel files using JavaScript?

Similar answer posted here.

Link for working example

var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];
var sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];
var opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];
var result = alasql('SELECT * INTO XLSX("sample_file.xlsx",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);

Main libraries required -

<script src="http://alasql.org/console/alasql.min.js"></script> 
<script src="http://alasql.org/console/xlsx.core.min.js"></script> 

How to write multiple conditions of if-statement in Robot Framework

You should use small caps "or" and "and" instead of OR and AND.

And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).

Here is a code sample with your three keywords working fine:

Here is the file ts.txt:

  *** test cases ***
  mytest
    ${color} =  set variable  Red
    Run Keyword If  '${color}' == 'Red'  log to console  \nexecuted with single condition
    Run Keyword If  '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink'  log to console  \nexecuted with multiple or

    ${color} =  set variable  Blue
    ${Size} =  set variable  Small
    ${Simple} =  set variable  Simple
    ${Design} =  set variable  Simple
    Run Keyword If  '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}'  log to console  \nexecuted with multiple and

    ${Size} =  set variable  XL
    ${Design} =  set variable  Complicated
    Run Keyword Unless  '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple'  log to console  \nexecuted with unless and multiple or

and here is what I get when I execute it:

$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest                                                                .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest                                                                | PASS |
------------------------------------------------------------------------------

Excel compare two columns and highlight duplicates

There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).

So for A1, you can set a conditional format using the following formula:

=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))

Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.

What the above formula is doing:

  • VLOOKUP is looking up the value of Cell A1 (first parameter) against the whole of column B ($B:$B), in the first column (that's the 3rd parameter, redundant here, but typically VLOOKUP looks up a table rather than a column). The last parameter, FALSE, specifies that the match must be exact rather than just the closest match.
  • VLOOKUP will return #ISNA if no match is found, so the NOT(ISNA(...)) returns true for all cells which have a match in column B.

How do you select the entire excel sheet with Range using VBA?

I have found that the Worksheet ".UsedRange" method is superior in many instances to solve this problem. I struggled with a truncation issue that is a normal behaviour of the ".CurrentRegion" method. Using [ Worksheets("Sheet1").Range("A1").CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted). In this case, the ".CurrentRegion" will truncate at the first record. I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):

Sub mytest_GetAllUsedCells_in_Worksheet()
    Dim myRange

    Set myRange = Worksheets("Sheet1").UsedRange
    'Alternative code:  set myRange = activesheet.UsedRange

   'use msgbox or debug.print to show the address range and counts
   MsgBox myRange.Address      
   MsgBox myRange.Columns.Count
   MsgBox myRange.Rows.Count

  'Copy the Range of data to another sheet
  'Note: contains all the cells with that are non-empty
   myRange.Copy (Worksheets("Sheet2").Range("A1"))
   'Note:  transfers all cells starting at "A1" location.  
   '       You can transfer to another area of the 2nd sheet
   '       by using an alternate starting location like "C5".

End Sub

Using setDate in PreparedStatement

The docs explicitly says that java.sql.Date will throw:

  • IllegalArgumentException - if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d)

Also you shouldn't need to convert a date to a String then to a sql.date, this seems superfluous (and bug-prone!). Instead you could:

java.sql.Date sqlDate := new java.sql.Date(now.getTime());
prs.setDate(2, sqlDate);
prs.setDate(3, sqlDate);

MySQL equivalent of DECODE function in Oracle

Select Name, 
case 
  when Age = 13 then 'Thirteen'
  when Age = 14 then 'Fourteen'
  when Age = 15 then 'Fifteen'
  when Age = 16 then 'Sixteen'
  when Age = 17 then 'Seventeen'
  when Age = 18 then 'Eighteen'
  when Age = 19 then 'Nineteen'
  else 'Adult'
end as AgeBracket
FROM Person

How can I make Flexbox children 100% height of their parent?

I have answered a similar question here.

I know you have already said position: absolute; is inconvenient, but it works. See below for further information on fixing the resize issue.

Also see this jsFiddle for a demo, although I have only added WebKit prefixes so open in Chrome.

You basically have two issues which I will deal with separately.

  1. Getting the child of a flex-item to fill height 100%
  • Set position: relative; on the parent of the child.
  • Set position: absolute; on the child.
  • You can then set width/height as required (100% in my sample).
  1. Fixing the resize scrolling "quirk" in Chrome
  • Put overflow-y: auto; on the scrollable div.
  • The scrollable div must have an explicit height specified. My sample already has height 100%, but if none is already applied you can specify height: 0;

See this answer for more information on the scrolling issue.

Subversion stuck due to "previous operation has not finished"?

In my case, the error appeared when trying to commit from within an IDE. When I executed the commit of the same directories with TortoiseSVN in the explorer, the operation succeeded.

How to get a reversed list view on a list in Java?

You can also do this:

static ArrayList<String> reverseReturn(ArrayList<String> alist)
{
   if(alist==null || alist.isEmpty())
   { 
       return null;
   }

   ArrayList<String> rlist = new ArrayList<>(alist);

   Collections.reverse(rlist);
   return rlist;
}

Determine direct shared object dependencies of a Linux binary?

You can use readelf to explore the ELF headers. readelf -d will list the direct dependencies as NEEDED sections.

 $ readelf -d elfbin

Dynamic section at offset 0xe30 contains 22 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libssl.so.1.0.0]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000c (INIT)               0x400520
 0x000000000000000d (FINI)               0x400758
 ...

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

Sometimes you don't have a local REF for pushing that branch back to the origin.
Try

git push origin master:master

This explicitly indicates which branch to push to (and from)

jQuery scroll to element

Using this simple script

if($(window.location.hash).length > 0){
        $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}

Would make in sort that if a hash tag is found in the url, the scrollTo animate to the ID. If not hash tag found, then ignore the script.

Run a string as a command within a Bash script

To see all commands that are being executed by the script, add the -x flag to your shabang line, and execute the command normally:

#! /bin/bash -x

matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"

teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'

cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'

Then if you sometimes want to ignore the debug output, redirect stderr somewhere.

Is there a simple way to convert C++ enum to string?

This can be done in C++11

#include <map>
enum MyEnum { AA, BB, CC, DD };

static std::map< MyEnum, const char * > info = {
   {AA, "This is an apple"},
   {BB, "This is a book"},
   {CC, "This is a coffee"},
   {DD, "This is a door"}
};

void main()
{
    std::cout << info[AA] << endl
              << info[BB] << endl
              << info[CC] << endl
              << info[DD] << endl;
}

Best approach to real time http streaming to HTML5 video client

Try binaryjs. Its just like socket.io but only thing it do well is that it stream audio video. Binaryjs google it

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

How can I Insert data into SQL Server using VBNet

Imports System.Data

Imports System.Data.SqlClient

Public Class Form2

Dim myconnection As SqlConnection

Dim mycommand As SqlCommand

Dim dr As SqlDataReader

Dim dr1 As SqlDataReader

Dim ra As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")

    'you need to provide password for sql server

    myconnection.Open()

    mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)

    mycommand.ExecuteNonQuery()

    MessageBox.Show("New Row Inserted" & ra)

    myconnection.Close()

End Sub

End Class

inserting characters at the start and end of a string

Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:

s = "something about cupcakes"
print(f"L{s}LL")

Better way to sum a property value in an array

I thought I'd drop my two cents on this: this is one of those operations that should always be purely functional, not relying on any external variables. A few already gave a good answer, using reduce is the way to go here.

Since most of us can already afford to use ES2015 syntax, here's my proposition:

const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);

We're making it an immutable function while we're at it. What reduce is doing here is simply this: Start with a value of 0 for the accumulator, and add the value of the current looped item to it.

Yay for functional programming and ES2015! :)

File changed listener in Java

Java commons-io has a FileAlterationObserver. it does polling in combination with a FileAlterationMonitor. Similar to commons VFS. The advantag is that it has much less dependencies.

edit: Less dependencies is not true, they are optional for VFS. But it uses java File instead of the VFS abstraction layer.

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

One of the principal issues with pushing to a GIT is that the material you push will appear as your material, and will block submissions from other people on a team. As a GIT repository administrator, you will have to manage the hooks to prevent Alice's push from blocking Bob from pushing. To do that, you will want to ensure that your developers all belong to a group, lets call it 'developers' and that the repository is owned by root:developers, and then add this to the hooks/post-update script:

sudo chown -R root:developers $GIT_DIR
sudo chmod -R g+w $GIT_DIR

That will make it so that team members are able to push to the repository without stepping on each other's toes.

What do 'lazy' and 'greedy' mean in the context of regular expressions?

try to understand the following behavior:

    var input = "0014.2";

Regex r1 = new Regex("\\d+.{0,1}\\d+");
Regex r2 = new Regex("\\d*.{0,1}\\d*");

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // "0014.2"

input = " 0014.2";

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // " 0014"

input = "  0014.2";

Console.WriteLine(r1.Match(input).Value); // "0014.2"
Console.WriteLine(r2.Match(input).Value); // ""

How do I detect unsigned integer multiply overflow?

Try this macro to test the overflow bit of 32-bit machines (adapted the solution of Angel Sinigersky)

#define overflowflag(isOverflow){   \
size_t eflags;                      \
asm ("pushfl ;"                     \
     "pop %%eax"                    \
    : "=a" (eflags));               \
isOverflow = (eflags >> 11) & 1;}

I defined it as a macro because otherwise the overflow bit would have been overwritten.

Subsequent is a little application with the code segement above:

#include <cstddef>
#include <stdio.h>
#include <iostream>
#include <conio.h>
#if defined( _MSC_VER )
#include <intrin.h>
#include <oskit/x86>
#endif

using namespace std;

#define detectOverflow(isOverflow){     \
size_t eflags;                      \
asm ("pushfl ;"                     \
    "pop %%eax"                     \
    : "=a" (eflags));               \
isOverflow = (eflags >> 11) & 1;}

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

    bool endTest = false;
    bool isOverflow;

    do {
        cout << "Enter two intergers" << endl;
        int x = 0;
        int y = 0;
        cin.clear();
        cin >> x >> y;
        int z = x * y;
        detectOverflow(isOverflow)
        printf("\nThe result is: %d", z);
        if (!isOverflow) {
            std::cout << ": no overflow occured\n" << std::endl;
        } else {
            std::cout << ": overflow occured\n" << std::endl;
        }

        z = x * x * y;
        detectOverflow(isOverflow)
        printf("\nThe result is: %d", z);
        if (!isOverflow) {
            std::cout << ": no overflow ocurred\n" << std::endl;
        } else {
            std::cout << ": overflow occured\n" << std::endl;
        }

        cout << "Do you want to stop? (Enter \"y\" or \"Y)" << endl;

        char c = 0;

        do {
            c = getchar();
        } while ((c == '\n') && (c != EOF));

        if (c == 'y' || c == 'Y') {
            endTest = true;
        }

        do {
            c = getchar();
        } while ((c != '\n') && (c != EOF));

    } while (!endTest);
}

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

I'd like to add that for accessibility, I think you should add focus trigger :

i.e. $("#popover").popover({ trigger: "hover focus" });

Command line for looking at specific port

netstat -a -n | find /c "10.240.199.9:8080"

it will give you number of sockets active on a specific IP and port(Server port number)

How to convert password into md5 in jquery?

You need additional plugin for this.

take a look at this plugin

Git branching: master vs. origin/master vs. remotes/origin/master

Technically there aren't actually any "remote" things at all1 in your Git repo, there are just local names that should correspond to the names on another, different repo. The ones named origin/whatever will initially match up with those on the repo you cloned-from:

git clone ssh://some.where.out.there/some/path/to/repo # or git://some.where...

makes a local copy of the other repo. Along the way it notes all the branches that were there, and the commits those refer-to, and sticks those into your local repo under the names refs/remotes/origin/.

Depending on how long you go before you git fetch or equivalent to update "my copy of what's some.where.out.there", they may change their branches around, create new ones, and delete some. When you do your git fetch (or git pull which is really fetch plus merge), your repo will make copies of their new work and change all the refs/remotes/origin/<name> entries as needed. It's that moment of fetching that makes everything match up (well, that, and the initial clone, and some cases of pushing too—basically whenever Git gets a chance to check—but see caveat below).

Git normally has you refer to your own refs/heads/<name> as just <name>, and the remote ones as origin/<name>, and it all just works because it's obvious which one is which. It's sometimes possible to create your own branch names that make it not obvious, but don't worry about that until it happens. :-) Just give Git the shortest name that makes it obvious, and it will go from there: origin/master is "where master was over there last time I checked", and master is "where master is over here based on what I have been doing". Run git fetch to update Git on "where master is over there" as needed.


Caveat: in versions of Git older than 1.8.4, git fetch has some modes that don't update "where master is over there" (more precisely, modes that don't update any remote-tracking branches). Running git fetch origin, or git fetch --all, or even just git fetch, does update. Running git fetch origin master doesn't. Unfortunately, this "doesn't update" mode is triggered by ordinary git pull. (This is mainly just a minor annoyance and is fixed in Git 1.8.4 and later.)


1Well, there is one thing that is called a "remote". But that's also local! The name origin is the thing Git calls "a remote". It's basically just a short name for the URL you used when you did the clone. It's also where the origin in origin/master comes from. The name origin/master is called a remote-tracking branch, which sometimes gets shortened to "remote branch", especially in older or more informal documentation.

How do I pick randomly from an array?

myArray.sample(x) can also help you to get x random elements from the array.

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

Check whether a value is a number in JavaScript or jQuery

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

if(!isNaN(miscCharge))
{
   //do some thing if it's a number
}else{
   //do some thing if it's NOT a number
}

hope it works

How to get the error message from the error code returned by GetLastError()?

//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
    //Get the error message ID, if any.
    DWORD errorMessageID = ::GetLastError();
    if(errorMessageID == 0) {
        return std::string(); //No error message has been recorded
    }
    
    LPSTR messageBuffer = nullptr;

    //Ask Win32 to give us the string version of that message ID.
    //The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be).
    size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
    
    //Copy the error message into a std::string.
    std::string message(messageBuffer, size);
    
    //Free the Win32's string's buffer.
    LocalFree(messageBuffer);
            
    return message;
}

How do you clear the console screen in C?

A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):

#include <stdlib.h>

void clrscr()
{
    system("@cls||clear");
}

How to scp in Python?

You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko

Object cannot be cast from DBNull to other types

TryParse is usually the most elegant way to handle this type of thing:

long temp = 0;
if (Int64.TryParse(dataAccCom.GetParameterValue(IDbCmd, "op_Id").ToString(), out temp))
{
   DataTO.Id = temp;
}     

Check whether variable is number or string in JavaScript

Or just use the invert of isNaN():

if(!isNaN(data))
  do something with the number
else
  it is a string

And yes, using jQuery's $.isNumeric() is more fun for the buck.

ActiveModel::ForbiddenAttributesError when creating new user

There is an easier way to avoid the Strong Parameters at all, you just need to convert the parameters to a regular hash, as:

unlocked_params = ActiveSupport::HashWithIndifferentAccess.new(params)

model.create!(unlocked_params)

This defeats the purpose of strong parameters of course, but if you are in a situation like mine (I'm doing my own management of allowed params in another part of my system) this will get the job done.

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

CreateProcess error=2, The system cannot find the file specified

The complete first argument of exec is being interpreted as the executable. Use

p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
            null, 
            dir);

Retrieve filename from file descriptor in C

I had this problem on Mac OS X. We don't have a /proc virtual file system, so the accepted solution cannot work.

We do, instead, have a F_GETPATH command for fcntl:

 F_GETPATH          Get the path of the file descriptor Fildes.  The argu-
                    ment must be a buffer of size MAXPATHLEN or greater.

So to get the file associated to a file descriptor, you can use this snippet:

#include <sys/syslimits.h>
#include <fcntl.h>

char filePath[PATH_MAX];
if (fcntl(fd, F_GETPATH, filePath) != -1)
{
    // do something with the file path
}

Since I never remember where MAXPATHLEN is defined, I thought PATH_MAX from syslimits would be fine.

How to get first character of a string in SQL?

SUBSTRING ( MyColumn, 1 , 1 ) for the first character and SUBSTRING ( MyColumn, 1 , 2 ) for the first two.

How to launch html using Chrome at "--allow-file-access-from-files" mode?

That flag is dangerous!! Leaves your file system open for access. Documents originating from anywhere, local or web, should not, by default, have any access to local file:/// resources.

Much better solution is to run a little http server locally.

--- For Windows ---

The easiest is to install http-server globally using node's package manager:

npm install -g http-server

Then simply run http-server in any of your project directories:

Eg. d:\my_project> http-server

Starting up http-server, serving ./
Available on:
 http:169.254.116.232:8080
 http:192.168.88.1:8080
 http:192.168.0.7:8080
 http:127.0.0.1:8080
Hit CTRL-C to stop the server

Or as prusswan suggested, you can also install Python under windows, and follow the instructions below.

--- For Linux ---

Since Python is usually available in most linux distributions, just run python -m SimpleHTTPServer in your project directory, and you can load your page on http://localhost:8000

In Python 3 the SimpleHTTPServer module has been merged into http.server, so the new command is python3 -m http.server.

Easy, and no security risk of accidentally leaving your browser open vulnerable.

how to implement login auth in node.js

Why not disecting a bare minimum authentication module?

SweetAuth

A lightweight, zero-configuration user authentication module which doesn't depend on a database.

https://www.npmjs.com/package/sweet-auth

It's simple as:

app.get('/private-page', (req, res) => {

    if (req.user.isAuthorized) {
        // user is logged in! send the requested page
        // you can access req.user.email
    }
    else {
        // user not logged in. redirect to login page
    }
})

How do you log content of a JSON object in Node.js?

This will for most of the objects for outputting in nodejs console

_x000D_
_x000D_
var util = require('util')_x000D_
function print (data){_x000D_
  console.log(util.inspect(data,true,12,true))_x000D_
  _x000D_
}_x000D_
_x000D_
print({name : "Your name" ,age : "Your age"})
_x000D_
_x000D_
_x000D_

SQL Server: Difference between PARTITION BY and GROUP BY

It has really different usage scenarios. When you use GROUP BY you merge some of the records for the columns that are same and you have an aggregation of the result set.

However when you use PARTITION BY your result set is same but you just have an aggregation over the window functions and you don't merge the records, you will still have the same count of records.

Here is a rally helpful article explaining the difference: http://alevryustemov.com/sql/sql-partition-by/

How to Kill A Session or Session ID (ASP.NET/C#)

It is also a good idea to instruct the client browser to clear session id cookie value.

Session.Clear();
Session.Abandon();
Response.Cookies["ASP.NET_SessionId"].Value = string.Empty;
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-10);

Adding asterisk to required fields in Bootstrap 3

.form-group .required .control-label:after should probably be .form-group.required .control-label:after. The removal of the space between .form-group and .required is the change.

NULL or BLANK fields (ORACLE)

One should NEVER treat "BLANK" and NULL as the same.

Back in the olden days before there was a SQL standard, Oracle made the design decision that empty strings in VARCHAR/ VARCHAR2 columns were NULL and that there was only one sense of NULL (there are relational theorists that would differentiate between data that has never been prompted for, data where the answer exists but is not known by the user, data where there is no answer, etc. all of which constitute some sense of NULL). By the time that the SQL standard came around and agreed that NULL and the empty string were distinct entities, there were already Oracle users that had code that assumed the two were equivalent. So Oracle was basically left with the options of breaking existing code, violating the SQL standard, or introducing some sort of initialization parameter that would change the functionality of potentially large number of queries. Violating the SQL standard (IMHO) was the least disruptive of these three options.

Oracle has left open the possibility that the VARCHAR data type would change in a future release to adhere to the SQL standard (which is why everyone uses VARCHAR2 in Oracle since that data type's behavior is guaranteed to remain the same going forward).

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

It depends on which range you're talking about, but the dynamic range goes up to 65535 or 2^16-1 (16 bits).

http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

socket programming multiple client to one server

Here is code for Multiple Client to one Server Working Fine .. Give it a try :)

Server.java:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{


}
Multi(Socket s) throws IOException{
    this.s=s;
    infromClient = new DataInputStream(s.getInputStream());
}
public void run(){  

    String SQL=new String();
    try {
        SQL = infromClient.readUTF();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Query: " + SQL); 
    try {
        System.out.println("Socket Closing");
        s.close();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
       }
   }  
}
public class Server {

public static void main(String args[]) throws IOException, 
InterruptedException{   

    while(true){
        ServerSocket ss=new ServerSocket(11111);
        System.out.println("Server is Awaiting"); 
        Socket s=ss.accept();
        Multi t=new Multi(s);
        t.start();

        Thread.sleep(2000);
        ss.close();
    }    




    }   
}

Client1.java:

 import java.io.DataOutputStream;
 import java.io.ObjectInputStream;
 import java.net.Socket;


public class client1 {
   public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I  am  client 1";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
}

Client2.java

import java.io.DataOutputStream; 
import java.net.Socket;


public class client2 {
    public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I am  Client 2";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
 }

c# regex matches example

Regex regex = new Regex("%download#(\\d+?)%", RegexOptions.SingleLine);
Matches m = regex.Matches(input);

I think will do the trick (not tested).

How to JSON serialize sets?

If you need just quick dump and don't want to implement custom encoder. You can use the following:

json_string = json.dumps(data, iterable_as_array=True)

This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.

WooCommerce - get category for product page

$product->get_categories() is deprecated since version 3.0! Use wc_get_product_category_list instead.

https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

In my case, there were two different 'AWS_SECRET_ACCESS_KEY' and 'AWS_ACCESS_KEY_ID' values set one through the Windows environment variable and one through the command line.

So, update these two and the default_region using a command line

> aws configure

Press enter and follow the steps to fill the correct AWS_ACESS_KEY_ID AWS_SECRET_ACCESS_KEY and AWS_DEFAULT_REGION

> aws sts get-caller-identity

should return the new set credentials

Linear Layout and weight in Android

Below are the changes (Marked in BOLD) in your code:

<LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

  </LinearLayout>

Since your LinearLayout has orientation as horizontal, therefore you will need to keep your width only as 0dp. for using weights in that direction . (If your orientation was vertical, you would have kept your height only 0dp).

Since there are 2 views and you have placed android:layout_weight="1" for both the views, it means it will divide the two views equally in horizontal direction (or by width).

Total size of the contents of all the files in a directory

There are at least three ways to get the "sum total of all the data in files and subdirectories" in bytes that work in both Linux/Unix and Git Bash for Windows, listed below in order from fastest to slowest on average. For your reference, they were executed at the root of a fairly deep file system (docroot in a Magento 2 Enterprise installation comprising 71,158 files in 30,027 directories).

1.

$ time find -type f -printf '%s\n' | awk '{ total += $1 }; END { print total" bytes" }'
748660546 bytes

real    0m0.221s
user    0m0.068s
sys     0m0.160s

2.

$ time echo `find -type f -print0 | xargs -0 stat --format=%s | awk '{total+=$1} END {print total}'` bytes
748660546 bytes

real    0m0.256s
user    0m0.164s
sys     0m0.196s

3.

$ time echo `find -type f -exec du -bc {} + | grep -P "\ttotal$" | cut -f1 | awk '{ total += $1 }; END { print total }'` bytes
748660546 bytes

real    0m0.553s
user    0m0.308s
sys     0m0.416s


These two also work, but they rely on commands that don't exist on Git Bash for Windows:

1.

$ time echo `find -type f -printf "%s + " | dc -e0 -f- -ep` bytes
748660546 bytes

real    0m0.233s
user    0m0.116s
sys     0m0.176s

2.

$ time echo `find -type f -printf '%s\n' | paste -sd+ | bc` bytes
748660546 bytes

real    0m0.242s
user    0m0.104s
sys     0m0.152s


If you only want the total for the current directory, then add -maxdepth 1 to find.


Note that some of the suggested solutions don't return accurate results, so I would stick with the solutions above instead.

$ du -sbh
832M    .

$ ls -lR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
Total: 583772525

$ find . -type f | xargs stat --format=%s | awk '{s+=$1} END {print s}'
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
4390471

$ ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'
Total 968133

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

Create application.properties file under src/main/resources folder and write content as

server.port=8084

Its runs fine. But every time before run need to stop application first by click on red button upper on the IDE enter image description here

or try

RightClick on console>click terminate/Disconnect All

How to split a string into an array of characters in Python?

Unpack them:

word = "Paralelepipedo"
print([*word])

Open Facebook Page in Facebook App (if installed) on Android

you can use this:

try {
                Intent followIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" +
                        "https://www.facebook.com/app_scoped_user_id/"+scoped user id+"/"));
                activity.startActivity(followIntent);
            } catch (Exception e) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + user name)));
                String errorMessage = (e.getMessage() == null) ? "Message is empty" : e.getMessage();
            }

attention: you can get scoped user id from "link" permission facebook api

Best Practices for mapping one object to another

Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.

Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.

Is Visual Studio Community a 30 day trial?

VS 17 Community Edition is free. You just need to sign-in with your Microsoft account and everything will be fine again.

How to fix Cannot find module 'typescript' in Angular 4?

This should do the trick,

npm install -g typescript

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

Just as Commonsware mentioned, you shouldn't assume, that the stream you get via ContentResolver is convertable into file.

What you really should do is to open the InputStream from the ContentProvider, then create a Bitmap out of it. And it works on 4.4 and earlier versions as well, no need for reflection.

    //cxt -> current context

    InputStream input;
    Bitmap bmp;
    try {
        input = cxt.getContentResolver().openInputStream(fileUri);
        bmp = BitmapFactory.decodeStream(input);
    } catch (FileNotFoundException e1) {

    }

Of course if you handle big images, you should load them with appropriate inSampleSize: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html. But that's another topic.

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {
     fn(results[0].geometry.location); 
  });
}

foo("address", function(location){
  alert(location); // this is where you get the return value
});

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

Build the full path filename in Python

This works fine:

os.path.join(dir_name, base_filename + "." + filename_suffix)

Keep in mind that os.path.join() exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote) because they are always connected to the rest of the name with a dot character, on every OS.

If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:

os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))

If you prefer to keep your code clean, simply include the dot in the suffix:

suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)

That approach also happens to be compatible with the suffix conventions in pathlib, which was introduced in python 3.4 after this question was asked. New code that doesn't require backward compatibility can do this:

suffix = '.pdf'
pathlib.PurePath(dir_name, base_filename + suffix)

You might prefer the shorter Path instead of PurePath if you're only handling paths for the local OS.

Warning: Do not use pathlib's with_suffix() for this purpose. That method will corrupt base_filename if it ever contains a dot.


Footnote: Outside of Micorsoft operating systems, there is no such thing as a file name "extension". Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.

How to show SVG file on React Native?

import React from 'react'
import SvgUri from 'react-native-svg-uri';

export default function Splash() {
  return (
    <View style={styles.container}>
      {/* provided the svg file is stored locally */}
      <SvgUri
        width="400"
        height="200"
        source={require('./logo.svg')}
      />
      {/* if the svg is online */}
      <SvgUri
        width="200"
        height="200"
        source={{ uri: 'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg' }}
      />

      <Text style={styles.logoText}>
        Text
      </Text>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  logoText: {
    fontSize: 50
  }
});

Getting a HeadlessException: No X11 DISPLAY variable was set

I assume you're trying to tunnel into some unix box.

Make sure X11 forwarding is enabled in your PuTTY settings.

enter image description here

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Solved 403: Forbidden when visiting localhost. Using ports 80,443,3308 (the later to handle conflict with MySQL Server installation) Windows 10, XAMPP 7.4.1, Apache 2.4.x My web files are in a separate folder.

httpd.conf - look for these lines and set it up where you have your files, mine is web folder.

DocumentRoot "C:/web"
<Directory "C:/web">

Changed these 2 lines.

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Order allow,deny
  allow from all
 </Directory>
</VirtualHost>

to this

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot "C:/web/project1"
 ServerName project1.localhost
 <Directory "C:/web/project1">
  Require all granted
 </Directory>
</VirtualHost>

Add your details in your hosts file C:\Windows\System32\drivers\etc\hosts file

127.0.0.1 localhost
127.0.0.1 project1.localhost

Stop start XAMPP, and click Apache admin (or localhost) and the wonderful XAMPP dashboard now displays! And visit your project at project1.localhost

SQL how to check that two tables has exactly the same data?

Enhancement to dietbuddha's answer...

select * from
(
    select * from tableA
    minus
    select * from tableB
)
union all
select * from
(
    select * from tableB
    minus
    select * from tableA
)

JavaScript: SyntaxError: missing ) after argument list

You have an extra closing } in your function.

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }        // <== remove this brace
    }, false);
};

You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

set option "selected" attribute from dynamic created option

I was trying something like this using the $(...).val() function, but the function did not exist. It turns out that you can manually set the value the same way you do it for an <input>:

// Set value to Indonesia ("ID"):
$('#country').value = 'ID'

...and it get's automatically updated in the select. Works on Firefox at least; you might want to try it out in the others.

How to ignore whitespace in a regular expression subject string?

While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

If you want to search for "my cats", instead of:

myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)

Just do:

myString.replace(/\s*/g,"").match(/mycats/g)

Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

Laravel Eloquent limit and offset

You can use skip and take functions as below:

$products = $art->products->skip($offset*$limit)->take($limit)->get();

// skip should be passed param as integer value to skip the records and starting index

// take gets an integer value to get the no. of records after starting index defined by skip

EDIT

Sorry. I was misunderstood with your question. If you want something like pagination the forPage method will work for you. forPage method works for collections.

REf : https://laravel.com/docs/5.1/collections#method-forpage

e.g

$products = $art->products->forPage($page,$limit);

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

What is the best way to implement constants in Java?

Just avoid using an interface:

public interface MyConstants {
    String CONSTANT_ONE = "foo";
}

public class NeddsConstant implements MyConstants {

}

It is tempting, but violates encapsulation and blurs the distinction of class definitions.

Preferred Java way to ping an HTTP URL for availability

The following code performs a HEAD request to check whether the website is available or not.

public static boolean isReachable(String targetUrl) throws IOException
{
    HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
            targetUrl).openConnection();
    httpUrlConnection.setRequestMethod("HEAD");

    try
    {
        int responseCode = httpUrlConnection.getResponseCode();

        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (UnknownHostException noInternetConnection)
    {
        return false;
    }
}

MySQL timezone change?

If you have the SUPER privilege, you can set the global server time zone value at runtime with this statement:

mysql> SET GLOBAL time_zone = timezone;

Insert data through ajax into mysql database

I will tell you steps how you can insert data in ajax using PHP

AJAX Code

<script type="text/javascript">
function insertData() {
var student_name=$("#student_name").val();
var student_roll_no=$("#student_roll_no").val();
var student_class=$("#student_class").val();


// AJAX code to send data to php file.
    $.ajax({
        type: "POST",
        url: "insert-data.php",
        data: {student_name:student_name,student_roll_no:student_roll_no,student_class:s
         tudent_class},
        dataType: "JSON",
        success: function(data) {
         $("#message").html(data);
        $("p").addClass("alert alert-success");
        },
        error: function(err) {
        alert(err);
        }
    });

 }

</script>

PHP Code:

<?php

include('db.php');
$student_name=$_POST['student_name'];
$student_roll_no=$_POST['student_roll_no'];
$student_class=$_POST['student_class'];

$stmt = $DBcon->prepare("INSERT INTO 
student(student_name,student_roll_no,student_class) 
VALUES(:student_name, :student_roll_no,:student_class)");

 $stmt->bindparam(':student_name', $student_name);
 $stmt->bindparam(':student_roll_no', $student_roll_no);
 $stmt->bindparam(':student_class', $student_class);
 if($stmt->execute())
 {
  $res="Data Inserted Successfully:";
  echo json_encode($res);
  }
  else {
  $error="Not Inserted,Some Probelm occur.";
  echo json_encode($error);
  }



  ?>

You can customize it according to your needs. you can also check complete steps of AJAX Insert Data PHP

Better way to set distance between flexbox items

I came across the same issue earlier, then stumbled upon the answer for this. Hope it will help others for future reference.

long answer short, add a border to your child flex-items. then you can specify margins between flex-items to whatever you like. In the snippet, i use black for illustration purposes, you can use 'transparent' if you like.

_x000D_
_x000D_
#box {_x000D_
  display: flex;_x000D_
  width: 100px;_x000D_
  /* margin: 0 -5px; *remove this*/_x000D_
}_x000D_
.item {_x000D_
  background: gray;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  /* margin: 0 5px; *remove this*/_x000D_
  border: 1px solid black; /* add this */_x000D_
}_x000D_
.item.special{ margin: 0 10px; }
_x000D_
<div id='box'>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item special'></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

Redirect pages in JSP?

Just define the target page in the action attribute of the <form> containing the submit button.

So, in page1.jsp:

<form action="page2.jsp">
    <input type="submit">
</form>

Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.

When should I write the keyword 'inline' for a function/method?

You still need to explicitly inline your function when doing template specialization (if specialization is in .h file)

Add target="_blank" in CSS

This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:

var i_will_target_self = document.querySelectorAll("ul.menu li a#example")

this example uses css to target links in a menu with id = "example"

that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):

for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}

That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."

read more here: http://xahlee.info/js/js_get_elements.html

Java String.split() Regex

You could split on a word boundary with \b

Why does an SSH remote command get fewer environment variables then when run manually?

I had similar issue, but in the end I found out that ~/.bashrc was all I needed.

However, in Ubuntu, I had to comment the line that stops processing ~/.bashrc :

#If not running interactively, don't do anything
[ -z "$PS1" ] && return

How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
{
    display: block;
}

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

I hope this is what you meant.

jsFiddle

Addendum

If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

How I can filter a Datatable?

It is better to use DataView for this task.

Example of the using it you can find in this post: How to filter data in dataview

How to check if a character is upper-case in Python?

To test that all words start with an upper case use this:

print all(word[0].isupper() for word in words)

Brackets.io: Is there a way to auto indent / format <html>

I found an add-on for Brackets.io that uses auto-indent called Indentator.
It uses shortcut keys Ctrl + Alt + I

Get the number of rows in a HTML table

In the DOM, a tr element is (implicitly or explicitly) a child of tbody, thead, or tfoot, not a child of table (hence the 0 you got). So a general answer is:

var count = $('#gvPerformanceResult > * > tr').length;

This includes the rows of the table but excludes rows of any inner table.

Input placeholders for Internet Explorer

With a jQuery implementation you can EASILY remove the default values when it is time to submit. Below is an example:

$('#submit').click(function(){
   var text = this.attr('placeholder');
   var inputvalue = this.val();  // you need to collect this anyways
   if (text === inputvalue) inputvalue = "";

   // $.ajax(...  // do your ajax thing here

});

I know that you are looking for an overlay, but you might prefer the ease of this route (now knowing what I wrote above). If so, then I wrote this for my own projects and it works really nice (requires jQuery) and takes just a couple minutes to implement for your entire site. It offers grey text at first, light grey when in focus, and black when typing. It also offers the placeholder text whenever the input field is empty.

First set up your form and include your placeholder attributes on the input tags.

<input placeholder="enter your email here">

Just copy this code and save it as placeholder.js.

(function( $ ){

   $.fn.placeHolder = function() {  
      var input = this;
      var text = input.attr('placeholder');  // make sure you have your placeholder attributes completed for each input field
      if (text) input.val(text).css({ color:'grey' });
      input.focus(function(){  
         if (input.val() === text) input.css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){     
            input.val("").css({ color:'black' });  
         });
      });
      input.blur(function(){ 
         if (input.val() == "" || input.val() === text) input.val(text).css({ color:'grey' }); 
      }); 
      input.keyup(function(){ 
        if (input.val() == "") input.val(text).css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
            input.val("").css({ color:'black' });
        });               
      });
      input.mouseup(function(){
        if (input.val() === text) input.selectRange(0,0); 
      });   
   };

   $.fn.selectRange = function(start, end) {
      return this.each(function() {
        if (this.setSelectionRange) { this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true); 
            range.moveEnd('character', end); 
            range.moveStart('character', start); 
            range.select(); 
        }
      });
   };

})( jQuery );

To use on just one input

$('#myinput').placeHolder();  // just one

This is how I recommend you implement it on all input fields on your site when the browser does not support HTML5 placeholder attributes:

var placeholder = 'placeholder' in document.createElement('input');  
if (!placeholder) {      
  $.getScript("../js/placeholder.js", function() {   
      $(":input").each(function(){   // this will work for all input fields
        $(this).placeHolder();
      });
  });
} 

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

How to fix 'Notice: Undefined index:' in PHP form action

short way, you can use Ternary Operators

$filename = !empty($_POST['filename'])?$_POST['filename']:'-';

Java JDBC - How to connect to Oracle using Service Name instead of SID

This discussion helped me resolve the issue I was struggling with for days. I looked around all over the internet until I found the answered by Jim Tough on May 18 '11 at 15:17. With that answer I was able to connect. Now I want to give back and help others with a complete example. Here goes:

import java.sql.*; 

public class MyDBConnect {

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

        try { 
            String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=whatEverYourHostNameIs)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=yourServiceName)))";
            String strUserID = "yourUserId";
            String strPassword = "yourPassword";
            Connection myConnection=DriverManager.getConnection(dbURL,strUserID,strPassword);

            Statement sqlStatement = myConnection.createStatement();
            String readRecordSQL = "select * from sa_work_order where WORK_ORDER_NO = '1503090' ";  
            ResultSet myResultSet = sqlStatement.executeQuery(readRecordSQL);
            while (myResultSet.next()) {
                System.out.println("Record values: " + myResultSet.getString("WORK_ORDER_NO"));
            }
            myResultSet.close();
            myConnection.close();

        } catch (Exception e) {
            System.out.println(e);
        }       
    }
}

How can bcrypt have built-in salts?

This is bcrypt:

Generate a random salt. A "cost" factor has been pre-configured. Collect a password.

Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.

When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.

Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.


Stored in the database, a bcrypt "hash" might look something like this:

$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa

This is actually three fields, delimited by "$":

  • 2a identifies the bcrypt algorithm version that was used.
  • 10 is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)
  • vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.

This example is taken from the documentation for Coda Hale's ruby implementation.

Help needed with Median If in Excel

one solution could be to find a way of pulling the numbers from the string and placing them in a column of just numbers the using the =MEDIAN() function giving the new number column as the range

PHP session handling errors

I got these two error messages, along with two others, and fiddled around for a while before discovering that all I needed to do was restart XAMPP! I hope this helps save someone else from the same wasted time!

Warning: session_start(): open(/var/folders/zw/hdfw48qd25xcch5sz9dd3w600000gn/T/sess_f8bgs41qn3fk6d95s0pfps60n4, O_RDWR) failed: Permission denied (13) in /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php on line 3

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php:3) in /Applications/XAMPP/xamppfiles/htdocs/foo/bar.php on line 3

Warning: Unknown: open(/var/lib/php/session/sess_isu2r2bqudeosqvpoo8a67oj02, O_RDWR) failed: Permission denied (13) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0

How to add a "confirm delete" option in ASP.Net Gridview?

This code is working fine for me.

jQuery("a").filter(function () {
        return this.innerHTML.indexOf("Delete") == 0;
        }).click(function () { return confirm("Are you sure you want to delete this record?"); 
});

How to count instances of character in SQL Column

You can also Try This

-- DECLARE field because your table type may be text
DECLARE @mmRxClaim nvarchar(MAX) 

-- Getting Value from table
SELECT top (1) @mmRxClaim = mRxClaim FROM RxClaim WHERE rxclaimid_PK =362

-- Main String Value
SELECT @mmRxClaim AS MainStringValue

-- Count Multiple Character for this number of space will be number of character
SELECT LEN(@mmRxClaim) - LEN(REPLACE(@mmRxClaim, 'GS', ' ')) AS CountMultipleCharacter

-- Count Single Character for this number of space will be one
SELECT LEN(@mmRxClaim) - LEN(REPLACE(@mmRxClaim, 'G', '')) AS CountSingleCharacter

Output:

enter image description here

Sort an ArrayList based on an object field

Use a custom comparator:

Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});

Using python map and other functional tools

Functional programming is about creating side-effect-free code.

map is a functional list transformation abstraction. You use it to take a sequence of something and turn it into a sequence of something else.

You are trying to use it as an iterator. Don't do that. :)

Here is an example of how you might use map to build the list you want. There are shorter solutions (I'd just use comprehensions), but this will help you understand what map does a bit better:

def my_transform_function(input):
    return [input, [1, 2, 3]]

new_list = map(my_transform, input_list)

Notice at this point, you've only done a data manipulation. Now you can print it:

for n,l in new_list:
    print n, ll

-- I'm not sure what you mean by 'without loops.' fp isn't about avoiding loops (you can't examine every item in a list without visiting each one). It's about avoiding side-effects, thus writing fewer bugs.

How to disable a input in angular2

And also if the input box/button has to remain disable, then simply <button disabled> or <input disabled> works.

Android translate animation - permanently move View to new position using AnimationListener

I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.

Try this out, see if it works for you:

TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);

anim.setAnimationListener(new TranslateAnimation.AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) 
    {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
        params.topMargin += amountToMoveDown;
        params.leftMargin += amountToMoveRight;
        view.setLayoutParams(params);
    }
});

view.startAnimation(anim);

Make sure to make amountToMoveRight / amountToMoveDown final

Hope this helps :)

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Java: How to access methods from another class

I have another solution. If Alpha and Beta are your only extra class then why not make a static variable with the image of the class.

Like in Alpha class :

public class Alpha{
        public static Alpha alpha;
        public Alpha(){
                this.alpha = this;
}

Now you you can call the function in Beta class by just using these lines :

new Alpha();
Alpha.alpha.DoSomethingAlpha();

Set colspan dynamically with jquery

td.setAttribute('rowspan',x);

Get average color of image via Javascript

AFAIK, the only way to do this is with <canvas/>...

DEMO V2: http://jsfiddle.net/xLF38/818/

Note, this will only work with images on the same domain and in browsers that support HTML5 canvas:

function getAverageRGB(imgEl) {

    var blockSize = 5, // only visit every 5 pixels
        defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
        canvas = document.createElement('canvas'),
        context = canvas.getContext && canvas.getContext('2d'),
        data, width, height,
        i = -4,
        length,
        rgb = {r:0,g:0,b:0},
        count = 0;

    if (!context) {
        return defaultRGB;
    }

    height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
    width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;

    context.drawImage(imgEl, 0, 0);

    try {
        data = context.getImageData(0, 0, width, height);
    } catch(e) {
        /* security error, img on diff domain */
        return defaultRGB;
    }

    length = data.data.length;

    while ( (i += blockSize * 4) < length ) {
        ++count;
        rgb.r += data.data[i];
        rgb.g += data.data[i+1];
        rgb.b += data.data[i+2];
    }

    // ~~ used to floor values
    rgb.r = ~~(rgb.r/count);
    rgb.g = ~~(rgb.g/count);
    rgb.b = ~~(rgb.b/count);

    return rgb;

}

For IE, check out excanvas.

getDate with Jquery Datepicker

try

$('#page_output').html(str_output);

Storing an object in state of a React component?

Even though it can be done via immutability-helper or similar I do not wan't to add external dependencies to my code unless I really have to. When I need to do it I use Object.assign. Code:

this.setState({ abc : Object.assign({}, this.state.abc , {xyz: 'new value'})})

Can be used on HTML Event Attributes as well, example:

onChange={e => this.setState({ abc : Object.assign({}, this.state.abc, {xyz : 'new value'})})}

C# string reference type?

For curious minds and to complete the conversation: Yes, String is a reference type:

unsafe
{
     string a = "Test";
     string b = a;
     fixed (char* p = a)
     {
          p[0] = 'B';
     }
     Console.WriteLine(a); // output: "Best"
     Console.WriteLine(b); // output: "Best"
}

But note that this change only works in an unsafe block! because Strings are immutable (From MSDN):

The contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

string b = "h";  
b += "ello";  

And keep in mind that:

Although the string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references.

How to get the connection String from a database

If you have installed and setup MS SQL Server and Management Studio, go to Visual Studio (Visual Studio not SQL Server Management Studio).

1] In Visual Studio go to Tools -> Connect to Database.

2] Under Server Name Select your Database Server Name (Let the list Populate if its taking time).

3] Under Connect to a Database, Select Select or enter a database name.

4] Select your Database from Dropdown.

5] After selecting Database try Test Connection.

6] If Test Connection Succeeds, Click Ok.

7] In Visual Studio go to View -> Server Explorer.

8] In Server Explorer window, Under Data Connections Select your Database. Right Click your Database -> Click Properties.

9] In Properties window you will see your Connection String.

How to drop all tables from a database with one SQL query?

Use the following script to drop all constraints:

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' ALTER TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) +    ' NOCHECK CONSTRAINT all; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

Then run the following to drop all tables:

select @sql='';

SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

This worked for me in Azure SQL Database where 'sp_msforeachtable' was not available!

How do I consume the JSON POST data in an Express application

For Express v4+

install body-parser from the npm.

$ npm install body-parser

https://www.npmjs.org/package/body-parser#installation

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next()
})

C# Iterate through Class properties

// the index of each item in fieldNames must correspond to 
// the correct index in resultItems
var fieldnames = new []{"itemtype", "etc etc "};

for (int e = 0; e < fieldNames.Length - 1; e++)
{
    newRecord
       .GetType()
       .GetProperty(fieldNames[e])
       .SetValue(newRecord, resultItems[e]);
}

How do I concatenate a string with a variable?

Another way to do it simpler using jquery.

sample:

function add(product_id){

    // the code to add the product
    //updating the div, here I just change the text inside the div. 
    //You can do anything with jquery, like change style, border etc.
    $("#added_"+product_id).html('the product was added to list');

}

Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.

Best Regards!

How to set NODE_ENV to production/development in OS X

Windows CMD -> set NODE_ENV=production

Windows Powershell -> $env:NODE_ENV="production"

MAC -> export NODE_ENV=production

How to set delay in android?

If you use delay frequently in your app, use this utility class

import android.os.Handler;


public class Utils {

    // Delay mechanism

    public interface DelayCallback{
        void afterDelay();
    }

    public static void delay(int secs, final DelayCallback delayCallback){
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                delayCallback.afterDelay();
            }
        }, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
    }
}

Usage:

// Call this method directly from java file

int secs = 2; // Delay in seconds

Utils.delay(secs, new Utils.DelayCallback() {
    @Override
    public void afterDelay() {
        // Do something after delay

    }
});

How to pass a JSON array as a parameter in URL

I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand & is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R. So the acc parameter ends when it reaches the ampersand character.

That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.

Adb over wireless without usb cable at all for not rooted phones

Had same issue, however I'm using Macbook Pro (2016) which has USB-c only and I forgot my adapter at home.

Since unable to run adb at all on my development machine, I found a different approach.

Connecting phone with USB cable to another computer (in same WiFi) and enable run adb tcpip from there.

Master-machine : computer where development goes on, with only USB-C connectors

Slave-machine: another computer with USB and in same WiFi

Steps:

  1. Connect the phone to a different computer (slave-machine)
  2. Run adb usb && adb tcpip 5555 from there
  3. On master machine

    deko$: adb devices
    List of devices attached
    
    deko$: adb connect 10.0.20.153:5555
    connected to 10.0.20.153:5555
    
  4. Now Android Studio or Xamarin can install and run app on the phone


Sidenote:

I also tested Bluetooth tethering from the Phone to Master-machine and successfully connected to phone. Both Android Studio and Xamarin worked well, however the upload process, from Xamarin was taking long time. But it works.

Remove shadow below actionbar

I have this same problem, and I have successfully solved this problem. All you have to do is just change the elevation to 0 floating point value in that activity in which you want to remove the elevation.

If you want to change it in an activity called MyActivity.java so you have to get the ActionBar first.

First import the ActionBar class

import android.support.v7.app.ActionBar;

after importing you have to initialize a variable of action bar and set its elevation to 0.

 private ActionBar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    .
    .
    toolbar=getSupportActionBar();
    toolbar.setElevation(0);
    .
    .
    }

AngularJS ng-if with multiple conditions

OR operator:

<div ng-repeat="k in items">
    <div ng-if="k || 'a' or k == 'b'">
        <!-- SOME CONTENT -->
    </div>
</div>

Even though it is simple enough to read, I hope as a developer you are use better names than 'a' 'k' 'b' etc..

For Example:

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin || group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

Another OR example

<p ng-if="group.title != 'Dispatcher News' or group.title != 'Coordinator News'" style="padding: 5px;">No links in group.</p>

AND operator (For those stumbling across this stackoverflow answer looking for an AND instead of OR condition)

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin && group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

$(window).scrollTop() vs. $(document).scrollTop()

Cross browser way of doing this is

var top = ($(window).scrollTop() || $("body").scrollTop());

Google Chrome "window.open" workaround?

menubar must no, or 0, for Google Chrome to open in new window instead of tab.

Curl error: Operation timed out

$curl = curl_init();

  curl_setopt_array($curl, array(
  CURLOPT_URL => "", // Server Path
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000, // increase this
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"email\":\"[email protected]\",\"password\":\"markus William\",\"username\":\"Daryl Brown\",\"mobile\":\"013132131112\","msg":"No more SSRIs." }",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json",
    "Postman-Token: 4867c7a3-2b3d-4e9a-9791-ed6dedb046b1",
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

initialize array index "CURLOPT_TIMEOUT" with a value in seconds according to time required for response .

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

This answer assumes you understand implementing the perfect algorithm for P1 and discusses how to achieve a win in conditions against ordinary human players, who will make some mistakes more commonly than others.

The game of course should end in a draw if both players play optimally. At a human level, P1 playing in a corner produces wins far more often. For whatever psychological reason, P2 is baited into thinking that playing in the center is not that important, which is unfortunate for them, since it's the only response that does not create a winning game for P1.

If P2 does correctly block in the center, P1 should play the opposite corner, because again, for whatever psychological reason, P2 will prefer the symmetry of playing a corner, which again produces a losing board for them.

For any move P1 may make for the starting move, there is a move P2 may make that will create a win for P1 if both players play optimally thereafter. In that sense P1 may play wherever. The edge moves are weakest in the sense that the largest fraction of possible responses to this move produce a draw, but there are still responses that will create a win for P1.

Empirically (more precisely, anecdotally) the best P1 starting moves seem to be first corner, second center, and last edge.

The next challenge you can add, in person or via a GUI, is not to display the board. A human can definitely remember all the state but the added challenge leads to a preference for symmetric boards, which take less effort to remember, leading to the mistake I outlined in the first branch.

I'm a lot of fun at parties, I know.

Finding current executable's path without /proc/self/exe

You can use argv[0] and analyze the PATH environment variable. Look at : A sample of a program that can find itself

Postgres ERROR: could not open file for reading: Permission denied

Copy the CSV file to /tmp

For me this solved the issue.

What is a void pointer in C++?

A void* does not mean anything. It is a pointer, but the type that it points to is not known.

It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

  • It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
  • It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
  • It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to.

This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.

And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

How can I scale an image in a CSS sprite

Easy... Using two copies of same image with different scale on the sprite's sheet. Set the Coords and size on the app's logic.