Programs & Examples On #Hidden characters

In Perl, how to remove ^M from a file?

Little script I have for that. A modification of it helped to filter out some other non-printable characters in cross-platform legacy files.

#!/usr/bin/perl
# run this as
# convert_dos2unix.pl < input_file > output_file
undef $/;
$_ = <>;
s/\r//ge;
print;

Make Vim show ALL white spaces as a character

You could use

:set list

to really see the structure of a line. You will see tabs and newlines explicitly. When you see a blank, it's really a blank.

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

What is the difference between atan and atan2 in C++?

I guess the main question tries to figure out: "when should I use one or the other", or "which should I use", or "Am I using the right one"?

I guess the important point is atan only was intended to feed positive values in a right-upwards direction curve like for time-distance vectors. Cero is always at the bottom left, and thigs can only go up and right, just slower or faster. atan doesn't return negative numbers, so you can't trace things in the 4 directions on a screen just by adding/subtracting its result.

atan2 is intended for the origin to be in the middle, and things can go backwards or down. That's what you'd use in a screen representation, because it DOES matter what direction you want the curve to go. So atan2 can give you negative numbers, because its cero is in the center, and its result is something you can use to trace things in 4 directions.

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

Set Option  Value
textsize    2147483647
language    us_english
dateformat  mdy
datefirst   7
lock_timeout    -1
quoted_identifier   SET
arithabort  SET
ansi_null_dflt_on   SET
ansi_warnings   SET
ansi_padding    SET
ansi_nulls  SET
concat_null_yields_null SET
isolation level read committed

How do I use a custom deleter with a std::unique_ptr member?

You just need to create a deleter class:

struct BarDeleter {
  void operator()(Bar* b) { destroy(b); }
};

and provide it as the template argument of unique_ptr. You'll still have to initialize the unique_ptr in your constructors:

class Foo {
  public:
    Foo() : bar(create()), ... { ... }

  private:
    std::unique_ptr<Bar, BarDeleter> bar;
    ...
};

As far as I know, all the popular c++ libraries implement this correctly; since BarDeleter doesn't actually have any state, it does not need to occupy any space in the unique_ptr.

Java SSL: how to disable hostname verification

In case you're using apache's http-client 4:

SSLConnectionSocketFactory sslConnectionSocketFactory = 
    new SSLConnectionSocketFactory(sslContext,
             new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
                    public boolean verify(String arg0, SSLSession arg1) {
                            return true;
            }
      });

Callback function for JSONP with jQuery AJAX

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}

Check if a Class Object is subclass of another Class Object in Java

In addition to @To-kra's answer. If someone doesn't like recurrence:

    public static boolean isSubClassOf(Class<?> clazz, Class<?> superClass) {
        if(Object.class.equals(superClass)) {
            return true;
        }

        for(; !Object.class.equals(clazz); clazz = clazz.getSuperclass()) {
            if(clazz.getSuperclass().equals(superClass)) {
                return true;
            }
        }

        return false;
    }

NOTE: no null checking for clarity.

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

angular ng-repeat in reverse

You can reverse by the $index parameter

<tr ng-repeat="friend in friends | orderBy:'$index':true">

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

TypeError: no implicit conversion of Symbol into Integer

myHash.each{|item|..} is returning you array object for item iterative variable like the following :--

[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]

You should do this:--

def format
  output = Hash.new
  myHash.each do |k, v|
    output[k] = cleanup(v)
  end
  output
end

How does the keyword "use" work in PHP and can I import classes with it?

Using the keyword "use" is for shortening namespace literals. You can use both with aliasing and without it. Without aliasing you must use last part of full namespace.

<?php
    use foo\bar\lastPart;
    $obj=new lastPart\AnyClass(); //If there's not the line above, a fatal error will be encountered.
?>

Indent List in HTML and CSS

_x000D_
_x000D_
li {
  padding-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and your text.

_x000D_
_x000D_
li {
  margin-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
  <li>List item</li>
</ul>
_x000D_
_x000D_
_x000D_ The above will add 30px of space between the bullet or number and the left edge of the container.

ORDER BY date and time BEFORE GROUP BY name in mysql

I had a different variation on this question where I only had a single DATETIME field and needed a limit after a group by or distinct after sorting descending based on the datetime field, but this is what helped me:

select distinct (column) from
(select column from database.table
order by date_column DESC) as hist limit 10

In this instance with the split fields, if you can sort on a concat, then you might be able to get away with something like:

select name,date,time from
(select name from table order by concat(date,' ',time) ASC)
as sorted

Then if you wanted to limit you would simply add your limit statement to the end:

select name,date,time from
(select name from table order by concat(date,' ',time) ASC)
as sorted limit 10

Convert Map<String,Object> to Map<String,String>

If your Objects are containing of Strings only, then you can do it like this:

Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String
Map<String,String> newMap =new HashMap<String,String>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
       if(entry.getValue() instanceof String){
            newMap.put(entry.getKey(), (String) entry.getValue());
          }
 }

If every Objects are not String then you can replace (String) entry.getValue() into entry.getValue().toString().

How to set 'X-Frame-Options' on iframe?

and if nothing helps and you still want to present that website in an iframe consider using X Frame Bypass Component which will utilize a proxy.

Angular ForEach in Angular4/Typescript?

in angular4 foreach like that. try this.

 selectChildren(data, $event) {
      let parentChecked = data.checked;
       this.hierarchicalData.forEach(obj => {
          obj.forEach(childObj=> {
            value.checked = parentChecked;
         });
      });
    }

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

Error Cannot redirect after HTTP headers have been sent.

System.Web.HttpException (0x80004005): Cannot redirect after HTTP headers have been sent.

Suggestion

If we use asp.net mvc and working on same controller and redirect to different Action then you do not need to write..
Response.Redirect("ActionName","ControllerName");
its better to use only
return RedirectToAction("ActionName");
or
return View("ViewName");

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I needed to use this as a cell function (like SUM or VLOOKUP) and found that it was easy to:

  1. Make sure you are in a Macro Enabled Excel File (save as xlsm).
  2. Open developer tools Alt + F11
  3. Add Microsoft VBScript Regular Expressions 5.5 as in other answers
  4. Create the following function either in workbook or in its own module:

    Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
        Dim regex As New VBScript_RegExp_55.RegExp
        Dim strInput As String
    
        strInput = myRange.Value
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
    
        REGPLACE = regex.Replace(strInput, outputPattern)
    
    End Function
    
  5. Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2") (ex: "A 243" to "A243")

Find distance between two points on map using Google Map API V2

The distance between two geo-coordinates can be found by using Haversine formula . This formula is effective to calculate distance in a spherical body i.e earth in our case.

Unable to establish SSL connection, how do I fix my SSL cert?

I meet this same question. The port 443 wasn't open in Centos.

Check the 443 port with the following command:

sudo lsof -i tcp:443

In the first line of /etc/httpd/conf.d/ssl.conf add this two lines:

LoadModule ssl_module modules/mod_ssl.so
Listen 443

Does IE9 support console.log, and is it a real function?

I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js

Difference between Iterator and Listiterator?

There are two differences:

  1. We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.

    That is, we can get a Iterator object by using Set and List, see here:

    By using Iterator we can retrieve the elements from Collection Object in forward direction only.

    Methods in Iterator:

    1. hasNext()
    2. next()
    3. remove()
    Iterator iterator = Set.iterator();
    Iterator iterator = List.iterator();
  2. But we get ListIterator object only from the List interface, see here:

    where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like hasPrevious() and previous() other than those of Iterator. Also, we can get indexes of the next or previous elements (using nextIndex() and previousIndex() respectively )

    Methods in ListIterator:

    1. hasNext()
    2. next()
    3. previous()
    4. hasPrevious()
    5. remove()
    6. nextIndex()
    7. previousIndex()
    ListIterator listiterator = List.listIterator();

    i.e., we can't get ListIterator object from Set interface.

Reference : - What is the difference between Iterator and ListIterator ?

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

How to embed fonts in HTML?

Try Facetype.js, you convert your .TTF font into a Javascript file. Full SEO compatible, supports FF, IE6 and Safari and degrades gracefully on other browsers.

Get root password for Google Cloud Engine VM

This work at least in the Debian Jessie image hosted by Google:

The way to enable to switch from you regular to the root user (AKA “super user”) after authentificating with your Google Computer Engine (GCE) User in the local environment (your Linux server in GCE) is pretty straight forward, in fact it just involves just one command to enable it and another every time to use it:

$ sudo passwd
Enter the new UNIX password: <your new root password>
Retype the new UNIX password: <your new root password>
passwd: password updated successfully

After executing the previous command and once logged with your GCE User you will be able to switch to root anytime by just entering the following command:

$ su
Password: <your newly created root password>
root@intance:/#

As we say in economics “caveat emptor” or buyer be aware: Using the root user is far from a best practice in system’s administration. Using it can be the cause a lot of trouble, from wiping everything in your drives and boot disks without a hiccup to many other nasty stuff that would be laborious to backtrack, troubleshoot and rebuilt. On the other hand, I have never met a SysAdmin that doesn’t think he knows better and root more than he should.

REMEMBER: We humans are programmed in such a way that given enough time at one at some point or another are going to press enter without taking into account that we have escalated to root and I can assure you that it will great source of pain, regret and extra work. PLEASE USE ROOT PRIVILEGES SPARSELY AND WITH EXTREME CARE.

Having said all the boring stuff, Have fun, live on the edge, life is short, you only get to live it once, the more you break the more you learn.

'too many values to unpack', iterating over a dict. key=>string, value=>list

Python 2

You need to use something like iteritems.

for field, possible_values in fields.iteritems():
    print field, possible_values

See this answer for more information on iterating through dictionaries, such as using items(), across python versions.

Python 3

Since Python 3 iteritems() is no longer supported. Use items() instead.

for field, possible_values in fields.items():
    print(field, possible_values)

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

Use Conda instead of pip. It works perfectly

conda install PyAudio

Mongoimport of json file

I was able to fix the error using the following query:

mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray

Hopefully this is helpful to someone.

Create an Oracle function that returns a table

To return the whole table at once you could change the SELECT to:

SELECT  ...
BULK COLLECT INTO T
FROM    ...

This is only advisable for results that aren't excessively large, since they all have to be accumulated in memory before being returned; otherwise consider the pipelined function as suggested by Charles, or returning a REF CURSOR.

Why does Google prepend while(1); to their JSON responses?

After authentication is in place, JSON hijacking protection can take a variety of forms. Google appends while(1) into their JSON data, so that if any malicious script evaluates it, the malicious script enters an infinite loop.

Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast

How do I calculate tables size in Oracle

IIRC the tables you need are DBA_TABLES, DBA_EXTENTS or DBA_SEGMENTS and DBA_DATA_FILES. There are also USER_ and ALL_ versions of these for tables you can see if you don't have administration permissions on the machine.

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

How can I do an OrderBy with a dynamic string parameter?

I did so:

using System.Linq.Expressions;

namespace System.Linq
{
    public static class LinqExtensions
    {

        public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string field, string dir = "asc")
        {
            // parametro => expressão
            var parametro = Expression.Parameter(typeof(TSource), "r");
            var expressao = Expression.Property(parametro, field);
            var lambda = Expression.Lambda(expressao, parametro); // r => r.AlgumaCoisa
            var tipo = typeof(TSource).GetProperty(field).PropertyType;

            var nome = "OrderBy";
            if (string.Equals(dir, "desc", StringComparison.InvariantCultureIgnoreCase))
            {
                nome = "OrderByDescending";
            }
            var metodo = typeof(Queryable).GetMethods().First(m => m.Name == nome && m.GetParameters().Length == 2);
            var metodoGenerico = metodo.MakeGenericMethod(new[] { typeof(TSource), tipo });
            return metodoGenerico.Invoke(source, new object[] { source, lambda }) as IOrderedQueryable<TSource>;

        }

        public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, string field, string dir = "asc")
        {
            var parametro = Expression.Parameter(typeof(TSource), "r");
            var expressao = Expression.Property(parametro, field);
            var lambda = Expression.Lambda<Func<TSource, string>>(expressao, parametro); // r => r.AlgumaCoisa
            var tipo = typeof(TSource).GetProperty(field).PropertyType;

            var nome = "ThenBy";
            if (string.Equals(dir, "desc", StringComparison.InvariantCultureIgnoreCase))
            {
                nome = "ThenByDescending";
            }

            var metodo = typeof(Queryable).GetMethods().First(m => m.Name == nome && m.GetParameters().Length == 2);
            var metodoGenerico = metodo.MakeGenericMethod(new[] { typeof(TSource), tipo });
            return metodoGenerico.Invoke(source, new object[] { source, lambda }) as IOrderedQueryable<TSource>;
        }

    }
}

