Programs & Examples On #Table locking

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

http://james.fedorapeople.org/yum/commands/find-repos-of-install.py

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

JavaScript ES6 promise for loop

Based on the excellent answer by trincot, I wrote a reusable function that accepts a handler to run over each item in an array. The function itself returns a promise that allows you to wait until the loop has finished and the handler function that you pass may also return a promise.

loop(items, handler) : Promise

It took me some time to get it right, but I believe the following code will be usable in a lot of promise-looping situations.

Copy-paste ready code:

// SEE https://stackoverflow.com/a/46295049/286685
const loop = (arr, fn, busy, err, i=0) => {
  const body = (ok,er) => {
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}
    catch(e) {er(e)}
  }
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()
  return busy ? run(busy,err) : new Promise(run)
}

Usage

To use it, call it with the array to loop over as the first argument and the handler function as the second. Do not pass parameters for the third, fourth and fifth arguments, they are used internally.

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const items = ['one', 'two', 'three']_x000D_
_x000D_
loop(items, item => {_x000D_
  console.info(item)_x000D_
})_x000D_
.then(() => console.info('Done!'))
_x000D_
_x000D_
_x000D_

Advanced use cases

Let's look at the handler function, nested loops and error handling.

handler(current, index, all)

The handler gets passed 3 arguments. The current item, the index of the current item and the complete array being looped over. If the handler function needs to do async work, it can return a promise and the loop function will wait for the promise to resolve before starting the next iteration. You can nest loop invocations and all works as expected.

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
  [],_x000D_
  ['one', 'two'],_x000D_
  ['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
  console.info('Performing test ' + idx)_x000D_
  return loop(test, (testCase) => {_x000D_
    console.info(testCase)_x000D_
  })_x000D_
  .then(testNext)_x000D_
  .catch(testFailed)_x000D_
}))_x000D_
.then(() => console.info('All tests done'))
_x000D_
_x000D_
_x000D_

Error handling

Many promise-looping examples I looked at break down when an exception occurs. Getting this function to do the right thing was pretty tricky, but as far as I can tell it is working now. Make sure to add a catch handler to any inner loops and invoke the rejection function when it happens. E.g.:

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
  [],_x000D_
  ['one', 'two'],_x000D_
  ['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
  console.info('Performing test ' + idx)_x000D_
  loop(test, (testCase) => {_x000D_
    if (idx == 2) throw new Error()_x000D_
    console.info(testCase)_x000D_
  })_x000D_
  .then(testNext)_x000D_
  .catch(testFailed)  //  <--- DON'T FORGET!!_x000D_
}))_x000D_
.then(() => console.error('Oops, test should have failed'))_x000D_
.catch(e => console.info('Succesfully caught error: ', e))_x000D_
.then(() => console.info('All tests done'))
_x000D_
_x000D_
_x000D_

UPDATE: NPM package

Since writing this answer, I turned the above code in an NPM package.

for-async

Install

npm install --save for-async

Import

var forAsync = require('for-async');  // Common JS, or
import forAsync from 'for-async';

Usage (async)

var arr = ['some', 'cool', 'array'];
forAsync(arr, function(item, idx){
  return new Promise(function(resolve){
    setTimeout(function(){
      console.info(item, idx);
      // Logs 3 lines: `some 0`, `cool 1`, `array 2`
      resolve(); // <-- signals that this iteration is complete
    }, 25); // delay 25 ms to make async
  })
})

See the package readme for more details.

How to find and return a duplicate value in array

detect only finds one duplicate. find_all will find them all:

a = ["A", "B", "C", "B", "A"]
a.find_all { |e| a.count(e) > 1 }

Iterating on a file doesn't work the second time

As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the file and there is nothing left to read. You can use file.tell() to see where in the file the pointer is and file.seek to set the pointer. For example:

>>> file = open('myfile.txt')
>>> file.tell()
0
>>> file.readline()
'one\n'
>>> file.tell()
4L
>>> file.readline()
'2\n'
>>> file.tell()
6L
>>> file.seek(4)
>>> file.readline()
'2\n'

Also, you should know that file.readlines() reads the whole file and stores it as a list. That's useful to know because you can replace:

for line in file.readlines():
    #do stuff
file.seek(0)
for line in file.readlines():
    #do more stuff

with:

lines = file.readlines()
for each_line in lines:
    #do stuff
for each_line in lines:
    #do more stuff

You can also iterate over a file, one line at a time, without holding the whole file in memory (this can be very useful for very large files) by doing:

for line in file:
    #do stuff

Trusting all certificates using HttpClient over HTTPS

There a many answers above but I wasn't able to get any of them working correctly (with my limited time), so for anyone else in the same situation you can try the code below which worked perfectly for my java testing purposes:

    public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}

and call like:

DefaultHttpClient baseClient = new DefaultHttpClient();
HttpClient httpClient = wrapClient(baseClient );

Reference: http://tech.chitgoks.com/2011/04/24/how-to-avoid-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-problem-using-apache-httpclient/

How do I catch a PHP fatal (`E_ERROR`) error?

You can't catch/handle fatal errors, but you can log/report them. For quick debugging I modified one answer to this simple code

function __fatalHandler()
{
    $error = error_get_last();

    // Check if it's a core/fatal error, otherwise it's a normal shutdown
    if ($error !== NULL && in_array($error['type'],
        array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
              E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {

        echo "<pre>fatal error:\n";
        print_r($error);
        echo "</pre>";
        die;
    }
}

register_shutdown_function('__fatalHandler');

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

do you try

[{"name":"myEnterprise", "departments":["HR"]}]

the square brace is the key point.

How to succinctly write a formula with many variables from a data frame?

There is a special identifier that one can use in a formula to mean all the variables, it is the . identifier.

y <- c(1,4,6)
d <- data.frame(y = y, x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
mod <- lm(y ~ ., data = d)

You can also do things like this, to use all variables but one (in this case x3 is excluded):

mod <- lm(y ~ . - x3, data = d)

Technically, . means all variables not already mentioned in the formula. For example

lm(y ~ x1 * x2 + ., data = d)

where . would only reference x3 as x1 and x2 are already in the formula.

How can I run multiple curl requests processed sequentially?

I think this uses more native capabilities

//printing the links to a file
$ echo "https://stackoverflow.com/questions/3110444/
https://stackoverflow.com/questions/8445445/
https://stackoverflow.com/questions/4875446/" > links_file.txt


$ xargs curl < links_file.txt

Enjoy!

Get text of label with jquery

for the line you wrote

var g = $('<%=Label1.ClientID%>').val(); // Also I tried .text() and .html()

you missed adding #. it should be like this

var g = $('#<%=Label1.ClientID%>').text();

also I do not prefer using this method

that's because if you are calling a control in master or nested master page or if you are calling a control in page from master. Also controls in Repeater. regardless the MVC. this will cause problems.

you should ALWAYS call the ID of the control directly. like this

$('#ControlID')

this is simple and clear. but do not forget to set

ClientIDMode="Static"

in your controls to remain with same ID name after render. that's because ASP.net will modify the ID name in HTML rendered file in some contexts i.e. the page is for Master page the control name will be ConetentPlaceholderName_controlID

I hope it clears the question Good Luck

Adding author name in Eclipse automatically to existing files

To old files I don't know how to do it... I think you will need a script to go thru all files and add the header.

To change the new ones you can do this.

Go to Eclipse menu bar

  1. Window menu.
  2. Preferences
  3. search for Templates
  4. go to Code templates
  5. click on +code
  6. Click on New Java files
  7. Click Edit
  8. add

/**
${user}
*/

And it's done every new File will have your name on it !

Toggle visibility property of div

To clean this up a little bit and maintain a single line of code (like you would with a toggle()), you can use a ternary operator so your code winds up looking like this (also using jQuery):

$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');

Calling a php function by onclick event

onclick event to call a function

  <strike> <input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />    </strike>

it will surely help you

it take a little more time than normal but wait it will work

Mod of negative number is melting my brain

Just add your modulus (arrayLength) to the negative result of % and you'll be fine.

TypeError: 'list' object is not callable while trying to access a list

To get elements of a list you have to use list[i] instead of list(i).

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

I would check the Installed value of

HKLM\SOFTWARE\[WOW6432Node]\Microsoft\Windows\CurrentVersion\Uninstall\{VCRedist_GUID} key

  • where GUID of VC++ 2012 (x86) is {33d1fd90-4274-48a1-9bc1-97e33d9c2d6f}
  • WOW6432Node will be present or not depending on the VC++ redist product

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

How to convert a huge list-of-vector to a matrix more efficiently?

I think you want

output <- do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))

i.e. combining @BlueMagister's use of do.call(rbind,...) with an lapply statement to convert the individual list elements into 11*10 matrices ...

Benchmarks (showing @flodel's unlist solution is 5x faster than mine, and 230x faster than the original approach ...)

n <- 1000
z <- replicate(n,matrix(1:110,ncol=10,byrow=TRUE),simplify=FALSE)
library(rbenchmark)
origfn <- function(z) {
    output <- NULL 
    for(i in 1:length(z))
        output<- rbind(output,matrix(z[[i]],ncol=10,byrow=TRUE))
}
rbindfn <- function(z) do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))
unlistfn <- function(z) matrix(unlist(z), ncol = 10, byrow = TRUE)

##          test replications elapsed relative user.self sys.self 
## 1   origfn(z)          100  36.467  230.804    34.834    1.540  
## 2  rbindfn(z)          100   0.713    4.513     0.708    0.012 
## 3 unlistfn(z)          100   0.158    1.000     0.144    0.008 

