Programs & Examples On #B2b

acronym for Business-to-business

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

Listing all permutations of a string/integer

If performance and memory is an issue, I suggest this very efficient implementation. According to Heap's algorithm in Wikipedia, it should be the fastest. Hope it will fits your need :-) !

Just as comparison of this with a Linq implementation for 10! (code included):

  • This: 36288000 items in 235 millisecs
  • Linq: 36288000 items in 50051 millisecs

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Runtime.CompilerServices;
    using System.Text;
    
    namespace WpfPermutations
    {
        /// <summary>
        /// EO: 2016-04-14
        /// Generator of all permutations of an array of anything.
        /// Base on Heap's Algorithm. See: https://en.wikipedia.org/wiki/Heap%27s_algorithm#cite_note-3
        /// </summary>
        public static class Permutations
        {
            /// <summary>
            /// Heap's algorithm to find all pmermutations. Non recursive, more efficient.
            /// </summary>
            /// <param name="items">Items to permute in each possible ways</param>
            /// <param name="funcExecuteAndTellIfShouldStop"></param>
            /// <returns>Return true if cancelled</returns> 
            public static bool ForAllPermutation<T>(T[] items, Func<T[], bool> funcExecuteAndTellIfShouldStop)
            {
                int countOfItem = items.Length;
    
                if (countOfItem <= 1)
                {
                    return funcExecuteAndTellIfShouldStop(items);
                }
    
                var indexes = new int[countOfItem];
                for (int i = 0; i < countOfItem; i++)
                {
                    indexes[i] = 0;
                }
    
                if (funcExecuteAndTellIfShouldStop(items))
                {
                    return true;
                }
    
                for (int i = 1; i < countOfItem;)
                {
                    if (indexes[i] < i)
                    { // On the web there is an implementation with a multiplication which should be less efficient.
                        if ((i & 1) == 1) // if (i % 2 == 1)  ... more efficient ??? At least the same.
                        {
                            Swap(ref items[i], ref items[indexes[i]]);
                        }
                        else
                        {
                            Swap(ref items[i], ref items[0]);
                        }
    
                        if (funcExecuteAndTellIfShouldStop(items))
                        {
                            return true;
                        }
    
                        indexes[i]++;
                        i = 1;
                    }
                    else
                    {
                        indexes[i++] = 0;
                    }
                }
    
                return false;
            }
    
            /// <summary>
            /// This function is to show a linq way but is far less efficient
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="list"></param>
            /// <param name="length"></param>
            /// <returns></returns>
            static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
            {
                if (length == 1) return list.Select(t => new T[] { t });
    
                return GetPermutations(list, length - 1)
                    .SelectMany(t => list.Where(e => !t.Contains(e)),
                        (t1, t2) => t1.Concat(new T[] { t2 }));
            }
    
            /// <summary>
            /// Swap 2 elements of same type
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="a"></param>
            /// <param name="b"></param>
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            static void Swap<T>(ref T a, ref T b)
            {
                T temp = a;
                a = b;
                b = temp;
            }
    
            /// <summary>
            /// Func to show how to call. It does a little test for an array of 4 items.
            /// </summary>
            public static void Test()
            {
                ForAllPermutation("123".ToCharArray(), (vals) =>
                {
                    Debug.Print(String.Join("", vals));
                    return false;
                });
    
                int[] values = new int[] { 0, 1, 2, 4 };
    
                Debug.Print("Non Linq");
                ForAllPermutation(values, (vals) =>
                {
                    Debug.Print(String.Join("", vals));
                    return false;
                });
    
                Debug.Print("Linq");
                foreach(var v in GetPermutations(values, values.Length))
                {
                    Debug.Print(String.Join("", v));
                }
    
                // Performance
                int count = 0;
    
                values = new int[10];
                for(int n = 0; n < values.Length; n++)
                {
                    values[n] = n;
                }
    
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Reset();
                stopWatch.Start();
    
                ForAllPermutation(values, (vals) =>
                {
                    foreach(var v in vals)
                    {
                        count++;
                    }
                    return false;
                });
    
                stopWatch.Stop();
                Debug.Print($"Non Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs");
    
                count = 0;
                stopWatch.Reset();
                stopWatch.Start();
    
                foreach (var vals in GetPermutations(values, values.Length))
                {
                    foreach (var v in vals)
                    {
                        count++;
                    }
                }
    
                stopWatch.Stop();
                Debug.Print($"Linq {count} items in {stopWatch.ElapsedMilliseconds} millisecs");
    
            }
        }
    }
    

How to use WinForms progress bar?

Hey there's a useful tutorial on Dot Net pearls: http://www.dotnetperls.com/progressbar

In agreement with Peter, you need to use some amount of threading or the program will just hang, somewhat defeating the purpose.

Example that uses ProgressBar and BackgroundWorker: C#

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            // Start the BackgroundWorker.
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 1; i <= 100; i++)
            {
                // Wait 100 milliseconds.
                Thread.Sleep(100);
                // Report progress.
                backgroundWorker1.ReportProgress(i);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Change the value of the ProgressBar to the BackgroundWorker progress.
            progressBar1.Value = e.ProgressPercentage;
            // Set the text.
            this.Text = e.ProgressPercentage.ToString();
        }
    }
} //closing here

Proper way to concatenate variable strings

Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):

{{ var1 + '-' + var2 + '-' + var3 }}

If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:

e.g. To concatenate our 3 vars, and get a sha512 hash:

{{ (var1 + var2 + var3) | hash('sha512') }}

Note: this works on Ansible 2.3. I haven't tested it on earlier versions.

Pass by Reference / Value in C++

My understanding of the words "If the function modifies that value, the modifications appear also within the scope of the calling function for both passing by value and by reference" is that they are an error.

Modifications made in a called function are not in scope of the calling function when passing by value.

Either you have mistyped the quoted words or they have been extracted out of whatever context made what appears to be wrong, right.

Could you please ensure you have correctly quoted your source and if there are no errors there give more of the text surrounding that statement in the source material.

Understanding the difference between Object.create() and new SomeFunction()

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

Yes, Object.create builds an object that inherits directly from the one passed as its first argument.

With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:

var o = new SomeConstructor();

In the above example, o inherits directly from SomeConstructor.prototype.

There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.

You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.

Well, you can create closures, e.g. using property descriptors argument:

var o = Object.create({inherited: 1}, {
  foo: {
    get: (function () { // a closure
      var closured = 'foo';
      return function () {
        return closured+'bar';
      };
    })()
  }
});

o.foo; // "foobar"

Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.

The method is starting to be natively implemented on latest browsers, check this compatibility table.

Python ValueError: too many values to unpack

Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity into (m, k).

My crystal ball says m.type and m.purity are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)

To fix this, you can iterate explicitly over the items of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.

(In 2.x, itervalues, iterkeys, and iteritems are typically a better idea; the non-iter versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter versions which just set up an iterator.)

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

VBA setting the formula for a cell

Try:

.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address

If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.

If this does not resolve it, please provide more information about the specific error or failure.

Update

In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:

strProjectName = Replace(strProjectName," ", "_")

But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:

  1. The file browse dialog appears
  2. The formula returns #REF error

The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.

So you need to do:

Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")

Then, your formula should work.

How can I generate random alphanumeric strings?

Question: Why should I waste my time using Enumerable.Range instead of typing in "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"?

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    public static void Main()
    {
        var randomCharacters = GetRandomCharacters(8, true);
        Console.WriteLine(new string(randomCharacters.ToArray()));
    }

    private static List<char> getAvailableRandomCharacters(bool includeLowerCase)
    {
        var integers = Enumerable.Empty<int>();
        integers = integers.Concat(Enumerable.Range('A', 26));
        integers = integers.Concat(Enumerable.Range('0', 10));

        if ( includeLowerCase )
            integers = integers.Concat(Enumerable.Range('a', 26));

        return integers.Select(i => (char)i).ToList();
    }

    public static IEnumerable<char> GetRandomCharacters(int count, bool includeLowerCase)
    {
        var characters = getAvailableRandomCharacters(includeLowerCase);
        var random = new Random();
        var result = Enumerable.Range(0, count)
            .Select(_ => characters[random.Next(characters.Count)]);

        return result;
    }
}

Answer: Magic strings are BAD. Did ANYONE notice there was no "I" in my string at the top? My mother taught me not to use magic strings for this very reason...

n.b. 1: As many others like @dtb said, don't use System.Random if you need cryptographic security...

n.b. 2: This answer isn't the most efficient or shortest, but I wanted the space to separate the answer from the question. The purpose of my answer is more to warn against magic strings than to provide a fancy innovative answer.

await vs Task.Wait - Deadlock?

Wait and await - while similar conceptually - are actually completely different.

Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use "async all the way down"; that is, don't block on async code. On my blog, I go into the details of how blocking in asynchronous code causes deadlock.

await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

You also mentioned a "cooperative block", by which I assume you mean a task that you're Waiting on may execute on the waiting thread. There are situations where this can happen, but it's an optimization. There are many situations where it can't happen, like if the task is for another scheduler, or if it's already started or if it's a non-code task (such as in your code example: Wait cannot execute the Delay task inline because there's no code for it).

You may find my async / await intro helpful.

Bulk Insertion in Laravel using eloquent ORM

You can just use Eloquent::insert().

For example:

$data = array(
    array('name'=>'Coder 1', 'rep'=>'4096'),
    array('name'=>'Coder 2', 'rep'=>'2048'),
    //...
);

Coder::insert($data);

CodeIgniter 500 Internal Server Error

This works fine for me

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >

How to get query string parameter from MVC Razor markup?

Similar thread

<div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

EDIT 01-10-2014: Since this question is so popular this answer has been improved.