Use :

example.OrderBy("Nome", "desc").ThenBy("other")

Work like:

example.OrderByDescending(r => r.Nome).ThenBy(r => r.other)

How to install a specific version of a ruby gem?

for Ruby 1.9+ use colon.

gem install sinatra:1.4.4 prawn:0.13.0

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

First please check in module.ts file that in @NgModule all properties are only one time. If any of are more than one time then also this error come. Because I had also occur this error but in module.ts file entryComponents property were two time that's why I was getting this error. I resolved this error by removing one time entryComponents from @NgModule. So, I recommend that first you check it properly.

How to uncheck checked radio button

try this

single function for all radio have class "radio-button"

work in chrome and FF

_x000D_
_x000D_
$('.radio-button').on("click", function(event){_x000D_
  $('.radio-button').prop('checked', false);_x000D_
  $(this).prop('checked', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio'  class='radio-button' name='re'>_x000D_
<input type='radio'  class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

The @android did not work for me. When I use android (without the @) it works like a charm.

Example:

<style name="CustomActionBarTheme"
       parent="android:style/Theme.Holo.Light.DarkActionBar">

Joining two table entities in Spring Data JPA

@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")

How do I make calls to a REST API using C#?

The answer marked here suggests using HttpClient directly and the disposing of it. This might work, but it's quite easy to run in to problems with HttpClient if you don't use it correctly.

If you're going to use HttpClient, you're better off handing over the creation/disposal of HttpClients to a third-party library that uses the factory pattern. RestClient.Net is one such library.

It comes with a very basic HttpClient factory so that you don't run in to the socket exhaustion problem,

public class DefaultHttpClientFactory : IHttpClientFactory, IDisposable
{
    #region Fields
    private bool disposed;
    private readonly ConcurrentDictionary<string, Lazy<HttpClient>> _httpClients;
    private readonly Func<string, Lazy<HttpClient>> _createClientFunc;
    #endregion

    #region Constructor
    public DefaultHttpClientFactory() : this(null)
    {
    }

    public DefaultHttpClientFactory(Func<string, Lazy<HttpClient>> createClientFunc)
    {
        _createClientFunc = createClientFunc;
        _httpClients = new ConcurrentDictionary<string, Lazy<HttpClient>>();

        if (_createClientFunc != null) return;
        _createClientFunc = name =>
        {
            return new Lazy<HttpClient>(() => new HttpClient(), LazyThreadSafetyMode.ExecutionAndPublication);
        };
    }
    #endregion

    #region Implementation
    public HttpClient CreateClient(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException(nameof(name));
        }

        return _httpClients.GetOrAdd(name, _createClientFunc).Value;
    }

    public void Dispose()
    {
        if (disposed) return;
        disposed = true;

        foreach (var name in _httpClients.Keys)
        {
            _httpClients[name].Value.Dispose();
        }
    }
    #endregion
}

But Microsoft's IHttpClientFactory implementation can also be used for the latest and greatest:

    var serviceCollection = new ServiceCollection();
    var baseUri = new Uri("http://www.test.com");
    serviceCollection.AddSingleton(typeof(ISerializationAdapter), typeof(NewtonsoftSerializationAdapter));
    serviceCollection.AddSingleton(typeof(ILogger), typeof(ConsoleLogger));
    serviceCollection.AddSingleton(typeof(IClient), typeof(Client));
    serviceCollection.AddDependencyInjectionMapping();
    serviceCollection.AddTransient<TestHandler>();

    //Make sure the HttpClient is named the same as the Rest Client
    serviceCollection.AddSingleton<IClient>(x => new Client(name: clientName, httpClientFactory: x.GetRequiredService<IHttpClientFactory>()));
    serviceCollection.AddHttpClient(clientName, (c) => { c.BaseAddress = baseUri; })
        .AddHttpMessageHandler<TestHandler>();

    var serviceProvider = serviceCollection.BuildServiceProvider();
    var client = serviceProvider.GetService<IClient>();
    await client.GetAsync<object>();

RestClient.Net takes in to account dependency injection, mocking, IoC containers, unit testability, and above all is fast. I've hunted around and the only the other client that seems to work in a similar capacity is Flurl.Http.

What are the differences between NP, NP-Complete and NP-Hard?

There are really nice answers for this particular question, so there is no point to write my own explanation. So I will try to contribute with an excellent resource about different classes of computational complexity.

For someone who thinks that computational complexity is only about P and NP, here is the most exhaustive resource about different computational complexity problems. Apart from problems asked by OP, it listed approximately 500 different classes of computational problems with nice descriptions and also the list of fundamental research papers which describe the class.

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

Django set default form values

Other solution: Set initial after creating the form:

form.fields['tank'].initial = 123

Select distinct using linq

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<> into a List<> seems to be a mystery to many people, you can simply write:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

The flipside to this advice is that each time you enumerate such an IEnumerable the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

SQL: capitalize first letter only

Create the below function

Alter FUNCTION InitialCap(@String VARCHAR(8000))
                  RETURNS VARCHAR(8000)
                 AS
 BEGIN 

                   DECLARE @Position INT;

SELECT @String   = STUFF(LOWER(@String),1,1,UPPER(LEFT(@String,1))) COLLATE Latin1_General_Bin,
                    @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);

                    WHILE @Position > 0
                    SELECT @String   = STUFF(@String,@Position,2,UPPER(SUBSTRING(@String,@Position,2))) COLLATE Latin1_General_Bin,
                    @Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);

                     RETURN @String;
  END ;

Then call it like

select dbo.InitialCap(columnname) from yourtable

How do you fade in/out a background color using jquery?

I wrote a super simple jQuery plugin to accomplish something similar to this. I wanted something really light weight (it's 732 bytes minified), so including a big plugin or UI was out of the question for me. It's still a little rough around the edges, so feedback is welcome.

You can checkout the plugin here: https://gist.github.com/4569265.

Using the plugin, it would be a simple matter to create a highlight effect by changing the background color and then adding a setTimeout to fire the plugin to fade back to the original background color.

Combating AngularJS executing controller twice

In some cases your directive runs twice when you simply not correct close you directive like this:

<my-directive>Some content<my-directive>

This will run your directive twice. Also there is another often case when your directive runs twice:

make sure you are not including your directive in your index.html TWICE!

How to control the line spacing in UILabel

The solutions stated here didn't work for me. I found a slightly different way to do it with the iOS 6 NSAttributeString:

myLabel.numberOfLines = 0; 
NSString* string = @"String with line one. \n Line two. \n Line three.";
NSMutableParagraphStyle *style  = [[NSMutableParagraphStyle alloc] init];
style.minimumLineHeight = 30.f;
style.maximumLineHeight = 30.f;
NSDictionary *attributtes = @{NSParagraphStyleAttributeName : style,};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:string
                                                         attributes:attributtes];   