If this scales appropriately (i.e. you don't run into memory problems), the full problem would take about 130*0.2 seconds = 26 seconds on a comparable machine (I did this on a 2-year-old MacBook Pro).

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

In Windows 10, no need to restart nor run in Administrator's mode but instead set openssl config like so:

set OPENSSL_CONF=C:\Program Files (x86)\GnuWin32\share\openssl.cnf

Of course, if you are using GnuWin32

How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView

You can use general compound drawable implementation, but if you need to define a size of drawable use this library:

https://github.com/a-tolstykh/textview-rich-drawable

Here is a small example of usage:

<com.tolstykh.textviewrichdrawable.TextViewRichDrawable
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some text"
        app:compoundDrawableHeight="24dp"
        app:compoundDrawableWidth="24dp" />

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Public Sub EmptyTxt(ByVal Frm As Form)
    Dim Ctl As Control
    For Each Ctl In Frm.Controls
        If TypeOf Ctl Is TextBox Then Ctl.Text = ""
        If TypeOf Ctl Is GroupBox Then
            Dim Ctl1 As Control
            For Each Ctl1 In Ctl.Controls
                If TypeOf Ctl1 Is TextBox Then
                    Ctl1.Text = ""
                End If
            Next
        End If
    Next
End Sub

add this code in form and call this function

EmptyTxt(Me)

Create a date time with month and day only, no year

There is no such thing like a DateTime without a year!

From what I gather your design is a bit strange:

I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.

After the event occurs you calculate the next and store that etc.

Width equal to content

Set display:inline-block and then adjust your margins.

fiddle here: http://jsfiddle.net/Q2MrC/

Using GSON to parse a JSON array

public static <T> List<T> toList(String json, Class<T> clazz) {
    if (null == json) {
        return null;
    }
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<T>(){}.getType());
}

sample call:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

It really doesn't matter.
If you feed .c to a c++ compiler it will compile as cpp, .cc/.cxx is just an alternative to .cpp used by some compilers.

.hpp is an attempt to distinguish header files where there are significant c and c++ differences. A common usage is for the .hpp to have the necessary cpp wrappers or namespace and then include the .h in order to expose a c library to both c and c++.

How to call a vue.js function on page load

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....

jquery function val() is not equivalent to "$(this).value="?

One thing you can do is this:

$(this)[0].value = "Something";

This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

Limiting Python input strings to certain characters and lengths

Regexes can also limit the number of characters.

r = re.compile("^[a-z]{1,15}$")

gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.

How can a Javascript object refer to values in itself?

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

How to uninstall pip on OSX?

Since pip is a package, pip uninstall pip Will do it.
EDIT: If that does not work, try sudo -H pip uninstall pip.

LINQ Group By and select collection

you may also like this

var Grp = Model.GroupBy(item => item.Order.Customer)
      .Select(group => new 
        { 
             Customer = Model.First().Customer, 
             CustomerId= group.Key,  
             Orders= group.ToList() 
       })
      .ToList();

How to position two elements side by side using CSS

You can use float:left to align div in one line.

Fiddle

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

$song = DB::table('songs')->find($id);

here you use method find($id)

for Laravel, if you use this method, you should have column named 'id' and set it as primary key, so then you'll be able to use method find()

otherwise use where('SongID', $id) instead of find($id)

json_encode is returning NULL?

few day ago I have the SAME problem with 1 table.

Firstly try:

echo json_encode($rows);
echo json_last_error();  // returns 5 ?

If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.

Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.

You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...

Illegal string offset Warning PHP

In my case, I solved it when I changed in function that does sql query after: return json_encode($array) then: return $array

Time calculation in php (add 10 hours)?

In order to increase or decrease time using strtotime you could use a Relative format in the first argument.

In your case to increase the current time by 10 hours:

$date = date('h:i:s A', strtotime('+10 hours'));

In case you need to apply the change to another timestamp, the second argument can be specified.

Note:

Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

So, the recommended way since PHP 5.3:

$dt = new DateTime(); // assuming we need to add to the current time
$dt->add(new DateInterval('PT10H'));
$date = $dt->format('h:i:s A');

or using aliases:

$dt = date_create(); // assuming we need to add to the current time
date_add($dt, date_interval_create_from_date_string('10 hours')); 
$date = date_format($dt, 'h:i:s A');

In all cases the default time zone will be used unless a time zone is specified.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I was facing the same error. The solution that worked for me is:

From the server end, while returning JSON response, change the content-type: text/html

Now the browsers (Chrome, Firefox and IE8) do not give an error.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Convert List<T> to ObservableCollection<T> in WP7

ObservableCollection has several constructors which have input parameter of List<T> or IEnumerable<T>:
List<T> list = new List<T>();
ObservableCollection<T> collection = new ObservableCollection<T>(list);

SQL Server Case Statement when IS NULL

  case isnull(B.[stat],0)
  when 0 then dateadd(dd,10,(c.[Eventdate]))
  end

you can add in else statement if you want to add 30 days to the same .

How to kill a process running on particular port in Linux?

  1. first check the process netstat -lt
  2. check process id fuser <port number>/tcp
  3. kill the process running on the port kill <process id>

Can I disable a CSS :hover effect via JavaScript?

I used the not() CSS operator and jQuery's addClass() function. Here is an example, when you click on a list item, it won't hover anymore:

For example:

HTML

<ul class="vegies">
    <li>Onion</li>
    <li>Potato</li>
    <li>Lettuce</li>
<ul>

CSS

.vegies li:not(.no-hover):hover { color: blue; }

jQuery

$('.vegies li').click( function(){
    $(this).addClass('no-hover');
});

How to grep recursively, but only in files with certain extensions?

Just use the --include parameter, like this:

grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]

that should do what you want.

To take the explanation from HoldOffHunger's answer below:

  • grep: command

  • -r: recursively

  • -i: ignore-case

  • -n: each output line is preceded by its relative line number in the file

  • --include \*.cpp: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)

  • ./: Start at current directory.

Append values to a set in Python

Use update like this:

keep.update(newvalues)

Play audio with Python

Install playsound package using :

pip install playsound

Usage:

from playsound import playsound
playsound("file location\audio.p3")

calculate the mean for each column of a matrix in R

For diversity: Another way is to converts a vector function to one that works with data frames by using plyr::colwise()

set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))

plyr::colwise(mean)(m)


#   X1   X2   X3   X4
# 1 47 64.4 44.8 67.8

How to display an alert box from C# in ASP.NET?

If you don't have a Page.Redirect(), use this

Response.Write("<script>alert('Inserted successfully!')</script>"); //works great

But if you do have Page.Redirect(), use this

Response.Write("<script>alert('Inserted..');window.location = 'newpage.aspx';</script>"); //works great

works for me.

Hope this helps.

Get latitude and longitude based on location name with Google Autocomplete API

I hope this can help someone in the future.

You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script type="text/javascript">
        function initialize() {
        var address = (document.getElementById('my-address'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
      });
}
function codeAddress() {
    geocoder = new google.maps.Geocoder();
    var address = document.getElementById("my-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

      alert("Latitude: "+results[0].geometry.location.lat());
      alert("Longitude: "+results[0].geometry.location.lng());
      } 

      else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
google.maps.event.addDomListener(window, 'load', initialize);

        </script>
    </head>
    <body>
        <input type="text" id="my-address">
        <button id="getCords" onClick="codeAddress();">getLat&Long</button>
    </body>
</html>

Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.

Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).

Hope this helps, and read the documentation for more information, cheers.

Edit #1: Fiddle

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

I know that this is an old question but I am just going to place this here:

To prevent skype from using port 80 and port 443, open the Skype window, then click on the Tools menu and select Options.
Click on the Advanced tab, and go to the Connection sub-tab.
Uncheck the checkbox for Use port 80 and 443 as an alternative for additional incoming connections option.
Click on the Save button and then restart Skype.
After you restart skype, skype wont use port 88 or 443 anymore.

Hope this might help someone.

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

How do I write a compareTo method which compares objects?

This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

This won't even compile:

if (this.getLastName() < s.getLastName())

Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
    d = getLastName().compareTo(s.getLastName());
return d;

How to determine if a string is a number with C++?