The example above will only get the values from RouteData, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest. Fastest way is by calling (as TruMan pointed out) `Request.Querystring' so the answer should be:

<div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>

You can also check RouteValues vs QueryString MVC?

EDIT 03-05-2019: Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query object from Context.Request path. So it would be:

<div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div>

Please notice I am using StringValues("1") in the statement because Query returns StringValues struct instead of pure string. That's cleanes way for this scenerio which I've found.

Converting string to byte array in C#

You could use MemoryMarshal API to perform very fast and efficient conversion. String will implicitly be cast to ReadOnlySpan<byte>, as MemoryMarshal.Cast accepts either Span<byte> or ReadOnlySpan<byte> as an input parameter.

public static class StringExtensions
{
    public static byte[] ToByteArray(this string s) => s.ToByteSpan().ToArray(); //  heap allocation, use only when you cannot operate on spans
    public static ReadOnlySpan<byte> ToByteSpan(this string s) => MemoryMarshal.Cast<char, byte>(s);
}

Following benchmark shows the difference:

Input: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,"

|                       Method |       Mean |     Error |    StdDev |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|----------------------------- |-----------:|----------:|----------:|-------:|------:|------:|----------:|
| UsingEncodingUnicodeGetBytes | 160.042 ns | 3.2864 ns | 6.4099 ns | 0.0780 |     - |     - |     328 B |
| UsingMemoryMarshalAndToArray |  31.977 ns | 0.7177 ns | 1.5753 ns | 0.0781 |     - |     - |     328 B |
|           UsingMemoryMarshal |   1.027 ns | 0.0565 ns | 0.1630 ns |      - |     - |     - |         - |

Cannot find pkg-config error

Answer to my question (after several Google searches) revealed the following:

$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz
$ tar -zxf pkgconfig.tgz && cd pkg-config-0.29
$ ./configure && make install

from the following link: Link showing above

Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!

Doing this fixed my issues as mentioned above.

vertical divider between two columns in bootstrap

Assuming you have a column space, this is an option. Rebalance the columns depending on what you need.

<div class="col-1">
    <div class="col-6 vhr">
    </div>
</div>
.vhr{
  border-right: 1px solid #333;
  height:100%;
}

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

How to get `DOM Element` in Angular 2?

Use ViewChild with #localvariable as shown here,

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

In component,

OLDEST Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

ngAfterViewInit()
{
   this.el.nativeElement.focus();
}


OLD Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer) {}
ngAfterViewInit() {
    this.rd.invokeElementMethod(this.el.nativeElement,'focus');
}


Updated on 22/03(March)/2017

NEW Way

Please note from Angular v4.0.0-rc.3 (2017-03-10) few things have been changed. Since Angular team will deprecate invokeElementMethod, above code no longer can be used.

BREAKING CHANGES

since 4.0 rc.1:

rename RendererV2 to Renderer2
rename RendererTypeV2 to RendererType2
rename RendererFactoryV2 to RendererFactory2

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

console.log(this.rd) will give you following methods and you can see now invokeElementMethod is not there. Attaching img as yet it is not documented.

NOTE: You can use following methods of Rendere2 with/without ViewChild variable to do so many things.

enter image description here

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

How does HTTP file upload work?

An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.

http://www.tutorialspoint.com/http/http_messages.htm

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

Getting input values from text box

This is the sample code for the email and javascript.

params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += "      Query:    ";
content += unescape(params["FormsMultiLine4"]);
var email = "[email protected]";
document.write('<a href="mailto:'+email+'?subject='+subject+'&body='+content+'">SUBMIT QUERY</a>');

JQuery - Call the jquery button click event based on name property

You can use normal CSS selectors to select an element by name using jquery. Like this:

Button Code
<button type="button" name="mybutton">Click Me!</button>

Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

I was able to sort this out using Gorgando's fix, but instead of moving imports away, I commented each out individually, built the app, then edited accordingly until I got rid of them.

Switch statement fall-through...should it be allowed?

It is powerful and dangerous. The biggest problem with fall-through is that it's not explicit. For example, if you come across frequently-edited code that has a switch with fall-throughs, how do you know that's intentional and not a bug?

Anywhere I use it, I ensure that it's properly commented:

switch($var) {
    case 'first':
        // Fall-through
    case 'second':
        i++;
        break;
 }

How to gracefully handle the SIGKILL signal in Java

There is one way to react to a kill -9: that is to have a separate process that monitors the process being killed and cleans up after it if necessary. This would probably involve IPC and would be quite a bit of work, and you can still override it by killing both processes at the same time. I assume it will not be worth the trouble in most cases.

Whoever kills a process with -9 should theoretically know what he/she is doing and that it may leave things in an inconsistent state.

-bash: export: `=': not a valid identifier

You cannot put spaces around the = sign when you do:

export foo=bar

Remove the spaces you have and you should be good to go.

If you type:

export foo = bar

the shell will interpret that as a request to export three names: foo, = and bar. = isn't a valid variable name, so the command fails. The variable name, equals sign and it's value must not be separated by spaces for them to be processed as a simultaneous assignment and export.

Difference between private, public, and protected inheritance

Limiting the visibility of inheritance will make code not able to see that some class inherits another class: Implicit conversions from the derived to the base won't work, and static_cast from the base to the derived won't work either.

Only members/friends of a class can see private inheritance, and only members/friends and derived classes can see protected inheritance.

public inheritance

  1. IS-A inheritance. A button is-a window, and anywhere where a window is needed, a button can be passed too.

    class button : public window { };
    

protected inheritance

  1. Protected implemented-in-terms-of. Rarely useful. Used in boost::compressed_pair to derive from empty classes and save memory using empty base class optimization (example below doesn't use template to keep being at the point):

    struct empty_pair_impl : protected empty_class_1 
    { non_empty_class_2 second; };
    
    struct pair : private empty_pair_impl {
      non_empty_class_2 &second() {
        return this->second;
      }
    
      empty_class_1 &first() {
        return *this; // notice we return *this!
      }
    };
    

private inheritance

  1. Implemented-in-terms-of. The usage of the base class is only for implementing the derived class. Useful with traits and if size matters (empty traits that only contain functions will make use of the empty base class optimization). Often containment is the better solution, though. The size for strings is critical, so it's an often seen usage here

    template<typename StorageModel>
    struct string : private StorageModel {
    public:
      void realloc() {
        // uses inherited function
        StorageModel::realloc();
      }
    };
    

public member

  1. Aggregate

    class pair {
    public:
      First first;
      Second second;
    };
    
  2. Accessors

    class window {
    public:
        int getWidth() const;
    };
    

protected member

  1. Providing enhanced access for derived classes

    class stack {
    protected:
      vector<element> c;
    };
    
    class window {
    protected:
      void registerClass(window_descriptor w);
    };
    

private member

  1. Keep implementation details

    class window {
    private:
      int width;
    };
    

Note that C-style casts purposely allows casting a derived class to a protected or private base class in a defined and safe manner and to cast into the other direction too. This should be avoided at all costs, because it can make code dependent on implementation details - but if necessary, you can make use of this technique.

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Alternative #6233....

Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:

// Using the current date/time
let now_local = new Date();
let now_utc = new Date();

// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())

// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';

// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));

I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:

enter image description here

Start a fragment via Intent within a Fragment

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...

Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.

@Override
public void onClick(View v) {
    // Create new fragment and transaction
    Fragment newFragment = new chartsFragment(); 
    // consider using Java coding conventions (upper first char class names!!!)
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit(); 
}

http://developer.android.com/guide/components/fragments.html#Transactions

SQL Server query to find all current database names

SELECT datname FROM pg_database WHERE datistemplate = false

#for postgres

Most efficient way to concatenate strings in JavaScript?

I have no comment on the concatenation itself, but I'd like to point out that @Jakub Hampl's suggestion:

For building strings in the DOM, in some cases it might be better to iteratively add to the DOM, rather then add a huge string at once.

is wrong, because it's based on a flawed test. That test never actually appends into the DOM.

This fixed test shows that creating the string all at once before rendering it is much, MUCH faster. It's not even a contest.

(Sorry this is a separate answer, but I don't have enough rep to comment on answers yet.)

How to run Selenium WebDriver test cases in Chrome

All the previous answers are correct. Following is the little deep dive into the problem and solution.

The driver constructor in Selenium for example

WebDriver driver = new ChromeDriver();

searches for the driver executable, in this case the Google Chrome driver searches for a Chrome driver executable. In case the service is unable to find the executable, the exception is thrown.

This is where the exception comes from (note the check state method)

 /**
   *
   * @param exeName Name of the executable file to look for in PATH
   * @param exeProperty Name of a system property that specifies the path to the executable file
   * @param exeDocs The link to the driver documentation page
   * @param exeDownload The link to the driver download page
   *
   * @return The driver executable as a {@link File} object
   * @throws IllegalStateException If the executable not found or cannot be executed
   */
  protected static File findExecutable(
      String exeName,
      String exeProperty,
      String exeDocs,
      String exeDownload) {
    String defaultPath = new ExecutableFinder().find(exeName);
    String exePath = System.getProperty(exeProperty, defaultPath);
    checkState(exePath != null,
        "The path to the driver executable must be set by the %s system property;"
            + " for more information, see %s. "
            + "The latest version can be downloaded from %s",
            exeProperty, exeDocs, exeDownload);

    File exe = new File(exePath);
    checkExecutable(exe);
    return exe;
  }

The following is the check state method which throws the exception:

  /**
   * Ensures the truth of an expression involving the state of the calling instance, but not
   * involving any parameters to the calling method.
   *
   * <p>See {@link #checkState(boolean, String, Object...)} for details.
   */
  public static void checkState(
      boolean b,
      @Nullable String errorMessageTemplate,
      @Nullable Object p1,
      @Nullable Object p2,
      @Nullable Object p3) {
    if (!b) {
      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
    }
  }

SOLUTION: set the system property before creating driver object as follows.

System.setProperty("webdriver.gecko.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();

The following is the code snippet (for Chrome and Firefox) where the driver service searches for the driver executable:

Chrome:

   @Override
    protected File findDefaultExecutable() {
      return findExecutable("chromedriver", CHROME_DRIVER_EXE_PROPERTY,
          "https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver",
          "http://chromedriver.storage.googleapis.com/index.html");
    }

Firefox:

@Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

where CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver" and GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver"

Similar is the case for other browsers, and the following is the snapshot of the list of the available browser implementation:

Enter image description here

Expected block end YAML error

I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.

Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart.

I have solved it by fixing, the Alignment issue inside the same .yml file.

If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.

Now i am doing well.

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

A generic list of anonymous class

static void Main()
{
    List<int> list = new List<int>();
    list.Add(2);
    list.Add(3);
    list.Add(5);
    list.Add(7);
}

CSS Grid Layout not working in IE11 even with prefixes

Michael has given a very comprehensive answer, but I'd like to point out a few things which you can still do to be able to use grids in IE in a nearly painless way.

The repeat functionality is supported

You can still use the repeat functionality, it's just hiding behind a different syntax. Instead of writing repeat(4, 1fr), you have to write (1fr)[4]. That's it. See this series of articles for the current state of affairs: https://css-tricks.com/css-grid-in-ie-debunking-common-ie-grid-misconceptions/

Supporting grid-gap

Grid gaps are supported in all browsers except IE. So you can use the @supports at-rule to set the grid-gaps conditionally for all new browsers:

Example:

.grid {
  display: grid;
}
.item {
  margin-right: 1rem;
  margin-bottom: 1rem;
}
@supports (grid-gap: 1rem) {
  .grid {
    grid-gap: 1rem;
  }
  .item {
    margin-right: 0;
    margin-bottom: 0;
  }
}

It's a little verbose, but on the plus side, you don't have to give up grids altogether just to support IE.

Use Autoprefixer

I can't stress this enough - half the pain of grids is solved just be using autoprefixer in your build step. Write your CSS in a standards-complaint way, and just let autoprefixer do it's job transforming all older spec properties automatically. When you decide you don't want to support IE, just change one line in the browserlist config and you'll have removed all IE-specific code from your built files.

Java Programming: call an exe from Java and passing parameters

import java.io.IOException;
import java.lang.ProcessBuilder;

public class handlingexe {
    public static void main(String[] args) throws IOException {
        ProcessBuilder p = new ProcessBuilder();
        System.out.println("Started EXE");
        p.command("C:\\Users\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");   

        p.start();
        System.out.println("Started EXE"); 
    }
}

How do I put hint in a asp:textbox

asp:TextBox ID="txtName" placeholder="any text here"

HTML img scaling

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

MySQL create stored procedure syntax with delimiter

Here is the sample MYSQL Stored Procedure with delimiter and how to call..

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
  IN loc_username VARCHAR(255),
  IN loc_password VARCHAR(255)
)
BEGIN

  SELECT user_id,
         user_name,
         user_emailid,
         user_profileimage,
         last_update
    FROM tbl_user
   WHERE user_name = loc_username
     AND password = loc_password
     AND status = 1;

END $$

DELIMITER ;

and call by, mysql_connection specification and

$loginCheck="call sp_user_login('".$username."','".$password."');";

it will return the result from the procedure.

Convert JSON String to JSON Object c#

JObject defines method Parse for this:

JObject json = JObject.Parse(str);

You might want to refer to Json.NET documentation.

How do you get the currently selected <option> in a <select> via JavaScript?

Using the selectedOptions property:

var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);

It works in all browsers except Internet Explorer.

Converting an int or String to a char array on Arduino

  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

    char charBuf[50];
    stringOne.toCharArray(charBuf, 50)
    

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

Just convert the text explicitly to string using str(). Worked for me.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

How can I initialize a String array with length 0 in Java?

Make a function which will not return null instead return an empty array you can go through below code to understand.

    public static String[] getJavaFileNameList(File inputDir) {
    String[] files = inputDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File current, String name) {
            return new File(current, name).isFile() && (name.endsWith("java"));
        }
    });

    return files == null ? new String[0] : files;
}

How to update only one field using Entity Framework?