[myLabel sizeToFit];

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

You can use bootstrap 3 classes and build a table using the ng-repeat directive

Example:

_x000D_
_x000D_
angular.module('App', []);_x000D_
_x000D_
function ctrl($scope) {_x000D_
    $scope.items = [_x000D_
        ['A', 'B', 'C'],_x000D_
        ['item1', 'item2', 'item3'],_x000D_
        ['item4', 'item5', 'item6']_x000D_
    ];_x000D_
}
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="App">_x000D_
  <div ng-controller="ctrl">_x000D_
    _x000D_
    _x000D_
    <table class="table table-bordered">_x000D_
      <thead>_x000D_
        <tr>_x000D_
          <th ng-repeat="itemA in items[0]">{{itemA}}</th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td ng-repeat="itemB in items[1]">{{itemB}}</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td ng-repeat="itemC in items[2]">{{itemC}}</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
    _x000D_
    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

live example: http://jsfiddle.net/choroshin/5YDJW/5/

Update:

or you can always try the popular ng-grid , ng-grid is good for sorting, searching, grouping etc, but I haven't tested it yet on a large scale data.

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.

Below is the code which always works for me if I want to scroll up or down

 // This  will scroll page 400 pixel vertical
  ((JavascriptExecutor)driver).executeScript("scroll(0,400)");

You can get full code from here Scroll Page in Selenium

If you want to scroll for a element then below piece of code will work for you.

je.executeScript("arguments[0].scrollIntoView(true);",element);

You will get the full doc here Scroll for specific Element

Cannot invoke an expression whose type lacks a call signature

Perhaps create a shared Fruit interface that provides isDecayed. fruits is now of type Fruit[] so the type can be explicit. Like this:

interface Fruit {
    isDecayed: boolean;
}

interface Apple extends Fruit {
    color: string;
}

interface Pear extends Fruit {
    weight: number;
}

interface FruitBasket {
    apples: Apple[];
    pears: Pear[];
}


const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears'; 
const fruits: Fruit[] = fruitBasket[key];

const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);

html table cell width for different rows

One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:

_x000D_
_x000D_
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
    <colgroup>_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
    </colgroup>_x000D_
    <tr>_x000D_
        <td colspan=5>25</td>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=5>25</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=6>30</td>_x000D_
        <td colspan=4>20</td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Excel Validation Drop Down list using VBA

This worked on my test file (note the index in VBA starts from zero):

Sub DV_Test()
    Dim ValidationList(5) As Variant, i As Integer

    For i = 0 To UBound(ValidationList)
        ValidationList(i) = i + 1
    Next

    With Range("A1").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
            Operator:=xlEqual, Formula1:=Join(ValidationList, ",")
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End Sub

I used xlEqual because that's what I think you are trying to get people to select one of the list.

How to center HTML5 Videos?

I was having the same problem. This worked for me:

.center {
    margin: 0 auto; 
    width: 400px;
    **display:block**
 }

How to write a test which expects an Error to be thrown in Jasmine?

In my case the function throwing error was async so I followed here:

await expectAsync(asyncFunction()).toBeRejected();
await expectAsync(asyncFunction()).toBeRejectedWithError(...);

node.js string.replace doesn't work?

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

You can always just set the string to the modified value:

variableABC = variableABC.replace('B', 'D')

Edit: The code given above is to only replace the first occurrence.

To replace all occurrences, you could do:

 variableABC = variableABC.replace(/B/g, "D");  

To replace all occurrences and ignore casing

 variableABC = variableABC.replace(/B/gi, "D");  

SSH to Vagrant box in Windows?

There is an OpenSSH package for Windows which is basically a stripped down Cygwin. It has an msi-Installer and (after setting your path accordingly) works with "vsagrant ssh":

http://sourceforge.net/projects/opensshwindows/?source=directory

ResultSet exception - before start of result set

You have to call next() before you can start reading values from the first row. beforeFirst puts the cursor before the first row, so there's no data to read.

How can I set the focus (and display the keyboard) on my EditText programmatically

Here is KeyboardHelper Class for hiding and showing keyboard

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by khanhamza on 06-Mar-17.
 */

public class KeyboardHelper {
public static void hideSoftKeyboard(final Context context, final View view) {
    if (context == null) {
        return;
    }
    view.requestFocus();
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}, 1000);
}

public static void hideSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}, 1000);
}


public static void openSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 1000);
}
}

Which regular expression operator means 'Don't' match this character?

[^] ( within [ ] ) is negation in regular expression whereas ^ is "begining of string"

[^a-z] matches any single character that is not from "a" to "z"

^[a-z] means string starts with from "a" to "z"

Reference

How do I convert a C# List<string[]> to a Javascript array?

For one dimension array

Controller:

using Newtonsoft.Json;
var listOfIds = _dbContext.Countries.Where(x => x.Id == Country.USA).First().Cities.Where(x => x.IsCoveredByCompany).Select(x => x.Id).ToList();
string strArrayForJS = JsonConvert.SerializeObject(listOfIds); //  [1,2,6,7,8,18,25,61,129]
//Now pass it to the view through the model or ViewBag 

View:

<script>
    $(function () {
        var myArray = @HTML.Raw(Model.strArrayForJS);
        console.log(myArray); // [1, 2, 6, 7, 8, 18, 25, 61, 129]
        console.log(typeof (myArray)); //object
    });
</script>

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Rails 4 - passing variable to partial

ou are able to create local variables once you call the render function on a partial, therefore if you want to customize a partial you can for example render the partial _form.html.erb by:

<%= render 'form', button_label: "Create New Event", url: new_event_url %>
<%= render 'form', button_label: "Update Event", url: edit_event_url %>

this way you can access in the partial to the label for the button and the URL, those are different if you try to create or update a record. finally, for accessing to this local variables you have to put in your code local_assigns[:button_label] (local_assigns[:name_of_your_variable])

<%=form_for(@event, url: local_assigns[:url]) do |f|  %>
<%= render 'shared/error_messages_events' %>
<%= f.label :title ,"Title"%>
  <%= f.text_field :title, class: 'form-control'%>
  <%=f.label :date, "Date"%>
  <%=f.date_field :date, class: 'form-control'  %>
  <%=f.label :description, "Description"%>
  <%=f.text_area :description, class: 'form-control'  %>
  <%= f.submit local_assigns[:button_label], class:"btn btn-primary"%>
<%end%>

Convert timestamp long to normal date format

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

EDIT: Return time with TimeZone

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

public String convertTimeWithTimeZome(long time){
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " 
            + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
            + cal.get(Calendar.MINUTE));

}

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

Converting a Uniform Distribution to a Normal Distribution

This is my JavaScript implementation of Algorithm P (Polar method for normal deviates) from Section 3.4.1 of Donald Knuth's book The Art of Computer Programming:

function normal_random(mean,stddev)
{
    var V1
    var V2
    var S
    do{
        var U1 = Math.random() // return uniform distributed in [0,1[
        var U2 = Math.random()
        V1 = 2*U1-1
        V2 = 2*U2-1
        S = V1*V1+V2*V2
    }while(S >= 1)
    if(S===0) return 0
    return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))
}

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

For OS X and Sublime Text

Make subl available.

Put this in ~/.bash_profile

[[ -s ~/.bashrc ]] && source ~/.bashrc

Put this in ~/.bashrc

export EDITOR=subl

How to reference a .css file on a razor view?

For CSS that are reused among the entire site I define them in the <head> section of the _Layout:

<head>
    <link href="@Url.Content("~/Styles/main.css")" rel="stylesheet" type="text/css" />
    @RenderSection("Styles", false)
</head>

and if I need some view specific styles I define the Styles section in each view:

@section Styles {
    <link href="@Url.Content("~/Styles/view_specific_style.css")" rel="stylesheet" type="text/css" />
}

Edit: It's useful to know that the second parameter in @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will blissfully ignore the fact that there is no "Styles" section defined in your view. If true, the view won't render and an error will be thrown unless the "Styles" section has been defined.

How to add /usr/local/bin in $PATH on Mac

I've had the same problem with you.

cd to ../etc/ then use ls to make sure your "paths" file is in , vim paths, add "/usr/local/bin" at the end of the file.

jQuery - Trigger event when an element is removed from the DOM

You can use jQuery special events for this.

In all simplicity,

Setup:

(function($){
  $.event.special.destroyed = {
    remove: function(o) {
      if (o.handler) {
        o.handler()
      }
    }
  }
})(jQuery)

Usage:

$('.thing').bind('destroyed', function() {
  // do stuff
})

Addendum to answer Pierre and DesignerGuy's comments:

To not have the callback fire when calling $('.thing').off('destroyed'), change the if condition to: if (o.handler && o.type !== 'destroyed') { ... }

How to handle the modal closing event in Twitter Bootstrap?

There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden". As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:

$( '#modal' )
   .on('hide', function() {
       console.log('hide');
   })
   .on('hidden', function(){
       console.log('hidden');
   })
   .on('show', function() {
       console.log('show');
   })
   .on('shown', function(){
      console.log('shown' )
   });