My solution using C++11 regex (#include <regex>), it can be used for more precise check, like unsigned int, double etc:

static const std::regex INT_TYPE("[+-]?[0-9]+");
static const std::regex UNSIGNED_INT_TYPE("[+]?[0-9]+");
static const std::regex DOUBLE_TYPE("[+-]?[0-9]+[.]?[0-9]+");
static const std::regex UNSIGNED_DOUBLE_TYPE("[+]?[0-9]+[.]?[0-9]+");

bool isIntegerType(const std::string& str_)
{
  return std::regex_match(str_, INT_TYPE);
}

bool isUnsignedIntegerType(const std::string& str_)
{
  return std::regex_match(str_, UNSIGNED_INT_TYPE);
}

bool isDoubleType(const std::string& str_)
{
  return std::regex_match(str_, DOUBLE_TYPE);
}

bool isUnsignedDoubleType(const std::string& str_)
{
  return std::regex_match(str_, UNSIGNED_DOUBLE_TYPE);
}

You can find this code at http://ideone.com/lyDtfi, this can be easily modified to meet the requirements.

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

Angular 5 Scroll to top on every Route click

Try this:

app.component.ts

import {Component, OnInit, OnDestroy} from '@angular/core';
import {Router, NavigationEnd} from '@angular/router';
import {filter} from 'rxjs/operators';
import {Subscription} from 'rxjs';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, OnDestroy {
    subscription: Subscription;

    constructor(private router: Router) {
    }

    ngOnInit() {
        this.subscription = this.router.events.pipe(
            filter(event => event instanceof NavigationEnd)
        ).subscribe(() => window.scrollTo(0, 0));
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

Update Rows in SSIS OLEDB Destination

Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html

Steps to do update:

  1. Drag OLEDB Command [instead of oledb destination]
  2. Go to properties window
  3. Under Custom properties select SQLCOMMAND and insert update command ex:

    UPDATE table1 SET col1 = ?, col2 = ? where id = ?

  4. map columns in exact order from source to output as in update command

setting system property

For JBoss, in standalone.xml, put after .

<extensions>
</extensions>

<system-properties>
    <property name="my.project.dir" value="/home/francesco" />
</system-properties>

For eclipse:

http://www.avajava.com/tutorials/lessons/how-do-i-set-system-properties.html?page=2

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'
/

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott
/

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

DECLARE
  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
BEGIN
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
  DBMS_LOB.CLOSE(v_src_loc);
  COMMIT;
END;
/

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

Difference between a class and a module

Module in Ruby, to a degree, corresponds to Java abstract class -- has instance methods, classes can inherit from it (via include, Ruby guys call it a "mixin"), but has no instances. There are other minor differences, but this much information is enough to get you started.

How do I position an image at the bottom of div?

< img style="vertical-align: bottom" src="blah.png" >

Works for me. Inside a parallax div as well.

Checking for empty result (php, pdo, mysql)

Even though this is an old thread, I thought I would weigh in as I had to deal with this lately.

You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

//I would usually put this all in a try/catch block, but kept it the same for continuity
if(!$sth->execute(array(':today'=>$today))) 
{
    $db = null ;
    exit();
}

$result = $sth->fetch(PDO::FETCH_OBJ)

if(!isset($result->id_email))
{
    echo "empty";
}
else
{
    echo "not empty, value is $result->id_email";
}

$db = null;

Of course this is only for a single result, as you might have when looping over a dataset.

Installing MySQL-python

  1. find the folder: sudo find / -name "mysql_config" (assume it's "/opt/local/lib/mysql5/bin")

  2. add it into PATH:export PATH:export PATH=/opt/local/lib/mysql5/bin:$PATH

  3. install it again

How to automatically update your docker containers, if base-images are updated

A 'docker way' would be to use docker hub automated builds. The Repository Links feature will rebuild your container when an upstream container is rebuilt, and the Webhooks feature will send you a notification.

It looks like the webhooks are limited to HTTP POST calls. You'd need to set up a service to catch them, or maybe use one of the POST to email services out there.

I haven't looked into it, but the new Docker Universal Control Plane might have a feature for detecting updated containers and re-deploying.

Indent List in HTML and CSS

Normally, all lists are being displayed vertically anyways. So do you want to display it horizontally?

Anyways, you asked to override the main css file and set some css locally. You cannot do it inside <ul> with style="", that it would apply on the children (<li>).

Closest thing to locally manipulating your list would be:

<style>
    li {display: inline-block;}
</style>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
        <li>Black tea</li>
        <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

For me the problem was solved by deleting a .pid file named after my computer:

sudo rm /var/mysql/computername.pid

What are the advantages of NumPy over regular Python lists?

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04

Maximum packet size for a TCP connection

The absolute limitation on TCP packet size is 64K (65535 bytes), but in practicality this is far larger than the size of any packet you will see, because the lower layers (e.g. ethernet) have lower packet sizes.

The MTU (Maximum Transmission Unit) for Ethernet, for instance, is 1500 bytes. Some types of networks (like Token Ring) have larger MTUs, and some types have smaller MTUs, but the values are fixed for each physical technology.

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

Python: No acceptable C compiler found in $PATH when installing python

You would need to install it as non root, since its shared hosting. Here is a tut that points how this step. http://luiarthur.github.io/gccinstall

cd ~/src
wget http://www.netgull.com/gcc/releases/gcc-5.2.0/gcc-5.2.0.tar.gz

or equivalent gcc source, then

tar -xvf gcc-5.2.0.tar.gz
cd gcc-5.2.0
./contrib/download_prerequisites
cd ..
mkdir objdir
cd objdir
$PWD/../gcc-5.2.0/configure --prefix=$HOME/gcc-5.2.0 --enable-languages=c,c++,fortran,go
make
make install

then add to .bashrc, or equivalent

export PATH=~/gcc-5.2.0/bin:$PATH
export LD_LIBRARY_PATH=~/gcc-5.2.0/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=~/gcc-5.2.0/lib64:$LD_LIBRARY_PATH

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

How to parse a CSV in a Bash script?

In a CSV file, each field is separated by a comma. The problem is, a field itself might have an embedded comma:

Name,Phone
"Woo, John",425-555-1212

You really need a library package that offer robust CSV support instead of relying on using comma as a field separator. I know that scripting languages such as Python has such support. However, I am comfortable with the Tcl scripting language so that is what I use. Here is a simple Tcl script which does what you are asking for:

#!/usr/bin/env tclsh

package require csv 
package require Tclx

# Parse the command line parameters
lassign $argv fileName columnNumber expectedValue

# Subtract 1 from columnNumber because Tcl's list index starts with a
# zero instead of a one
incr columnNumber -1

for_file line $fileName {
    set columns [csv::split $line]
    set columnValue [lindex $columns $columnNumber]
    if {$columnValue == $expectedValue} {
        puts $line
    }   
}

Save this script to a file called csv.tcl and invoke it as:

$ tclsh csv.tcl filename indexNumber expectedValue

Explanation

The script reads the CSV file line by line and store the line in the variable $line, then it split each line into a list of columns (variable $columns). Next, it picks out the specified column and assigned it to the $columnValue variable. If there is a match, print out the original line.

Comparing two files in linux terminal

Try sdiff (man sdiff)

sdiff -s file1 file2

Convert an NSURL to an NSString

I just fought with this very thing and this update didn't work.

This eventually did in Swift:

let myUrlStr : String = myUrl!.relativePath!

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

When one should inline :

1.When one want to avoid overhead of things happening when function is called like parameter passing , control transfer, control return etc.

2.The function should be small,frequently called and making inline is really advantageous since as per 80-20 rule,try to make those function inline which has major impact on program performance.

As we know that inline is just a request to compiler similar to register and it will cost you at Object code size.

SQL Group By with an Order By

Try this query

 SELECT  data_collector_id , count (data_collector_id ) as frequency 
    from rent_flats 
    where is_contact_person_landlord = 'True' 
    GROUP BY data_collector_id 
    ORDER BY count(data_collector_id) DESC

scrollable div inside container

The simplest way is as this example:

<div>
   <div style=' height:300px;'>
     SOME LOGO OR CONTENT HERE
   </div>
   <div style='overflow-x: hidden;overflow-y: scroll;'> 
      THIS IS SOME TEXT
   </DIV>

You can see the test cases on: https://www.w3schools.com/css/css_overflow.asp

Vue 'export default' vs 'new Vue'

export default is used to create local registration for Vue component.

Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e

How to pause javascript code execution for 2 seconds

There's no (safe) way to pause execution. You can, however, do something like this using setTimeout:

function writeNext(i)
{
    document.write(i);

    if(i == 5)
        return;

    setTimeout(function()
    {
        writeNext(i + 1);

    }, 2000);
}

writeNext(1);

Reorder / reset auto increment primary key

This works - https://stackoverflow.com/a/5437720/10219008.....but if you run into an issue 'Error Code: 1265. Data truncated for column 'id' at row 1'...Then run the following. Adding ignore on the update query.

SET @count = 0;
set sql_mode = 'STRICT_ALL_TABLES';
UPDATE IGNORE web_keyword SET id = @count := (@count+1);

SET NOCOUNT ON usage

At the risk of making things more complicated, I encourage a slightly different rule to all those I see above:

  • Always set NOCOUNT ON at the top of a proc, before you do any work in the proc, but also always SET NOCOUNT OFF again, before returning any recordsets from the stored proc.

So "generally keep nocount on, except when you are actually returning a resultset". I don't know any ways that this can break any client code, it means client code never needs to know anything about the proc internals, and it isn't particularly onerous.

Passing an Object from an Activity to a Fragment

In your activity class:

public class BasicActivity extends Activity {

private ComplexObject co;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_page);

    co=new ComplexObject();
    getIntent().putExtra("complexObject", co);

    FragmentManager fragmentManager = getFragmentManager();
    Fragment1 f1 = new Fragment1();
    fragmentManager.beginTransaction()
            .replace(R.id.frameLayout, f1).commit();

}

Note: Your object should implement Serializable interface

Then in your fragment :

public class Fragment1 extends Fragment {

ComplexObject co;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Intent i = getActivity().getIntent();

    co = (ComplexObject) i.getSerializableExtra("complexObject");

    View view = inflater.inflate(R.layout.test_page, container, false);
    TextView textView = (TextView) view.findViewById(R.id.DENEME);
    textView.setText(co.getName());

    return view;
}
}

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

This happened to me because I was using OpenVPN. I found a way that I don't need to stop using the VPN or manually add a network to the docker-compose file nor run any crazy script.

I switched to WireGuard instead of OpenVPN. More specifically, as I am running the nordvpn solution, I installed WireGuard and used their version of it, NordLynx.

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

how to format date in Component of angular 5

There is equally formatDate

const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);

According to the API it takes as param either a date string, a Date object, or a timestamp.

Gotcha: Out of the box, only en-US is supported.

If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:

import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");

Don't forget to add corresponding import:

import { formatDate } from "@angular/common";

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;
}

#header {
    position: relative;
    height: 50px;
    padding: 10px;
}

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Update

Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;
}

Here's a post talking about how box-sizing works.

Error 0x80005000 and DirectoryServices

Just had that problem in a production system in the company where I live... A webpage that made a LDAP bind stopped working after an IP changed.

The solution... ... I installed Basic Authentication to perform the troubleshooting indicated here: https://support.microsoft.com/en-us/kb/329986

And after that, things just started to work. Even after I re-disabled Basic Authentication in the page I was testing, all other pages started working again with Windows Authentication.

Regards, Acácio

What's the difference between compiled and interpreted language?

Here is the Basic Difference between Compiler vs Interpreter Language.

Compiler Language

  • Takes entire program as single input and converts it into object code which is stored in the file.
  • Intermediate Object code is generated
  • e.g: C,C++
  • Compiled programs run faster because compilation is done before execution.
  • Memory requirement is more due to the creation of object code.
  • Error are displayed after the entire program is compiled
  • Source code ---Compiler ---Machine Code ---Output

Interpreter Language:

  • Takes single instruction as single input and executes instructions.
  • Intermediate Object code is NOT generated
  • e.g: Perl, Python, Matlab
  • Interpreted programs run slower because compilation and execution take place simultaneously.
  • Memory requirement is less.
  • Error are displayed for every single instruction.
  • Source Code ---Interpreter ---Output

Need to combine lots of files in a directory

Use the Windows 'copy' command.