I know this is an old thread but I was also looking for a similar solution and decided to go with the solution @Doku-so provided. I'm commenting to answer the question asked by @Imran Rizvi , I followed @Doku-so link that shows a similar implementation. @Imran Rizvi's question was that he was getting an error using the provided solution 'Cannot convert Lambda expression to Type 'Expression> [] ' because it is not a delegate type'. I wanted to offer a small modification I made to @Doku-so's solution that fixes this error in case anyone else comes across this post and decides to use @Doku-so's solution.

The issue is the second argument in the Update method,

public int Update(T entity, Expression<Func<T, object>>[] properties). 

To call this method using the syntax provided...

Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn); 

You must add the 'params' keyword in front of the second arugment as so.

public int Update(T entity, params Expression<Func<T, object>>[] properties)

or if you don't want to change the method signature then to call the Update method you need to add the 'new' keyword, specify the size of the array, then finally use the collection object initializer syntax for each property to update as seen below.

Update(Model, new Expression<Func<T, object>>[3] { d=>d.Name }, { d=>d.SecondProperty }, { d=>d.AndSoOn });

In @Doku-so's example he is specifying an array of Expressions so you must pass the properties to update in an array, because of the array you must also specify the size of the array. To avoid this you could also change the expression argument to use IEnumerable instead of an array.

Here is my implementation of @Doku-so's solution.

public int Update<TEntity>(LcmsEntities dataContext, DbEntityEntry<TEntity> entityEntry, params Expression<Func<TEntity, object>>[] properties)
     where TEntity: class
    {
        entityEntry.State = System.Data.Entity.EntityState.Unchanged;

        properties.ToList()
            .ForEach((property) =>
            {
                var propertyName = string.Empty;
                var bodyExpression = property.Body;
                if (bodyExpression.NodeType == ExpressionType.Convert
                    && bodyExpression is UnaryExpression)
                {
                    Expression operand = ((UnaryExpression)property.Body).Operand;
                    propertyName = ((MemberExpression)operand).Member.Name;
                }
                else
                {
                    propertyName = System.Web.Mvc.ExpressionHelper.GetExpressionText(property);
                }

                entityEntry.Property(propertyName).IsModified = true;
            });

        dataContext.Configuration.ValidateOnSaveEnabled = false;

        return dataContext.SaveChanges();
    }

Usage:

this.Update<Contact>(context, context.Entry(modifiedContact), c => c.Active, c => c.ContactTypeId);

@Doku-so provided a cool approach using generic's, I used the concept to solve my issue but you just can't use @Doku-so's solution as is and in both this post and the linked post no one answered the usage error questions.

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

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


Add this column to your model:

public byte[] Content { get; set; }

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

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

        return ms.ToArray();
    }
}

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

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

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

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

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

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

Iterate through pairs of items in a Python list

From the itertools recipes:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for v, w in pairwise(a):
    ...

Common Header / Footer with static HTML

Short of using a local templating system like many hundreds now exist in every scripting language or even using your homebrewed one with sed or m4 and sending the result over to your server, no, you'd need at least SSI.

Spring can you autowire inside an abstract class?

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

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

This error apears when you have some form controls (like Inputs, Selects, etc) in your form group tags with no formControlName property.

Those examples throws the error:

<form [formGroup]="myform">
    <input type="text">
    <input type="text" [ngmodel]="nameProperty">
    <input type="text" [formGroup]="myform" [name]="name">
</fom>

There are two ways, the stand alone:

<form [formGroup]="myform">
    <input type="text" [ngModelOptions]="{standalone: true}">
    <input type="text" [ngmodel]="nameProperty" [ngModelOptions]="{standalone: true}">
    <!-- input type="text" [formGroup]="myform" [name]="name" --> <!-- no works with standalone --
</form>

Or including it into the formgroup

<form [formGroup]="myform">
    <input type="text" formControlName="field1">
    <input type="text" formControlName="nameProperty">
    <input type="text" formControlName="name">
</fom>

The last one implies to define them in the initialization formGroup

this.myForm =  new FormGroup({
    field1: new FormControl(''),
    nameProperty: new FormControl(''),
    name: new FormControl('')
});

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

Tkinter scrollbar for frame

"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"

Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.

"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"

You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.

"What so special about using anchor='nw' when creating window on canvas?"

The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

Read data from a text file using Java

public class ReadFileUsingFileInputStream {

/**
* @param args
*/
static int ch;

public static void main(String[] args) {
    File file = new File("C://text.txt");
    StringBuffer stringBuffer = new StringBuffer("");
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            while((ch = fileInputStream.read())!= -1){
                stringBuffer.append((char)ch);  
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("File contents :");
    System.out.println(stringBuffer);
    }
}

MySQL the right syntax to use near '' at line 1 error

the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.

Either put it on one line or append on each line :o)

Sqlyog must be trimming white spaces on each line which explains why its working.

Example:

$qr2="INSERT INTO wp_bp_activity
      (
            user_id,
 (this stuff)component,
     (is)      `type`,
    (a)        `action`,
  (problem)  content,
             primary_link,
             item_id,....

Combine multiple Collections into a single logical Collection?

With Guava, you can use Iterables.concat(Iterable<T> ...), it creates a live view of all the iterables, concatenated into one (if you change the iterables, the concatenated version also changes). Then wrap the concatenated iterable with Iterables.unmodifiableIterable(Iterable<T>) (I hadn't seen the read-only requirement earlier).

From the Iterables.concat( .. ) JavaDocs:

Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary. The returned iterable's iterator supports remove() when the corresponding input iterator supports it.

While this doesn't explicitly say that this is a live view, the last sentence implies that it is (supporting the Iterator.remove() method only if the backing iterator supports it is not possible unless using a live view)

Sample Code:

final List<Integer> first  = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third  = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
    Iterables.unmodifiableIterable(
        Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9999999]


Edit:

By Request from Damian, here's a similar method that returns a live Collection View

public final class CollectionsX {

    static class JoinedCollectionView<E> implements Collection<E> {

        private final Collection<? extends E>[] items;

        public JoinedCollectionView(final Collection<? extends E>[] items) {
            this.items = items;
        }

        @Override
        public boolean addAll(final Collection<? extends E> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void clear() {
            for (final Collection<? extends E> coll : items) {
                coll.clear();
            }
        }

        @Override
        public boolean contains(final Object o) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean containsAll(final Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean isEmpty() {
            return !iterator().hasNext();
        }

        @Override
        public Iterator<E> iterator() {
            return Iterables.concat(items).iterator();
        }

        @Override
        public boolean remove(final Object o) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean removeAll(final Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean retainAll(final Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        @Override
        public int size() {
            int ct = 0;
            for (final Collection<? extends E> coll : items) {
                ct += coll.size();
            }
            return ct;
        }

        @Override
        public Object[] toArray() {
            throw new UnsupportedOperationException();
        }

        @Override
        public <T> T[] toArray(T[] a) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean add(E e) {
            throw new UnsupportedOperationException();
        }

    }

    /**
     * Returns a live aggregated collection view of the collections passed in.
     * <p>
     * All methods except {@link Collection#size()}, {@link Collection#clear()},
     * {@link Collection#isEmpty()} and {@link Iterable#iterator()}
     *  throw {@link UnsupportedOperationException} in the returned Collection.
     * <p>
     * None of the above methods is thread safe (nor would there be an easy way
     * of making them).
     */
    public static <T> Collection<T> combine(
        final Collection<? extends T>... items) {
        return new JoinedCollectionView<T>(items);
    }

    private CollectionsX() {
    }

}

Implementing IDisposable correctly

You have no need to do your User class being IDisposable since the class doesn't acquire any non-managed resources (file, database connection, etc.). Usually, we mark classes as IDisposable if they have at least one IDisposable field or/and property. When implementing IDisposable, better put it according Microsoft typical scheme:

public class User: IDisposable {
  ...
  protected virtual void Dispose(Boolean disposing) {
    if (disposing) {
      // There's no need to set zero empty values to fields 
      // id = 0;
      // name = String.Empty;
      // pass = String.Empty;

      //TODO: free your true resources here (usually IDisposable fields)
    }
  }

  public void Dispose() {
    Dispose(true);

    GC.SuppressFinalize(this);
  } 
}

How do I connect to my existing Git repository using Visual Studio Code?

  1. Use git clone to clone your repository into a folder (say work). You should see a new subfolder, work/.git.
  2. Open folder work in Visual Studio Code - everything should work fine!

PS: Blow away the temporary folder.

How to Detect Browser Window /Tab Close Event?

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

    window.onbeforeunload = function () {
        return "Are you sure?";
    }

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });

SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

    SELECT COUNT(*) FROM your_table;

bash: mkvirtualenv: command not found

Prerequisites to execute this command -

  1. pip (recursive acronym of Pip Installs Packages) is a package management system used to install and manage software packages written in Python. Many packages can be found in the Python Package Index (PyPI).

    sudo apt-get install python-pip

  2. Install Virtual Environment. Used to create virtual environment, to install packages and dependencies of multiple projects isolated from each other.

    sudo pip install virtualenv

  3. Install virtual environment wrapper About virtual env wrapper

    sudo pip install virtualenvwrapper

After Installing prerequisites you need to bring virtual environment wrapper into action to create virtual environment. Following are the steps -

  1. set virtual environment directory in path variable- export WORKON_HOME=(directory you need to save envs)

  2. source /usr/local/bin/virtualenvwrapper.sh -p $WORKON_HOME

As mentioned by @Mike, source `which virtualenvwrapper.sh` or which virtualenvwrapper.sh can used to locate virtualenvwrapper.sh file.

It's best to put above two lines in ~/.bashrc to avoid executing the above commands every time you open new shell. That's all you need to create environment using mkvirtualenv

Points to keep in mind -

  • Under Ubuntu, you may need install virtualenv and virtualenvwrapper as root. Simply prefix the command above with sudo.
  • Depending on the process used to install virtualenv, the path to virtualenvwrapper.sh may vary. Find the appropriate path by running $ find /usr -name virtualenvwrapper.sh. Adjust the line in your .bash_profile or .bashrc script accordingly.

How do you create a temporary table in an Oracle database?

Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE, not DROP) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).

Parse HTML table to Python list?

Sven Marnach excellent solution is directly translatable into ElementTree which is part of recent Python distributions:

from xml.etree import ElementTree as ET

s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""

table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print(dict(zip(headers, values)))

same output as Sven Marnach's answer...

Multiple returns from a function

There is no way of returning 2 variables. Although, you can propagate an array and return it; create a conditional to return a dynamic variable, etc.

For instance, this function would return $var2

function wtf($blahblah = true) {
    $var1 = "ONe";
    $var2 = "tWo";

    if($blahblah === true) {
      return $var2;
    }
    return $var1;
}

In application:

echo wtf();
//would echo: tWo
echo wtf("not true, this is false");
//would echo: ONe

If you wanted them both, you could modify the function a bit

function wtf($blahblah = true) {
    $var1 = "ONe";
    $var2 = "tWo";

    if($blahblah === true) {
      return $var2;
    }

    if($blahblah == "both") {
      return array($var1, $var2);
    }

    return $var1;
}

echo wtf("both")[0]
//would echo: ONe
echo wtf("both")[1]
//would echo: tWo

list($first, $second) = wtf("both")
// value of $first would be $var1, value of $second would be $var2

Creating a LinkedList class from scratch

How about a fully functional implementation of a non-recursive Linked List?

I created this for my Algorithms I class as a stepping stone to gain a better understanding before moving onto writing a doubly-linked queue class for an assignment.

Here's the code:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<T> implements Iterable<T> {
    private Node first;
    private Node last;
    private int N;

    public LinkedList() {
        first = null;
        last = null;
        N = 0;
    }

    public void add(T item) {
        if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
        if (!isEmpty()) {
            Node prev = last;
            last = new Node(item, null);
            prev.next = last;
        }
        else {
            last = new Node(item, null);
            first = last;
        }
        N++;
    }

    public boolean remove(T item) {
        if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
        boolean result = false;
        Node prev = first;
        Node curr = first;
        while (curr.next != null || curr == last) {
            if (curr.data.equals(item)) {
                // remove the last remaining element
                if (N == 1) { first = null; last = null; }
                // remove first element
                else if (curr.equals(first)) { first = first.next; }
                // remove last element
                else if (curr.equals(last)) { last = prev; last.next = null; }
                // remove element
                else { prev.next = curr.next; }
                N--;
                result = true;
                break;
            }
            prev = curr;
            curr = prev.next;
        }
        return result;
    }

    public int size() {
        return N;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    private class Node {
        private T data;
        private Node next;

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    public Iterator<T> iterator() { return new LinkedListIterator(); }

    private class LinkedListIterator implements Iterator<T> {
        private Node current = first;

        public T next() {
            if (!hasNext()) { throw new NoSuchElementException(); }
            T item = current.data;
            current = current.next;
            return item;
        }

        public boolean hasNext() { return current != null; }

        public void remove() { throw new UnsupportedOperationException(); }
    }

    @Override public String toString() {
        StringBuilder s = new StringBuilder();
        for (T item : this)
            s.append(item + " ");
        return s.toString();
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        while(!StdIn.isEmpty()) {
            String input = StdIn.readString();
            if (input.equals("print")) { StdOut.println(list.toString()); continue; }
            if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
            if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
            break;
        }
    }
}

Note: It's a pretty basic implementation of a singly-linked-list. The 'T' type is a generic type placeholder. Basically, this linked list should work with any type that inherits from Object. If you use it for primitive types be sure to use the nullable class equivalents (ex 'Integer' for the 'int' type). The 'last' variable isn't really necessary except that it shortens insertions to O(1) time. Removals are slow since they run in O(N) time but it allows you to remove the first occurrence of a value in the list.

If you want you could also look into implementing:

  • addFirst() - add a new item to the beginning of the LinkedList
  • removeFirst() - remove the first item from the LinkedList
  • removeLast() - remove the last item from the LinkedList
  • addAll() - add a list/array of items to the LinkedList
  • removeAll() - remove a list/array of items from the LinkedList
  • contains() - check to see if the LinkedList contains an item
  • contains() - clear all items in the LinkedList

Honestly, it only takes a few lines of code to make this a doubly-linked list. The main difference between this and a doubly-linked-list is that the Node instances of a doubly-linked list require an additional reference that points to the previous element in the list.

The benefit of this over a recursive implementation is that it's faster and you don't have to worry about flooding the stack when you traverse large lists.

There are 3 commands to test this in the debugger/console:

  • Prefixing a value by a '+' will add it to the list.
  • Prefixing with a '-' will remove the first occurrence from the list.
  • Typing 'print' will print out the list with the values separated by spaces.

If you have never seen the internals of how one of these works I suggest you step through the following in the debugger:

  • add() - tacks a new node onto the end or initializes the first/last values if the list is empty
  • remove() - walks the list from the start-to-end. If it finds a match it removes that item and connects the broken links between the previous and next links in the chain. Special exceptions are added when there is no previous or next link.
  • toString() - uses the foreach iterator to simply walk the list chain from beginning-to-end.

While there are better and more efficient approaches for lists like array-lists, understanding how the application traverses via references/pointers is integral to understanding how many higher-level data structures work.

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

Using $window or $location to Redirect in AngularJS

It seems that for full page reload $window.location.href is the preferred way.

It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.

https://docs.angularjs.org/guide/$location

document.getElementById().value doesn't set the value

The only case I could imagine is, that you run this on a webkit browser like Chrome or Safari and your return value in responseText, contains a string value.

In that constelation, the value cannot be displayed (it would get blank)

Example: http://jsfiddle.net/BmhNL/2/


My point here is, that I expect a wrong/double encoded string value. Webkit browsers are more strict on the type = number. If there is "only" a white-space issue, you can try to implicitly call the Number() constructor, like

document.getElementById("points").value = +request.responseText;

Array functions in jQuery

Have a look at https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array for documentation on JavaScript Arrays.
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!

Laravel 5 Class 'form' not found

Form isn't included in laravel 5.0 as it was on 4.0, steps to include it:

Begin by installing laravelcollective/html package through Composer. Edit your project's composer.json file to require:

"require": {
    "laravelcollective/html": "~5.0"
}

Next, update composer from the Terminal:

composer update

Next, add your new provider to the providers array of config/app.php:

'providers' => [
  // ...
  'Collective\Html\HtmlServiceProvider',
  // ...
],

Finally, add two class aliases to the aliases array of config/app.php:

'aliases' => [
// ...
  'Form' => 'Collective\Html\FormFacade',
  'Html' => 'Collective\Html\HtmlFacade',
// ...
],

At this point, Form should be working

Source


Update Laravel 5.8 (2019-04-05):

In Laravel 5.8, the providers in the config/app.php can be declared as:

Collective\Html\HtmlServiceProvider::class,

instead of:

'Collective\Html\HtmlServiceProvider',

This notation is the same for the aliases.

Java Desktop application: SWT vs. Swing

One thing to consider: Screenreaders

For some reasons, some Swing components do not work well when using a screenreader (and the Java AccessBridge for Windows). Know that different screenreaders result in different behaviour. And in my experience the SWT-Tree performs a lot better than the Swing-Tree in combination with a screenreader. Thus our application ended up in using both SWT and Swing components.

For distributing and loading the proper SWT-library, you might find this link usefull: http://www.chrisnewland.com/select-correct-swt-jar-for-your-os-and-jvm-at-runtime-191

How to fully delete a git repository created with init?

You can create an alias for it. I am using ZSH shell with Oh-my-Zsh and here is an handy alias:

# delete and re-init git
# usage: just type 'gdelinit' in a local repository
alias gdelinit="trash .git && git init"

I am using Trash to trash the .git folder since using rm is really dangerous:

trash .git

Then I am re-initializing the git repo:

git init

Resolve absolute path from relative path and/or file name

Small improvement to BrainSlugs83's excellent solution. Generalized to allow naming the output environment variable in the call.

@echo off
setlocal EnableDelayedExpansion

rem Example input value.
set RelativePath=doc\build

rem Resolve path.
call :ResolvePath AbsolutePath %RelativePath%

rem Output result.
echo %AbsolutePath%

rem End.
exit /b

rem === Functions ===

rem Resolve path to absolute.
rem Param 1: Name of output variable.
rem Param 2: Path to resolve.
rem Return: Resolved absolute path.
:ResolvePath
    set %1=%~dpfn2
    exit /b

If run from C:\project output is:

C:\project\doc\build

Not Able To Debug App In Android Studio

Sync your project with Gradle files and that shall help.

How to install psycopg2 with "pip" on Python?

On OSX 10.11.6 (El Capitan)

brew install postgresql
PATH=$PATH:/Library/PostgreSQL/9.4/bin pip install psycopg2

How to switch Python versions in Terminal?

pyenv is a 3rd party version manager which is super commonly used (18k stars, 1.6k forks) and exactly what I looked for when I came to this question.

Install pyenv.

Usage

$ pyenv install --list
Available versions:
  2.1.3
  [...]
  3.8.1
  3.9-dev
  activepython-2.7.14
  activepython-3.5.4
  activepython-3.6.0
  anaconda-1.4.0
  [... a lot more; including anaconda, miniconda, activepython, ironpython, pypy, stackless, ....]

$ pyenv install 3.8.1
Downloading Python-3.8.1.tar.xz...
-> https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tar.xz
Installing Python-3.8.1...
Installed Python-3.8.1 to /home/moose/.pyenv/versions/3.8.1

$ pyenv versions
* system (set by /home/moose/.pyenv/version)
  2.7.16
  3.5.7
  3.6.9
  3.7.4
  3.8-dev

$ python --version
Python 2.7.17
$ pip --version
pip 19.3.1 from /home/moose/.local/lib/python3.6/site-packages/pip (python 3.6)

$ mkdir pyenv-experiment && echo "3.8.1" > "pyenv-experiment/.python-version"
$ cd pyenv-experiment

$ python --version
Python 3.8.1
$ pip --version
pip 19.2.3 from /home/moose/.pyenv/versions/3.8.1/lib/python3.8/site-packages/pip (python 3.8)

What is the difference between require() and library()?

Another benefit of require() is that it returns a logical value by default. TRUE if the packages is loaded, FALSE if it isn't.

> test <- library("abc")
Error in library("abc") : there is no package called 'abc'
> test
Error: object 'test' not found
> test <- require("abc")
Loading required package: abc
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'abc'
> test
[1] FALSE

So you can use require() in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.

if(require("lme4")){
    print("lme4 is loaded correctly")
} else {
    print("trying to install lme4")
    install.packages("lme4")
    if(require(lme4)){
        print("lme4 installed and loaded")
    } else {
        stop("could not install lme4")
    }
}

Import existing source code to GitHub

  1. Open your GitHub dashboard (it's at https://github.com/ if you're logged in)
  2. Click on New Repository
  3. Fill in the blanks; click on Create Repository
  4. Follow instructions on the page that appears then

How to correctly save instance state of Fragments in back stack?

This is the way I am using at this moment... it's very complicated but at least it handles all the possible situations. In case anyone is interested.

public final class MyFragment extends Fragment {
    private TextView vstup;
    private Bundle savedState = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.whatever, null);
        vstup = (TextView)v.findViewById(R.id.whatever);

        /* (...) */

        /* If the Fragment was destroyed inbetween (screen rotation), we need to recover the savedState first */
        /* However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it */
        if(savedInstanceState != null && savedState == null) {
            savedState = savedInstanceState.getBundle(App.STAV);
        }
        if(savedState != null) {
            vstup.setText(savedState.getCharSequence(App.VSTUP));
        }
        savedState = null;

        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        savedState = saveState(); /* vstup defined here for sure */
        vstup = null;
    }

    private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
        Bundle state = new Bundle();
        state.putCharSequence(App.VSTUP, vstup.getText());
        return state;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /* If onDestroyView() is called first, we can use the previously savedState but we can't call saveState() anymore */
        /* If onSaveInstanceState() is called first, we don't have savedState, so we need to call saveState() */
        /* => (?:) operator inevitable! */
        outState.putBundle(App.STAV, (savedState != null) ? savedState : saveState());
    }

    /* (...) */

}

Alternatively, it is always a possibility to keep the data displayed in passive Views in variables and using the Views only for displaying them, keeping the two things in sync. I don't consider the last part very clean, though.

Accessing dictionary value by index in python

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

How can I debug git/git-shell related problems?

For older git versions (1.8 and before)

I could find no suitable way to enable SSH debugging in an older git and ssh versions. I looked for environment variables using ltrace -e getenv ... and couldn't find any combination of GIT_TRACE or SSH_DEBUG variables that would work.

Instead here's a recipe to temporarily inject 'ssh -v' into the git->ssh sequence:

$ echo '/usr/bin/ssh -v ${@}' >/tmp/ssh
$ chmod +x /tmp/ssh
$ PATH=/tmp:${PATH} git clone ...
$ rm -f /tmp/ssh

Here's output from git version 1.8.3 with ssh version OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013 cloning a github repo:

$ (echo '/usr/bin/ssh -v ${@}' >/tmp/ssh; chmod +x /tmp/ssh; PATH=/tmp:${PATH} \
   GIT_TRACE=1 git clone https://github.com/qneill/cliff.git; \
   rm -f /tmp/ssh) 2>&1 | tee log
trace: built-in: git 'clone' 'https://github.com/qneill/cliff.git'
trace: run_command: 'git-remote-https' 'origin' 'https://github.com/qneill/cliff.git'
Cloning into 'cliff'...
OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
debug1: Reading configuration data /home/q.neill/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to github.com ...
...
Transferred: sent 4120, received 724232 bytes, in 0.2 seconds
Bytes per second: sent 21590.6, received 3795287.2
debug1: Exit status 0
trace: run_command: 'rev-list' '--objects' '--stdin' '--not' '--all'
trace: exec: 'git' 'rev-list' '--objects' '--stdin' '--not' '--all'
trace: built-in: git 'rev-list' '--objects' '--stdin' '--not' '--all'

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