And, as for your question, I think you should listen to the 'hide' event of your modal.

Applying styles to tables with Twitter Bootstrap

Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.

   <h3>NATO Phonetic Alphabet</h3>    
   <table class="table table-striped table-bordered table-condensed table-hover">
   <thead>
    <tr> 
        <th>Letter</th>
        <th>Phonetic Letter</th>

    </tr>
    </thead>
  <tr>
    <th>A</th>
    <th>Alpha</th>

  </tr>
  <tr>
    <td>B</td>
    <td>Bravo</td>

  </tr>
  <tr>
    <td>C</td>
    <td>Charlie</td>

  </tr>

</table>

Dart: mapping a list (list.map)

I'm new to flutter. I found that one can also achieve it this way.

 tabs: [
    for (var title in movieTitles) Tab(text: title)
  ]

Note: It requires dart sdk version to be >= 2.3.0, see here

Program to find largest and smallest among 5 numbers without using array

Use a sorting network!

#include <iostream>
#include <utility>

int main()
{
    int a, b, c, d, e;
    std::cin >> a >> b >> c >> d >> e;

    if (a < b) std::swap(a, b);
    if (d < e) std::swap(d, e);
    if (c < e) std::swap(c, e);
    if (c < d) std::swap(c, d);
    if (b < e) std::swap(b, e);
    if (a < d) std::swap(a, d);
    if (a < c) std::swap(a, c);
    if (b < d) std::swap(b, d);
    if (b < c) std::swap(b, c);

    std::cout << "largest = " << a << '\n';
    std::cout << "smallest = " << e << '\n';
}

Add a Progress Bar in WebView

in oncreate method where you have set your Webview.

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web_view);

web_view = (WebView) findViewById(R.id.web_view);
pd = new ProgressDialog(SiteOpenInWebView.this);
    pd.setMessage("Please wait Loading...");
    pd.show();
    web_view.setWebViewClient(new MyWebViewClient());
    web_view.loadUrl("ur site name");
 }

WebViewClient

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);

    if (!pd.isShowing()) {
        pd.show();
    }

    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    System.out.println("on finish");
    if (pd.isShowing()) {
        pd.dismiss();
    }

  }
}

How to determine if a point is in a 2D triangle?

I just want to use some simple vector math to explain the barycentric coordinates solution which Andreas had given, it will be way easier to understand.

  1. Area A is defined as any vector given by s * v02 + t * v01, with condition s >= 0 and t >= 0. If any point inside the triangle v0, v1, v2, it must be inside Area A.

enter image description here

  1. If further restrict s, and t belongs to [0, 1]. We get Area B which contains all vectors of s * v02 + t * v01, with condition s, t belongs to [0, 1]. It is worth to note that the low part of the Area B is the mirror of Triangle v0, v1, v2. The problem comes to if we can give certain condition of s, and t, to further excluding the low part of Area B.

enter image description here

  1. Assume we give a value s, and t is changing in [0, 1]. In the following pic, point p is on the edge of v1v2. All the vectors of s * v02 + t * v01 which are along the dash line by simple vector sum. At v1v2 and dash line cross point p, we have:

(1-s)|v0v2| / |v0v2| = tp|v0v1| / |v0v1|

we get 1 - s = tp, then 1 = s + tp. If any t > tp, which 1 < s + t where is on the double dash line, the vector is outside the triangle, any t <= tp, which 1 >= s + t where is on single dash line, the vector is inside the triangle.

Then if we given any s in [0, 1], the corresponding t must meet 1 >= s + t, for the vector inside triangle.

enter image description here

So finally we get v = s * v02 + t * v01, v is inside triangle with condition s, t, s+t belongs to [0, 1]. Then translate to point, we have

p - p0 = s * (p1 - p0) + t * (p2 - p0), with s, t, s + t in [0, 1]

which is the same as Andreas' solution to solve equation system p = p0 + s * (p1 - p0) + t * (p2 - p0), with s, t, s + t belong to [0, 1].

Facebook Oauth Logout

This solution no longer works with FaceBook's current API (seems it was unintended to begin with)

http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com;

Try to give this link on you signout link or button where "yoursitename.com" is where u want to redirect back after signout may be ur home page.

It works..

A beginner's guide to SQL database design

Experience counts for a lot, but in terms of table design you can learn a lot from how ORMs like Hibernate and Grails operate to see why they do things. In addition:

  1. Keep different types of data separate - don't store addresses in your order table, link to an address in a separate addresses table, for example.

  2. I personally like having an integer or long surrogate key on each table (that holds data, not those that link different tables together, e,g., m:n relationships) that is the primary key.

  3. I also like having a created and modified timestamp column.

  4. Ensure that every column that you do "where column = val" in any query has an index. Maybe not the most perfect index in the world for the data type, but at least an index.

  5. Set up your foreign keys. Also set up ON DELETE and ON MODIFY rules where relevant, to either cascade or set null, depending on your object structure (so you only need to delete once at the 'head' of your object tree, and all that object's sub-objects get removed automatically).

  6. If you want to modularise your code, you might want to modularise your DB schema - e.g., this is the "customers" area, this is the "orders" area, and this is the "products" area, and use join/link tables between them, even if they're 1:n relations, and maybe duplicate the important information (i.e., duplicate the product name, code, price into your order_details table). Read up on normalisation.

  7. Someone else will recommend exactly the opposite for some or all of the above :p - never one true way to do some things eh!

css padding is not working in outlook

Padding will not work in Outlook. Instead of adding blank Image, you can simply use multiple spaces(& nbsp;) before elements/texts for padding left For padding top or bottom, you can add a div containing just spaces(& nbsp;) alone. This will work!!!

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

How to find foreign key dependencies in SQL Server?

try: sp_help [table_name]

you will get all information about table, including all foreign keys

Open soft keyboard programmatically

InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

What is sharding and why is it important?

If you have queries to a DBMS for which the locality is quite restricted (say, a user only fires selects with a 'where username = $my_username') it makes sense to put all the usernames starting with A-M on one server and all from N-Z on the other. By this you get near linear scaling for some queries.

Long story short: Sharding is basically the process of distributing tables onto different servers in order to balance the load onto both equally.

Of course, it's so much more complicated in reality. :)

How to get records randomly from the oracle database?

SAMPLE() is not guaranteed to give you exactly 20 rows, but might be suitable (and may perform significantly better than a full query + sort-by-random for large tables):

SELECT *
FROM   table SAMPLE(20);

Note: the 20 here is an approximate percentage, not the number of rows desired. In this case, since you have 100 rows, to get approximately 20 rows you ask for a 20% sample.

bodyParser is deprecated express 4

app.use(bodyParser.urlencoded({extended: true}));

I have the same problem but this work for me. You can try this extended part.

How to generate sample XML documents from their DTD or XSD?

The camprocessor available on Sourceforge.net will do xml test case generation for any XSD. There is a tutorial available to show you how to generate your own test examples - including using content hints to ensure realistic examples, not just random junk ones.

The tutorial is available here: http://www.oasis-open.org/committees/download.php/29661/XSD%20and%20jCAM%20tutorial.pdf

And more information on the tool - which is using the OASIS Content Assembly Mechanism (CAM) standard to refactor your XSD into a more XSLT friendly structure - can be found from the resource website - http://www.jcam.org.uk

Enjoy, DW

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

So far, the accepted answer has worked best for me. However, my concern has always been that there is a likely scenario where I might refactor the notebooks directory into subdirectories, requiring to change the module_path in every notebook. I decided to add a python file within each notebook directory to import the required modules.

Thus, having the following project structure:

project
|__notebooks
   |__explore
      |__ notebook1.ipynb
      |__ notebook2.ipynb
      |__ project_path.py
   |__ explain
       |__notebook1.ipynb
       |__project_path.py
|__lib
   |__ __init__.py
   |__ module.py

I added the file project_path.py in each notebook subdirectory (notebooks/explore and notebooks/explain). This file contains the code for relative imports (from @metakermit):

import sys
import os

module_path = os.path.abspath(os.path.join(os.pardir, os.pardir))
if module_path not in sys.path:
    sys.path.append(module_path)

This way, I just need to do relative imports within the project_path.py file, and not in the notebooks. The notebooks files would then just need to import project_path before importing lib. For example in 0.0-notebook.ipynb:

import project_path
import lib

The caveat here is that reversing the imports would not work. THIS DOES NOT WORK:

import lib
import project_path

Thus care must be taken during imports.

Negation in Python

try instead:

if not os.path.exists(pathName):
    do this

Why doesn't Python have a sign function?

In Python 2, cmp() returns an integer: there's no requirement that the result be -1, 0, or 1, so sign(x) is not the same as cmp(x,0).

In Python 3, cmp() has been removed in favor of rich comparison. For cmp(), Python 3 suggests this:

def cmp(a, b):
    return (a > b) - (a < b)

which is fine for cmp(), but again can't be used for sign() because the comparison operators need not return booleans.

To deal with this possibility, the comparison results must be coerced to booleans:

 def sign(x):
    return bool(x > 0) - bool(x < 0)

This works for any type which is totally ordered (including special values like NaN or infinities).

How do I solve this error, "error while trying to deserialize parameter"

In my case; my WCF service function was using List<byte> Types parameter and i was getting this exception in the client side. Then i changed it to byte[] Types, updated service reference and problem is solved.

How to add headers to a multicolumn listbox in an Excel userform using VBA

Another variant on Lunatik's response is to use a local boolean and the change event so that the row can be highlighted upon initializing, but deselected and blocked after a selection change is made by the user:

Private Sub lbx_Change()

    If Not bHighlight Then

        If Me.lbx.Selected(0) Then Me.lbx.Selected(0) = False

    End If

    bHighlight = False

End Sub

When the listbox is initialized you then set bHighlight and lbx.Selected(0) = True, which will allow the header-row to initialize selected; afterwards, the first change will deselect and prevent the row from being selected again...

Convert a number into a Roman Numeral in javaScript

If it is just for display purpose, use the standard HTML with a bit of JS for the value (if needed) and CSS to make it inline:

_x000D_
_x000D_
ol.roman-lowercase,_x000D_
ol.roman-uppercase {_x000D_
  display: inline-flex;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
ol.roman-lowercase {_x000D_
  list-style: lower-roman inside;_x000D_
}_x000D_
_x000D_
ol.roman-uppercase {_x000D_
  list-style: upper-roman inside;_x000D_
}
_x000D_
<ol class="roman-lowercase"><li value="4"></li></ol> <!-- iv. -->_x000D_
<ol class="roman-uppercase"><li value="142"></li></ol> <!-- CXLII. -->
_x000D_
_x000D_
_x000D_

How to append text to a text file in C++?

 #include <fstream>
 #include <iostream>

 FILE * pFileTXT;
 int counter

int main()
{
 pFileTXT = fopen ("aTextFile.txt","a");// use "a" for append, "w" to overwrite, previous content will be deleted

 for(counter=0;counter<9;counter++)
 fprintf (pFileTXT, "%c", characterarray[counter] );// character array to file

 fprintf(pFileTXT,"\n");// newline

 for(counter=0;counter<9;counter++)
 fprintf (pFileTXT, "%d", digitarray[counter] );    // numerical to file

 fprintf(pFileTXT,"A Sentence");                   // String to file

 fprintf (pFileXML,"%.2x",character);              // Printing hex value, 0x31 if character= 1

 fclose (pFileTXT); // must close after opening

 return 0;

}

Wait Until File Is Completely Written

There is only workaround for the issue you are facing.

Check whether file id in process before starting the process of copy. You can call the following function until you get the False value.

1st Method, copied directly from this answer:

private bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

2nd Method:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
    //check that problem is not in destination file
    if (File.Exists(file) == true)
    {
        FileStream stream = null;
        try
        {
            stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (Exception ex2)
        {
            //_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
            int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
            if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
            {
                return true;
            }
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
    }
    return false;
}

How to add a custom right-click menu to a webpage?

I know this has already been answered, but I spent some time wrestling with the second answer to get the native context menu to disappear and have it show up where the user clicked.
HTML

<body>
    <div id="test1">
        <a href="www.google.com" class="test">Google</a>
        <a href="www.google.com" class="test">Link 2</a>
        <a href="www.google.com" class="test">Link 3</a>
        <a href="www.google.com" class="test">Link 4</a>
    </div>

    <!-- initially hidden right-click menu -->
    <div class="hide" id="rmenu">
        <ul>
            <li class="White">White</li>
            <li>Green</li>
            <li>Yellow</li>
            <li>Orange</li>
            <li>Red</li>
            <li>Blue</li>
        </ul>
    </div>
</body>

CSS

.hide {
  display: none;
}

#rmenu {
  border: 1px solid black;
  background-color: white;
}

#rmenu ul {
  padding: 0;
  list-style: none;
}
#rmenu li
{
  list-style: none;
  padding-left: 5px;
  padding-right: 5px;
}

JavaScript

if (document.getElementById('test1').addEventListener) {
    document.getElementById('test1').addEventListener('contextmenu', function(e) {
            $("#rmenu").toggleClass("hide");
            $("#rmenu").css(
              {
                position: "absolute",
                top: e.pageY,
                left: e.pageX
              }
            );
            e.preventDefault();
     }, false);
}

// this is from another SO post...  
$(document).bind("click", function(event) {
  document.getElementById("rmenu").className = "hide";
});

CodePen Example

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

Cocoa Touch: How To Change UIView's Border Color And Thickness?

Try this code:

view.layer.borderColor =  [UIColor redColor].CGColor;
view.layer.borderWidth= 2.0;
[view setClipsToBounds:YES];

Best way to resolve file path too long exception

What worked for me is moving my project as it was on the desktop (C:\Users\lachezar.l\Desktop\MyFolder) to (C:\0\MyFolder) which as you can see uses shorter path and reducing it solved the problem.

How can I cast int to enum?

var result = Enum.TryParse(yourString, out yourEnum) 

And make sure to check the result to determine if the conversion failed.

HTML img scaling

Adding max-width: 100%; to the img tag works for me.

How to make a phone call in android and come back to my activity when the call is done?

Steps:

1)Add the required permissions in the Manifest.xml file.