C:\Users\dan>help copy
    Copies one or more files to another location.

    COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/L] [/A | /B ] source [/A | /B]
         [+ source [/A | /B] [+ ...]] [destination [/A | /B]]

      source       Specifies the file or files to be copied.
      /A           Indicates an ASCII text file.
      /B           Indicates a binary file.
      /D           Allow the destination file to be created decrypted
      destination  Specifies the directory and/or filename for the new file(s).
      /V           Verifies that new files are written correctly.
      /N           Uses short filename, if available, when copying a file with 
                   a non-8dot3 name.
      /Y           Suppresses prompting to confirm you want to overwrite an
                   existing destination file.
      /-Y          Causes prompting to confirm you want to overwrite an
                   existing destination file.
      /Z           Copies networked files in restartable mode.
      /L           If the source is a symbolic link, copy the link to the 
                   target
                   instead of the actual file the source link points to.

    The switch /Y may be preset in the COPYCMD environment variable.
    This may be overridden with /-Y on the command line.  Default is
    to prompt on overwrites unless COPY command is being executed from
    within a batch script.

    **To append files, specify a single file for destination, but 
    multiple files for source (using wildcards or file1+file2+file3 
    format).**

So in your case:

copy *.txt destination.txt

Will concatenate all .txt files in alphabetical order into destination.txt

Thanks for asking, I learned something new!

How do I access properties of a javascript object if I don't know the names?

You can loop through keys like this:

for (var key in data) {
  console.log(key);
}

This logs "Name" and "Value".

If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    console.log(key);
  }
}

As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:

for each (var value in data) {
  console.log(value);
}

This example loops through values, so it would log Property Name and 0. N.B.: The for each syntax is mostly only supported in Firefox, but not in other browsers.

If your target browsers support ES5, or your site includes es5-shim.js (recommended), you can also use Object.keys:

var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]

and loop with Array.prototype.forEach:

Object.keys(data).forEach(function (key) {
  console.log(data[key]);
});
// => Logs "Property Name", 0

MS SQL Date Only Without Time

Alternatively you could use

declare @d datetimeselect
@d =  '2008-12-1 14:30:12'
where tstamp 
  BETWEEN dateadd(dd, datediff(dd, 0, @d)+0, 0) 
  AND dateadd(dd, datediff(dd, 0, @d)+1, 0)

Remove leading zeros from a number in Javascript

regexp:

"014".replace(/^0+/, '')

Google Text-To-Speech API

I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World

And requested with python library..however I'm getting HTTP 403 FORBIDDEN

In the end I had to mock the User-Agent header with the browser's one to succeed.

Unit testing with mockito for constructors

I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach

Class First {

   private Second second;

   public First(int num, String str) {
     if(second== null)
     {
       //when junit runs, you get the mocked object(not null), hence don't 
       //initialize            
       second = new Second(str);
     }
     this.num = num;
   }

   ... // some other methods
}

And, for test:

class TestFirst{
    @InjectMock
    First first;//inject mock the real testable class
    @Mock
    Second second

    testMethod(){

        //now you can play around with any method of the Second class using its 
        //mocked object(second),like:
        when(second.getSomething(String.class)).thenReturn(null);
    }
}

What's the best way to send a signal to all members of a process group?

I can't comment (not enough reputation), so I am forced to add a new answer, even though this is not really an answer.

There is a slight problem with the otherwise very nice and thorough answer given by @olibre on Feb 28. The output of ps opgid= $PID will contain leading spaces for a PID shorter than five digits because ps is justifying the column (rigth align the numbers). Within the entire command line, this results in a negative sign, followed by space(s), followed by the group PID. Simple solution is to pipe ps to tr to remove spaces:

kill -- -$( ps opgid= $PID | tr -d ' ' )

Is there a "between" function in C#?

No, but you can write your own:

public static bool Between(this int num, int lower, int upper, bool inclusive = false)
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

How to break out from a ruby block?

use the keyword break instead of return

How do I check if PHP is connected to a database already?

before... (I mean somewhere in some other file you're not sure you've included)

$db = mysql_connect()

later...

if (is_resource($db)) {
// connected
} else {
$db = mysql_connect();
}

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

For those working in Anaconda in Windows, I had the same problem. Notepad++ help me to solve it.

Open the file in Notepad++. In the bottom right it will tell you the current file encoding. In the top menu, next to "View" locate "Encoding". In "Encoding" go to "character sets" and there with patiente look for the enconding that you need. In my case the encoding "Windows-1252" was found under "Western European"

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

You must analyse the actual HTML output, for the hint.

By giving the path like this means "from current location", on the other hand if you start with a / that would mean "from the context".

Take multiple lists into dataframe

I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
    {'lst1Title': lst1,
     'lst2Title': lst2,
     'lst3Title': lst3
    })

percentile_list
    lst1Title  lst2Title  lst3Title
0          0         0         0
1          1         1         1
2          2         2         2
3          3         3         3
4          4         4         4
5          5         5         5
6          6         6         6
...

If you need a more performant solution you can use np.column_stack rather than zip as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:

import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]), 
                               columns=['lst1Title', 'lst2Title', 'lst3Title'])

How do I convert a dictionary to a JSON String in C#?

Here's how to do it using only standard .Net libraries from Microsoft …

using System.IO;
using System.Runtime.Serialization.Json;

private static string DataToJson<T>(T data)
{
    MemoryStream stream = new MemoryStream();

    DataContractJsonSerializer serialiser = new DataContractJsonSerializer(
        data.GetType(),
        new DataContractJsonSerializerSettings()
        {
            UseSimpleDictionaryFormat = true
        });

    serialiser.WriteObject(stream, data);

    return Encoding.UTF8.GetString(stream.ToArray());
}

Saving images in Python at a very high quality

In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:

Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:

import seaborn as sb

image = sb.heatmap(matrix)   # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png")   # This saves it

This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.

Another way I like is this. I set the size of the next image as follows:

plt.subplots(figsize=(15,15))

And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

How to bind an enum to a combobox control in WPF?

Use ObjectDataProvider:

<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>

and then bind to static resource:

ItemsSource="{Binding Source={StaticResource enumValues}}"

based on this article

What's better at freeing memory with PHP: unset() or $var = null

PHP 7 is already worked on such memory management issues and its reduced up-to minimal usage.

<?php
  $start = microtime(true);
  for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    $a = NULL;
  }
  $elapsed = microtime(true) - $start;

  echo "took $elapsed seconds\r\n";

  $start = microtime(true);
  for ($i = 0; $i < 10000000; $i++) {
     $a = 'a';
     unset($a);
  }
  $elapsed = microtime(true) - $start;

  echo "took $elapsed seconds\r\n";

?>

PHP 7.1 Outpu:

took 0.16778993606567 seconds took 0.16630101203918 seconds

SVN- How to commit multiple files in a single shot

Use a changeset. You can add as many files as you like to the changeset, all at once, or over several commands; and then commit them all in one go.

How to pass the id of an element that triggers an `onclick` event to the event handling function

Use this:

<link onclick='doWithThisElement(this.attributes["id"].value)' />

In the context of the onclick JavaScript, this refers to the current element (which in this case is the whole HTML element link).

milliseconds to time in javascript

Editing RobG's solution and using JavaScript's Date().

function msToTime(ms) {

    function addZ(n) {
        return (n<10? '0':'') + n;
    }
    var dt = new Date(ms);
    var hrs = dt.getHours();
    var mins = dt.getMinutes();
    var secs = dt.getSeconds();
    var millis = dt.getMilliseconds();

    var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
    return tm;
}

How to open new browser window on button click event?

It can be done all on the client-side using the OnClientClick[MSDN] event handler and window.open[MDN]:

<asp:Button 
     runat="server" 
     OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
     Open a new window!
</asp:Button>

MySQL error - #1062 - Duplicate entry ' ' for key 2

Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday

Convert/cast an stdClass object to another class

Convert it to an array, return the first element of that array, and set the return param to that class. Now you should get the autocomplete for that class as it will regconize it as that class instead of stdclass.

/**
 * @return Order
 */
    public function test(){
    $db = new Database();

    $order = array();
    $result = $db->getConnection()->query("select * from `order` where productId in (select id from product where name = 'RTX 2070')");
    $data = $result->fetch_object("Order"); //returns stdClass
    array_push($order, $data);

    $db->close();
    return $order[0];
}

sqlalchemy: how to join several tables by one query?

This function will produce required table as list of tuples.

def get_documents_by_user_email(email):
    query = session.query(
       User.email, 
       User.name, 
       Document.name, 
       DocumentsPermissions.readAllowed, 
       DocumentsPermissions.writeAllowed,
    )
    join_query = query.join(Document).join(DocumentsPermissions)

    return join_query.filter(User.email == email).all()

user_docs = get_documents_by_user_email(email)

don't fail jenkins build if execute shell fails

To stop further execution when command fails:

command || exit 0

To continue execution when command fails:

command || true

Convert utf8-characters to iso-88591 and back in PHP

Have a look at iconv() or mb_convert_encoding(). Just by the way: why don't utf8_encode() and utf8_decode() work for you?

utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

utf8_encode — Encodes an ISO-8859-1 string to UTF-8

So essentially

$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');

$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');

all should do the same - with utf8_en/decode() requiring no special extension, mb_convert_encoding() requiring ext/mbstring and iconv() requiring ext/iconv.

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

Try to reinstall new version of XAMPP. Find "<Directory "C:/xampp/php">" and then change to something like this

<Directory "C:/xampp/php">
    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all
    Require all granted
</Directory>

How do I use namespaces with TypeScript external modules?

The proper way to organize your code is to use separate directories in place of namespaces. Each class will be in it's own file, in it's respective namespace folder. index.ts will only re-export each file; no actual code should be in the index.ts file. Organizing your code like this makes it far easier to navigate, and is self-documenting based on directory structure.

// index.ts
import * as greeter from './greeter';
import * as somethingElse from './somethingElse';

export {greeter, somethingElse};

// greeter/index.ts
export * from './greetings.js';
...

// greeter/greetings.ts
export const helloWorld = "Hello World";

You would then use it as such:

import { greeter } from 'your-package'; //Import it like normal, be it from an NPM module or from a directory.
// You can also use the following syntax, if you prefer:
import * as package from 'your-package';