I was having this same issue this morning. When I checked my Device Manager, it showed COM4 properly, and when I checked in the Arduino IDE COM4 just wasn't an option. Only COM1 was listed.
I tried unplugging and plugging my Arduino in and out a couple more times and eventually COM4 showed up again in the IDE. I didn't have to change any settings.
Hopefully that helps somebody.

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

I do the "in clause" query with spring jdbc like this:

String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";

List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template = 
    new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

List<Long> list = template.queryForList(sql, paramMap, Long.class);

Difference between if () { } and if () : endif;

Personally I prefer making it in two seperate sections but within the same PHP like:

<?php 
    if (question1) { $variable_1 = somehtml; }
    else { $variable_1 = someotherhtml; } 

    if (question2) {
        $variable_2 = somehtml2;
    }

    else { 
        $variable_2 = someotherhtml2;
    }         

etc.
$output=<<<HERE
htmlhtmlhtml$variable1htmlhtmlhtml$varianble2htmletcetcetc
HERE;
echo $output;

?>

But maybe it is slower?

How do I convert NSMutableArray to NSArray?

In objective-c :

NSArray *myArray = [myMutableArray copy];

In swift :

 var arr = myMutableArray as NSArray

In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote

,"vote": {
  ".read" : true
  ,".write" : true
  ,"$issue" : {
    "user" : {
      "$user" : {
        ".validate" : "!data.exists() && 
             newData.val()==data.parent().parent().child('count').getPriority()+1 &&
             newData.val()==newData.GetPriority()" 

user can only vote once && count must be one higher than current count && data value must be same as priority.

      }
    }
    ,"count" : {
      ".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
             newData.getPriority()==data.getPriority()+1 "
    }

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

  }
}

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
  window.fb = new Firebase('https:...vote/iss1/');
  window.fb.child('count').once('value', function (dss) {
    votes = dss.getPriority();
    for (var i=1;i<10;i++) vote(dss,i+votes);
  } );

function vote(dss,count)
{
  var user='user/zz' + count; // replace with auth.id or whatever
  window.fb.child(user).setWithPriority(count,count);
  window.fb.child('count').setWithPriority(user,count);
}
</script>

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

How to ignore ansible SSH authenticity checking?

Use the parameter named as validate_certs to ignore the ssh validation

- ec2_ami:
    instance_id: i-0661fa8b45a7531a7
    wait: yes
    name: ansible
    validate_certs: false
    tags:
      Name: ansible
      Service: TestService

By doing this it ignores the ssh validation process

How to return only the Date from a SQL Server DateTime datatype

My Style

      select Convert(smalldatetime,Convert(int,Convert(float,getdate())))

How do I install SciPy on 64 bit Windows?

Okey, here I am going to share what I have done to install SciPy on my Windows PC without the command line.

My PC configuration is Windows 7 64-bit and Python 2.7

  • First I download the required packages form http://www.lfd.uci.edu/~gohlke/pythonlibs/ (which version match your configuration EX: cp27==>python2.7 & cp35==>3.5)
  • Second I extract the file using 7-Zip (also can be used any zipper like WinRAR)
  • Third I copy the scipy folder which I extracted and paste it into C:\Python27\Lib\site-packages (or put it where the exact location is in your PC like ..\..\Lib\site-packages)

NOTE: You have to install NumPy first before installing SciPy in this same way.

What is the difference between NULL, '\0' and 0?

A one-L NUL, it ends a string.

A two-L NULL points to no thing.

And I will bet a golden bull

That there is no three-L NULLL.

How do you deal with NUL?

Cannot read property 'getContext' of null, using canvas

I guess the problem is your js runs before the html is loaded.

If you are using jquery, you can use the document ready function to wrap your code:

$(function() {
    var Grid = function(width, height) {
        // codes...
    }
});

Or simply put your js after the <canvas>.

How to parse date string to Date?