<!--For using the phone calls -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--For reading phone call state-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

2)Create a listener for the phone state changes.

public class EndCallListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
    if(TelephonyManager.CALL_STATE_RINGING == state) {
    }
    if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
        //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
    }
    if(TelephonyManager.CALL_STATE_IDLE == state) {
        //when this state occurs, and your flag is set, restart your app
    Intent i = context.getPackageManager().getLaunchIntentForPackage(
                            context.getPackageName());
    //For resuming the application from the previous state
    i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    //Uncomment the following if you want to restart the application instead of bring to front.
    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(i);
    }
}
}

3)Initialize the listener in your OnCreate

EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

but if you want to resume your application last state or to bring it back from the back stack, then replace FLAG_ACTIVITY_CLEAR_TOP with FLAG_ACTIVITY_SINGLE_TOP

Reference this Answer

Segmentation fault on large array sizes

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

load scripts asynchronously

Here is my custom solution to eliminate render-blocking JavaScript:

// put all your JS files here, in correct order
const libs = {
  "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
  "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
  "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
  "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
}
const loadedLibs = {}
let counter = 0

const loadAsync = function(lib) {
  var http = new XMLHttpRequest()
  http.open("GET", libs[lib], true)
  http.onload = () => {
    loadedLibs[lib] = http.responseText
    if (++counter == Object.keys(libs).length) startScripts()
  }
  http.send()
}

const startScripts = function() {
  for (var lib in libs) eval(loadedLibs[lib])
  console.log("allLoaded")
}

for (var lib in libs) loadAsync(lib)

In short, it loads all your scripts asynchronously, and then executes them consequently.

Github repo: https://github.com/mudroljub/js-async-loader

Disable activity slide-in animation when launching new activity?

To clear things up: FLAG_ACTIVITY_NO_ANIMATION (or android:windowAnimationStyle = @null in the theme) work perfectly fine for both, enter and exit. The problem is, that the enter animation checks if the animation is enabled in the one activity and the exit animation checks it for the other one. So make sure to disable it in both activities.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

I was facing the same problem in IntelliJ. It was working from command line though.

I found the issue was because of an improper Gradle config in the IDE. I wasn't using the "default Gradle wrapper" as recommended:

enter image description here

Where do I put image files, css, js, etc. in Codeigniter?

add one folder any name e.g public and add .htaccess file and write allow from all it means, in this folder your all files and all folder will not give error Access forbidden! use it like this

<link href="<?php echo base_url(); ?>application/public/css/style.css" rel="stylesheet" type="text/css"  />
<script type="text/javascript" src="<?php echo base_url(); ?>application/public/js/javascript.js"></script>

What are WSDL, SOAP and REST?

Every time someone mentions SOAP/WSDL, I think of objects and classes defined in xml...

"You use SOAP just the same way that you would any PHP class. However, in this case the class does not exist in the local applications file system, but at a remote site accessed over http." ... "If we think of using a SOAP service as just another PHP class then the WSDL document is a list of all the available class methods and properties. "

http://www.doublehops.com/2009/07/07/quick-tutorial-on-getting-started-with-soap-in-php/comment-page-1/

..and whenever someone talks about REST I think of HTTP's commands (request methods) like POST, GET and DELETE

This certificate has an invalid issuer Apple Push Services

I think I've figured this one out. I imported the new WWDR Certificate that expires in 2023, but I was still getting problems building and my developer certificates were still showing the invalid issuer error.

  • In keychain access, go to View -> Show Expired Certificates. Then in your login keychain highlight the expired WWDR Certificate and delete it.
  • I also had the same expired certificate in my System keychain, so I deleted it from there too (important).

After deleting the expired certificate from the login and System keychains, I was able to build for Distribution again.

php: loop through json array

Decode the JSON string using json_decode() and then loop through it using a regular loop:

$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}

offsetTop vs. jQuery.offset().top

This is what jQuery API Doc says about .offset():

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

This is what MDN Web API says about .offsetTop:

offsetTop returns the distance of the current element relative to the top of the offsetParent node

This is what jQuery v.1.11 .offset() basically do when getting the coords:

var box = { top: 0, left: 0 };

// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
  box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
  top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
  left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
  • pageYOffset intuitively says how much was the page scrolled
  • docElem.scrollTop is the fallback for IE<9 (which are BTW unsupported in jQuery 2)
  • docElem.clientTop is the width of the top border of an element (the document in this case)
  • elem.getBoundingClientRect() gets the coords relative to the document viewport (see comments). It may return fraction values, so this is the source of your bug. It also may cause a bug in IE<8 when the page is zoomed. To avoid fraction values, try to calculate the position iteratively