console.log(greeter.helloWorld);

What is the maximum possible length of a .NET string?

Since the Length property of System.String is an Int32, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32 size). If it allowed longer you couldn't check the Length since that would fail.

Correct way to select from two tables in SQL Server with no common field to join on

Cross join will help to join multiple tables with no common fields.But be careful while joining as this join will give cartesian resultset of two tables. QUERY:

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
CROSS JOIN table2

Alternative way to join on some condition that is always true like

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
INNER JOIN table2 ON 1=1

But this type of query should be avoided for performance as well as coding standards.

Switch in Laravel 5 - Blade

In Laravel 5.1, this works in a Blade:

<?php
    switch( $machine->disposal ) {
        case 'DISPO': echo 'Send to Property Disposition'; break;
        case 'UNIT':  echo 'Send to Unit'; break;
        case 'CASCADE': echo 'Cascade the machine'; break;
        case 'TBD':   echo 'To Be Determined (TBD)'; break;
    }
?>

Check if a record exists in the database

sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM  tblAttendance",con);
sda.Fill(dt);

string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);

if (bar >= 1){

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "empty");
}

What does "all" stand for in a makefile?

The target "all" is an example of a dummy target - there is nothing on disk called "all". This means that when you do a "make all", make always thinks that it needs to build it, and so executes all the commands for that target. Those commands will typically be ones that build all the end-products that the makefile knows about, but it could do anything.

Other examples of dummy targets are "clean" and "install", and they work in the same way.

If you haven't read it yet, you should read the GNU Make Manual, which is also an excellent tutorial.

Pause Console in C++ program

This works for me.

void pause()
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    std::string dummy;
    std::cout << "Press any key to continue . . .";
    std::getline(std::cin, dummy);
}

Setting font on NSAttributedString on UITextView disregards line spacing

//For proper line spacing

NSString *text1 = @"Hello";
NSString *text2 = @"\nWorld";
UIFont *text1Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:10];
NSMutableAttributedString *attributedString1 =
[[NSMutableAttributedString alloc] initWithString:text1 attributes:@{ NSFontAttributeName : text1Font }];
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setAlignment:NSTextAlignmentCenter];
[paragraphStyle1 setLineSpacing:4];
[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attributedString1 length])];

UIFont *text2Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:16];
NSMutableAttributedString *attributedString2 =
[[NSMutableAttributedString alloc] initWithString:text2 attributes:@{NSFontAttributeName : text2Font }];
NSMutableParagraphStyle *paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle2 setLineSpacing:4];
[paragraphStyle2 setAlignment:NSTextAlignmentCenter];
[attributedString2 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle2 range:NSMakeRange(0, [attributedString2 length])];

[attributedString1 appendAttributedString:attributedString2];

Proper way to concatenate variable strings

As simple as joining lists in python itself.

ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost

localhost | SUCCESS => {
  "msg": "list-joined-together" }

Works the same way using variables:

ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost

Extract the filename from a path

You could get the result you want like this.

$file = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$a = $file.Split("\")
$index = $a.count - 1
$a.GetValue($index)

If you use "Get-ChildItem" to get the "fullname", you could also use "name" to just get the name of the file.

How to speed up insertion performance in PostgreSQL

For optimal Insertion performance disable the index if that's an option for you. Other than that, better hardware (disk, memory) is also helpful

How can I create a blank/hardcoded column in a sql query?

The answers above are correct, and what I'd consider the "best" answers. But just to be as complete as possible, you can also do this directly in CF using queryAddColumn.

See http://www.cfquickdocs.com/cf9/#queryaddcolumn

Again, it's more efficient to do it at the database level... but it's good to be aware of as many alternatives as possible (IMO, of course) :)

TypeScript: Creating an empty typed container array

I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.

I had

return [];

where [] was Criminal[] type.

Neither return: Criminal[] []; nor return []: Criminal[]; worked for me.

At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.

For thoroughness I'll report this solution in my answer too:

let temp: Criminal[] = [];
return temp;

Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:

return <Criminal[]>[];

Hope this will help future readers!

How to get response using cURL in PHP

Just use the below piece of code to get the response from restful web service url, I use social mention url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    ); 

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

Adding a simple spacer to twitter bootstrap

You can add a class to each of your .row divs to add some space in between them like so:

.spacer {
    margin-top: 40px; /* define margin as you see fit */
}

You can then use it like so:

<div class="row spacer">
   <div class="span4">...</div>
   <div class="span4">...</div>
   <div class="span4">...</div>
</div>

<div class="row spacer">
   <div class="span4">...</div>
   <div class="span4">...</div>
   <div class="span4">...</div>
</div>

The difference in months between dates in MySQL

You can also try this:

select MONTH(NOW())-MONTH(table_date) as 'Total Month Difference' from table_name;

OR

select MONTH(Newer_date)-MONTH(Older_date) as 'Total Month Difference' from table_Name;

Sort list in C# with LINQ

Well, the simplest way using LINQ would be something like this:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true, but the first form makes it clearer IMO, because everyone knows that 0 < 1.

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. If you want to sort in place, you should use the List<T>.Sort method.

How to check if a variable is null or empty string or all whitespace in JavaScript?

Old question, but I think it deservers a simpler answer.

You can simply do:

var addr = "  ";

if (addr && addr.trim()) {

    console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");

}

How do I include a JavaScript file in another JavaScript file?

Now, I may be totally misguided, but here's what I've recently started doing... Start and end your JavaScript files with a carriage return, place in the PHP script, followed by one more carriage return. The JavaScript comment "//" is ignored by PHP so the inclusion happens anyway. The purpose for the carriage returns is so that the first line of your included JavaScript isn't commented out.

Technically, you don't need the comment, but it posts errors in Dreamweaver that annoy me. If you're scripting in an IDE that doesn't post errors, you shouldn't need the comment or the carriage returns.

\n
//<?php require_once("path/to/javascript/dependency.js"); ?>

function myFunction(){
    // stuff
}
\n

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

In testing IE7/8/9 I was getting an ActiveX warning trying to use this code snippet:

filter:progid:DXImageTransform.Microsoft.gradient

After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

How do I clear (or redraw) the WHOLE canvas for a new layout (= try at the game) ?

Just call Canvas.drawColor(Color.BLACK), or whatever color you want to clear your Canvas with.

And: how can I update just a part of the screen ?

There is no such method that just update a "part of the screen" since Android OS is redrawing every pixel when updating the screen. But, when you're not clearing old drawings on your Canvas, the old drawings are still on the surface and that is probably one way to "update just a part" of the screen.

So, if you want to "update a part of the screen", just avoid calling Canvas.drawColor() method.

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

How do you synchronise projects to GitHub with Android Studio?

This isn't specific to Android Studio, but a generic behaviour with Intellij's IDEA.

Go to: Preferences > Version Control > GitHub

Also note that you don't need the github integration: the standard git functions should be enough (VCS > Git, Tool Windows > Changes)

Can we define min-margin and max-margin, max-padding and min-padding in css?

I wrote a library to do this, you can view it here: https://codepen.io/nicetransition/pen/OyRwKq

to use in your case:

.selector {
    scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-right);
    scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-left);
}
  • $context: Max-width of your container

  • $base-size: Root font size

  • $limit-size-min: The minimum size

  • $limit-size-max: The maximum size

    .selector { scale(1400px, 16px, 5px, 20px, $property: padding-right); scale(1400px, 16px, 5px, 20px, $property: padding-left); }

This would scale down to 5px and up to 20px, between 5-20 it is dynamic based of vw

Java compiler level does not match the version of the installed Java project facet

I resolved it by Myproject--->java Resource---->libraries-->JRE System Libraries[java-1.6] click on this go to its "property" select "Classpath Container" change the Execution Environment to java-1.8(jdk1.8.0-35) (that is latest)

Change the jdk to latest

Convert comma separated string to array in PL/SQL

TYPE string_aa IS TABLE OF VARCHAR2(32767) INDEX BY PLS_INTEGER;

FUNCTION string_to_list(p_string_in IN VARCHAR2)
    RETURN string_aa
    IS
      TYPE ref_cursor IS ref cursor;
      l_cur    ref_cursor;
      l_strlist string_aa;
      l_x      PLS_INTEGER;
    BEGIN      
      IF p_string_in IS NOT NULL THEN 
         OPEN l_cur FOR 
            SELECT regexp_substr(p_string_in,'[^,]+', 1, level) FROM dual
            CONNECT BY regexp_substr(p_string_in, '[^,]+', 1, level) IS NOT NULL;      
         l_x := 1; 
         LOOP
           FETCH l_cur INTO l_strlist(l_x);
           EXIT WHEN l_cur%notfound;
           -- excludes NULL items  e.g.   1,2,,,,5,6,7
           l_x := l_x + 1;
         END LOOP;
      END IF;   
      RETURN l_strlist;
   END string_to_list;

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">

How to retrieve current workspace using Jenkins Pipeline Groovy script?

I think you can also execute the pwd() function on the particular node:

node {
    def PWD = pwd();
    ...
}

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

How to monitor SQL Server table changes by using c#?

In the interests of completeness there are a couple of other solutions which (in my opinion) are more orthodox than solutions relying on the SqlDependency (and SqlTableDependency) classes. SqlDependency was originally designed to make refreshing distributed webserver caches easier, and so was built to a different set of requirements than if it were designed as an event producer.

There are broadly four options, some of which have not been covered here already:

  • Change Tracking
  • CDC
  • Triggers to queues
  • CLR

Change tracking

Source: https://docs.microsoft.com/en-us/sql/relational-databases/track-changes/about-change-tracking-sql-server

Change tracking is a lightweight notification mechanism in SQL server. Basically, a database-wide version number is incremented with every change to any data. The version number is then written to the change tracking tables with a bit mask including the names of the columns which were changed. Note, the actual change is not persisted. The notification only contains the information that a particular data entity has changed. Further, because the change table versioning is cumulative, change notifications on individual items are not preserved and are overwritten by newer notifications. This means that if an entity changes twice, change tracking will only know about the most recent change.