Here is a working example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class j4496359 {
    public static void main(String[] args) {
        try {
            String target = "Thu Sep 28 20:29:30 JST 2000";
            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
            Date result =  df.parse(target);
            System.out.println(result); 
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
    }
}

Will print:

Thu Sep 28 13:29:30 CEST 2000

What is "Connect Timeout" in sql server connection string?

Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. (MSDN, SqlConnection.ConnectionTimeout Property, 2013)

Get a list of dates between two dates

DELIMITER $$  
CREATE PROCEDURE popula_calendario_controle()
   BEGIN
      DECLARE a INT Default 0;
      DECLARE first_day_of_year DATE;
      set first_day_of_year = CONCAT(DATE_FORMAT(curdate(),'%Y'),'-01-01');
      one_by_one: LOOP
         IF dayofweek(adddate(first_day_of_year,a)) <> 1 THEN
            INSERT INTO calendario.controle VALUES(null,150,adddate(first_day_of_year,a),adddate(first_day_of_year,a),1);
         END IF;
         SET a=a+1;
         IF a=365 THEN
            LEAVE one_by_one;
         END IF;
      END LOOP one_by_one;
END $$

this procedure will insert all dates from the beginning of the year till now, just substitue the days of the "start" and "end", and you are ready to go!

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

Java - No enclosing instance of type Foo is accessible

Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.

 public class PQ {

    public static void main(String[] args) {

        // create dog object here
        Dog dog = new PQ().new Dog();
        //OR
        PQ pq = new PQ();
        Dog dog1 = pq.new Dog();
    }

    abstract class Animal {
        abstract void checkup();
    }

    class Dog extends Animal {
        @Override
        void checkup() {
            System.out.println("Dog checkup");

        }
    }

    class Cat extends Animal {
        @Override
        void checkup() {
            System.out.println("Cat Checkup");

        }
    }
}

NoClassDefFoundError in Java: com/google/common/base/Function

A NoClassDefFoundError is thrown when the JRE can't find a class. In your case, it can't find the class com.google.common.base.Function, which you most probably did not add to your classpath.

EDIT

After downloading the following libraries:

and unzipping them and putting all JAR files in a folder called lib, the test class:

import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {
    public static void main(String[] args) {
        try{
            FirefoxDriver driver = new FirefoxDriver();
            driver.get("http:www.yahoo.com");
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

ran without any problems.

You can compile and run the class as follows:

# compile and run on Linux & Mac
javac -cp .:lib/* Test.java 
java -cp .:lib/* Test

# compile and run on Windows
javac -cp .;lib/* Test.java 
java -cp .;lib/* Test

What are the differences between a program and an application?

A "program" can be as simple as a "set of instructions" to implement a logic.

It can be part of an "application", "component", "service" or another "program".

Application is a possibly a collection of coordinating program instances to solve a user's purpose.

Histogram with Logarithmic Scale and custom breaks

A histogram is a poor-man's density estimate. Note that in your call to hist() using default arguments, you get frequencies not probabilities -- add ,prob=TRUE to the call if you want probabilities.

As for the log axis problem, don't use 'x' if you do not want the x-axis transformed:

plot(mydata_hist$count, log="y", type='h', lwd=10, lend=2)

gets you bars on a log-y scale -- the look-and-feel is still a little different but can probably be tweaked.

Lastly, you can also do hist(log(x), ...) to get a histogram of the log of your data.

When to use RSpec let()?

let is functional as its essentially a Proc. Also its cached.

One gotcha I found right away with let... In a Spec block that is evaluating a change.

let(:object) {FactoryGirl.create :object}

expect {
  post :destroy, id: review.id
}.to change(Object, :count).by(-1)

You'll need to be sure to call let outside of your expect block. i.e. you're calling FactoryGirl.create in your let block. I usually do this by verifying the object is persisted.

object.persisted?.should eq true

Otherwise when the let block is called the first time a change in the database will actually happen due to the lazy instantiation.

Update

Just adding a note. Be careful playing code golf or in this case rspec golf with this answer.

In this case, I just have to call some method to which the object responds. So I invoke the _.persisted?_ method on the object as its truthy. All I'm trying to do is instantiate the object. You could call empty? or nil? too. The point isn't the test but bringing the object ot life by calling it.

So you can't refactor

object.persisted?.should eq true

to be

object.should be_persisted 

as the object hasn't been instantiated... its lazy. :)

Update 2

leverage the let! syntax for instant object creation, which should avoid this issue altogether. Note though it will defeat a lot of the purpose of the laziness of the non banged let.

Also in some instances you might actually want to leverage the subject syntax instead of let as it may give you additional options.

subject(:object) {FactoryGirl.create :object}

How can I add spaces between two <input> lines using CSS?

You can also wrap your text in label fields, so your form will be more self-explainable semantically.

Just remember to float labels and inputs to the left and to add a specific width to them, and the containing form. Then you can add margins to both of them, to adjust the spacing between the lines (you understand, of course, that this is a pretty minimal markup that expects content to be as big as to some limit).

That way you wont have to add any more elements, just the label-input pairs, all of them wrapped in a form element.

For example:

<form>
<label for="txtName">Name</label>
<input id"txtName" type="text">
<label for="txtEmail">Email</label>
<input id"txtEmail" type="text">
<label for="txtAddress">Address</label>
<input id"txtAddress" type="text">
...
<input type="submit" value="Submit The Form">
</form>

And the css will be:

form{
float:left; /*to clear the floats of inner elements,usefull if you wanna add a border or background image*/
width:300px;
}
label{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
input{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}

Efficient iteration with index in Scala

Indeed, calling zipWithIndex on a collection will traverse it and also create a new collection for the pairs. To avoid this, you can just call zipWithIndex on the iterator for the collection. This will just return a new iterator that keeps track of the index while iterating, so without creating an extra collection or additional traversing.

This is how scala.collection.Iterator.zipWithIndex is currently implemented in 2.10.3:

  def zipWithIndex: Iterator[(A, Int)] = new AbstractIterator[(A, Int)] {
    var idx = 0
    def hasNext = self.hasNext
    def next = {
      val ret = (self.next, idx)
      idx += 1
      ret
    }
  }

This should even be a bit more efficient than creating a view on the collection.

How to redirect stderr and stdout to different files in the same line in script?

Try this:

your_command 2>stderr.log 1>stdout.log

More information

The numerals 0 through 9 are file descriptors in bash. 0 stands for standard input, 1 stands for standard output, 2 stands for standard error. 3 through 9 are spare for any other temporary usage.

Any file descriptor can be redirected to a file or to another file descriptor using the operator >. You can instead use the operator >> to appends to a file instead of creating an empty one.

Usage:

file_descriptor > filename

file_descriptor > &file_descriptor

Please refer to Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.

How do I convert a double into a string in C++?

I would look at the C++ String Toolkit Libary. Just posted a similar answer elsewhere. I have found it very fast and reliable.

#include <strtk.hpp>

double pi = M_PI;
std::string pi_as_string  = strtk::type_to_string<double>( pi );

Cordova - Error code 1 for command | Command failed for

Delete all the apk files from platfroms >> android >> build >> generated >> outputs >> apk and run command cordova run android

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

If in your XML you have layout with id "root" It`s problem, just change id name

Python - How to cut a string in Python?

string = 'http://www.domain.com/?s=some&two=20'
cut_string = string.split('&')
new_string = cut_string[0]
print(new_string)

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

The problem you're having is the NSAutoresizingMaskLayoutConstraints should not be in there. This is the old system of springs and struts. To get rid of it, run this method on each view that you're wanting to constrain:

[view setTranslatesAutoresizingMaskIntoConstraints:NO];

How to call a method with a separate thread in Java?

Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        // code goes here.
    }
});  
t1.start();

or

new Thread(new Runnable() {
     @Override
     public void run() {
          // code goes here.
     }
}).start();

or

new Thread(() -> {
    // code goes here.
}).start();

or

Executors.newSingleThreadExecutor().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});

or

Executors.newCachedThreadPool().execute(new Runnable() {
    @Override
    public void run() {
        myCustomMethod();
    }
});

How do I get an OAuth 2.0 authentication token in C#

https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.

Can we pass model as a parameter in RedirectToAction?

  [HttpPost]
    public async Task<ActionResult> Capture(string imageData)
    {                      
        if (imageData.Length > 0)
        {
            var imageBytes = Convert.FromBase64String(imageData);
            using (var stream = new MemoryStream(imageBytes))
            {
                var result = (JsonResult)await IdentifyFace(stream);
                var serializer = new JavaScriptSerializer();
                var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));

                if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });

            }
        }

        return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);

    }


// GET: Auth
    [HttpGet]
    public ActionResult Index(string param)
    {
        var serializer = new JavaScriptSerializer();
        var faceRecon = serializer.Deserialize<FaceIdentity>(param);


        return View(faceRecon);
    }

ASP.NET MVC View Engine Comparison

ASP.NET MVC View Engines (Community Wiki)

Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine (e.g. VirtualPathProviderViewEngine) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.


System.Web.Mvc.WebFormViewEngine

Design Goals:

A view engine that is used to render a Web Forms page to the response.

Pros:

  • ubiquitous since it ships with ASP.NET MVC
  • familiar experience for ASP.NET developers
  • IntelliSense
  • can choose any language with a CodeDom provider (e.g. C#, VB.NET, F#, Boo, Nemerle)
  • on-demand compilation or precompiled views

Cons:

  • usage is confused by existence of "classic ASP.NET" patterns which no longer apply in MVC (e.g. ViewState PostBack)
  • can contribute to anti-pattern of "tag soup"
  • code-block syntax and strong-typing can get in the way
  • IntelliSense enforces style not always appropriate for inline code blocks
  • can be noisy when designing simple templates

Example:

<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
    <% foreach(var p in model){%>
    <li><%=p.Name%></li>
    <%}%>
</ul>
<%}else{%>
    <p>No products available</p>
<%}%>

System.Web.Razor

Design Goals:

Pros:

  • Compact, Expressive, and Fluid
  • Easy to Learn
  • Is not a new language
  • Has great Intellisense
  • Unit Testable
  • Ubiquitous, ships with ASP.NET MVC

Cons:

  • Creates a slightly different problem from "tag soup" referenced above. Where the server tags actually provide structure around server and non-server code, Razor confuses HTML and server code, making pure HTML or JS development challenging (see Con Example #1) as you end up having to "escape" HTML and / or JavaScript tags under certain very common conditions.
  • Poor encapsulation+reuseability: It's impractical to call a razor template as if it were a normal method - in practice razor can call code but not vice versa, which can encourage mixing of code and presentation.
  • Syntax is very html-oriented; generating non-html content can be tricky. Despite this, razor's data model is essentially just string-concatenation, so syntax and nesting errors are neither statically nor dynamically detected, though VS.NET design-time help mitigates this somewhat. Maintainability and refactorability can suffer due to this.
  • No documented API, http://msdn.microsoft.com/en-us/library/system.web.razor.aspx

Con Example #1 (notice the placement of "string[]..."):

@{
    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}

Bellevue

Design goals:

  • Respect HTML as first-class language as opposed to treating it as "just text".
  • Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
  • Enforce strict Model-View separation

Brail

Design Goals:

The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.

Pros:

  • modeled after "wrist-friendly python syntax"
  • On-demand compiled views (but no precompilation available)

Cons:

  • designed to be written in the language Boo

Example:

<html>    
<head>        
<title>${title}</title>
</head>    
<body>        
     <p>The following items are in the list:</p>  
     <ul><%for element in list:    output "<li>${element}</li>"%></ul>
     <p>I hope that you would like Brail</p>    
</body>
</html>

Hasic

Hasic uses VB.NET's XML literals instead of strings like most other view engines.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular VB.NET code
  • Unit testable

Cons:

  • Performance: Builds the whole DOM before sending it to client.

Example:

Protected Overrides Function Body() As XElement
    Return _
    <body>
        <h1>Hello, World</h1>
    </body>
End Function

NDjango

Design Goals:

NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.

Pros:


NHaml

Design Goals:

.NET port of Rails Haml view engine. From the Haml website:

Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.

Pros:

  • terse structure (i.e. D.R.Y.)
  • well indented
  • clear structure
  • C# Intellisense (for VS2008 without ReSharper)

Cons:

  • an abstraction from XHTML rather than leveraging familiarity of the markup
  • No Intellisense for VS2010

Example:

@type=IEnumerable<Product>
- if(model.Any())
  %ul
    - foreach (var p in model)
      %li= p.Name
- else
  %p No products available

NVelocityViewEngine (MvcContrib)

Design Goals:

A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.

Pros:

  • easy to read/write
  • concise view code

Cons:

  • limited number of helper methods available on the view
  • does not automatically have Visual Studio integration (IntelliSense, compile-time checking of views, or refactoring)

Example:

#foreach ($p in $viewdata.Model)
#beforeall
    <ul>
#each
    <li>$p.Name</li>
#afterall
    </ul>
#nodata 
    <p>No products available</p>
#end

SharpTiles

Design Goals:

SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).

Pros:

  • familiar to Java developers
  • XML-style code blocks

Cons:

  • ...

Example:

<c:if test="${not fn:empty(Page.Tiles)}">
  <p class="note">
    <fmt:message key="page.tilesSupport"/>
  </p>
</c:if>

Spark View Engine

Design Goals:

The idea is to allow the html to dominate the flow and the code to fit seamlessly.

Pros:

  • Produces more readable templates
  • C# Intellisense (for VS2008 without ReSharper)
  • SparkSense plug-in for VS2010 (works with ReSharper)
  • Provides a powerful Bindings feature to get rid of all code in your views and allows you to easily invent your own HTML tags

Cons:

  • No clear separation of template logic from literal markup (this can be mitigated by namespace prefixes)

Example:

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
    <li each="var p in products">${p.Name}</li>
</ul>
<else>
    <p>No products available</p>
</else>

<Form style="background-color:olive;">
    <Label For="username" />
    <TextBox For="username" />
    <ValidationMessage For="username" Message="Please type a valid username." />
</Form>

StringTemplate View Engine MVC

Design Goals:

  • Lightweight. No page classes are created.
  • Fast. Templates are written to the Response Output stream.
  • Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
  • Dynamic. Templates can be generated on the fly in code.
  • Flexible. Templates can be nested to any level.
  • In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.

Pros:

  • familiar to StringTemplate Java developers

Cons:

  • simplistic template syntax can interfere with intended output (e.g. jQuery conflict)

Wing Beats

Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular F# code
  • Unit testable

Cons:

  • You don't really write HTML but code that represents HTML in a DSL.

XsltViewEngine (MvcContrib)

Design Goals:

Builds views from familiar XSLT

Pros:

  • widely ubiquitous
  • familiar template language for XML developers
  • XML-based
  • time-tested
  • Syntax and element nesting errors can be statically detected.

Cons:

  • functional language style makes flow control difficult
  • XSLT 2.0 is (probably?) not supported. (XSLT 1.0 is much less practical).

Where can I set path to make.exe on Windows?

I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.

For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

Return HTML content as a string, given URL. Javascript Function

after you get the response just do call this function to append data to your body element

function createDiv(responsetext)
{
    var _body = document.getElementsByTagName('body')[0];
    var _div = document.createElement('div');
    _div.innerHTML = responsetext;
    _body.appendChild(_div);
}

@satya code modified as below

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            createDiv(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();    
}

LINQ's Distinct() on a particular property

You should be able to override Equals on person to actually do Equals on Person.id. This ought to result in the behavior you're after.

Synchronous XMLHttpRequest warning and <script>

Even the latest jQuery has that line, so you have these options:

  • Change the source of jQuery yourself - but maybe there is a good reason for its usage
  • Live with the warning, please note that this option is deprecated and not obsolete.
  • Change your code, so it does not use this function

I think number 2 is the most sensible course of action in this case.

By the way if you haven't already tried, try this out: $.ajaxSetup({async:true});, but I don't think it will work.

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

i had the same issue with ionic .

cordova platform remove android
cordova platform add [email protected]

And replace in platform/android/projet.properties

cordova.system.library.1=com.android.support:support-v4+

To

cordova.system.library.1=com.android.support:support-v4:26+

Git checkout - switching back to HEAD

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

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

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

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

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

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

What do 3 dots next to a parameter type mean in Java?

This is the Java way to pass varargs (variable number arguments).

If you are familiar with C, this is similar to the ... syntax used it the printf function:

int printf(const char * format, ...);

but in a type safe fashion: every argument has to comply with the specified type (in your sample, they should be all String).

This is a simple sample of how you can use varargs:

class VarargSample {

   public static void PrintMultipleStrings(String... strings) {
      for( String s : strings ) {
          System.out.println(s);
      }
   }

   public static void main(String[] args) {
      PrintMultipleStrings("Hello", "world");
   }
}

The ... argument is actually an array, so you could pass a String[] as the parameter.

java.math.BigInteger cannot be cast to java.lang.Long

Better option is use SQLQuery#addScalar than casting to Long or BigDecimal.

Here is modified query that returns count column as Long

Query query = session
             .createSQLQuery("SELECT COUNT(*) as count
                             FROM SpyPath 
                             WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) 
                             GROUP BY DATE(time) 
                             ORDER BY time;")
             .addScalar("count", LongType.INSTANCE);

Then

List<Long> result = query.list(); //No ClassCastException here  

Related link

Cannot find Microsoft.Office.Interop Visual Studio

You can find it at link:

C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Word\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll

Browse it then add references

Android Studio: Unable to start the daemon process

In Eclipse, go to windows -> preferences -> gradle->arguments. Find JVM Arguments choose from radio button "USE :" and write arguments -Xms128m -Xmx512m Then click button Apply

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

How to use RecyclerView inside NestedScrollView?

Replace your recyclerView with,

<android.support.v7.widget.RecyclerView
    android:id="@+id/conversation"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

here,

app:layout_behavior="@string/appbar_scrolling_view_behavior"

will manage the rest of things.

One more thing, no need to put your recyclerView inside NestedScrollView

How to initialize an array of custom objects

Use a "Here-String" and cast to XML.

[xml]$myxml = @"
<stuff>
 <item name="Joe" age="32">
  <info>something about him</info>
 </item>
 <item name="Sue" age="29">
  <info>something about her</info>
 </item>
 <item name="Cat" age="12">
  <info>something else</info>
 </item>
</stuff>
"@

[array]$myitems = $myxml.stuff.Item

$myitems

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

SQL Server Installation - What is the Installation Media Folder?

If you've downloaded SQL from the Microsoft site, rename the file to a zip file and then you can extract the files inside to a folder, then choose that one when you "Browse for SQL server Installation Media"

SQLEXPRADV_x64_ENU.exe > SQLEXPRADV_x64_ENU.zip

7zip will open it (standard Windows zip doesn't work though)

Extract to something like C:\SQLInstallMedia

You will get folders like 1033_enu_lp, resources, x64 and a bunch of files.

C# Timer or Thread.Sleep

I agree as well, using a timer is the best option. I have tried a solution similar to yours in the past and started having issues where the loop would misfire, and I would have to wait for another Thread.Sleep() before it would fire again. Also, it did cause all sorts of issues with stopping the service, I would get constant errors about how it wasn't responding and had to be closed.

@Prashanth's code should be exactly what you need.

How to format a floating number to fixed width in Python

You can also left pad with zeros. For example if you want number to have 9 characters length, left padded with zeros use:

print('{:09.3f}'.format(number))

Thus, if number = 4.656, the output is: 00004.656

For your example the output will look like this:

numbers  = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
for x in numbers: 
    print('{:010.4f}'.format(x))

prints:

00023.2300
00000.1233
00001.0000
00004.2230
09887.2000

One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...

Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

An existing connection was forcibly closed by the remote host - WCF

In my case it was also with serialization. I need to add [KnownType(typeof(...)] for all the classes that could appear in the serialization.

Make a DIV fill an entire table cell

I had to set a fake height to the <tr> and height: inherit for <td>s

tr has height: 1px (it's ignored anyway)

Then set the td height: inherit

Then set the div to height: 100%

This worked for me in IE edge and Chrome:

_x000D_
_x000D_
<table style="width:200px;">
    <tr style="height: 1px;">
        <td style="height: inherit; border: 1px solid #000; width: 100px;">
            <div>
              Something big with multi lines and makes table bigger
            </div>
        </td>
        <td style="height: inherit; border: 1px solid #000; width: 100px;">
            <div style="background-color: red; height: 100%;">
                full-height div
            </div>
        </td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

TypeError: $.ajax(...) is not a function?

You have an error in your AJAX function, too much brackets, try instead $.ajax({

python ValueError: invalid literal for float()

Watch out for possible unintended literals in your argument

for example you can have a space within your argument, rendering it to a string / literal:

float(' 0.33')

After making sure the unintended space did not make it into the argument, I was left with:

float(0.33) 

Like this it works like a charm.

Take away is: Pay Attention for unintended literals (e.g. spaces that you didn't see) within your input.

How to manually reload Google Map with JavaScript

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

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

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

Hope that helps!

How to deploy a React App on Apache web server

As said in the post, React is a browser based technology. It only renders a view in an HTML document.

To be able to have access to your "React App", you need to:

  1. Bundle your React app in a bundle
  2. Have Apache pointing to your html file in your server, and allowing access externally.

You might have all the informations here: https://httpd.apache.org/docs/trunk/getting-started.html for the Apache server, and here to make your javascript bundle https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

How do I find out if first character of a string is a number?

Character.isDigit(string.charAt(0))

Note that this will allow any Unicode digit, not just 0-9. You might prefer:

char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');

Or the slower regex solutions:

s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")

However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0) and substring(0, 1) will throw a StringIndexOutOfBoundsException. startsWith does not have this problem.

To make the entire condition one line and avoid length checks, you can alter the regexes to the following:

s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")

If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.

How to calculate the IP range when the IP address and the netmask is given?

I know this is an older question, but I found this nifty library on nuget that seems to do just the trick for me:

http://nuget.org/packages/TakeIo.NetworkAddress/

How do I split a string by a multi-character delimiter in C#?

You can use the Regex.Split method, something like this:

Regex regex = new Regex(@"\bis\b");
string[] substrings = regex.Split("This is a sentence");

foreach (string match in substrings)
{
   Console.WriteLine("'{0}'", match);
}

Edit: This satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.

How to download all dependencies and packages to directory

Same question already answered here: How to list/download the recursive dependencies of a debian package?

try:

PACKAGES="wget unzip"
apt-get download $(apt-cache depends --recurse --no-recommends --no-suggests \
  --no-conflicts --no-breaks --no-replaces --no-enhances \
  --no-pre-depends ${PACKAGES} | grep "^\w")

Convert string to BigDecimal in java

The BigDecimal(double) constructor can have unpredictable behaviors. It is preferable to use BigDecimal(String) or BigDecimal.valueOf(double).

System.out.println(new BigDecimal(135.69)); //135.68999999999999772626324556767940521240234375
System.out.println(new BigDecimal("135.69")); // 135.69
System.out.println(BigDecimal.valueOf(135.69)); // 135.69

The documentation for BigDecimal(double) explains in detail:

  1. The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
  2. The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
  3. When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

C - error: storage size of ‘a’ isn’t known

you define the struct as xyx but you're trying to create the struct called xyz.

PHP Error: Function name must be a string

Try square braces with your $_COOKIE, not parenthesis. Like this:

<?php
if ($_COOKIE['CaptchaResponseValue'] == "false")
{
    header('Location: index.php');
    return;
}
?>

I also corrected your location header call a little too.

ps1 cannot be loaded because running scripts is disabled on this system

If you are using visual studio code:

  1. Open terminal
  2. Run the command: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
  3. Then run the command protractor conf.js

This is related to protractor test script execution related and I faced the same issue and it was resolved like this.

LINQ equivalent of foreach for IEnumerable<T>

There is no ForEach extension for IEnumerable; only for List<T>. So you could do

items.ToList().ForEach(i => i.DoStuff());

Alternatively, write your own ForEach extension method:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}

How to force a UIViewController to Portrait orientation in iOS 6

Just go to project.plist then add Supported interface orientation and then add only Portrait (bottom home button) and Portrait (top home button).

You can add or remove there orientation as per your project requirement .

Thanks

Google Maps JavaScript API RefererNotAllowedMapError

you show a screenshot of your api credentials page, but you have to click on "Browser key 1" and go from there to add referrers.

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

.btn is the best way, in modern website, it's not good while using anchor element without href so make the anchor tag to button is better.

Javascript Print iframe contents only

At this time, there is no need for the script tag inside the iframe. This works for me (tested in Chrome, Firefox, IE11 and node-webkit 0.12):

<script>
window.onload = function() {
    var body = 'dddddd';
    var newWin = document.getElementById('printf').contentWindow;
    newWin.document.write(body);
    newWin.document.close(); //important!
    newWin.focus(); //IE fix
    newWin.print();
}
</script>

<iframe id="printf"></iframe>

Thanks to all answers, save my day.

How to select all instances of selected region in Sublime Text

In the other posts, you have the shortcut keys, but if you want the menu option in every system, just go to Find > Quick Find All, as shown in the image attached.

Also, check the other answers for key binding to do it faster than menu clicking.

Sublime Text 3

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

Show which git tag you are on?

Edit: Jakub Narebski has more git-fu. The following much simpler command works perfectly:

git describe --tags

(Or without the --tags if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)

original answer follows:

git describe --exact-match --tags $(git log -n1 --pretty='%h')

Someone with more git-fu may have a more elegant solution...

This leverages the fact that git-log reports the log starting from what you've checked out. %h prints the abbreviated hash. Then git describe --exact-match --tags finds the tag (lightweight or annotated) that exactly matches that commit.

The $() syntax above assumes you're using bash or similar.

Why use a READ UNCOMMITTED isolation level?

Regarding reporting, we use it on all of our reporting queries to prevent a query from bogging down databases. We can do that because we're pulling historical data, not up-to-the-microsecond data.

Setting TIME_WAIT TCP

Usually, only the endpoint that issues an 'active close' should go into TIME_WAIT state. So, if possible, have your clients issue the active close which will leave the TIME_WAIT on the client and NOT on the server.

See here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html and http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ for details (the later also explains why it's not always possible due to protocol design that doesn't take TIME_WAIT into consideration).

How to remove all namespaces from XML with C#?

The tagged most useful answer has two flaws:

  • It ignores attributes
  • It doesn't work with "mixed mode" elements

Here is my take on this:

 public static XElement RemoveAllNamespaces(XElement e)
 {
    return new XElement(e.Name.LocalName,
      (from n in e.Nodes()
        select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
          (e.HasAttributes) ? 
            (from a in e.Attributes() 
               where (!a.IsNamespaceDeclaration)  
               select new XAttribute(a.Name.LocalName, a.Value)) : null);
  }          

Sample code here.

Access to file download dialog in Firefox

I was stuck with the same problem, but I found a solution. I did it the same way as this blog did.

Of course this was Java, I've translated it to Python:

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

browser = webdriver.Firefox(firefox_profile=fp)

In my example it was a CSV file. But when you need more, there are stored in the ~/.mozilla/$USER_PROFILE/mimeTypes.rdf

Firebase Storage How to store and Retrieve images

Using Base64 string in JSON will be very heavy. The parser has to do a lot of heavy lifting. Currently, Fresco only supports base supports Base64. Better you put something on Amazon Cloud or Firebase Cloud. And get an image as a URL. So that you can use Picasso or Glide for caching.

Defining an abstract class without any abstract methods

Yes you can. Sometimes you may get asked this question that what is the purpose doing this? The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class

QString to char* conversion

The easiest way to convert a QString to char* is qPrintable(const QString& str), which is a macro expanding to str.toLocal8Bit().constData().

Spring Data: "delete by" is supported?

Deprecated answer (Spring Data JPA <=1.6.x):

@Modifying annotation to the rescue. You will need to provide your custom SQL behaviour though.

public interface UserRepository extends JpaRepository<User, Long> {
    @Modifying
    @Query("delete from User u where u.firstName = ?1")
    void deleteUsersByFirstName(String firstName);
}

Update:

In modern versions of Spring Data JPA (>=1.7.x) query derivation for delete, remove and count operations is accessible.

public interface UserRepository extends CrudRepository<User, Long> {

    Long countByFirstName(String firstName);

    Long deleteByFirstName(String firstName);

    List<User> removeByFirstName(String firstName);

}

Does HTML5 <video> playback support the .avi format?

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.

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

Javascript loop through object array?

The suggested for loop is quite fine but you have to check the properties with hasOwnProperty. I'd rather suggest using Object.keys() that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

_x000D_
_x000D_
var data = {_x000D_
    "messages": [{_x000D_
        "msgFrom": "13223821242",_x000D_
        "msgBody": "Hi there"_x000D_
    }, {_x000D_
        "msgFrom": "Bill",_x000D_
        "msgBody": "Hello!"_x000D_
    }]_x000D_
};_x000D_
_x000D_
data.messages.forEach(function(message, index) {_x000D_
    console.log('message index '+ index);_x000D_
    Object.keys(message).forEach(function(prop) {    _x000D_
        console.log(prop + " = " + message[prop]);_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

How do I get the total Json record count using JQuery?

The OP is trying to count the number of properties in a JSON object. This could be done with an incremented temp variable in the iterator, but he seems to want to know the count before the iteration begins. A simple function that meets the need is provided at the bottom of this page.

Here's a cut and paste of the code, which worked for me:

function countProperties(obj) {
  var prop;
  var propCount = 0;

  for (prop in obj) {
    propCount++;
  }
  return propCount;
}

This should work well for a JSON object. For other objects, which may derive properties from their prototype chain, you would need to add a hasOwnProperty() test.

How do you import an Eclipse project into Android Studio now?

Simple steps: 1.Go to Android Studio. 2.Close all open projects if any. 3.There will be an option which says import non Android Studio Projects(Eclipse ect). 4.Click on it and choose ur project Thats't it enjoy!!!

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller:

ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a ViewBag.id to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:

GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)

So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

Using jQuery, Restricting File Size Before Uploading

I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:

LimitRequestBody 2097152

This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).

Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:

Requested content-length of 4000107 is larger than the configured limit of 2097152

And it will also display this message back in the web browser:

<h1>Request Entity Too Large</h1>

So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.

By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...

Redirect 413 413.html

...and provide a more graceful error result back.

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

Set database from SINGLE USER mode to MULTI USER

You couldn't do that becouse database in single mode. Above all right but you should know that: when you opened the sql management studio it doesn't know any user on the database but when you click the database it consider you the single user and your command not working. Just do that: Close management studio and re open it. new query window without selecting any database write the command script.

USE [master];
GO
ALTER DATABASE [tuncayoto] SET MULTI_USER WITH NO_WAIT;
GO 

make f5 wolla everything ok !

C# refresh DataGridView when updating or inserted on another form

// Form A
public void loaddata()
{
    //do what you do in load data in order to update data in datagrid
}

then on Form B define:

// Form B
FormA obj = (FormA)Application.OpenForms["FormA"];

private void button1_Click(object sender, EventArgs e)
{
    obj.loaddata();
    datagridview1.Update();
    datagridview1.Refresh();
}

#ifdef in C#

C# does have a preprocessor. It works just slightly differently than that of C++ and C.

Here is a MSDN links - the section on all preprocessor directives.

How to change the output color of echo in Linux

My favourite answer so far is coloredEcho.

Just to post another option, you can check out this little tool xcol

https://ownyourbits.com/2017/01/23/colorize-your-stdout-with-xcol/

you use it just like grep, and it will colorize its stdin with a different color for each argument, for instance

sudo netstat -putan | xcol httpd sshd dnsmasq pulseaudio conky tor Telegram firefox "[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+" ":[[:digit:]]+" "tcp." "udp." LISTEN ESTABLISHED TIME_WAIT

xcol example

Note that it accepts any regular expression that sed will accept.

This tool uses the following definitions

#normal=$(tput sgr0)                      # normal text
normal=$'\e[0m'                           # (works better sometimes)
bold=$(tput bold)                         # make colors bold/bright
red="$bold$(tput setaf 1)"                # bright red text
green=$(tput setaf 2)                     # dim green text
fawn=$(tput setaf 3); beige="$fawn"       # dark yellow text
yellow="$bold$fawn"                       # bright yellow text
darkblue=$(tput setaf 4)                  # dim blue text
blue="$bold$darkblue"                     # bright blue text
purple=$(tput setaf 5); magenta="$purple" # magenta text
pink="$bold$purple"                       # bright magenta text
darkcyan=$(tput setaf 6)                  # dim cyan text
cyan="$bold$darkcyan"                     # bright cyan text
gray=$(tput setaf 7)                      # dim white text
darkgray="$bold"$(tput setaf 0)           # bold black = dark gray text
white="$bold$gray"                        # bright white text

I use these variables in my scripts like so

echo "${red}hello ${yellow}this is ${green}coloured${normal}"

Linq Select Group By

    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

How to parse month full form string using DateFormat in Java?

You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

Try specifying the locale you wish to use, for example Locale.US:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27,  2007");

Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.

How to highlight a current menu item?

Here's a simple approach that works well with Angular.

<ul>
    <li ng-class="{ active: isActive('/View1') }"><a href="#/View1">View 1</a></li>
    <li ng-class="{ active: isActive('/View2') }"><a href="#/View2">View 2</a></li>
    <li ng-class="{ active: isActive('/View3') }"><a href="#/View3">View 3</a></li>
</ul>

Within your AngularJS controller:

$scope.isActive = function (viewLocation) {
     var active = (viewLocation === $location.path());
     return active;
};

This thread has a number of other similar answers.

How to set bootstrap navbar active class with Angular JS?

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Original documentation you can find here : https://dev.mysql.com/doc/dev/connector-nodejs/8.0/

'use strict';

const mysqlx = require('@mysql/xdevapi');

const options = {
  host: 'localhost',
  port: 33060,
  password: '******',
  user: 'root',
  schema: 'yourconference'
};

mysqlx.getSession(options)
  .then(session => {
          console.log(session.inspect());
           session.close();
  }).catch(err => {
    console.error(err.stack);
    process.exit(1);
  });

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

Importing csv file into R - numeric values read as characters

In read.table (and its relatives) it is the na.strings argument which specifies which strings are to be interpreted as missing values NA. The default value is na.strings = "NA"

If missing values in an otherwise numeric variable column are coded as something else than "NA", e.g. "." or "N/A", these rows will be interpreted as character, and then the whole column is converted to character.

Thus, if your missing values are some else than "NA", you need to specify them in na.strings.

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

I am in ubuntu 14.04 and mongod is registered as an upstart service. The answers in this post sent me in the right direction. The only adaptation I had to do to make things work with the upstart service was to edit /etc/mongod.conf. Look for the lines that read:

# Enable the HTTP interface (Defaults to port 28017).
# httpinterface = true

Just remove the # in front of httpinterface and restart the mongod service:

sudo restart mongod

Note: You can also enable the rest interface by adding a line that reads rest=true right below the httpinterface line mentioned above.

How to plot ROC curve in Python

I have made a simple function included in a package for the ROC curve. I just started practicing machine learning so please also let me know if this code has any problem!

Have a look at the github readme file for more details! :)

https://github.com/bc123456/ROC

from sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score, roc_curve
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

def plot_ROC(y_train_true, y_train_prob, y_test_true, y_test_prob):
    '''
    a funciton to plot the ROC curve for train labels and test labels.
    Use the best threshold found in train set to classify items in test set.
    '''
    fpr_train, tpr_train, thresholds_train = roc_curve(y_train_true, y_train_prob, pos_label =True)
    sum_sensitivity_specificity_train = tpr_train + (1-fpr_train)
    best_threshold_id_train = np.argmax(sum_sensitivity_specificity_train)
    best_threshold = thresholds_train[best_threshold_id_train]
    best_fpr_train = fpr_train[best_threshold_id_train]
    best_tpr_train = tpr_train[best_threshold_id_train]
    y_train = y_train_prob > best_threshold

    cm_train = confusion_matrix(y_train_true, y_train)
    acc_train = accuracy_score(y_train_true, y_train)
    auc_train = roc_auc_score(y_train_true, y_train)

    print 'Train Accuracy: %s ' %acc_train
    print 'Train AUC: %s ' %auc_train
    print 'Train Confusion Matrix:'
    print cm_train

    fig = plt.figure(figsize=(10,5))
    ax = fig.add_subplot(121)
    curve1 = ax.plot(fpr_train, tpr_train)
    curve2 = ax.plot([0, 1], [0, 1], color='navy', linestyle='--')
    dot = ax.plot(best_fpr_train, best_tpr_train, marker='o', color='black')
    ax.text(best_fpr_train, best_tpr_train, s = '(%.3f,%.3f)' %(best_fpr_train, best_tpr_train))
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.0])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('ROC curve (Train), AUC = %.4f'%auc_train)

    fpr_test, tpr_test, thresholds_test = roc_curve(y_test_true, y_test_prob, pos_label =True)

    y_test = y_test_prob > best_threshold

    cm_test = confusion_matrix(y_test_true, y_test)
    acc_test = accuracy_score(y_test_true, y_test)
    auc_test = roc_auc_score(y_test_true, y_test)

    print 'Test Accuracy: %s ' %acc_test
    print 'Test AUC: %s ' %auc_test
    print 'Test Confusion Matrix:'
    print cm_test

    tpr_score = float(cm_test[1][1])/(cm_test[1][1] + cm_test[1][0])
    fpr_score = float(cm_test[0][1])/(cm_test[0][0]+ cm_test[0][1])

    ax2 = fig.add_subplot(122)
    curve1 = ax2.plot(fpr_test, tpr_test)
    curve2 = ax2.plot([0, 1], [0, 1], color='navy', linestyle='--')
    dot = ax2.plot(fpr_score, tpr_score, marker='o', color='black')
    ax2.text(fpr_score, tpr_score, s = '(%.3f,%.3f)' %(fpr_score, tpr_score))
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.0])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('ROC curve (Test), AUC = %.4f'%auc_test)
    plt.savefig('ROC', dpi = 500)
    plt.show()

    return best_threshold

A sample roc graph produced by this code

include antiforgerytoken in ajax post ASP.NET MVC

Feel free to use the function below:

function AjaxPostWithAntiForgeryToken(destinationUrl, successCallback) {
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
$.ajax({
    type: "POST",
    url: destinationUrl,
    data: { __RequestVerificationToken: token }, // Your other data will go here
    dataType: "json",
    success: function (response) {
        successCallback(response);
    },
    error: function (xhr, status, error) {
       // handle failure
    }
});

}

Java, return if trimmed String in List contains String

You can use your own code. You don't need to use the looping structure, if you don't want to use the looping structure as you said above. Only you have to focus to remove space or trim the String of the list.

If you are using java8 you can simply trim the String using the single line of the code:

myList = myList.stream().map(String :: trim).collect(Collectors.toList());

The importance of the above line is, in the future, you can use a List or set as well. Now you can use your own code:

if(myList.contains("A")){
    //true
}else{
    // false
}

How to add an image to a JPanel?

I'm doing something very similar in a private project I'm working on. Thus far I've generated images up to 1024x1024 without any problems (except memory) and can display them very quickly and without any performance problems.

Overriding the paint method of JPanel subclass is overkill and requires more work than you need to do.

The way I do it is:

Class MapIcon implements Icon {...}

OR

Class MapIcon extends ImageIcon {...}

The code you use to generate the image will be in this class. I use a BufferedImage to draw onto then when the paintIcon() is called, use g.drawImvge(bufferedImage); This reduces the amount of flashing done while you generate your images, and you can thread it.

Next I extend JLabel:

Class MapLabel extends Scrollable, MouseMotionListener {...}

This is because I want to put my image on a scroll pane, I.e. display part of the image and have the user scroll around as needed.

So then I use a JScrollPane to hold the MapLabel, which contains only the MapIcon.

MapIcon map = new MapIcon (); 
MapLabel mapLabel = new MapLabel (map);
JScrollPane scrollPane = new JScrollPane();

scrollPane.getViewport ().add (mapLabel);

But for your scenario (just show the whole image every time). You need to add the MapLabel to the top JPanel, and make sure to size them all to the full size of the image (by overriding the GetPreferredSize()).

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

The current answer is incomplete. Installing libv4l-dev creates a /usr/include/linux/videodev2.h but doesn't solve the stated problem of not being able to find linux/videodev.h. The library does ship header files for compatibility, but fails to put them where applications will look for them.

sudo apt-get install libv4l-dev
cd /usr/include/linux
sudo ln -s ../libv4l1-videodev.h videodev.h

This provides a linux/videodev.h, and of the right version (1).

Python "SyntaxError: Non-ASCII character '\xe2' in file"

Based on PEP 0263 -- Defining Python Source Code Encodings

Python will default to ASCII as standard encoding if no other
encoding hints are given.

To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, such as:

      # coding=<encoding name>

or (using formats recognized by popular editors)

      #!/usr/bin/python
      # -*- coding: <encoding name> -*-

or

      #!/usr/bin/python
      # vim: set fileencoding=<encoding name> :

Forward host port to docker container

A simple but relatively insecure way would be to use the --net=host option to docker run.

This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.

This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.

For example, you can test it out by running the following command, which assumes your image is called my_image, your image includes the telnet utility, and the service you want to connect to is on port 25:

docker run --rm -i -t --net=host my_image telnet localhost 25

If you consider doing it this way, please see the caution about security on this page:

https://docs.docker.com/articles/networking/

It says:

--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.

Cast to generic type in C#

You can't do that. You could try telling your problem from a more high level point of view (i.e. what exactly do you want to accomplish with the casted variable) for a different solution.

You could go with something like this:

 public abstract class Message { 
     // ...
 }
 public class Message<T> : Message {
 }

 public abstract class MessageProcessor {
     public abstract void ProcessMessage(Message msg);
 }
 public class SayMessageProcessor : MessageProcessor {
     public override void ProcessMessage(Message msg) {
         ProcessMessage((Message<Say>)msg);
     }
     public void ProcessMessage(Message<Say> msg) {
         // do the actual processing
     }
 }

 // Dispatcher logic:
 Dictionary<Type, MessageProcessor> messageProcessors = {
    { typeof(Say), new SayMessageProcessor() },
    { typeof(string), new StringMessageProcessor() }
 }; // properly initialized

 messageProcessors[msg.GetType().GetGenericArguments()[0]].ProcessMessage(msg);

Playing a MP3 file in a WinForm application

You can do it using old DirectShow functionality.

This answer teaches you how to create QuartzTypeLib.dll:

  1. Run tlbimp tool (in your case path will be different):

  2. Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll

Alternatively, this project contains the library interop.QuartzTypeLib.dll, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:

  1. Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")

  2. In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).

  3. In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266

  4. Use this class to play your favorite MP3 file:

    using QuartzTypeLib;
    
    public sealed class DirectShowPlayer
    {
        private FilgraphManager FilterGraph;
    
        public void Play(string path)
        {
            FilgraphManager = new FilgraphManager();
            FilterGraph.RenderFile(path);
            FilterGraph.Run();
        }
    
        public void Stop()
        {
            FilterGraph?.Stop();
        }
    }
    

PS: TlbImp.exe can be found here: "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin", or in "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"