Conclusion

  • If you want coords relative to the parent node, use element.offsetTop. Add element.scrollTop if you want to take the parent scrolling into account. (or use jQuery .position() if you are fan of that library)
  • If you want coords relative to the viewport use element.getBoundingClientRect().top. Add window.pageYOffset if you want to take the document scrolling into account. You don't need to subtract document's clientTop if the document has no border (usually it doesn't), so you have position relative to the document
  • Subtract element.clientTop if you don't consider the element border as the part of the element

Delete all documents from index/type without deleting type

Starting from Elasticsearch 2.x delete is not anymore allowed, since documents remain in the index causing index corruption.

How to declare or mark a Java method as deprecated?

Use both @Deprecated annotation and the @deprecated JavaDoc tag.

The @deprecated JavaDoc tag is used for documentation purposes.

The @Deprecated annotation instructs the compiler that the method is deprecated. Here is what it says in Sun/Oracles document on the subject:

Using the @Deprecated annotation to deprecate a class, method, or field ensures that all compilers will issue warnings when code uses that program element. In contrast, there is no guarantee that all compilers will always issue warnings based on the @deprecated Javadoc tag, though the Sun compilers currently do so. Other compilers may not issue such warnings. Thus, using the @Deprecated annotation to generate warnings is more portable that relying on the @deprecated Javadoc tag.

You can find the full document at How and When to Deprecate APIs

how to make div click-able?

The simplest of them all:

<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>

Parse JSON with R

For the record, rjson and RJSONIO do change the file type, but they don't really parse per se. For instance, I receive ugly MongoDB data in JSON format, convert it with rjson or RJSONIO, then use unlist and tons of manual correction to actually parse it into a usable matrix.

Hot to get all form elements values using jQuery?

Try this for getting form input text value to JavaScript object...

var fieldPair = {};
$("#form :input").each(function() {
    if($(this).attr("name").length > 0) {
        fieldPair[$(this).attr("name")] = $(this).val();
    }
});

console.log(fieldPair);

After installation of Gulp: “no command 'gulp' found”

Installing on a Mac - Sierra - After numerous failed attempts to install and run gulp globally via the command line using several different instructions I found I added this to my path and it worked:

export PATH=/usr/local/Cellar/node/7.6.0/libexec/npm/bin/:$PATH

I got that path from the text output when installing gulp.

Finish all previous activities

for API >= 15 to API 23 simple solution.

 Intent nextScreen = new Intent(currentActivity.this, MainActivity.class);
 nextScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(nextScreen);
 ActivityCompat.finishAffinity(currentActivity.this);

How to bind a List<string> to a DataGridView control?

An alternate is to use a new helper function which will take values from List and update in the DataGridView as following:

    private void DisplayStringListInDataGrid(List<string> passedList, ref DataGridView gridToUpdate, string newColumnHeader)
    {
        DataTable gridData = new DataTable();
        gridData.Columns.Add(newColumnHeader);

        foreach (string listItem in passedList)
        {
            gridData.Rows.Add(listItem);
        }

        BindingSource gridDataBinder = new BindingSource();
        gridDataBinder.DataSource = gridData;
        dgDataBeingProcessed.DataSource = gridDataBinder;
    }

Then we can call this function the following way:

    DisplayStringListInDataGrid(<nameOfListWithStrings>, ref <nameOfDataGridViewToDisplay>, <nameToBeGivenForTheNewColumn>);

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

I got similar message when running command line mvn (version 3.3.3) on Linux with Java 8. By opening maven script /$MAVEN-HOME/bin/mvn, found the following line

MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"

Where $MAVEN_PROJECTBASEDIR by default is your home directory. So two places you can take a look, first is file $MAVEN_PROJECTBASEDIR/.mvn/jvm.config if it exists. Secondly look at files possibly set up the environment variable MAVEN_OPTS. Candidate files are .bashrc, .bash_profile, .profile and those files included by them such as /etc/profile, /etc/bash.bashrc

I located

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256m"

in .bashrc in my system, change it to

export MAVEN_OPTS="-Xmx512m"

issue resolved

Getting RSA private key from PEM BASE64 Encoded private key file

As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec needs to understand it. If you don't want to convert the key using openssl pkcs8 or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:

static final Base64.Decoder DECODER = Base64.getMimeDecoder();

private static byte[] buildPKCS8Key(File privateKey) throws IOException {
  final String s = new String(Files.readAllBytes(privateKey.toPath()));
  if (s.contains("--BEGIN PRIVATE KEY--")) {
    return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
  }
  if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
    throw new RuntimeException("Invalid cert format: "+ s);
  }

  final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
  final byte[] result = new byte[innerKey.length + 26];
  System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
  System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
  System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
  System.arraycopy(innerKey, 0, result, 26, innerKey.length);
  return result;
}

Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));

How can I solve equations in Python?

How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…

Postgresql GROUP_CONCAT equivalent?

Hope below Oracle query will work.

Select First_column,LISTAGG(second_column,',') 
    WITHIN GROUP (ORDER BY second_column) as Sec_column, 
    LISTAGG(third_column,',') 
    WITHIN GROUP (ORDER BY second_column) as thrd_column 
FROM tablename 
GROUP BY first_column

C++ string to double conversion

The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.

To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:

double lol;
openfile >> lol;

This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:

double lol;
openfile >> lol;

if (openfile.fail()) {
    cout << "Couldn't read a double from the file." << endl;
}

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Git merge two local branches

Here's a clear picture:

Assuming we have branch-A and branch-B

We want to merge branch-B into branch-A

on branch-B -> A: switch to branch-A

on branch-A: git merge branch-B

ImportError: cannot import name NUMPY_MKL

I recently got the same error when trying to load scipy in jupyter (python3.x, win10), although just having upgraded to numpy-1.13.3+mkl through pip. The solution was to simply upgrade the scipy package (from v0.19 to v1.0.0).

Jquery Chosen plugin - dynamically populate list by Ajax

Ashirvad's answer no longer works. Note the class name changes and using the option element instead of the li element. I've updated my answer to not use the deprecated "success" event, instead opting for .done():

$('.chosen-search input').autocomplete({
    minLength: 3,
    source: function( request, response ) {
        $.ajax({
            url: "/some/autocomplete/url/"+request.term,
            dataType: "json",
            beforeSend: function(){ $('ul.chosen-results').empty(); $("#CHOSEN_INPUT_FIELDID").empty(); }
        }).done(function( data ) {
                response( $.map( data, function( item ) {
                    $('#CHOSEN_INPUT_FIELDID').append('<option value="blah">' + item.name + '</option>');
                }));

               $("#CHOSEN_INPUT_FIELDID").trigger("chosen:updated");
        });
    }
});

How to render an ASP.NET MVC view as a string?

I saw an implementation for MVC 3 and Razor from another website, it worked for me:

    public static string RazorRender(Controller context, string DefaultAction)
    {
        string Cache = string.Empty;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.TextWriter tw = new System.IO.StringWriter(sb); 

        RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
        view_.Render(new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw), tw);

        Cache = sb.ToString(); 

        return Cache;

    } 

    public static string RenderRazorViewToString(string viewName, object model)
    {

        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();
        }
    } 

    public static class HtmlHelperExtensions
    {
        public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
        {
            ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);

            if (result.View != null)
            {
                StringBuilder sb = new StringBuilder();
                using (StringWriter sw = new StringWriter(sb))
                {
                    using (HtmlTextWriter output = new HtmlTextWriter(sw))
                    {
                        ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
                        result.View.Render(viewContext, output);
                    }
                }
                return sb.ToString();
            } 

            return String.Empty;

        }

    }

More on Razor render- MVC3 View Render to String

Hibernate: How to fix "identifier of an instance altered from X to Y"?

In my particular case, this was caused by a method in my service implementation that needed the spring @Transactional(readOnly = true) annotation. Once I added that, the issue was resolved. Unusual though, it was just a select statement.

Spring: @Component versus @Bean

You can use @Bean to make an existing third-party class available to your Spring framework application context.

@Bean
public ViewResolver viewResolver() {

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

By using the @Bean annotation, you can wrap a third-party class (it may not have @Component and it may not use Spring), as a Spring bean. And then once it is wrapped using @Bean, it is as a singleton object and available in your Spring framework application context. You can now easily share/reuse this bean in your app using dependency injection and @Autowired.

So think of the @Bean annotation is a wrapper/adapter for third-party classes. You want to make the third-party classes available to your Spring framework application context.

By using @Bean in the code above, I'm explicitly declare a single bean because inside of the method, I'm explicitly creating the object using the new keyword. I'm also manually calling setter methods of the given class. So I can change the value of the prefix field. So this manual work is referred to as explicit creation. If I use the @Component for the same class, the bean registered in the Spring container will have default value for the prefix field.

On the other hand, when we annotate a class with @Component, no need for us to manually use the new keyword. It is handled automatically by Spring.

Can't ping a local VM from the host

Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is 192.168.71.105, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: 192.168.71.1

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

TLS 1.2 in .NET Framework 4.0

I code in VB and was able to add the following line to my Global.asax.vb file inside of Application_Start

ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)    'TLS 1.2

How to send post request to the below post method using postman rest client

1.Open postman app 2.Enter the URL in the URL bar in postman app along with the name of the design.Use slash(/) after URL to give the design name. 3.Select POST from the dropdown list from URL textbox. 4.Select raw from buttons available below the URL textbox. 5.Select JSON from the dropdown. 6.In the text area enter your data to be updated and enter send. 7.Select GET from dropdown list from URL textbox and enter send to see the updated result.

Combine Regexp?

Combining the regex for the fourth option with any of the others doesn't work within one regex. 4 + 1 would mean either the string starts with @ or doesn't contain @ at all. You're going to need two separate comparisons to do that.