In order to capture these changes in c#, polling must be used. The change tracking tables can be polled and each change inspected to see if is of interest. If it is of interest, it is necessary to then go directly to the data to retrieve the current state.

Change Data Capture

Source: https://technet.microsoft.com/en-us/library/bb522489(v=sql.105).aspx

Change data capture (CDC) is more powerful but most costly than change tracking. Change data capture will track and notify changes based on monitoring the database log. Because of this CDC has access to the actual data which has been changed, and keeps a record of all individual changes.

Similarly to change tracking, in order to capture these changes in c#, polling must be used. However, in the case of CDC, the polled information will contain the change details, so it's not strictly necessary to go back to the data itself.

Triggers to queues

Source: https://code.msdn.microsoft.com/Service-Broker-Message-e81c4316

This technique depends on triggers on the tables from which notifications are required. Each change will fire a trigger, and the trigger will write this information to a service broker queue. The queue can then be connected to via C# using the Service Broker Message Processor (sample in the link above).

Unlike change tracking or CDC, triggers to queues do not rely on polling and thereby provides realtime eventing.

CLR

This is a technique I have seen used, but I would not recommend it. Any solution which relies on the CLR to communicate externally is a hack at best. The CLR was designed to make writing complex data processing code easier by leveraging C#. It was not designed to wire in external dependencies like messaging libraries. Furthermore, CLR bound operations can break in clustered environments in unpredictable ways.

This said, it is fairly straightforward to set up, as all you need to do is register the messaging assembly with CLR and then you can call away using triggers or SQL jobs.

In summary...

It has always been a source of amazement to me that Microsoft has steadfastly refused to address this problem space. Eventing from database to code should be a built-in feature of the database product. Considering that Oracle Advanced Queuing combined with the ODP.net MessageAvailable event provided reliable database eventing to C# more than 10 years ago, this is woeful from MS.

The upshot of this is that none of the solutions listed to this question are very nice. They all have technical drawbacks and have a significant setup cost. Microsoft if you're listening, please sort out this sorry state of affairs.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

I am so glad to solve this problem:

HttpPost httppost = new HttpPost(postData); 
CookieStore cookieStore = new BasicCookieStore(); 
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", getSessionId());

//cookie.setDomain("your domain");
cookie.setPath("/");

cookieStore.addCookie(cookie); 
client.setCookieStore(cookieStore); 
response = client.execute(httppost); 

So Easy!

How can I change the default width of a Twitter Bootstrap modal box?

Bootstrap 3: In order to maintain responsive features for small and extra small devices I did the following:

@media (min-width: 768px) {
.modal-dialog-wide
{ width: 750px;/* your width */ }
}

Event binding on dynamically created elements?

You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.

var mouseOverHandler = function() {
    // Do stuff
};
var mouseOutHandler = function () {
    // Do stuff
};

$(function() {
    // On the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);
});

// This next part would be in the callback from your Ajax call
$("<select></select>")
    .append( /* Your <option>s */ )
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo( /* Wherever you need the select box */ )
;

How to fix "Incorrect string value" errors?

"\xE4\xC5\xCC\xC9\xD3\xD8" isn't valid UTF-8. Tested using Python:

>>> "\xE4\xC5\xCC\xC9\xD3\xD8".decode("utf-8")
...
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-2: invalid data

If you're looking for a way to avoid decoding errors within the database, the cp1252 encoding (aka "Windows-1252" aka "Windows Western European") is the most permissive encoding there is - every byte value is a valid code point.

Of course it's not going to understand genuine UTF-8 any more, nor any other non-cp1252 encoding, but it sounds like you're not too concerned about that?

How does bitshifting work in Java?

>> is the Arithmetic Right Shift operator. All of the bits in the first operand are shifted the number of places indicated by the second operand. The leftmost bits in the result are set to the same value as the leftmost bit in the original number. (This is so that negative numbers remain negative.)

Here's your specific case:

00101011
  001010 <-- Shifted twice to the right (rightmost bits dropped)
00001010 <-- Leftmost bits filled with 0s (to match leftmost bit in original number)

Swift alert view with OK and Cancel: which button tapped?

You may want to consider using SCLAlertView, alternative for UIAlertView or UIAlertController.

UIAlertController only works on iOS 8.x or above, SCLAlertView is a good option to support older version.

github to see the details

example:

let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
    print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")

var functionName = function() {} vs function functionName() {}

A function declaration and a function expression assigned to a variable behave the same once the binding is established.

There is a difference however at how and when the function object is actually associated with its variable. This difference is due to the mechanism called variable hoisting in JavaScript.

Basically, all function declarations and variable declarations are hoisted to the top of the function in which the declaration occurs (this is why we say that JavaScript has function scope).

  • When a function declaration is hoisted, the function body "follows" so when the function body is evaluated, the variable will immediately be bound to a function object.

  • When a variable declaration is hoisted, the initialization does not follow, but is "left behind". The variable is initialized to undefined at the start of the function body, and will be assigned a value at its original location in the code. (Actually, it will be assigned a value at every location where a declaration of a variable with the same name occurs.)

The order of hoisting is also important: function declarations take precedence over variable declarations with the same name, and the last function declaration takes precedence over previous function declarations with the same name.

Some examples...

var foo = 1;
function bar() {
  if (!foo) {
    var foo = 10 }
  return foo; }
bar() // 10

Variable foo is hoisted to the top of the function, initialized to undefined, so that !foo is true, so foo is assigned 10. The foo outside of bar's scope plays no role and is untouched.

function f() {
  return a; 
  function a() {return 1}; 
  var a = 4;
  function a() {return 2}}
f()() // 2

function f() {
  return a;
  var a = 4;
  function a() {return 1};
  function a() {return 2}}
f()() // 2

Function declarations take precedence over variable declarations, and the last function declaration "sticks".

function f() {
  var a = 4;
  function a() {return 1}; 
  function a() {return 2}; 
  return a; }
f() // 4

In this example a is initialized with the function object resulting from evaluating the second function declaration, and then is assigned 4.

var a = 1;
function b() {
  a = 10;
  return;
  function a() {}}
b();
a // 1

Here the function declaration is hoisted first, declaring and initializing variable a. Next, this variable is assigned 10. In other words: the assignment does not assign to outer variable a.

How to tell git to use the correct identity (name and email) for a given project?

One solution is to run manually a shell function that sets my environment to work or personal, but I am pretty sure that I will often forget to switch to the correct identity resulting in committing under the wrong identity.

That was exactly my problem. I have written a hook script which warns you if you have any github remote and not defined a local username.

Here's how you set it up:

  1. Create a directory to hold the global hook

    mkdir -p ~/.git-templates/hooks

  2. Tell git to copy everything in ~/.git-templates to your per-project .git directory when you run git init or clone

    git config --global init.templatedir '~/.git-templates'

  3. And now copy the following lines to ~/.git-templates/hooks/pre-commit and make the file executable (don't forget this otherwise git won't execute it!)

#!/bin/bash

RED='\033[0;31m' # red color
NC='\033[0m' # no color

GITHUB_REMOTE=$(git remote -v | grep github.com)
LOCAL_USERNAME=$(git config --local user.name)

if [ -n "$GITHUB_REMOTE" ] && [ -z "$LOCAL_USERNAME" ]; then
    printf "\n${RED}ATTENTION: At least one Github remote repository is configured, but no local username. "
    printf "Please define a local username that matches your Github account.${NC} [pre-commit hook]\n\n"
    exit 1
fi

If you use other hosts for your private repositories you have to replace github.com according to your needs.

Now every time you do a git init or git clone git will copy this script to the repository and executes it before any commit is done. If you have not set a local username it will output a warning and won't let you commit.

Undo a Git merge that hasn't been pushed yet

If you notice that you need to revert immediately after the merge and you haven't done anything else after the merge attempt, you can just issue this command: git reset --hard HEAD@{1}.

Essentially, your merge sha will be pointing to HEAD@{0} if nothing else was committed after the merge and so HEAD@{1} will be the previous point before the merge.

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

This can be changed in your my.ini file (on Windows, located in \Program Files\MySQL\MySQL Server) under the server section, for example:

[mysqld]

max_allowed_packet = 10M

Difference between two dates in Python

I tried a couple of codes, but end up using something as simple as (in Python 3):

from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])

If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.

If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):

df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date

And then run:

df['difference_in_days'] = abs(df['end_date'] - df['start_date'])

Regex to match alphanumeric and spaces

I suspect ^ doesn't work the way you think it does outside of a character class.

What you're telling it to do is replace everything that isn't an alphanumeric with an empty string, OR any leading space. I think what you mean to say is that spaces are ok to not replace - try moving the \s into the [] class.

What does "to stub" mean in programming?

You have also a very good testing frameworks to create such a stub. One of my preferrable is Mockito There is also EasyMock and others... But Mockito is great you should read it - very elegant and powerfull package

How to get File Created Date and Modified Date

You can use this code to see the last modified date of a file.

DateTime dt = File.GetLastWriteTime(path);

And this code to see the creation time.

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

Keras model.summary() result - Understanding the # of Parameters

The easiest way to calculate number of neurons in one layer is: Param value / (number of units * 4)

  • Number of units is in predictivemodel.add(Dense(514,...)
  • Param value is Param in model.summary() function

For example in Paul Lo's answer , number of neurons in one layer is 264710 / (514 * 4 ) = 130

How can one see content of stack with GDB?

You need to use gdb's memory-display commands. The basic one is x, for examine. There's an example on the linked-to page that uses

gdb> x/4xw $sp

to print "four words (w ) of memory above the stack pointer (here, $sp) in hexadecimal (x)". The quotation is slightly paraphrased.

Excel how to find values in 1 column exist in the range of values in another

This is what you need:

 =NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0)))  ## pseudo code

For the first cell of A, this would be:

 =NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))

Enter formula (and drag down) as follows:

enter image description here

You will get:

enter image description here

Attempt to write a readonly database - Django w/ SELinux error

You have to add writing rights to the directory in which your sqlite database is stored. So running chmod 664 /srv/mysite should help.

This is a security risk, so better solution is to change the owner of your database to www-data:

chown www-data:www-data /srv/mysite
chown www-data:www-data /srv/mysite/DATABASE.sqlite

batch script - read line by line

This has worked for me in the past and it will even expand environment variables in the file if it can.

for /F "delims=" %%a in (LogName.txt) do (
     echo %%a>>MyDestination.txt
)

What's the correct way to convert bytes to a hex string in Python 3?

If you want to convert b'\x61' to 97 or '0x61', you can try this:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

Reference:https://docs.python.org/3.5/library/struct.html

Angular ngClass and click event for toggling class

ngClass should be wrapped in square brackets as this is a property binding. Try this:

<div class="my_class" (click)="clickEvent($event)"  [ngClass]="{'active': toggle}">                
     Some content
</div>

In your component:

     //define the toogle property
     private toggle : boolean = false;

    //define your method
    clickEvent(event){
       //if you just want to toggle the class; change toggle variable.
       this.toggle = !this.toggle;       
    }

Hope that helps.

jQuery Datepicker localization

I just Added

jQuery.datetimepicker.setLocale('fr');

and It's worked

Make 2 functions run at the same time

Try this

from threading import Thread

def fun1():
    print("Working1")
def fun2():
    print("Working2")

t1 = Thread(target=fun1)
t2 = Thread(target=fun2)

t1.start()
t2.start()

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

jQuery Data vs Attr?

You can use data-* attribute to embed custom data. The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

jQuery .data() method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

jQuery .attr() method get/set attribute value for only the first element in the matched set.

Example:

<span id="test" title="foo" data-kind="primary">foo</span>

$("#test").attr("title");
$("#test").attr("data-kind");
$("#test").data("kind");
$("#test").data("value", "bar");

ngModel cannot be used to register form controls with a parent formGroup directive

when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.

<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>

if the error still conitnue try to set form control for all of object(myObject) field.

between start <form> </form> for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.

jQuery Event : Detect changes to the html/text of a div

Tried some of answers given above but those fires event twice. Here is working solution if you may need the same.

$('mydiv').one('DOMSubtreeModified', function(){
    console.log('changed');
});

How to disable a button when an input is empty?

You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.

Example using state:

_x000D_
_x000D_
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
  getInitialState() {_x000D_
    return {email: ''}_x000D_
  },_x000D_
  handleChange(e) {_x000D_
    this.setState({email: e.target.value})_x000D_
  },_x000D_
  render() {_x000D_
    return <div>_x000D_
      <input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
      <button type="button" disabled={!this.state.email}>Button</button>_x000D_
    </div>_x000D_
  }_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
_x000D_
_x000D_

Checking if sys.argv[x] is defined

A solution working with map built-in fonction !

arg_names = ['command' ,'operation', 'parameter']
args = map(None, arg_names, sys.argv)
args = {k:v for (k,v) in args}

Then you just have to call your parameters like this:

if args['operation'] == "division":
    if not args['parameter']:
        ...
    if args['parameter'] == "euclidian":
        ...

Http post and get request in angular 6

Update : In angular 7, they are the same as 6

In angular 6

the complete answer found in live example

  /** POST: add a new hero to the database */
  addHero (hero: Hero): Observable<Hero> {
 return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
  .pipe(
    catchError(this.handleError('addHero', hero))
  );
}
  /** GET heroes from the server */
 getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(
    catchError(this.handleError('getHeroes', []))
  );
}

it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app

some rxjs functions are changed

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

more in MIGRATION

and Import paths

For JavaScript developers, the general rule is as follows:

rxjs: Creation methods, types, schedulers and utilities

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs/operators: All pipeable operators:

import { map, filter, scan } from 'rxjs/operators';

rxjs/webSocket: The web socket subject implementation

import { webSocket } from 'rxjs/webSocket';

rxjs/ajax: The Rx ajax implementation

import { ajax } from 'rxjs/ajax';

rxjs/testing: The testing utilities

import { TestScheduler } from 'rxjs/testing';

and for backward compatability you can use rxjs-compat

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Minimal settings to prevent resize events

form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;

How to prevent IFRAME from redirecting top-level window

Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.

There is also the iframe security attribute which only works on IE & Opera

:(

Disabling contextual LOB creation as createClob() method threw error

To get rid of the exception

INFO - HHH000424: Disabling contextual LOB creation as createClob() method threw error :java.lang.reflect.InvocationTargetException

In hibernate.cfg.xml file Add below property

<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>

How to add System.Windows.Interactivity to project?

I got it via the Prism.WPF NuGet-Package. (it includes Windows.System.Interactivity)

Add unique constraint to combination of two columns

In my case, I needed to allow many inactives and only one combination of two keys active, like this:

UUL_USR_IDF  UUL_UND_IDF    UUL_ATUAL
137          18             0
137          19             0
137          20             1
137          21             0

This seems to work:

CREATE UNIQUE NONCLUSTERED INDEX UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL
ON USER_UND(UUL_USR_IDF, UUL_ATUAL)
WHERE UUL_ATUAL = 1;

Here are my test cases:

SELECT * FROM USER_UND WHERE UUL_USR_IDF = 137

insert into USER_UND values (137, 22, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 23, 0) --I CAN
insert into USER_UND values (137, 24, 0) --I CAN

DELETE FROM USER_UND WHERE UUL_USR_ID = 137

insert into USER_UND values (137, 22, 1) --I CAN
insert into USER_UND values (137, 27, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 28, 0) --I CAN
insert into USER_UND values (137, 29, 0) --I CAN

What does "if (rs.next())" mean?

The next() moves the cursor froward one row from its current position in the resultset. so its evident that if(rs.next()) means that if the next row is not null (means if it exist), Go Ahead.

Now w.r.t your problem,

ResultSet rs = stmt.executeQuery(sql);  //This is wrong
                                  ^       

note that executeQuery(String) is used in case you use a sql-query as string.

Whereas when you use a PreparedStatement, use executeQuery() which executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

Solution :

Use : ResultSet rs = stmt.executeQuery();

shorthand If Statements: C#

To use shorthand to get the direction:

int direction = column == 0
                ? 0
                : (column == _gridSize - 1 ? 1 : rand.Next(2));

To simplify the code entirely:

if (column == gridSize - 1 || rand.Next(2) == 1)
{
}
else
{
}

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

Pythonic way to find maximum value and its index in a list?

Here is a complete solution to your question using Python's built-in functions:

# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",") 

# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers] 

# Loop through the list with a for-loop

for elements in numberL:
    maxEle = max(numberL)
    indexMax = numberL.index(maxEle)

print(maxEle)
print(indexMax)

What is the purpose of meshgrid in Python / NumPy?

meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])

Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:

f(*np.meshgrid(x, y))

Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.

Referred from here

Richtextbox wpf binding

Guys why bother with all the faff. This works perfectly. No code required

<RichTextBox>
    <FlowDocument>
        <Paragraph>
            <Run Text="{Binding Mytextbinding}"/>
        </Paragraph>
    </FlowDocument>
</RichTextBox>

Delete all local git branches

The following script deletes branches. Use it and modify it at your own risk, etc. etc.

Based on the other answers in this question, I ended up writing a quick bash script for myself. I called it "gitbd" (git branch -D) but if you use it, you can rename it to whatever you want.