Different ways of clearing lists

del list[:] 

Will delete the values of that list variable

del list

Will delete the variable itself from memory

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

git fetch origin
git reset --hard origin/master
git pull

Explanation:

  • Fetch will download everything from another repository, in this case, the one marked as "origin".
  • Reset will discard changes and revert to the mentioned branch, "master" in repository "origin".
  • Pull will just get everything from a remote repository and integrate.

See documentation at http://git-scm.com/docs.

How to detect a textbox's content has changed

Use closures to remember what was the text in the checkbox before the key stroke and check whether this has changed.

Yep. You don't have to use closures necessarily, but you will need to remember the old value and compare it to the new.

However! This still won't catch every change, because there a ways of editing textbox content that do not involve any keypress. For example selecting a range of text then right-click-cut. Or dragging it. Or dropping text from another app into the textbox. Or changing a word via the browser's spell-check. Or...

So if you must detect every change, you have to poll for it. You could window.setInterval to check the field against its previous value every (say) second. You could also wire onkeyup to the same function so that changes that are caused by keypresses are reflected quicker.

Cumbersome? Yes. But it's that or just do it the normal HTML onchange way and don't try to instant-update.

Tool for comparing 2 binary files in Windows

I prefer to use objcopy to convert to hex, then use diff.

How to specify the download location with wget?

From the manual page:

-P prefix
--directory-prefix=prefix
           Set directory prefix to prefix.  The directory prefix is the
           directory where all other files and sub-directories will be
           saved to, i.e. the top of the retrieval tree.  The default
           is . (the current directory).

So you need to add -P /tmp/cron_test/ (short form) or --directory-prefix=/tmp/cron_test/ (long form) to your command. Also note that if the directory does not exist it will get created.

MySql Error: 1364 Field 'display_name' doesn't have default value

I got this error when I forgot to add new form fields/database columns to the $fillable array in the Laravel model - the model was stripping them out.

push_back vs emplace_back

emplace_back shouldn't take an argument of type vector::value_type, but instead variadic arguments that are forwarded to the constructor of the appended item.

template <class... Args> void emplace_back(Args&&... args); 

It is possible to pass a value_type which will be forwarded to the copy constructor.

Because it forwards the arguments, this means that if you don't have rvalue, this still means that the container will store a "copied" copy, not a moved copy.

 std::vector<std::string> vec;
 vec.emplace_back(std::string("Hello")); // moves
 std::string s;
 vec.emplace_back(s); //copies

But the above should be identical to what push_back does. It is probably rather meant for use cases like:

 std::vector<std::pair<std::string, std::string> > vec;
 vec.emplace_back(std::string("Hello"), std::string("world")); 
 // should end up invoking this constructor:
 //template<class U, class V> pair(U&& x, V&& y);
 //without making any copies of the strings

Set default format of datetimepicker as dd-MM-yyyy

Try this,

string Date = datePicker1.SelectedDate.Value.ToString("dd-MMM-yyyy");

It worked for me the output format will be '02-May-2016'

How to send a message to a particular client with socket.io

You can use socket.io rooms. From the client side emit an event ("join" in this case, can be anything) with any unique identifier (email, id).

Client Side:

var socket = io.connect('http://localhost');
socket.emit('join', {email: [email protected]});

Now, from the server side use that information to create an unique room for that user

Server Side:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.on('join', function (data) {
    socket.join(data.email); // We are using room of socket io
  });
});

So, now every user has joined a room named after user's email. So if you want to send a specific user a message you just have to

Server Side:

io.sockets.in('[email protected]').emit('new_msg', {msg: 'hello'});

The last thing left to do on the client side is listen to the "new_msg" event.

Client Side:

socket.on("new_msg", function(data) {
    alert(data.msg);
}

I hope you get the idea.

How to add include path in Qt Creator?

For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:

enter image description here

Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

If You installed SQL Express or any .Net Server then you need to stop. open cmd in administrator mode and type this line ...

net stop Was

now start apache

What's the purpose of the LEA instruction?

Here is an example.

// compute parity of permutation from lexicographic index
int parity (int p)
{
  assert (p >= 0);
  int r = p, k = 1, d = 2;
  while (p >= k) {
    p /= d;
    d += (k << 2) + 6; // only one lea instruction
    k += 2;
    r ^= p;
  }
  return r & 1;
}

With -O (optimize) as compiler option, gcc will find the lea instruction for the indicated code line.

What is N-Tier architecture?

Martin Fowler demonstrating clearly:

Layering is one of the most common techniques that software designers use to break apart a complicated software system. You see it in machine architectures, where layers descend from a programming language with operating system calls into device drivers and CPU instruction sets, and into logic gates inside chips. Networking has FTP layered on top of TCP, which is on top of IP, which is on top of ethernet.

When thinking of a system in terms of layers, you imagine the principal subsystems in the software arranged in some form of layer cake, where each layer rests on a lower layer. In this scheme the higher layer uses various services defined by the lower layer, but the lower layer is unaware of the higher layer. Furthermore, each layer usually hides its lower layers from the layers above, so layer 4 uses the services of layer 3, which uses the services of layer 2, but layer 4 is unaware of layer 2. (Not all layering architectures are opaque like this, but most are—or rather most are mostly opaque.)

Breaking down a system into layers has a number of important benefits.

• You can understand a single layer as a coherent whole without knowing much about the other layers. You can understand how to build an FTP service on top of TCP without knowing the details of how ethernet works.

• You can substitute layers with alternative implementations of the same basic services. An FTP service can run without change over ethernet, PPP, or whatever a cable company uses.

• You minimize dependencies between layers. If the cable company changes its physical transmission system, providing they make IP work, we don’t have to alter our FTP service.

• Layers make good places for standardization. TCP and IP are standards because they define how their layers should operate.

• Once you have a layer built, you can use it for many higher-level services. Thus, TCP/IP is used by FTP, telnet, SSH, and HTTP. Otherwise, all of these higher-level protocols would have to write their own lower-level protocols. From the Library of Kyle Geoffrey Passarelli

Layering is an important technique, but there are downsides.

• Layers encapsulate some, but not all, things well. As a result you sometimes get cascading changes. The classic example of this in a layered enterprise application is adding a field that needs to display on the UI, must be in the database, and thus must be added to every layer in between.

• Extra layers can harm performance. At every layer things typically need to be transformed from one representation to another. However, the encapsulation of an underlying function often gives you efficiency gains that more than compensate. A layer that controls transactions can be optimized and will then make everything faster. But the hardest part of a layered architecture is deciding what layers to have and what the responsibility of each layer should be.

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

New Array from Index Range Swift

Array functional way:

   array.enumerated().filter { $0.offset < limit }.map { $0.element }

ranged:

 array.enumerated().filter { $0.offset >= minLimit && $0.offset < maxLimit }.map { $0.element }

The advantage of this method is such implementation is safe.

Critical t values in R

The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:

abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))

Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value

abs(qt(0.01/2, 40)) # 99% confidence, 2 sided

How to repeat a char using printf?

If you have a compiler that supports the alloca() function, then this is possible solution (quite ugly though):

printf("%s", (char*)memset(memset(alloca(10), '\0', 10), 'x', 9));

It basically allocates 10 bytes on the stack which are filled with '\0' and then the first 9 bytes are filled with 'x'.

If you have a C99 compiler, then this might be a neater solution:

for (int i = 0;  i < 10;  i++, printf("%c", 'x'));

Beautiful Soup and extracting a div and its contents by ID

You should post your example document, because the code works fine:

>>> import BeautifulSoup
>>> soup = BeautifulSoup.BeautifulSoup('<html><body><div id="articlebody"> ... </div></body></html')
>>> soup.find("div", {"id": "articlebody"})
<div id="articlebody"> ... </div>

Finding <div>s inside <div>s works as well:

>>> soup = BeautifulSoup.BeautifulSoup('<html><body><div><div id="articlebody"> ... </div></div></body></html')
>>> soup.find("div", {"id": "articlebody"})
<div id="articlebody"> ... </div>

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

How to send email by using javascript or jquery

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Simple PHP mail script

Using a script like that, you'd POST the contents of your web form to the script, using a function like this:

jQuery.post

And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.

How to change the bootstrap primary color?

Using SaSS
change the brand color

$brand-primary:#some-color;

this will change the primary color accross all UI.

Using css-
suppose you want to change button primary color.So

btn.primary{
  background:#some-color;
}

search the element and add a new css/sass rule in a new file and attach it after u load the bootstrap css.

How to cast Object to its actual type?

If you know the actual type, then just:

SomeType typed = (SomeType)obj;
typed.MyFunction();

If you don't know the actual type, then: not really, no. You would have to instead use one of:

  • reflection
  • implementing a well-known interface
  • dynamic

For example:

// reflection
obj.GetType().GetMethod("MyFunction").Invoke(obj, null);

// interface
IFoo foo = (IFoo)obj; // where SomeType : IFoo and IFoo declares MyFunction
foo.MyFunction();

// dynamic
dynamic d = obj;
d.MyFunction();

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
});

The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.

Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/

Kudos to this answer for showing me the way.

Reading entire html file to String?

I prefers using Guava :

import com.google.common.base.Charsets;
import com.google.common.io.Files;
File file = new File("/path/to/file", Charsets.UTF_8);
String content = Files.toString(file);

Select2 open dropdown on focus

Here is an alternate solution for version 4.x of Select2. You can use listeners to catch the focus event and then open the select.

$('#test').select2({
    // Initialisation here
}).data('select2').listeners['*'].push(function(name, target) { 
    if(name == 'focus') {
        $(this.$element).select2("open");
    }
});

Find the working example here based the exampel created by @tonywchen

Linux command (like cat) to read a specified quantity of characters

head works too:

head -c 100 file  # returns the first 100 bytes in the file

..will extract the first 100 bytes and return them.

What's nice about using head for this is that the syntax for tail matches:

tail -c 100 file  # returns the last 100 bytes in the file

You can combine these to get ranges of bytes. For example, to get the second 100 bytes from a file, read the first 200 with head and use tail to get the last 100:

head -c 200 file | tail -c 100

Certificate is trusted by PC but not by Android

I had a similar problem and wrote a detailed article about it. If anyone has the same problem, feel free to read my article.

https://developer-blog.net/administration/ssl-zertifikat-installieren/

It is a detailed problem description in German language.

How to set background image of a view?

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

more info with example project

Add a new item to a dictionary in Python

default_data['item3'] = 3

Easy as py.

Another possible solution:

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once.

Splitting a string into separate variables

An array is created with the -split operator. Like so,

$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago

When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,

$arr[2] # 3rd element
and
$arr[4] # 5th element
years

How to get 'System.Web.Http, Version=5.2.3.0?

The packages you installed introduced dependencies to version 5.2.3.0 dll's as user Bracher showed above. Microsoft.AspNet.WebApi.Cors is an example package. The path I take is to update the MVC project proir to any package installs:

Install-Package Microsoft.AspNet.Mvc -Version 5.2.3

https://www.nuget.org/packages/microsoft.aspnet.mvc

How can I create directory tree in C++/Linux?

If dir does not exist, create it:

boost::filesystem::create_directories(boost::filesystem::path(output_file).parent_path().string().c_str()); 

Python pip install module is not found. How to link python to pip location?

As a quick workaround, and assuming that you are on a bash-like terminal (Linux/OSX), you can try to export the PYTHONPATH environment variable:

export PYTHONPATH="${PYTHONPATH}:/usr/local/lib/python2.7/site-packages:/usr/lib/python2.7/site-packages"

For Python 2.7

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

Get week day name from a given month, day and year individually in SQL Server

I used

select
case
when (extract (weekday from DATE)=0) then 'Sunday'

and so on...

0 Sunday, 1 Monday...

Max retries exceeded with URL in requests

Check your network connection. I had this and the VM did not have a proper network connection.

Difference between DOMContentLoaded and load events

DOMContentLoaded==window.onDomReady()

Load==window.onLoad()

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $(document).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $(window).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

See: Using JQuery Core's document-ready documentation.

Excel - Combine multiple columns into one column

Try this. Click anywhere in your range of data and then use this macro:

Sub CombineColumns()
Dim rng As Range
Dim iCol As Integer
Dim lastCell As Integer

Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1

For iCol = 2 To rng.Columns.Count
    Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
    ActiveSheet.Paste Destination:=Cells(lastCell, 1)
    lastCell = lastCell + rng.Columns(iCol).Rows.Count
Next iCol
End Sub

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

Rails: call another controller action from a controller

Perhaps the logic could be extracted into a helper? helpers are available to all classes and don't transfer control. You could check within it, perhaps for controller name, to see how it was called.

What is the Java ?: operator called and what does it do?

int count = isHere ? getHereCount(index) : getAwayCount(index);

means :

if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}

Convert array of indices to 1-hot encoded numpy array

If using tensorflow, there is one_hot():

import tensorflow as tf
import numpy as np

a = np.array([1, 0, 3])
depth = 4
b = tf.one_hot(a, depth)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[0., 1., 0.],
#        [1., 0., 0.],
#        [0., 0., 0.]], dtype=float32)>

what does mysql_real_escape_string() really do?

Best explained here.

http://www.w3schools.com/php/func_mysql_real_escape_string.asp

http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

It generally it helps to avoid SQL injection, for example consider the following code:

<?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?>

and a hacker can send a query like:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

In my case, none of the above worked, however, replacing 5.2.3.0 with 4.0.0.0 did solve the problem.

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

Xcode/Simulator: How to run older iOS version?

The simulator CANNOT be downloaded from:

Xcode -> Preferences -> Downloads

Only the iOS devices symbols. As this option says:

This package includes information and symbols that Xcode needs for debugging your app on iOS devices running versions of iOS prior to iOS 4.2. If you intend to debug your app on a device running one of these versions of iOS you should install this package.

That is, you need an iOS 4.2 device to test an iOS 4.2 application

How to set a variable inside a loop for /F

I struggeld for many hours on this. This is my loop to register command line vars. Example : Register.bat /param1:value1 /param2:value2

What is does, is loop all the commandline params, and that set the variable with the proper name to the value.

After that, you can just use set value=!param1! set value2=!param2!

regardless the sequence the params are given. (so called named parameters). Note the !<>!, instead of the %<>%.

SETLOCAL ENABLEDELAYEDEXPANSION

FOR %%P IN (%*) DO (
    call :processParam %%P
)

goto:End

:processParam [%1 - param]

    @echo "processparam : %1"
    FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO (
        @echo a,b %%G %%H
        set nameWithSlash=%%G
        set name=!nameWithSlash:~1!
        @echo n=!name!
        set value=%%H
        set !name!=!value!
    )
    goto :eof

:End    

How to add default signature in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

How to get html to print return value of javascript function?

There are some options to do that.

One would be:

document.write(produceMessage())

Other would be appending some element in your document this way:

var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);

Or just:

document.body.appendChild(document.createTextNode(produceMessage()));

If you're using jQuery, you can do this:

$(document.body).append(produceMessage());

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

How to install a gem or update RubyGems if it fails with a permissions error

Try nathanwhy's answer before using my original answer below. His recommendation of --user-install should accomplish the same purpose without having to muck with your .bash_profile or determine your ruby version.


If you are not concerned about a specific ruby version, you can skip the heavy-lift ruby environment manager options, and just add these lines to ~/.bash_profile:

export GEM_HOME="$HOME/.gem/ruby/2.0.0"
export GEM_PATH="$HOME/.gem/ruby/2.0.0"

The path is stolen from the original output of gem env:

RubyGems Environment:
  - RUBYGEMS VERSION: 2.0.14
  - RUBY VERSION: 2.0.0
  - INSTALLATION DIRECTORY: /Library/Ruby/Gems/2.0.0
  - RUBY EXECUTABLE: /System/Library/.../2.0/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-14
  - GEM PATHS:
     - /Library/Ruby/Gems/2.0.0
     - /Users/mylogin/.gem/ruby/2.0.0 # <-- This guy, right here.
     - /System/Library/.../usr/lib/ruby/gems/2.0.0
  ...

No sudoing is required, and you can use the already-installed ruby, courtesy of Apple.

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

Are you talking about drag and drop, when you say copy and paste? If yes, you can also use Rightclick on object on your main computer and click copy. And then you go into the Virtual Machine and Rightclick the position where you want the file to get copied to.

If this doesn't work use the method KaiserM11 explained and get yourselfe VMware Tools like in this Video: https://www.youtube.com/watch?v=McjwI_6BKZY

Hope my answer was helpfull to you and happy coding :D

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/sales.us.acme.com\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:

SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'

Authentication plugin 'caching_sha2_password' cannot be loaded

Note: For Linux (Debian, Ubuntu, Mint)

I got this error:

MySQL Error Message: Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory

I solved with this steps:

  1. Enter on mysql console: $ mysql -u root -p, if you don't has a password for root user, then:

  2. Use mysql db: mysql> use mysql;

  3. Alter your user for solve the problem: mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

  4. Exit... mysql> quit;

  5. Done!

Get a worksheet name using Excel VBA

This works for me.

worksheetName = ActiveSheet.Name  

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

Cache busting via params

 <script>
    var storedSrcElements = [
         "js/exampleFile.js",
         "js/sampleFile.js",
         "css/style.css"
          ];

    var head= document.getElementsByTagName('head')[0];
    var script;
    var link;
    var versionNumberNew = 4.6;

    for(i=0;i<storedSrcElements.length;i++){
     script= document.createElement('script');
     script.type= 'text/javascript';
     script.src= storedSrcElements[i] + "?" + versionNumberNew;
     head.appendChild(script);
    }     


     </script> 


       ### Change the version number  (versionNumberNew) when you want the new files to be loaded  ###

What does the "yield" keyword do?

It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as C#'s iterator blocks if you're familiar with those.

The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values - as if the generator method was paused. Now obviously you can't really "pause" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.

How to check if object property exists with a variable holding the property name?

For own property :

var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount")) 
{ 
   //will execute
}

Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like

var foo = {
      hasOwnProperty: function() {
        return false;
      },
      bar: 'Here be dragons'
    };

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)

const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi) 
    console.log("Yoshi can skulk");

if (!("sneak" in yoshi)) 
    console.log("Yoshi cannot sneak");

if (!("creep" in yoshi)) 
    console.log("Yoshi cannot creep");

Object.setPrototypeOf(yoshi, hattori);

if ("sneak" in yoshi)
    console.log("Yoshi can now sneak");
if (!("creep" in hattori))
    console.log("Hattori cannot creep");

Object.setPrototypeOf(hattori, kuma);

if ("creep" in hattori)
    console.log("Hattori can now creep");
if ("creep" in yoshi)
    console.log("Yoshi can also creep");

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...

var loan = { amount: 150 };

loan.installment = undefined;

if("installment" in loan) // correct
{
    // will execute
}

if(typeof loan["installment"] !== "undefined") // incorrect
{
    // will not execute
}