gitbd() {
if [ $# -le 1 ]
  then
    local branches_to_delete=`git for-each-ref --format '%(refname:short)' refs/heads/ | grep "$1"`
    printf "Matching branches:\n\n$branches_to_delete\n\nDelete? [Y/n] "
    read -n 1 -r # Immediately continue after getting 1 keypress
    echo # Move to a new line
    if [[ ! $REPLY == 'N' && ! $REPLY == 'n' ]]
      then
        echo $branches_to_delete | xargs git branch -D
    fi
else
  echo "This command takes one arg (match pattern) or no args (match all)"
fi
}

It will offer to delete any branches which match a pattern argument, if passed in, or all local branches when called with with no arguments. It will also give you a confirmation step, since, you know, we're deleting things, so that's nice.

It's kind of dumb - if there are no branches that match the pattern, it doesn't realize it.

An example output run:

$ gitbd test
Matching branches:

dummy+test1
dummy+test2
dummy+test3

Delete? [Y/n] 

Removing multiple keys from a dictionary safely

Using Dict Comprehensions

final_dict = {key: t[key] for key in t if key not in [key1, key2]}

where key1 and key2 are to be removed.

In the example below, keys "b" and "c" are to be removed & it's kept in a keys list.

>>> a
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> keys = ["b", "c"]
>>> print {key: a[key] for key in a if key not in keys}
{'a': 1, 'd': 4}
>>> 

Getter and Setter?

I made an experiment using the magic method __call. Not sure if I should post it (because of all the "DO NOT USE MAGIC METHODS" warnings in the other answers and comments) but i'll leave it here.. just in case someone find it useful.


public function __call($_name, $_arguments){
    $action  = substr($_name, 0, 4);
    $varName = substr($_name, 4);

    if (isset($this->{$varName})){
        if ($action === "get_") return $this->{$varName};
        if ($action === "set_") $this->{$varName} = $_arguments[0];
    }
}

Just add that method above in your class, now you can type:

class MyClass{
    private foo = "bar";
    private bom = "bim";
    // ...
    // public function __call(){ ... }
    // ...
}
$C = new MyClass();

// as getter
$C->get_foo(); // return "bar"
$C->get_bom(); // return "bim"

// as setter
$C->set_foo("abc"); // set "abc" as new value of foo
$C->set_bom("zam"); // set "zam" as new value of bom


This way you can get/set everything in your class if it exist so, if you need it for only a few specific elements, you could use a "whitelist" as filter.

Example:

private $callWhiteList = array(
    "foo" => "foo",
    "fee" => "fee",
    // ...
);

public function __call($_name, $_arguments){
    $action  = substr($_name, 0, 4);
    $varName = $this->callWhiteList[substr($_name, 4)];

    if (!is_null($varName) && isset($this->{$varName})){
        if ($action === "get_") return $this->{$varName};
        if ($action === "set_") $this->{$varName} = $_arguments[0];
    }
}

Now you can only get/set "foo" and "fee".
You can also use that "whitelist" to assign custom names to access to your vars.
For example,

private $callWhiteList = array(
    "myfoo" => "foo",
    "zim" => "bom",
    // ...
);

With that list you can now type:

class MyClass{
    private foo = "bar";
    private bom = "bim";
    // ...
    // private $callWhiteList = array( ... )
    // public function __call(){ ... }
    // ...
}
$C = new MyClass();

// as getter
$C->get_myfoo(); // return "bar"
$C->get_zim(); // return "bim"

// as setter
$C->set_myfoo("abc"); // set "abc" as new value of foo
$C->set_zim("zam"); // set "zam" as new value of bom

.
.
.
That's all.


Doc: __call() is triggered when invoking inaccessible methods in an object context.

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Entity
@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @Id
    @Column(name="useranswer_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

What's the proper way to compare a String to an enum value?

public class Main {

    enum Vehical{
        Car,
        Bus,
        Van
    }

    public static void main(String[] args){

      String vehicalType = "CAR";

        if(vehicalType.equals(Vehical.Car.name())){
            System.out.println("The provider is Car");
        }

     String vehical_Type = "BUS";

       if(vehical_Type.equals(Vehical.Bus.toString())){
            System.out.println("The provider is Bus");
        }


    }
}

Creating a UICollectionView programmatically

Swift 3

class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let flowLayout = UICollectionViewFlowLayout()

        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.cyan

        self.view.addSubview(collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor.green
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }

}

Calling a function when ng-repeat has finished

I'm very surprised not to see the most simple solution among the answers to this question. What you want to do is add an ngInit directive on your repeated element (the element with the ngRepeat directive) checking for $last (a special variable set in scope by ngRepeat which indicates that the repeated element is the last in the list). If $last is true, we're rendering the last element and we can call the function we want.

ng-init="$last && test()"

The complete code for your HTML markup would be:

<div ng-app="testApp" ng-controller="myC">
    <p ng-repeat="t in ta" ng-init="$last && test()">{{t}}</p>
</div>

You don't need any extra JS code in your app besides the scope function you want to call (in this case, test) since ngInit is provided by Angular.js. Just make sure to have your test function in the scope so that it can be accessed from the template:

$scope.test = function test() {
    console.log("test executed");
}

How do I capture the output into a variable from an external process in PowerShell?

Note: The command in the question uses Start-Process, which prevents direct capturing of the target program's output. Generally, do not use Start-Process to execute console applications synchronously - just invoke them directly, as in any shell. Doing so keeps the application connected to the calling console's standard streams, allowing its output to be captured by simple assignment $output = netdom ..., as detailed below.

Fundamentally, capturing output from external programs works the same as with PowerShell-native commands (you may want a refresher on how to execute external programs; <command> is a placeholder for any valid command below):

$cmdOutput = <command>   # captures the command's success stream / stdout output

Note that $cmdOutput receives an array of objects if <command> produces more than 1 output object, which in the case of an external program means a string[1] array containing the program's output lines.

If you want to make sure that the result is always an array - even if only one object is output, type-constrain the variable as an array, or wrap the command in @(), the array-subexpression operator):

[array] $cmdOutput = <command> # or: $cmdOutput = @(<command>)

By contrast, if you want $cmdOutput to always receive a single - potentially multi-line - string, use Out-String, though note that a trailing newline is invariably added:

# Note: Adds a trailing newline.
$cmdOutput = <command> | Out-String

With calls to external programs - which by definition only ever return strings in PowerShell[1] - you can avoid that by using the -join operator instead:

# NO trailing newline.
$cmdOutput = (<command>) -join "`n"

Note: For simplicity, the above uses "`n" to create Unix-style LF-only newlines, which PowerShell happily accepts on all platforms; if you need platform-appropriate newlines (CRLF on Windows, LF on Unix), use [Environment]::NewLine instead.


To capture output in a variable and print to the screen:

<command> | Tee-Object -Variable cmdOutput # Note how the var name is NOT $-prefixed

Or, if <command> is a cmdlet or advanced function, you can use common parameter
-OutVariable / -ov
:

<command> -OutVariable cmdOutput   # cmdlets and advanced functions only

Note that with -OutVariable, unlike in the other scenarios, $cmdOutput is always a collection, even if only one object is output. Specifically, an instance of the array-like [System.Collections.ArrayList] type is returned.
See this GitHub issue for a discussion of this discrepancy.


To capture the output from multiple commands, use either a subexpression ($(...)) or call a script block ({ ... }) with & or .:

$cmdOutput = $(<command>; ...)  # subexpression

$cmdOutput = & {<command>; ...} # script block with & - creates child scope for vars.

$cmdOutput = . {<command>; ...} # script block with . - no child scope

Note that the general need to prefix with & (the call operator) an individual command whose name/path is quoted - e.g., $cmdOutput = & 'netdom.exe' ... - is not related to external programs per se (it equally applies to PowerShell scripts), but is a syntax requirement: PowerShell parses a statement that starts with a quoted string in expression mode by default, whereas argument mode is needed to invoke commands (cmdlets, external programs, functions, aliases), which is what & ensures.

The key difference between $(...) and & { ... } / . { ... } is that the former collects all input in memory before returning it as a whole, whereas the latter stream the output, suitable for one-by-one pipeline processing.


Redirections also work the same, fundamentally (but see caveats below):

$cmdOutput = <command> 2>&1 # redirect error stream (2) to success stream (1)

However, for external commands the following is more likely to work as expected:

$cmdOutput = cmd /c <command> '2>&1' # Let cmd.exe handle redirection - see below.

Considerations specific to external programs:

  • External programs, because they operate outside PowerShell's type system, only ever return strings via their success stream (stdout); similarly, PowerShell only ever sends strings to external programs via the pipeline.[1]

    • Character-encoding issues can therefore come into play:
      • On sending data via the pipeline to external programs, PowerShell uses the encoding stored in the $OutVariable preference variable; which in Windows PowerShell defaults to ASCII(!) and in PowerShell [Core] to UTF-8.

      • On receiving data from an external program, PowerShell uses the encoding stored in [Console]::OutputEncoding to decode the data, which in both PowerShell editions defaults to the system's active OEM code page.

      • See this answer for more information; this answer discusses the still-in-beta (as of this writing) Windows 10 feature that allows you to set UTF-8 as both the ANSI and the OEM code page system-wide.

  • If the output contains more than 1 line, PowerShell by default splits it into an array of strings. More accurately, the output lines are stored in an array of type [System.Object[]] whose elements are strings ([System.String]).

  • If you want the output to be a single, potentially multi-line string, use the -join operator (you can alternatively pipe to Out-String, but that invariably adds a trailing newline):
    $cmdOutput = (<command>) -join [Environment]::NewLine

  • Merging stderr into stdout with 2>&1, so as to also capture it as part of the success stream, comes with caveats:

    • To do this at the source, let cmd.exe handle the redirection, using the following idioms (works analogously with sh on Unix-like platforms):
      $cmdOutput = cmd /c <command> '2>&1' # *array* of strings (typically)
      $cmdOutput = (cmd /c <command> '2>&1') -join "`r`n" # single string

      • cmd /c invokes cmd.exe with command <command> and exits after <command> has finished.

      • Note the single quotes around 2>&1, which ensures that the redirection is passed to cmd.exe rather than being interpreted by PowerShell.

      • Note that involving cmd.exe means that its rules for escaping characters and expanding environment variables come into play, by default in addition to PowerShell's own requirements; in PS v3+ you can use special parameter --% (the so-called stop-parsing symbol) to turn off interpretation of the remaining parameters by PowerShell, except for cmd.exe-style environment-variable references such as %PATH%.

      • Note that since you're merging stdout and stderr at the source with this approach, you won't be able to distinguish between stdout-originated and stderr-originated lines in PowerShell; if you do need this distinction, use PowerShell's own 2>&1 redirection - see below.

    • Use PowerShell's 2>&1 redirection to know which lines came from what stream:

      • Stderr output is captured as error records ([System.Management.Automation.ErrorRecord]), not strings, so the output array may contain a mix of strings (each string representing a stdout line) and error records (each record representing a stderr line). Note that, as requested by 2>&1, both the strings and the error records are received through PowerShell's success output stream).

      • Note: The following only applies to Windows PowerShell - these problems have been corrected in PowerShell [Core] v6+, though the filtering technique by object type shown below ($_ -is [System.Management.Automation.ErrorRecord]) can also be useful there.

      • In the console, the error records print in red, and the 1st one by default produces multi-line display, in the same format that a cmdlet's non-terminating error would display; subsequent error records print in red as well, but only print their error message, on a single line.

      • When outputting to the console, the strings typically come first in the output array, followed by the error records (at least among a batch of stdout/stderr lines output "at the same time"), but, fortunately, when you capture the output, it is properly interleaved, using the same output order you would get without 2>&1; in other words: when outputting to the console, the captured output does NOT reflect the order in which stdout and stderr lines were generated by the external command.

      • If you capture the entire output in a single string with Out-String, PowerShell will add extra lines, because the string representation of an error record contains extra information such as location (At line:...) and category (+ CategoryInfo ...); curiously, this only applies to the first error record.

        • To work around this problem, apply the .ToString() method to each output object instead of piping to Out-String:
          $cmdOutput = <command> 2>&1 | % { $_.ToString() };
          in PS v3+ you can simplify to:
          $cmdOutput = <command> 2>&1 | % ToString
          (As a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console.)

        • Alternatively, filter the error records out and send them to PowerShell's error stream with Write-Error (as a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console):

$cmdOutput = <command> 2>&1 | ForEach-Object {
  if ($_ -is [System.Management.Automation.ErrorRecord]) {
    Write-Error $_
  } else {
    $_
  }
}

[1] As of PowerShell 7.1, PowerShell knows only strings when communicating with external programs. There is generally no concept of raw byte data in a PowerShell pipeline. If you want raw byte data returned from an external program, you must shell out to cmd.exe /c (Windows) or sh -c (Unix), save to a file there, then read that file in PowerShell. See this answer for more information.