Programs & Examples On #Delegates

Delegates can refer to several concepts. An object can rely on another (a delegate) to perform a function. Delegation can also refer to programming language feature making use of the method lookup rules for dispatching self-calls. In C#, a delegate defines which method to call when an event is triggered.

How do I set up a simple delegate to communicate between two view controllers?

This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.

First you need to declare a protocol:

Let's call it MyFirstControllerDelegate.h

@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end

Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate

#import "MyFirstControllerDelegate.h"

@interface FirstController : UIViewController<MyFirstControllerDelegate>
{

}

@end

In the implementation file, you need to implement both functions of protocol:

@implementation FirstController 


    - (void) FunctionOne: (MyDataOne*) dataOne
      {
          //Put your finction code here
      }
    - (void) FunctionTwo: (MyDatatwo*) dataTwo
      {
          //Put your finction code here
      }

     //Call below function from your code
    -(void) CreateSecondController
     {
             SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
           //..... push second controller into navigation stack 
            mySecondController.delegate = self ;
            [mySecondController release];
     }

@end

in your SecondController:

@interface SecondController:<UIViewController>
{
   id <MyFirstControllerDelegate> delegate;
}

@property (nonatomic,assign)  id <MyFirstControllerDelegate> delegate;

@end

In the implementation file of SecondController.

@implementation SecondController

@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
   [delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
   [delegate FunctionTwo:myDataSecond];
}

@end

Here is the wiki article on delegate.

Java Delegates?

Short story: ­­­­­­­­­­­­­­­­­­­no.

Introduction

The newest version of the Microsoft Visual J++ development environment supports a language construct called delegates or bound method references. This construct, and the new keywords delegate and multicast introduced to support it, are not a part of the JavaTM programming language, which is specified by the Java Language Specification and amended by the Inner Classes Specification included in the documentation for the JDKTM 1.1 software.

It is unlikely that the Java programming language will ever include this construct. Sun already carefully considered adopting it in 1996, to the extent of building and discarding working prototypes. Our conclusion was that bound method references are unnecessary and detrimental to the language. This decision was made in consultation with Borland International, who had previous experience with bound method references in Delphi Object Pascal.

We believe bound method references are unnecessary because another design alternative, inner classes, provides equal or superior functionality. In particular, inner classes fully support the requirements of user-interface event handling, and have been used to implement a user-interface API at least as comprehensive as the Windows Foundation Classes.

We believe bound method references are harmful because they detract from the simplicity of the Java programming language and the pervasively object-oriented character of the APIs. Bound method references also introduce irregularity into the language syntax and scoping rules. Finally, they dilute the investment in VM technologies because VMs are required to handle additional and disparate types of references and method linkage efficiently.

Delegates in swift?

Simple Example:

protocol Work: class {
    func doSomething()
}

class Manager {
    weak var delegate: Work?
    func passAlong() {
        delegate?.doSomething()
    }
}

class Employee: Work {
    func doSomething() {
        print("Working on it")
    }
}

let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it

List<object>.RemoveAll - How to create an appropriate Predicate

Little bit off topic but say i want to remove all 2s from a list. Here's a very elegant way to do that.

void RemoveAll<T>(T item,List<T> list)
{
    while(list.Contains(item)) list.Remove(item);
}

With predicate:

void RemoveAll<T>(Func<T,bool> predicate,List<T> list)
{
    while(list.Any(predicate)) list.Remove(list.First(predicate));
}

+1 only to encourage you to leave your answer here for learning purposes. You're also right about it being off-topic, but I won't ding you for that because of there is significant value in leaving your examples here, again, strictly for learning purposes. I'm posting this response as an edit because posting it as a series of comments would be unruly.

Though your examples are short & compact, neither is elegant in terms of efficiency; the first is bad at O(n2), the second, absolutely abysmal at O(n3). Algorithmic efficiency of O(n2) is bad and should be avoided whenever possible, especially in general-purpose code; efficiency of O(n3) is horrible and should be avoided in all cases except when you know n will always be very small. Some might fling out their "premature optimization is the root of all evil" battle axes, but they do so naïvely because they do not truly understand the consequences of quadratic growth since they've never coded algorithms that have to process large datasets. As a result, their small-dataset-handling algorithms just run generally slower than they could, and they have no idea that they could run faster. The difference between an efficient algorithm and an inefficient algorithm is often subtle, but the performance difference can be dramatic. The key to understanding the performance of your algorithm is to understand the performance characteristics of the primitives you choose to use.

In your first example, list.Contains() and Remove() are both O(n), so a while() loop with one in the predicate & the other in the body is O(n2); well, technically O(m*n), but it approaches O(n2) as the number of elements being removed (m) approaches the length of the list (n).

Your second example is even worse: O(n3), because for every time you call Remove(), you also call First(predicate), which is also O(n). Think about it: Any(predicate) loops over the list looking for any element for which predicate() returns true. Once it finds the first such element, it returns true. In the body of the while() loop, you then call list.First(predicate) which loops over the list a second time looking for the same element that had already been found by list.Any(predicate). Once First() has found it, it returns that element which is passed to list.Remove(), which loops over the list a third time to yet once again find that same element that was previously found by Any() and First(), in order to finally remove it. Once removed, the whole process starts over at the beginning with a slightly shorter list, doing all the looping over and over and over again starting at the beginning every time until finally no more elements matching the predicate remain. So the performance of your second example is O(m*m*n), or O(n3) as m approaches n.

Your best bet for removing all items from a list that match some predicate is to use the generic list's own List<T>.RemoveAll(predicate) method, which is O(n) as long as your predicate is O(1). A for() loop technique that passes over the list only once, calling list.RemoveAt() for each element to be removed, may seem to be O(n) since it appears to pass over the loop only once. Such a solution is more efficient than your first example, but only by a constant factor, which in terms of algorithmic efficiency is negligible. Even a for() loop implementation is O(m*n) since each call to Remove() is O(n). Since the for() loop itself is O(n), and it calls Remove() m times, the for() loop's growth is O(n2) as m approaches n.

How can I clear event subscriptions in C#?

Remove all events, assume the event is an "Action" type:

Delegate[] dary = TermCheckScore.GetInvocationList();

if ( dary != null )
{
    foreach ( Delegate del in dary )
    {
        TermCheckScore -= ( Action ) del;
    }
}

Why would you use Expression<Func<T>> rather than Func<T>?

The primary reason is when you don't want to run the code directly, but rather, want to inspect it. This can be for any number of reasons:

  • Mapping the code to a different environment (ie. C# code to SQL in Entity Framework)
  • Replacing parts of the code in runtime (dynamic programming or even plain DRY techniques)
  • Code validation (very useful when emulating scripting or when doing analysis)
  • Serialization - expressions can be serialized rather easily and safely, delegates can't
  • Strongly-typed safety on things that aren't inherently strongly-typed, and exploiting compiler checks even though you're doing dynamic calls in runtime (ASP.NET MVC 5 with Razor is a nice example)

How can I make a weak protocol reference in 'pure' Swift (without @objc)

protocol must be subClass of AnyObject, class

example given below

    protocol NameOfProtocol: class {
   // member of protocol
    }
   class ClassName: UIViewController {
      weak var delegate: NameOfProtocol? 
    }

C# cannot convert method to non delegate type

You can simplify your class code to this below and it will work as is but if you want to make your example work, add parenthesis at the end : string x = getTitle();

public class Pin
{
   public string Title { get; set;}
}

Uses of Action delegate in C#

I used it as a callback in an event handler. When I raise the event, I pass in a method taking a string a parameter. This is what the raising of the event looks like:

SpecialRequest(this,
    new BalieEventArgs 
    { 
            Message = "A Message", 
            Action = UpdateMethod, 
            Data = someDataObject 
    });

The Method:

   public void UpdateMethod(string SpecialCode){ }

The is the class declaration of the event Args:

public class MyEventArgs : EventArgs
    {
        public string Message;
        public object Data;
        public Action<String> Action;
    }

This way I can call the method passed from the event handler with a some parameter to update the data. I use this to request some information from the user.

What is a C++ delegate?

An option for delegates in C++ that is not otherwise mentioned here is to do it C style using a function ptr and a context argument. This is probably the same pattern that many asking this question are trying to avoid. But, the pattern is portable, efficient, and is usable in embedded and kernel code.

class SomeClass
{
    in someMember;
    int SomeFunc( int);

    static void EventFunc( void* this__, int a, int b, int c)
    {
        SomeClass* this_ = static_cast< SomeClass*>( this__);

        this_->SomeFunc( a );
        this_->someMember = b + c;
    }
};

void ScheduleEvent( void (*delegateFunc)( void*, int, int, int), void* delegateContext);

    ...
    SomeClass* someObject = new SomeObject();
    ...
    ScheduleEvent( SomeClass::EventFunc, someObject);
    ...

How to hide the keyboard when I press return key in a UITextField?

Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.

Either create an extension or use the ViewController in which you'd like to use this but make sure to implement UITextFieldDelegate. For reusability's sake I found it easier to use an extension:

extension UIViewController : UITextFieldDelegate {
    ...
}

but the alternative works as well:

class MyViewController: UIViewController {
    ...
}

Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    return textField.endEditing(false)
}

In your viewDidLoad method, set the textfield's delegate to self

@IBOutlet weak var myTextField: UITextField!
...

override func viewDidLoad() {
    ..
    myTextField.delegte = self;
    ..
}

That should be all. Now, when you press return the textFieldShouldReturn should be called.

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

You are checking Parent properties for null in your delegate. The same should work with lambda expressions too.

List<AnalysisObject> analysisObjects = analysisObjectRepository
        .FindAll()
        .Where(x => 
            (x.ID == packageId) || 
            (x.Parent != null &&
                (x.Parent.ID == packageId || 
                (x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
        .ToList();

When & why to use delegates?

Delegates Overview

Delegates have the following properties:

  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contra variance.
  • C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

Super-simple example of C# observer/observable with delegates

I did't want to change my source code to add additional observer , so I have written following simple example:

//EVENT DRIVEN OBSERVER PATTERN
public class Publisher
{
    public Publisher()
    {
        var observable = new Observable();
        observable.PublishData("Hello World!");
    }
}

//Server will send data to this class's PublishData method
public class Observable
{
    public event Receive OnReceive;

    public void PublishData(string data)
    {
        //Add all the observer below
        //1st observer
        IObserver iObserver = new Observer1();
        this.OnReceive += iObserver.ReceiveData;
        //2nd observer
        IObserver iObserver2 = new Observer2();
        this.OnReceive += iObserver2.ReceiveData;

        //publish data 
        var handler = OnReceive;
        if (handler != null)
        {
            handler(data);
        }
    }
}

public interface IObserver
{
    void ReceiveData(string data);
}

//Observer example
public class Observer1 : IObserver
{
    public void ReceiveData(string data)
    {
        //sample observers does nothing with data :)
    }
}

public class Observer2 : IObserver
{
    public void ReceiveData(string data)
    {
        //sample observers does nothing with data :)
    }
}

Pass Method as Parameter using C#

class PersonDB
{
  string[] list = { "John", "Sam", "Dave" };
  public void Process(ProcessPersonDelegate f)
  {
    foreach(string s in list) f(s);
  }
}

The second class is Client, which will use the storage class. It has a Main method that creates an instance of PersonDB, and it calls that object’s Process method with a method that is defined in the Client class.

class Client
{
  static void Main()
  {
    PersonDB p = new PersonDB();
    p.Process(PrintName);
  }
  static void PrintName(string name)
  {
    System.Console.WriteLine(name);
  }
}

How do I create delegates in Objective-C?

Delegate :- Create

@protocol addToCartDelegate <NSObject>

-(void)addToCartAction:(ItemsModel *)itemsModel isAdded:(BOOL)added;

@end

Send and please assign delegate to view you are sending data

[self.delegate addToCartAction:itemsModel isAdded:YES];

Function Pointers in Java

Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:

http://code.google.com/p/lambdaj/wiki/Closures

C# - using List<T>.Find() with custom objects

Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.

var element = myList.Find(e => [some condition on e]);

In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.

In your case, that would be:

var reponse = list.Find(r => r.Statement == "statement1")

And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:

var response = list.Find(delegate (Response r) {
    return r.Statement == "statement1";
});

Invoke(Delegate)

Invoke((MethodInvoker)delegate{ textBox1.Text = "Test"; });

What is Func, how and when is it used

Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.

Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2); 

So, Func is a built-in delegate which brings some functional programming features and helps reduce code verbosity.

What are the differences between delegates and events?

NOTE: If you have access to C# 5.0 Unleashed, read the "Limitations on Plain Use of Delegates" in Chapter 18 titled "Events" to understand better the differences between the two.


It always helps me to have a simple, concrete example. So here's one for the community. First I show how you can use delegates alone to do what Events do for us. Then I show how the same solution would work with an instance of EventHandler. And then I explain why we DON'T want to do what I explain in the first example. This post was inspired by an article by John Skeet.

Example 1: Using public delegate

Suppose I have a WinForms app with a single drop-down box. The drop-down is bound to an List<Person>. Where Person has properties of Id, Name, NickName, HairColor. On the main form is a custom user control that shows the properties of that person. When someone selects a person in the drop-down the labels in the user control update to show the properties of the person selected.

enter image description here

Here is how that works. We have three files that help us put this together:

  • Mediator.cs -- static class holds the delegates
  • Form1.cs -- main form
  • DetailView.cs -- user control shows all details

Here is the relevant code for each of the classes:

class Mediator
{
    public delegate void PersonChangedDelegate(Person p); //delegate type definition
    public static PersonChangedDelegate PersonChangedDel; //delegate instance. Detail view will "subscribe" to this.
    public static void OnPersonChanged(Person p) //Form1 will call this when the drop-down changes.
    {
        if (PersonChangedDel != null)
        {
            PersonChangedDel(p);
        }
    }
}

Here is our user control:

public partial class DetailView : UserControl
{
    public DetailView()
    {
        InitializeComponent();
        Mediator.PersonChangedDel += DetailView_PersonChanged;
    }

    void DetailView_PersonChanged(Person p)
    {
        BindData(p);
    }

    public void BindData(Person p)
    {
        lblPersonHairColor.Text = p.HairColor;
        lblPersonId.Text = p.IdPerson.ToString();
        lblPersonName.Text = p.Name;
        lblPersonNickName.Text = p.NickName;

    }
}

Finally we have the following code in our Form1.cs. Here we are Calling OnPersonChanged, which calls any code subscribed to the delegate.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Mediator.OnPersonChanged((Person)comboBox1.SelectedItem); //Call the mediator's OnPersonChanged method. This will in turn call all the methods assigned (i.e. subscribed to) to the delegate -- in this case `DetailView_PersonChanged`.
}

Ok. So that's how you would get this working without using events and just using delegates. We just put a public delegate into a class -- you can make it static or a singleton, or whatever. Great.

BUT, BUT, BUT, we do not want to do what I just described above. Because public fields are bad for many, many reason. So what are our options? As John Skeet describes, here are our options:

  1. A public delegate variable (this is what we just did above. don't do this. i just told you above why it's bad)
  2. Put the delegate into a property with a get/set (problem here is that subscribers could override each other -- so we could subscribe a bunch of methods to the delegate and then we could accidentally say PersonChangedDel = null, wiping out all of the other subscriptions. The other problem that remains here is that since the users have access to the delegate, they can invoke the targets in the invocation list -- we don't want external users having access to when to raise our events.
  3. A delegate variable with AddXXXHandler and RemoveXXXHandler methods

This third option is essentially what an event gives us. When we declare an EventHandler, it gives us access to a delegate -- not publicly, not as a property, but as this thing we call an event that has just add/remove accessors.

Let's see what the same program looks like, but now using an Event instead of the public delegate (I've also changed our Mediator to a singleton):

Example 2: With EventHandler instead of a public delegate

Mediator:

class Mediator
{

    private static readonly Mediator _Instance = new Mediator();

    private Mediator() { }

    public static Mediator GetInstance()
    {
        return _Instance;
    }

    public event EventHandler<PersonChangedEventArgs> PersonChanged; //this is just a property we expose to add items to the delegate.

    public void OnPersonChanged(object sender, Person p)
    {
        var personChangedDelegate = PersonChanged as EventHandler<PersonChangedEventArgs>;
        if (personChangedDelegate != null)
        {
            personChangedDelegate(sender, new PersonChangedEventArgs() { Person = p });
        }
    }
}

Notice that if you F12 on the EventHandler, it will show you the definition is just a generic-ified delegate with the extra "sender" object:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

The User Control:

public partial class DetailView : UserControl
{
    public DetailView()
    {
        InitializeComponent();
        Mediator.GetInstance().PersonChanged += DetailView_PersonChanged;
    }

    void DetailView_PersonChanged(object sender, PersonChangedEventArgs e)
    {
        BindData(e.Person);
    }

    public void BindData(Person p)
    {
        lblPersonHairColor.Text = p.HairColor;
        lblPersonId.Text = p.IdPerson.ToString();
        lblPersonName.Text = p.Name;
        lblPersonNickName.Text = p.NickName;

    }
}

Finally, here's the Form1.cs code:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        Mediator.GetInstance().OnPersonChanged(this, (Person)comboBox1.SelectedItem);
}

Because the EventHandler wants and EventArgs as a parameter, I created this class with just a single property in it:

class PersonChangedEventArgs
{
    public Person Person { get; set; }
}

Hopefully that shows you a bit about why we have events and how they are different -- but functionally the same -- as delegates.

In Typescript, How to check if a string is Numeric

Most of the time the value that we want to check is string or number, so here is function that i use:

const isNumber = (n: string | number): boolean => 
    !isNaN(parseFloat(String(n))) && isFinite(Number(n));

Codesandbox tests.

const willBeTrue = [0.1, '1', '-1', 1, -1, 0, -0, '0', "-0", 2e2, 1e23, 1.1, -0.1, '0.1', '2e2', '1e23', '-0.1', ' 898', '080']

const willBeFalse = ['9BX46B6A', "+''", '', '-0,1', [], '123a', 'a', 'NaN', 1e10000, undefined, null, NaN, Infinity, () => {}]

Configuration with name 'default' not found. Android Studio

Case matters I manually added a submodule :k3b-geohelper to the settings.gradle file

 include ':app', ':k3b-geohelper'

and everthing works fine on my mswindows build system

When i pushed the update to github the fdroid build system failed with

  Cannot evaluate module k3b-geohelper : Configuration with name 'default' not found

The final solution was that the submodule folder was named k3b-geoHelper not k3b-geohelper.

Under MSWindows case doesn-t matter but on linux system it does

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

How to change the output color of echo in Linux

A neat way to change color only for one echo is to define such function:

function coloredEcho(){
    local exp=$1;
    local color=$2;
    if ! [[ $color =~ '^[0-9]$' ]] ; then
       case $(echo $color | tr '[:upper:]' '[:lower:]') in
        black) color=0 ;;
        red) color=1 ;;
        green) color=2 ;;
        yellow) color=3 ;;
        blue) color=4 ;;
        magenta) color=5 ;;
        cyan) color=6 ;;
        white|*) color=7 ;; # white or invalid color
       esac
    fi
    tput setaf $color;
    echo $exp;
    tput sgr0;
}

Usage:

coloredEcho "This text is green" green

Or you could directly use color codes mentioned in Drew's answer:

coloredEcho "This text is green" 2

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

Fast way to discover the row count of a table in PostgreSQL

Counting rows in big tables is known to be slow in PostgreSQL. To get a precise number it has to do a full count of rows due to the nature of MVCC. There is a way to speed this up dramatically if the count does not have to be exact like it seems to be in your case.

Instead of getting the exact count (slow with big tables):

SELECT count(*) AS exact_count FROM myschema.mytable;

You get a close estimate like this (extremely fast):

SELECT reltuples::bigint AS estimate FROM pg_class where relname='mytable';

How close the estimate is depends on whether you run ANALYZE enough. It is usually very close.
See the PostgreSQL Wiki FAQ.
Or the dedicated wiki page for count(*) performance.

Better yet

The article in the PostgreSQL Wiki is was a bit sloppy. It ignored the possibility that there can be multiple tables of the same name in one database - in different schemas. To account for that:

SELECT c.reltuples::bigint AS estimate
FROM   pg_class c
JOIN   pg_namespace n ON n.oid = c.relnamespace
WHERE  c.relname = 'mytable'
AND    n.nspname = 'myschema'

Or better still

SELECT reltuples::bigint AS estimate
FROM   pg_class
WHERE  oid = 'myschema.mytable'::regclass;

Faster, simpler, safer, more elegant. See the manual on Object Identifier Types.

Use to_regclass('myschema.mytable') in Postgres 9.4+ to avoid exceptions for invalid table names:


TABLESAMPLE SYSTEM (n) in Postgres 9.5+

SELECT 100 * count(*) AS estimate FROM mytable TABLESAMPLE SYSTEM (1);

Like @a_horse commented, the newly added clause for the SELECT command might be useful if statistics in pg_class are not current enough for some reason. For example:

  • No autovacuum running.
  • Immediately after a big INSERT or DELETE.
  • TEMPORARY tables (which are not covered by autovacuum).

This only looks at a random n % (1 in the example) selection of blocks and counts rows in it. A bigger sample increases the cost and reduces the error, your pick. Accuracy depends on more factors:

  • Distribution of row size. If a given block happens to hold wider than usual rows, the count is lower than usual etc.
  • Dead tuples or a FILLFACTOR occupy space per block. If unevenly distributed across the table, the estimate may be off.
  • General rounding errors.

In most cases the estimate from pg_class will be faster and more accurate.

Answer to actual question

First, I need to know the number of rows in that table, if the total count is greater than some predefined constant,

And whether it ...

... is possible at the moment the count pass my constant value, it will stop the counting (and not wait to finish the counting to inform the row count is greater).

Yes. You can use a subquery with LIMIT:

SELECT count(*) FROM (SELECT 1 FROM token LIMIT 500000) t;

Postgres actually stops counting beyond the given limit, you get an exact and current count for up to n rows (500000 in the example), and n otherwise. Not nearly as fast as the estimate in pg_class, though.

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

In theory everything is possible but reality you find the numbers much lower than you might expect. I have been trying to address huge spaces on servers often and found that even though a server can have huge amounts of memory it surprised me that most software actually never can address it in real scenario's simply because the cpu's are not fast enough to really address them. Why would you say right ?! . Timings thats the endless downfall of every enormous machine which i have worked on. So i would advise to not go overboard by addressing huge amounts just because you can, but use what you think could be used. Actual values are often much lower than what you expected. Ofcourse non of us really uses hp 9000 systems at home and most of you actually ever will go near the capacity of your home system ever. For instance most users do not have more than 16 Gb of memory in their system. Ofcourse some of the casual gamers use work stations for a game once a month but i bet that is a very small percentage. So coming down to earth means i would address on a 8 Gb 64 bit system not much more than 512 mb for heapspace or if you go overboard try 1 Gb. I am pretty sure its even with these numbers pure overkill. I have constant monitored the memory usage during gaming to see if the addressing would make any difference but did not notice any difference at all when i addressed much lower values or larger ones. Even on the server/workstations there was no visible change in performance no matter how large i set the values. That does not say some jave users might be able to make use of more space addressed, but this far i have not seen any of the applications needing so much ever. Ofcourse i assume that their would be a small difference in performance if java instances would run out of enough heapspace to work with. This far i have not found any of it at all, however lack of real installed memory showed instant drops of performance if you set too much heapspace. When you have a 4 Gb system you run quickly out of heapspace and then you will see some errors and slowdowns because people address too much space which actually is not free in the system so the os starts to address drive space to make up for the shortage hence it starts to swap.

Do Facebook Oauth 2.0 Access Tokens Expire?

since i had the same problem - see the excellent post on this topic from ben biddington, who clarified all this issues with the wrong token and the right type to send for the requests.

http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/

How do I get a background location update every n minutes in my iOS application?

if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}

This is needed for background location tracking since iOS 9.

Find oldest/youngest datetime object in a list

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

JNI and Gradle in Android Studio

In my case, I'm on Windows and following the answer by Cameron above only works if you use the full name of the ndk-build which is ndk-build.cmd. I have to clean and rebuild the project, then restart the emulator before getting the app to work (Actually I imported the sample HelloJni from NDK, into Android Studio). However, make sure the path to NDK does not contain space.

Finally, my build.gradle is full listed as below:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.hellojni"
        minSdkVersion 4
        targetSdkVersion 4

        ndk {
            moduleName "hello-jni"
        }

        testApplicationId "com.example.hellojni.tests"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
    }
    sourceSets.main {
        jni.srcDirs = [] // This prevents the auto generation of Android.mk
//        sourceSets.main.jni.srcDirs = []
        jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
    }

    task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
        def ndkDir = android.plugin.ndkFolder
        commandLine "$ndkDir/ndk-build.cmd",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                '-j', Runtime.runtime.availableProcessors(),
                'all',
                'NDK_DEBUG=1'
    }

    task cleanNative(type: Exec, description: 'Clean JNI object files') {
        def ndkDir = android.plugin.ndkFolder
        commandLine "$ndkDir/ndk-build.cmd",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                'clean'
    }

    clean.dependsOn 'cleanNative'

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn buildNative
    }

}


dependencies {
    compile 'com.android.support:support-v4:21.0.3'
}

javascript toISOString() ignores timezone offset

Moment js solution to this is

var d = new Date(new Date().setHours(0,0,0,0));
m.add(m.utcOffset(), 'm')
m.toDate().toISOString()
// output "2019-07-18T00:00:00.000Z"

Generate class from database table

A bit late but I've created a web tool to help create a C# (or other) objects from SQL result, SQL Table and SQL SP.

sql2object.com

This can really safe you having to type all your properties and types.

If the types are not recognised the default will be selected.

Node.js: get path from the request

You can use this in app.js file .

var apiurl = express.Router();
apiurl.use(function(req, res, next) {
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});
app.use('/', apiurl);

How to exit a 'git status' list in a terminal?

exit did it for me. My results after pressing return;

my-mac:Car Game mymac$ exit
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
    ...completed.
[Process completed]

Adding Only Untracked Files

I tried this and it worked :

git stash && git add . && git stash pop

git stash will only put all modified tracked files into separate stack, then left over files are untracked files. Then by doing git add . will stage all files untracked files, as required. Eventually, to get back all modified files from stack by doing git stash pop

Is it possible to use std::string in a constexpr?

As of C++20, yes.

As of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

Position of a string within a string using Linux shell script?

I used awk for this

a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'

Hiding the R code in Rmarkdown/knit and just showing the results

Sure, just do

```{r someVar, echo=FALSE}
someVariable
```

to show some (previously computed) variable someVariable. Or run code that prints etc pp.

So for plotting, I have eg

### Impact of choice of ....
```{r somePlot, echo=FALSE}
plotResults(Res, Grid, "some text", "some more text")
```

where the plotting function plotResults is from a local package.

Automatically size JPanel inside JFrame

You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);

This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.

How do I drop a MongoDB database from the command line?

Open another terminal window and execute the following commands,

mongodb
use mydb
db.dropDatabase()

Output of that operation shall look like the following

MAC:FOLDER USER$ mongodb
> show databases
local      0.78125GB
mydb       0.23012GB
test       0.23012GB
> use mydb
switched to db mydb
>db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
>

Please note that mydb is still in use, hence inserting any input at that time will initialize the database again.

How do I get hour and minutes from NSDate?

This seems to me to be what the question is after, no need for formatters:

NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

Why do python lists have pop() but not push()

Because it appends; it doesn't push. "Appending" adds to the end of a list, "pushing" adds to the front.

Think of a queue vs. a stack.

http://docs.python.org/tutorial/datastructures.html

Edit: To reword my second sentence more exactly, "Appending" very clearly implies adding something to the end of a list, regardless of the underlying implementation. Where a new element gets added when it's "pushed" is less clear. Pushing onto a stack is putting something on "top," but where it actually goes in the underlying data structure completely depends on implementation. On the other hand, pushing onto a queue implies adding it to the end.

How to Import Excel file into mysql Database from PHP

For >= 2nd row values insert into table-

$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    //print_r($emapData);
    //exit();
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
      mysql_query($sql);
    }                                              // add this line
}

Counting Line Numbers in Eclipse

For eclipse(Indigo), install (codepro).

After installation: - Right click on your project - Choose codepro tools --> compute metrics - And you will get your answer in a Metrics tab as Number of Lines.

#pragma once vs include guards?

I don't think it will make a significant difference in compile time but #pragma once is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent.

#pragma once is less prone to making mistakes and it is less code to type.

To speed up compile time more just forward declare instead of including in .h files when you can.

I prefer to use #pragma once.

See this wikipedia article about the possibility of using both.

Tomcat Server Error - Port 8080 already in use

Solution

You can use the troubleshooting tips below.

Troubleshooting Tip #1

  1. Exit Eclipse

  2. Open a web browser and visit, http://localhost:8080

  3. If you see a "Tomcat" web page then that means Tomcat is running as a Windows service. To stop Tomcat running as a Windows services, open your Windows Control Panel. Find the service "Apache Tomcat" and stop it.

  4. If you don't see a "Tomcat" web page, then stop the appropriate process displayed.

-- Troubleshooting Tip #2 - GUI Option

Steps to free port which is already used to run Tomcat server in Eclipse

  1. On MS Windows, select Start > All Programs > Accessories > System Tools >Resource Monitor

  2. Expand the Network Tab

  3. Move to the section for Listening Ports

  4. Look in the Port column and scroll to find entry for port 8080

  5. Select the given process and delete/kill the process

  6. Return back to Eclipse and start the Tomcat Server, it should start up now.


Troubleshooting Tip #3 - Command-Line Option

Steps to free port which is already used to run Tomcat server in Eclipse

For example , suppose 8080 port is used , we need to make free 8080 to run tomcat

Step 1: (open the CMD command)

C:\Users\username>netstat -o -n -a | findstr 0.0:8080

TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 3116

Now , we can see that LISTENING port is 3116 for 8080 ,

We need to kill 3116 now

Step 2:

C:\Users\username>taskkill /F /PID 3116

Step 3: Return back to Eclipse and start the Tomcat Server, it should start up now.

====

Mac/Linux SOLUTION

Step 0: Exit Eclipse

Step 1: Open a terminal window

Step 2: Enter the following command to find the process id

lsof -i :8080 This will give output of the application that is running on port 8080

Step 3: Enter the following command to kill the process

kill $(lsof -t -i :8080)

Step 4: Return back to Eclipse and start the Tomcat Server, it should start up now.

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

How to upgrade PowerShell version from 2.0 to 3.0

Just run this in a console.

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
cinst powershell

It installs the latest version using a Chocolatey repository.

Originally I was using command cinst powershell 3.0.20121027, but it looks like it later stopped working. Since this question is related to PowerShell 3.0 this was the right way. At this moment (June 26, 2014) cinst powershell refers to version 3.0 of PowerShell, and that may change in future.

See the Chocolatey PowerShell package page for details on what version will be installed.

Merge two dataframes by index

A silly bug that got me: the joins failed because index dtypes differed. This was not obvious as both tables were pivot tables of the same original table. After reset_index, the indices looked identical in Jupyter. It only came to light when saving to Excel...

Fixed with: df1[['key']] = df1[['key']].apply(pd.to_numeric)

Hopefully this saves somebody an hour!

Git log out user from command line

On a Mac, credentials are stored in Keychain Access. Look for Github and remove that credential. More info: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/

How do I remove a MySQL database?

drop database <db_name>;
FLUSH PRIVILEGES;

SQL keys, MUL vs PRI vs UNI

Let's understand in simple words

  • PRI - It's a primary key, and used to identify records uniquely.
  • UNI - It's a unique key, and also used to identify records uniquely. It looks similar like primary key but a table can have multiple unique keys and unique key can have one null value, on the other hand table can have only one primary key and can't store null as a primary key.
  • MUL - It's doesn't have unique constraint and table can have multiple MUL columns.

Note: These keys have more depth as a concept but this is good to start.

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

How do I restart my C# WinForm Application?

I had the same exact problem and I too had a requirement to prevent duplicate instances - I propose an alternative solution to the one HiredMind is proposing (which will work fine).

What I am doing is starting the new process with the processId of the old process (the one that triggers the restart) as a cmd line argument:

// Shut down the current app instance.
Application.Exit();

// Restart the app passing "/restart [processId]" as cmd line args
Process.Start(Application.ExecutablePath, "/restart" + Process.GetCurrentProcess().Id);

Then when the new app starts I first parse the cm line args and check if the restart flag is there with a processId, then wait for that process to Exit:

if (_isRestart)
{
   try
   {
      // get old process and wait UP TO 5 secs then give up!
      Process oldProcess = Process.GetProcessById(_restartProcessId);
      oldProcess.WaitForExit(5000);
   }
   catch (Exception ex)
   { 
      // the process did not exist - probably already closed!
      //TODO: --> LOG
   }
}

I am obviously not showing all the safety checks that I have in place etc.

Even if not ideal - I find this a valid alternative so that you don't have to have in place a separate app just to handle restart.

Convert Unicode to ASCII without errors in Python

For broken consoles like cmd.exe and HTML output you can always use:

my_unicode_string.encode('ascii','xmlcharrefreplace')

This will preserve all the non-ascii chars while making them printable in pure ASCII and in HTML.

WARNING: If you use this in production code to avoid errors then most likely there is something wrong in your code. The only valid use case for this is printing to a non-unicode console or easy conversion to HTML entities in an HTML context.

And finally, if you are on windows and use cmd.exe then you can type chcp 65001 to enable utf-8 output (works with Lucida Console font). You might need to add myUnicodeString.encode('utf8').

How to get relative path of a file in visual studio?

I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.

Suppose this is your file structure:

/BulutDepoProject
    /bin
        Main.exe
    /FolderIcon
        Folder.ico
        Main.cs

You need to write your path relative to the Main.exe file. So, you want to access Folder.ico, in your Main.cs you can use:

String path = "..\\FolderIcon\\Folder.ico"

That seemed to work for me!

How to create CSV Excel file C#?

I've added

public void ExportToFile(string path, DataTable tabela)
{

     DataColumnCollection colunas = tabela.Columns;

     foreach (DataRow linha in tabela.Rows)
     {

           this.AddRow();

           foreach (DataColumn coluna in colunas)

           {

               this[coluna.ColumnName] = linha[coluna];

           }

      }
      this.ExportToFile(path);

}

Previous code does not work with old .NET versions. For 3.5 version of framework use this other version:

        public void ExportToFile(string path)
    {
        bool abort = false;
        bool exists = false;
        do
        {
            exists = File.Exists(path);
            if (!exists)
            {
                if( !Convert.ToBoolean( File.CreateText(path) ) )
                        abort = true;
            }
        } while (!exists || abort);

        if (!abort)
        {
            //File.OpenWrite(path);
            using (StreamWriter w = File.AppendText(path))
            {
                w.WriteLine("hello");
            }

        }

        //File.WriteAllText(path, Export());
    }

TypeError: 'builtin_function_or_method' object is not subscriptable

instead of writing listb.pop[0] write

listb.pop()[0]
         ^
         |

How can I get the application's path in a .NET console application?

You can simply add to your project references System.Windows.Forms and then use the System.Windows.Forms.Application.StartupPath as usual .

So, not need for more complicated methods or using the reflection.

How do you install Boost on MacOS?

you can download bjam for OSX (or any other OS) here

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Update one table using Inner Join

  UPDATE Table1 SET name=ml.name
FROM table1 t inner JOIN
Table2 ml ON t.ID= ml.ID  

2D Euclidean vector rotations

You're calculating the y-part of your new coordinate based on the 'new' x-part of the new coordinate. Basically this means your calculating the new output in terms of the new output...

Try to rewrite in terms of input and output:

vector2<double> multiply( vector2<double> input, double cs, double sn ) {
  vector2<double> result;
  result.x = input.x * cs - input.y * sn;
  result.y = input.x * sn + input.y * cs;
  return result;
}

Then you can do this:

vector2<double> input(0,1);
vector2<double> transformed = multiply( input, cs, sn );

Note how choosing proper names for your variables can avoid this problem alltogether!

db.collection is not a function when using MongoClient v3.0

I solved it easily via running these codes:

 npm uninstall mongodb --save

 npm install [email protected] --save

Happy Coding!

java.lang.NoClassDefFoundError: org/json/JSONObject

The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject

You have not added the necessary jar file which will be having org.json.JSONObject class to your classpath.

You can Download it From Here

What is difference between Axios and Fetch?

Fetch and Axios are very similar in functionality, but for more backwards compatibility Axios seems to work better (fetch doesn't work in IE 11 for example, check this post)

Also, if you work with JSON requests, the following are some differences I stumbled upon with.

Fetch JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify({
                property_one: value_one,
                property_two: value_two
            })
        };
let response = await fetch(url, options);
let responseOK = response && response.ok;
if (responseOK) {
    let data = await response.json();
    // do something with data
}

Axios JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            url: url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data: {
                property_one: value_one,
                property_two: value_two
            }
        };
let response = await axios(options);
let responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
    let data = await response.data;
    // do something with data
}

So:

  • Fetch's body = Axios' data
  • Fetch's body has to be stringified, Axios' data contains the object
  • Fetch has no url in request object, Axios has url in request object
  • Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
  • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
  • To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.

Hope this helps.

Converting a char to ASCII?

You can use chars as is as single byte integers.

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

It is an abbreviation for 'optional' , used for optional software in some distros.

Retrieve the maximum length of a VARCHAR column in SQL Server

For Oracle, it is also LENGTH instead of LEN

SELECT MAX(LENGTH(Desc)) FROM table_name

Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.

If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example: http://jsfiddle.net/ftkbL/1/

What is the order of precedence for CSS?

Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest: CSS styling order

Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.

Can you get the column names from a SqlDataReader?

Already mentioned. Just a LINQ answer:

var columns = reader.GetSchemaTable().Rows
                                     .Cast<DataRow>()
                                     .Select(r => (string)r["ColumnName"])
                                     .ToList();

//Or

var columns = Enumerable.Range(0, reader.FieldCount)
                        .Select(reader.GetName)
                        .ToList();

The second one is cleaner and much faster. Even if you cache GetSchemaTable in the first approach, the querying is going to be very slow.

How to add a constant column in a Spark DataFrame?

In spark 2.2 there are two ways to add constant value in a column in DataFrame:

1) Using lit

2) Using typedLit.

The difference between the two is that typedLit can also handle parameterized scala types e.g. List, Seq, and Map

Sample DataFrame:

val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,"c"))).toDF("id", "col1")

+---+----+
| id|col1|
+---+----+
|  0|   a|
|  1|   b|
+---+----+

1) Using lit: Adding constant string value in new column named newcol:

import org.apache.spark.sql.functions.lit
val newdf = df.withColumn("newcol",lit("myval"))

Result:

+---+----+------+
| id|col1|newcol|
+---+----+------+
|  0|   a| myval|
|  1|   b| myval|
+---+----+------+

2) Using typedLit:

import org.apache.spark.sql.functions.typedLit
df.withColumn("newcol", typedLit(("sample", 10, .044)))

Result:

+---+----+-----------------+
| id|col1|           newcol|
+---+----+-----------------+
|  0|   a|[sample,10,0.044]|
|  1|   b|[sample,10,0.044]|
|  2|   c|[sample,10,0.044]|
+---+----+-----------------+

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I was experiencing this same error, and spent forever adding the suggested startup statements to various config files in my solution, attempting to isolate the framework mismatch. Nothing worked. I also added startup information to my XML schemas. That didn't help either. Looking at the actual file that was causing the problem (which would only say it was "moved or deleted") revealed it was actually the License Compiler (LC).

Deleting the offending licenses.licx file seems to have fixed the problem.

How to delete or add column in SQLITE?

I rewrote the @Udinic answer so that the code generates table creation query automatically. It also doesn't need ConnectionSource. It also has to do this inside a transaction.

public static String getOneTableDbSchema(SQLiteDatabase db, String tableName) {
    Cursor c = db.rawQuery(
            "SELECT * FROM `sqlite_master` WHERE `type` = 'table' AND `name` = '" + tableName + "'", null);
    String result = null;
    if (c.moveToFirst()) {
        result = c.getString(c.getColumnIndex("sql"));
    }
    c.close();
    return result;
}

public List<String> getTableColumns(SQLiteDatabase db, String tableName) {
    ArrayList<String> columns = new ArrayList<>();
    String cmd = "pragma table_info(" + tableName + ");";
    Cursor cur = db.rawQuery(cmd, null);

    while (cur.moveToNext()) {
        columns.add(cur.getString(cur.getColumnIndex("name")));
    }
    cur.close();

    return columns;
}

private void dropColumn(SQLiteDatabase db, String tableName, String[] columnsToRemove) {
    db.beginTransaction();
    try {
        List<String> columnNamesWithoutRemovedOnes = getTableColumns(db, tableName);
        // Remove the columns we don't want anymore from the table's list of columns
        columnNamesWithoutRemovedOnes.removeAll(Arrays.asList(columnsToRemove));

        String newColumnNamesSeparated = TextUtils.join(" , ", columnNamesWithoutRemovedOnes);
        String sql = getOneTableDbSchema(db, tableName);
        // Extract the SQL query that contains only columns
        String oldColumnsSql = sql.substring(sql.indexOf("(")+1, sql.lastIndexOf(")"));

        db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
        db.execSQL("CREATE TABLE `" + tableName + "` (" + getSqlWithoutRemovedColumns(oldColumnsSql, columnsToRemove)+ ");");
        db.execSQL("INSERT INTO " + tableName + "(" + newColumnNamesSeparated + ") SELECT " + newColumnNamesSeparated + " FROM " + tableName + "_old;");
        db.execSQL("DROP TABLE " + tableName + "_old;");
        db.setTransactionSuccessful();
    } catch {
        //Error in between database transaction 
    } finally {
        db.endTransaction();
    }


}

org.json.simple cannot be resolved

try this

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

ReferenceError: variable is not defined

Got the error (in the function init) with the following code ;

"use strict" ;

var hdr ;

function init(){ // called on load
    hdr = document.getElementById("hdr");
}

... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The fix for this was to change

var hdr ;

to

var hdr = null ;

Set database from SINGLE USER mode to MULTI USER

I have solved the problem easily

  1. Right click on database name rename it

  2. After changing, right click on database name --> properties --> options --> go to bottom of scrolling RestrictAccess (SINGLE_USER to MULTI_USER)

  3. Now again you can rename database as your old name.

How to use <DllImport> in VB.NET?

Imports System.Runtime.InteropServices

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

How to find largest objects in a SQL Server database?

This query help to find largest table in you are connection.

SELECT  TOP 1 OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2
ORDER BY st.row_count DESC

Font Awesome 5 font-family issue

I had tried all above the solutions for Font Awesome 5 but it wasn't working for me. :(

Finally, I got a solution!

Just use font-family: "Font Awesome 5 Pro"; in your CSS instead of using font-family: "Font Awesome 5 Free OR Solids OR Brands";

How to get row data by clicking a button in a row in an ASP.NET gridview

<ItemTemplate>
     <asp:Button ID="Button1" runat="server" Text="Button" 
            OnClick="MyButtonClick" />
</ItemTemplate>

and your method

 protected void MyButtonClick(object sender, System.EventArgs e)
{
     //Get the button that raised the event
Button btn = (Button)sender;

    //Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

How to "Open" and "Save" using java

You want to use a JFileChooser object. It will open and be modal, and block in the thread that opened it until you choose a file.

Open:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // load from file
}

Save:

JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
  File file = fileChooser.getSelectedFile();
  // save to file
}

There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser for details. There is also a page for "How to Use File Choosers" on Oracle's site:

http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

How can I disable all views inside the layout?

The easiest way is creating a <View in your xml, with match_parent for height and width, make sure the view is above every other views, then when you want to prevent clicks, make it visible add an onClickListener to that view with null as parameter.

Example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
        android:layout_height="fill_parent">
     <Button 
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:id="@+id/my_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/my_text_view"
            android:text="First Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/my_edit_view"
            android:width="100px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" /> 
        
        <View
            android:id="@+id/disable_layout_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"/>
    </LinearLayout>

</LinearLayout>

Then in your code:

val disableLayoutView = rootView.find<View>(R.id.disable_layout_view)
disableLayoutView.visibility = View.VISIBLE
disableLayoutView.setOnClickListener(null)

What does it mean when Statement.executeUpdate() returns -1?

This doesn't explain why it should be like that, but it explains why it could happen. The following byte-code sets -1 to the internal updateCount flag in the SQLServerStatement constructor:

// Method descriptor #401 (Lcom/microsoft/sqlserver/jdbc/SQLServerConnection;II)V
// Stack: 5, Locals: 8
SQLServerStatement(
  com.microsoft.sqlserver.jdbc.SQLServerConnection arg0, int arg1, int arg2) 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

34 aload_0 [this]
35 iconst_m1
36 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

Now, I will not analyse all possible control-flows, but I'd just say that this is the internal default initialisation value that somehow leaks out to client code. Note, this is also done in other methods:

// Method descriptor #383 ()V
// Stack: 2, Locals: 1
final void resetForReexecute() 
throws com.microsoft.sqlserver.jdbc.SQLServerException;

// [...]

10 aload_0 [this]
11 iconst_m1
12 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

// Method descriptor #383 ()V
// Stack: 3, Locals: 3
final void clearLastResult();
0 aload_0 [this]
1 iconst_m1
2 putfield com.microsoft.sqlserver.jdbc.SQLServerStatement.updateCount:int [27]

In other words, you're probably safe interpreting -1 as being the same as 0. If you rely on this result value, maybe stay on the safe side and do your checks as follows:

// No rows affected
if (stmt.executeUpdate() <= 0) {
}
// Rows affected
else {
}

UPDATE: While reading Mark Rotteveel's answer, I tend to agree with him, assuming that -1 is the JDBC-compliant value for "unknown update counts". Even if this isn't documented on the relevant method's Javadoc, it's documented in the JDBC specs, chapter 13.1.2.3 Returning Unknown or Multiple Results. In this very case, it could be said that an IF .. INSERT .. statement will have an "unknown update count", as this statement isn't SQL-standard compliant anyway.

Sniff HTTP packets for GET and POST requests from an application

post in http
Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet

Java correct way convert/cast object to Double

I tried this and it worked:

Object obj = 10;
String str = obj.toString(); 
double d = Double.valueOf(str).doubleValue();

Android custom Row Item for ListView

Add this row.xml to your layout folder

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Header"/>

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/text"/>
    
    
</LinearLayout>

make your main xml layout as this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>

This is your adapter

class yourAdapter extends BaseAdapter {

    Context context;
    String[] data;
    private static LayoutInflater inflater = null;

    public yourAdapter(Context context, String[] data) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.row, null);
        TextView text = (TextView) vi.findViewById(R.id.text);
        text.setText(data[position]);
        return vi;
    }
}

Your java activity

public class StackActivity extends Activity {

    ListView listview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(new yourAdapter(this, new String[] { "data1",
                "data2" }));
    }
}

the results

enter image description here

How to create JSON string in JavaScript?

The function JSON.stringify will turn your json object into a string:

var jsonAsString = JSON.stringify(obj);

In case the browser does not implement it (IE6/IE7), use the JSON2.js script. It's safe as it uses the native implementation if it exists.

Unstaged changes left after git reset --hard

Git won't reset files that aren't on repository. So, you can:

$ git add .
$ git reset --hard

This will stage all changes, which will cause Git to be aware of those files, and then reset them.

If this does not work, you can try to stash and drop your changes:

$ git stash
$ git stash drop

How to set JAVA_HOME in Linux for all users

Doing what Oracle does (as a former Sun Employee I can't get used to that one)

ln -s latestJavaRelease /usr/java/default
Where latestJavaRelease is the version that you want to use

then export JAVA_HOME=/usr/java/default

no debugging symbols found when using gdb

Some Linux distributions don't use the gdb style debugging symbols. (IIRC they prefer dwarf2.)

In general, gcc and gdb will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

In my case the solution was quite simple. I added this header and the browsers opened the file in every test. header('Content-Disposition: attachment; filename="filename.pdf"');

Find duplicate records in MySQL

Find duplicate users by email address with this query...

SELECT users.name, users.uid, users.mail, from_unixtime(created)
FROM users
INNER JOIN (
  SELECT mail
  FROM users
  GROUP BY mail
  HAVING count(mail) > 1
) dupes ON users.mail = dupes.mail
ORDER BY users.mail;

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

Get the distance between two geo points

a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)

c = 2 · atan2( va, v(1-a) )

distance = R · c

where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);

note that angles need to be in radians to pass to trig functions!

fun distanceInMeter(firstLocation: Location, secondLocation: Location): Double {
    val earthRadius = 6371000.0
    val deltaLatitudeDegree = (firstLocation.latitude - secondLocation.latitude) * Math.PI / 180f
    val deltaLongitudeDegree = (firstLocation.longitude - secondLocation.longitude) * Math.PI / 180f
    val a = sin(deltaLatitudeDegree / 2).pow(2) +
            cos(firstLocation.latitude * Math.PI / 180f) * cos(secondLocation.latitude * Math.PI / 180f) *
            sin(deltaLongitudeDegree / 2).pow(2)
    val c = 2f * atan2(sqrt(a), sqrt(1 - a))
    return earthRadius * c
}


data class Location(val latitude: Double, val longitude: Double)

Update .NET web service to use TLS 1.2

For me below worked:

Step 1: Downloaded and installed the web Installer exe from https://www.microsoft.com/en-us/download/details.aspx?id=48137 on the application server. Rebooted the application server after installation was completed.

Step 2: Added below changes in the web.config

<system.web>
    <compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->
    <!--Added this httpRuntime -->
    <httpRuntime targetFramework="4.6" />
</system.web>

Step 3: After completing step 1 and 2, it gave an error, "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)" and to resolve this error, I added below key in appsettings in my web.config file

<appSettings>
      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Shell - Write variable contents to a file

Use the echo command:

var="text to append";
destdir=/some/directory/path/filename

if [ -f "$destdir" ]
then 
    echo "$var" > "$destdir"
fi

The if tests that $destdir represents a file.

The > appends the text after truncating the file. If you only want to append the text in $var to the file existing contents, then use >> instead:

echo "$var" >> "$destdir"

The cp command is used for copying files (to files), not for writing text to a file.

How to detect READ_COMMITTED_SNAPSHOT is enabled?

Neither on SQL2005 nor 2012 does DBCC USEROPTIONS show is_read_committed_snapshot_on:

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

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

I'd like to add one important aspect to other answers, which actually explained this topic to me in the best way:

If 2 joined tables contain M and N rows, then cross join will always produce (M x N) rows, but full outer join will produce from MAX(M,N) to (M + N) rows (depending on how many rows actually match "on" predicate).

EDIT:

From logical query processing perspective, CROSS JOIN does indeed always produce M x N rows. What happens with FULL OUTER JOIN is that both left and right tables are "preserved", as if both LEFT and RIGHT join happened. So rows, not satisfying ON predicate, from both left and right tables are added to the result set.

Creating and Update Laravel Eloquent

Here's a full example of what "lu cip" was talking about:

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save();

Below is the updated link of the docs which is on the latest version of Laravel

Docs here: Updated link

How to give the background-image path in CSS?

Use the below.

background-image: url("././images/image.png");

This shall work.

PHP: How to use array_filter() to filter array keys?

With this function you can filter a multidimensional array

function filter_array_keys($array,$filter_keys=array()){

    $l=array(&$array);
    $c=1;
    //This first loop will loop until the count var is stable//
    for($r=0;$r<$c;$r++){
        //This loop will loop thru the child element list//
        $keys = array_keys($l[$r]);

        for($z=0;$z<count($l[$r]);$z++){
            $object = &$l[$r][$keys[$z]];

            if(is_array($object)){
                $i=0;
                $keys_on_array=array_keys($object);
                $object=array_filter($object,function($el) use(&$i,$keys_on_array,$filter_keys){
                    $key = $keys_on_array[$i];
                    $i++;

                    if(in_array($key,$filter_keys) || is_int($key))return false;                
                    return true;                        
                });
            }

            if(is_array($l[$r][$keys[$z]])){
                $l[] = &$l[$r][$keys[$z]];
                $c++;
            }//IF           
        }//FOR
    }//FOR  

    return $l[0];

}

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

If you can produce a small demo showing the onMouseEnter / onMouseLeave or onMouseDown / onMouseUp bug, it would be worthwhile to post it to ReactJS's issues page or mailing list, just to raise the question and hear what the developers have to say about it.

In your use case, you seem to imply that CSS :hover and :active states would be enough for your purposes, so I suggest you use them. CSS is orders of magnitude faster and more reliable than Javascript, because it's directly implemented in the browser.

However, :hover and :active states cannot be specified in inline styles. What you can do is assign an ID or a class name to your elements and write your styles either in a stylesheet, if they are somewhat constant in your application, or in a dynamically generated <style> tag.

Here's an example of the latter technique: https://jsfiddle.net/ors1vos9/

Keras, How to get the output of each layer?

This answer is based on: https://stackoverflow.com/a/59557567/2585501

To print the output of a single layer:

from tensorflow.keras import backend as K
layerIndex = 1
func = K.function([model.get_layer(index=0).input], model.get_layer(index=layerIndex).output)
layerOutput = func([input_data])  # input_data is a numpy array
print(layerOutput)

To print output of every layer:

from tensorflow.keras import backend as K
for layerIndex, layer in enumerate(model.layers):
    func = K.function([model.get_layer(index=0).input], layer.output)
    layerOutput = func([input_data])  # input_data is a numpy array
    print(layerOutput)

C# Copy a file to another location with a different name

If you want to use only FileInfo class try this

             string oldPath = @"C:\MyFolder\Myfile.xyz";
             string newpath = @"C:\NewFolder\";
             string newFileName = "new file name";
             FileInfo f1 = new FileInfo(oldPath);
           if(f1.Exists)
             {
                if(!Directory.Exists(newpath))
                {
                    Directory.CreateDirectory(newpath); 
                }
                 f1.CopyTo(string.Format("{0}{1}{2}", newpath, newFileName, f1.Extension));
             }

How can I send an xml body using requests library?

Just send xml bytes directly:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests

xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text

Output

{
  "origin": "x.x.x.x",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "48",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Connection": "keep-alive",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
    "Host": "httpbin.org",
    "Content-Type": "application/xml"
  },
  "json": null,
  "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}

Powershell remoting with ip-address as target

The error message is giving you most of what you need. This isn't just about the TrustedHosts list; it's saying that in order to use an IP address with the default authentication scheme, you have to ALSO be using HTTPS (which isn't configured by default) and provide explicit credentials. I can tell you're at least not using SSL, because you didn't use the -UseSSL switch.

Note that SSL/HTTPS is not configured by default - that's an extra step you'll have to take. You can't just add -UseSSL.

The default authentication mechanism is Kerberos, and it wants to see real host names as they appear in AD. Not IP addresses, not DNS CNAME nicknames. Some folks will enable Basic authentication, which is less picky - but you should also set up HTTPS since you'd otherwise pass credentials in cleartext. Enable-PSRemoting only sets up HTTP.

Adding names to your hosts file won't work. This isn't an issue of name resolution; it's about how the mutual authentication between computers is carried out.

Additionally, if the two computers involved in this connection aren't in the same AD domain, the default authentication mechanism won't work. Read "help about_remote_troubleshooting" for information on configuring non-domain and cross-domain authentication.

From the docs at http://technet.microsoft.com/en-us/library/dd347642.aspx

HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND
-----------------------------------------------------
    ERROR:  The WinRM client cannot process the request. If the
    authentication scheme is different from Kerberos, or if the client
    computer is not joined to a domain, then HTTPS transport must be used
    or the destination machine must be added to the TrustedHosts
    configuration setting.

The ComputerName parameters of the New-PSSession, Enter-PSSession and
Invoke-Command cmdlets accept an IP address as a valid value. However,
because Kerberos authentication does not support IP addresses, NTLM
authentication is used by default whenever you specify an IP address. 

When using NTLM authentication, the following procedure is required
for remoting.

1. Configure the computer for HTTPS transport or add the IP addresses
   of the remote computers to the TrustedHosts list on the local
   computer.

   For instructions, see "How to Add a Computer to the TrustedHosts
   List" below.


2. Use the Credential parameter in all remote commands.

   This is required even when you are submitting the credentials
   of the current user.

integrating barcode scanner into php application?

You can use AJAX for that. Whenever you scan a barcode, your scanner will act as if it is a keyboard typing into your input type="text" components. With JavaScript, capture the corresponding event, and send HTTP REQUEST and process responses accordingly.

HashMaps and Null values?

Its a good programming practice to avoid having null values in a Map.

If you have an entry with null value, then it is not possible to tell whether an entry is present in the map or has a null value associated with it.

You can either define a constant for such cases (Example: String NOT_VALID = "#NA"), or you can have another collection storing keys which have null values.

Please check this link for more details.

See line breaks and carriage returns in editor

by using cat and -A you can see new lines as $, tabs as ^I
cat -A myfile

Convert canvas to PDF

So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.

  // Download button
  $("#download-image").on('click', function () {
    let width = __CANVAS.width; 
    let height = __CANVAS.height;

    //set the orientation
    if(width > height){
      pdf = new jsPDF('l', 'px', [width, height]);
    }
    else{
      pdf = new jsPDF('p', 'px', [height, width]);
    }
    //then we get the dimensions from the 'pdf' file itself
    width = pdf.internal.pageSize.getWidth();
    height = pdf.internal.pageSize.getHeight();
    pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
    pdf.save("download.pdf");
  });

Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476

Determining type of an object in ruby

variable_name.class

Here variable name is "a" a.class

How to set time to midnight for current day?

Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.

double utcOffset= 10.0;  // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;

var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);

How to write an inline IF statement in JavaScript?

You don't necessarily need jQuery. JavaScript alone will do this.

var a = 2;
var b = 3;    
var c = ((a < b) ? 'minor' : 'major');

The c variable will be minor if the value is true, and major if the value is false.


This is known as a Conditional (ternary) Operator.

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

Insert entire DataTable into database at once instead of row by row?

Since you have a DataTable already, and since I am assuming you are using SQL Server 2008 or better, this is probably the most straightforward way. First, in your database, create the following two objects:

CREATE TYPE dbo.MyDataTable -- you can be more speciifc here
AS TABLE
(
  col1 INT,
  col2 DATETIME
  -- etc etc. The columns you have in your data table.
);
GO

CREATE PROCEDURE dbo.InsertMyDataTable
  @dt AS dbo.MyDataTable READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT dbo.RealTable(column list) SELECT column list FROM @dt;
END
GO

Now in your C# code:

DataTable tvp = new DataTable();
// define / populate DataTable

using (connectionObject)
{
    SqlCommand cmd = new SqlCommand("dbo.InsertMyDataTable", connectionObject);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlParameter tvparam = cmd.Parameters.AddWithValue("@dt", tvp);
    tvparam.SqlDbType = SqlDbType.Structured;
    cmd.ExecuteNonQuery();
}

If you had given more specific details in your question, I would have given a more specific answer.

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

How to SSH to a VirtualBox guest externally through a host?

Keeping the NAT adapter and adding a second host-only adapter works amazing, and is crucial for laptops (where the external network always changes).

http://muffinresearch.co.uk/archives/2010/02/08/howto-ssh-into-virtualbox-3-linux-guests/

Remember to create a host-only network in virtualbox itself (GUI -> settings -> network), otherwise you can't create the host-only interface on the guest.

Get decimal portion of a number with JavaScript

You could convert it to a string and use the replace method to replace the integer part with zero, then convert the result back to a number :

var number = 123.123812,
    decimals = +number.toString().replace(/^[^\.]+/,'0');

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Can pandas automatically recognize dates?

Perhaps the pandas interface has changed since @Rutger answered, but in the version I'm using (0.15.2), the date_parser function receives a list of dates instead of a single value. In this case, his code should be updated like so:

dateparse = lambda dates: [pd.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dates]

df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)

Join two sql queries

Try this:

select Activity, SUM(Incomes.Amount) as "Total Amount 2009", SUM(Incomes2008.Amount) 
as "Total Amount 2008" from
Activities, Incomes, Incomes2008
where Activities.UnitName = ?  AND
Incomes.ActivityId = Activities.ActivityID  AND
Incomes2008.ActivityId = Activities.ActivityID GROUP BY
Activity ORDER BY Activity;

Basically you have to JOIN Incomes2008 table with the output of your first query.

Select all DIV text with single mouse click

Using a text area field, you could use this: (Via Google)

<form name="select_all">

    <textarea name="text_area" rows="10" cols="80" 
    onClick="javascript:this.form.text_area.focus();this.form.text_area.select();">

    Text Goes Here 

    </textarea>
</form>

This is how I see most websites do it. They just style it with CSS so it doesn't look like a textarea.

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

More information will be useful.

When I was faced with the same error message all I had to do was to correctly configure the credentials page of the DataSource(I am using Report Builder 3). if you chose the default, the report would work fine in Report Builder but would fail on the Report Server.

You may review more details of this fix here: https://hodentekmsss.blogspot.com/2017/05/fix-for-rserroropeningconnection-in.html

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

in order to synchronize your branch list. The git manual says

-p, --prune
After fetching, remove any remote-tracking references that no longer exist on the remote. Tags are not subject to pruning if they are fetched only because of the default tag auto-following or due to a --tags option. However, if tags are fetched due to an explicit refspec (either on the command line or in the remote configuration, for example if the remote was cloned with the --mirror option), then they are also subject to pruning.

I personally like to use git fetch origin -p --progress because it shows a progress indicator.

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

Getting the PublicKeyToken of .Net assemblies

You can add this as an external tool to Visual Studio like so:

Title:

Get PublicKeyToken

Command:

c:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\sn.exe

(Path may differ between versions)

Arguments:

-T "$(TargetPath)"

And check the "Use Output window" option.

Why rgb and not cmy?

The difference lies in whether mixing colours results in LIGHTER or DARKER colours. When mixing light, the result is a lighter colour, so mixing red light and blue light becomes a lighter pink. When mixing paint (or ink), red and blue become a darker purple. Mixing paint results in DARKER colours, whereas mixing light results in LIGHTER colours. Therefore for paint the primary colours are Red Yellow Blue (or Cyan Magenta Yellow) as you stated. Yet for light the primary colours are Red Green Blue. It is (virtually) impossible to mix Red Green Blue paint into Yellow paint, or mixing Red Yellow Blue light into Green light.

Not Equal to This OR That in Lua

x ~= 0 or 1 is the same as ((x ~= 0) or 1)

x ~=(0 or 1) is the same as (x ~= 0).

try something like this instead.

function isNot0Or1(x)
    return (x ~= 0 and x ~= 1)
end

print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )

removing html element styles via javascript

In jQuery, you can use

$(".className").attr("style","");

HTML5 canvas ctx.fillText won't do line breaks?

Here is my function to draw multiple lines of text center in canvas (only break the line, don't break-word)

_x000D_
_x000D_
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

let text = "Hello World \n Hello World 2222 \n AAAAA \n thisisaveryveryveryveryveryverylongword. "
ctx.font = "20px Arial";

fillTextCenter(ctx, text, 0, 0, c.width, c.height)

function fillTextCenter(ctx, text, x, y, width, height) {
    ctx.textBaseline = 'middle';
    ctx.textAlign = "center";

    const lines = text.match(/[^\r\n]+/g);
    for(let i = 0; i < lines.length; i++) {
        let xL = (width - x) / 2
        let yL =  y + (height / (lines.length + 1)) * (i+1)

        ctx.fillText(lines[i], xL, yL)
    }
}
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
_x000D_
_x000D_
_x000D_

If you want to fit text size to canvas, you can also check here

String comparison in bash. [[: not found

As @Ansgar mentioned, [[ is a bashism, ie built into Bash and not available for other shells. If you want your script to be portable, use [. Comparisons will also need a different syntax: change == to =.

Refreshing all the pivot tables in my excel workbook with a macro

In certain circumstances you might want to differentiate between a PivotTable and its PivotCache. The Cache has it's own refresh method and its own collections. So we could have refreshed all the PivotCaches instead of the PivotTables.

The difference? When you create a new Pivot Table you are asked if you want it based on a previous table. If you say no, this Pivot Table gets its own cache and doubles the size of the source data. If you say yes, you keep your WorkBook small, but you add to a collection of Pivot Tables that share a single cache. The entire collection gets refreshed when you refresh any single Pivot Table in that collection. You can imagine therefore what the difference might be between refreshing every cache in the WorkBook, compared to refreshing every Pivot Table in the WorkBook.

How to capture a list of specific type with mockito

For an earlier version of junit, you can do

Class<Map<String, String>> mapClass = (Class) Map.class;
ArgumentCaptor<Map<String, String>> mapCaptor = ArgumentCaptor.forClass(mapClass);

How to show two figures using matplotlib?

You should call plt.show() only at the end after creating all the plots.

Formatting ISODate from Mongodb

JavaScript's Date object supports the ISO date format, so as long as you have access to the date string, you can do something like this:

> foo = new Date("2012-07-14T01:00:00+01:00")
Sat, 14 Jul 2012 00:00:00 GMT
> foo.toTimeString()
'17:00:00 GMT-0700 (MST)'

If you want the time string without the seconds and the time zone then you can call the getHours() and getMinutes() methods on the Date object and format the time yourself.

Cannot declare instance members in a static class in C#

As John Weldon said all members must be static in a static class. Try

public static class employee
{
     static NameValueCollection appSetting = ConfigurationManager.AppSettings;    

}

How to add url parameters to Django template url tag?

1: HTML

           <tbody>
            {% for ticket in tickets %}
              <tr>
                <td class="ticket_id">{{ticket.id}}</td>
                <td class="ticket_eam">{{ticket.eam}}</td>
                <td class="ticket_subject">{{ticket.subject}}</td>
                <td>{{ticket.zone}}</td>
                <td>{{ticket.plaza}}</td>
                <td>{{ticket.lane}}</td>
                <td>{{ticket.uptime}}</td>
                <td>{{ticket.downtime}}</td>
                <td><a href="{% url 'ticket_details' ticket_id=ticket.id %}"><button data-toggle="modal" data-target="#modaldemo3" class="value-modal"><i class="icon ion-edit"></a></i></button> <button><i class="fa fa-eye-slash"></i></button>
              </tr>
            {% endfor %}
            </tbody>

The {% url 'ticket_details' %} is the function name in your views

2: Views.py

def ticket_details(request, ticket_id):

   print(ticket_id)
   return render(request, ticket.html)

ticket_id is the parameter you will get from the ticket_id=ticket.id

3: URL.py

urlpatterns = [
path('ticket_details/?P<int:ticket_id>/', views.ticket_details, name="ticket_details") ]

/?P - where ticket_id is the name of the group and pattern is some pattern to match.

Control cannot fall through from one case label

Since it wasn't mentioned in the other answers, I'd like to add that if you want case SearchAuthors to be executed right after the first case, just like omitting the break in some other programming languages where that is allowed, you can simply use goto.

switch (searchType)
{
    case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    goto case "SearchAuthors";

    case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

How can I center a div within another div?

I have used the following method in a few projects:

https://jsfiddle.net/u3Ln0hm4/

.cellcenterparent{
  width: 100%;
  height: 100%;
  display: table;
}

.cellcentercontent{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

Writing File to Temp Folder

For %appdata% take a look to

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Java Serializable Object to Byte Array

If you use Java >= 7, you could improve the accepted solution using try with resources:

private byte[] convertToBytes(Object object) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutputStream out = new ObjectOutputStream(bos)) {
        out.writeObject(object);
        return bos.toByteArray();
    } 
}

And the other way around:

private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
         ObjectInputStream in = new ObjectInputStream(bis)) {
        return in.readObject();
    } 
}

Run react-native application on iOS device directly from command line?

The following worked for me (tested on react native 0.38 and 0.40):

npm install -g ios-deploy
# Run on a connected device, e.g. Max's iPhone:
react-native run-ios --device "Max's iPhone"

If you try to run run-ios, you will see that the script recommends to do npm install -g ios-deploy when it reach install step after building.

While the documentation on the various commands that react-native offers is a little sketchy, it is worth going to react-native/local-cli. There, you can see all the commands available and the code that they run - you can thus work out what switches are available for undocumented commands.

How to list imported modules?

This code lists modules imported by your module:

import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]

It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.

It won't list the sys module or modules imported from it.

EOFError: end of file reached issue with Net::HTTP

In Ruby on Rails I used this code, and it works perfectly:

req_profilepic = ActiveSupport::JSON.decode(open(URI.encode("https://graph.facebook.com/me/?fields=picture&type=large&access_token=#{fb_access_token}")))

profilepic_url = req_profilepic['picture']

Importing a Maven project into Eclipse from Git

Import without installing any additional connectors for Mylyn:

  1. Open Git Repositories view (Window->Show view->Git Repositories)
  2. Press Clone a Git Repository button and proceed with all steps
  3. In newly created repository expand Working Directory, right click on folder with your project and select Import Projects. Then either choose Import existing projects, or select Import as general project. If needed after importing right click on your project and select Configure->Convert to Maven Project (and Maven->Update Project).

Get values from other sheet using VBA

SomeVal=ActiveWorkbook.worksheets("Sheet2").cells(aRow,aCol).Value

did not work. However the following code only worked for me.

SomeVal = ThisWorkbook.Sheets(2).cells(aRow,aCol).Value

getActivity() returns null in Fragment function

Do as follows. I think it will be helpful to you.

private boolean isVisibleToUser = false;
private boolean isExecutedOnce = false;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_my, container, false);
    if (isVisibleToUser && !isExecutedOnce) {
        executeWithActivity(getActivity());
    }
    return root;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    this.isVisibleToUser = isVisibleToUser;
    if (isVisibleToUser && getActivity()!=null) {
        isExecutedOnce =true;
        executeWithActivity(getActivity());
    }
}


private void executeWithActivity(Activity activity){
    //Do what you have to do when page is loaded with activity

}

How do I change the language of moment.js?

I had to import also the language:

import moment from 'moment'
import 'moment/locale/es'  // without this line it didn't work
moment.locale('es')

Then use moment like you normally would

alert(moment(date).fromNow())

A full list of all the new/popular databases and their uses?

There are graph databases like:

A graph database stores data as nodes and relationships/edges.This is a good fit for semi-structured data, interconnected information and domains with deep relationships/traversal, for example social networks and knowledge representation. The data model is highly flexible and "whiteboard friendly". The underlying data model of the semantic web, RDF, is also a (labeled, directed multi-)graph.

Other stackoverflow threads with information on graph databases:

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

MongoDB SELECT COUNT GROUP BY

Starting in MongoDB 3.4, you can use the $sortByCount aggregation.

Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/

For example:

db.contest.aggregate([
    { $sortByCount: "$province" }
]);

How to check if a char is equal to an empty space?

Since char is a primitive type, you can just write c == ' '.
You only need to call equals() for reference types like String or Character.

Use FontAwesome or Glyphicons with css :before

This is the easiest way to do what you are trying to do:

http://jsfiddle.net/ZEDHT/

<style>
 ul {
   list-style-type: none;
 }
</style>

<ul class="icons">
 <li><i class="fa fa-bomb"></i> Lists</li>
 <li><i class="fa fa-bomb"></i> Buttons</li>
 <li><i class="fa fa-bomb"></i> Button groups</li>
 <li><i class="fa fa-bomb"></i> Navigation</li>
 <li><i class="fa fa-bomb"></i> Prepended form inputs</li>
</ul>

Can't subtract offset-naive and offset-aware datetimes

The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:

from datetime import datetime, timezone

now = datetime.now(timezone.utc)

On older Python versions, you could define the utc tzinfo object yourself (example from datetime docs):

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTC(tzinfo):
  def utcoffset(self, dt):
    return ZERO
  def tzname(self, dt):
    return "UTC"
  def dst(self, dt):
    return ZERO

utc = UTC()

then:

now = datetime.now(utc)

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

If it's reasonable to alter the original Map data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null key entries, if possible, before calling Jackson. That said...


To suppress serializing Map entries with null values:

Before Jackson 2.9

you can still make use of WRITE_NULL_MAP_VALUES, but note that it's moved to SerializationFeature:

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

Since Jackson 2.9

The WRITE_NULL_MAP_VALUES is deprecated, you can use the below equivalent:

mapper.setDefaultPropertyInclusion(
   JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))

To suppress serializing properties with null values, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To handle null Map keys, some custom serialization is necessary, as best I understand.

A simple approach to serialize null keys as empty strings (including complete examples of the two previously mentioned configurations):

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Map<String, Foo> foos = new HashMap<String, Foo>();
    foos.put("foo1", new Foo("foo1"));
    foos.put("foo2", new Foo(null));
    foos.put("foo3", null);
    foos.put(null, new Foo("foo4"));

    // System.out.println(new ObjectMapper().writeValueAsString(foos));
    // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
    System.out.println(mapper.writeValueAsString(foos));
    // output: 
    // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
  }
}

class MyNullKeySerializer extends JsonSerializer<Object>
{
  @Override
  public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) 
      throws IOException, JsonProcessingException
  {
    jsonGenerator.writeFieldName("");
  }
}

class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To suppress serializing Map entries with null keys, further custom serialization processing would be necessary.

How to do a LIKE query with linq?

2019 is here:

Requires EF6

using System.Data.Entity;
string searchStr ="bla bla bla";
var result = _dbContext.SomeTable.Where(x=> DbFunctions.Like(x.NameAr, string.Format("%{0}%", searchStr ))).FirstOrDefault();

Passing multiple values to a single PowerShell script parameter

Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:

param(
    [Parameter(Position = 0)]
    [string[]]$Hosts,
    [string]$VLAN
    )

foreach ($i in $Hosts)  
{ 
    Do-Stuff $i
}

Then call it like:

.\script.ps1 host1, host2, host3 -VLAN 2

Notice the comma between the values. This collects them in an array

Creating a SearchView that looks like the material design guidelines

It is actually quite easy to do this, if you are using android.support.v7 library.

Step - 1

Declare a menu item

<item android:id="@+id/action_search"
    android:title="Search"
    android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" />

Step - 2

Extend AppCompatActivity and in the onCreateOptionsMenu setup the SearchView.

import android.support.v7.widget.SearchView;

...

public class YourActivity extends AppCompatActivity {

    ...

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        // Retrieve the SearchView and plug it into SearchManager
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    ... 

}

Result

enter image description here

enter image description here

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

There are possible solutions here: http://forums.mysql.com/read.php?35,64808,254785#msg-254785 and here: http://forums.mysql.com/read.php?35,23138,254786#msg-254786

All of these are config settings. In my case I have two computers with everything in XAMPP synced. On the other computer phpMyAdmin did start normally. So the problem in my case seemed to be with the specific computer, not the config files. Stopping firewall didn't help.

Finally, more or less by accident, I bumped into the file:

...path_to_XAMPP\XAMPP...\mysql\bin\mysqld-debug.exe

Doubleclicking that file miraculously gave me back PhpMyAdmin. Posted here in case anyone might be helped by this too.

What is the difference between a pandas Series and a single-column DataFrame?

Series is a one-dimensional object that can hold any data type such as integers, floats and strings e.g

   import pandas as pd
   x = pd.Series([A,B,C]) 

0 A
1 B
2 C

The first column of Series is known as index i.e 0,1,2 the second column is your actual data i.e A,B,C

DataFrames is two-dimensional object that can hold series, list, dictionary

df=pd.DataFrame(rd(5,4),['A','B','C','D','E'],['W','X','Y','Z'])

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

Check if number is prime number

I've implemented a different method to check for primes because:

  • Most of these solutions keep iterating through the same multiple unnecessarily (for example, they check 5, 10, and then 15, something that a single % by 5 will test for).
  • A % by 2 will handle all even numbers (all integers ending in 0, 2, 4, 6, or 8).
  • A % by 5 will handle all multiples of 5 (all integers ending in 5).
  • What's left is to test for even divisions by integers ending in 1, 3, 7, or 9. But the beauty is that we can increment by 10 at a time, instead of going up by 2, and I will demonstrate a solution that is threaded out.
  • The other algorithms are not threaded out, so they don't take advantage of your cores as much as I would have hoped.
  • I also needed support for really large primes, so I needed to use the BigInteger data-type instead of int, long, etc.

Here is my implementation:

public static BigInteger IntegerSquareRoot(BigInteger value)
{
    if (value > 0)
    {
        int bitLength = value.ToByteArray().Length * 8;
        BigInteger root = BigInteger.One << (bitLength / 2);
        while (!IsSquareRoot(value, root))
        {
            root += value / root;
            root /= 2;
        }
        return root;
    }
    else return 0;
}

private static Boolean IsSquareRoot(BigInteger n, BigInteger root)
{
    BigInteger lowerBound = root * root;
    BigInteger upperBound = (root + 1) * (root + 1);
    return (n >= lowerBound && n < upperBound);
}

static bool IsPrime(BigInteger value)
{
    Console.WriteLine("Checking if {0} is a prime number.", value);
    if (value < 3)
    {
        if (value == 2)
        {
            Console.WriteLine("{0} is a prime number.", value);
            return true;
        }
        else
        {
            Console.WriteLine("{0} is not a prime number because it is below 2.", value);
            return false;
        }
    }
    else
    {
        if (value % 2 == 0)
        {
            Console.WriteLine("{0} is not a prime number because it is divisible by 2.", value);
            return false;
        }
        else if (value == 5)
        {
            Console.WriteLine("{0} is a prime number.", value);
            return true;
        }
        else if (value % 5 == 0)
        {
            Console.WriteLine("{0} is not a prime number because it is divisible by 5.", value);
            return false;
        }
        else
        {
            // The only way this number is a prime number at this point is if it is divisible by numbers ending with 1, 3, 7, and 9.
            AutoResetEvent success = new AutoResetEvent(false);
            AutoResetEvent failure = new AutoResetEvent(false);
            AutoResetEvent onesSucceeded = new AutoResetEvent(false);
            AutoResetEvent threesSucceeded = new AutoResetEvent(false);
            AutoResetEvent sevensSucceeded = new AutoResetEvent(false);
            AutoResetEvent ninesSucceeded = new AutoResetEvent(false);
            BigInteger squareRootedValue = IntegerSquareRoot(value);
            Thread ones = new Thread(() =>
            {
                for (BigInteger i = 11; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                onesSucceeded.Set();
            });
            ones.Start();
            Thread threes = new Thread(() =>
            {
                for (BigInteger i = 3; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                threesSucceeded.Set();
            });
            threes.Start();
            Thread sevens = new Thread(() =>
            {
                for (BigInteger i = 7; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                sevensSucceeded.Set();
            });
            sevens.Start();
            Thread nines = new Thread(() =>
            {
                for (BigInteger i = 9; i <= squareRootedValue; i += 10)
                {
                    if (value % i == 0)
                    {
                        Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
                        failure.Set();
                    }
                }
                ninesSucceeded.Set();
            });
            nines.Start();
            Thread successWaiter = new Thread(() =>
            {
                AutoResetEvent.WaitAll(new WaitHandle[] { onesSucceeded, threesSucceeded, sevensSucceeded, ninesSucceeded });
                success.Set();
            });
            successWaiter.Start();
            int result = AutoResetEvent.WaitAny(new WaitHandle[] { success, failure });
            try
            {
                successWaiter.Abort();
            }
            catch { }
            try
            {
                ones.Abort();
            }
            catch { }
            try
            {
                threes.Abort();
            }
            catch { }
            try
            {
                sevens.Abort();
            }
            catch { }
            try
            {
                nines.Abort();
            }
            catch { }
            if (result == 1)
            {
                return false;
            }
            else
            {
                Console.WriteLine("{0} is a prime number.", value);
                return true;
            }
        }
    }
}

Update: If you want to implement a solution with trial division more rapidly, you might consider having a cache of prime numbers. A number is only prime if it is not divisible by other prime numbers that are up to the value of its square root. Other than that, you might consider using the probabilistic version of the Miller-Rabin primality test to check for a number's primality if you are dealing with large enough values (taken from Rosetta Code in case the site ever goes down):

// Miller-Rabin primality test as an extension method on the BigInteger type.
// Based on the Ruby implementation on this page.
public static class BigIntegerExtensions
{
  public static bool IsProbablePrime(this BigInteger source, int certainty)
  {
    if(source == 2 || source == 3)
      return true;
    if(source < 2 || source % 2 == 0)
      return false;

    BigInteger d = source - 1;
    int s = 0;

    while(d % 2 == 0)
    {
      d /= 2;
      s += 1;
    }

    // There is no built-in method for generating random BigInteger values.
    // Instead, random BigIntegers are constructed from randomly generated
    // byte arrays of the same length as the source.
    RandomNumberGenerator rng = RandomNumberGenerator.Create();
    byte[] bytes = new byte[source.ToByteArray().LongLength];
    BigInteger a;

    for(int i = 0; i < certainty; i++)
    {
      do
      {
        // This may raise an exception in Mono 2.10.8 and earlier.
        // http://bugzilla.xamarin.com/show_bug.cgi?id=2761
        rng.GetBytes(bytes);
        a = new BigInteger(bytes);
      }
      while(a < 2 || a >= source - 2);

      BigInteger x = BigInteger.ModPow(a, d, source);
      if(x == 1 || x == source - 1)
        continue;

      for(int r = 1; r < s; r++)
      {
        x = BigInteger.ModPow(x, 2, source);
        if(x == 1)
          return false;
        if(x == source - 1)
          break;
      }

      if(x != source - 1)
        return false;
    }

    return true;
  }
}

How do I change the default schema in sql developer?

This will not change the default schema in Oracle Sql Developer but I wanted to point out that it is easy to quickly view another user schema, right click the Database Connection:

enter image description here

Select the user to see the schema for that user

enter image description here

html <input type="text" /> onchange event not working

onchange is only triggered when the control is blurred. Try onkeypress instead.

How to modify JsonNode in Java?

I think you can just cast to ObjectNode and use put method. Like this

ObjectNode o = (ObjectNode) jsonNode; o.put("value", "NO");

Convert python datetime to epoch with strftime

This works in Python 2 and 3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

Just following the official docs... https://docs.python.org/2/library/time.html#module-time

Example on ToggleButton

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    editString = ed.getText().toString();
    if(editString.equals("1")){

        toggle.setTextOff("TOGGLE ON");
        toggle.setChecked(true);

    }
    else if(editString.equals("0")){

        toggle.setTextOn("TOGGLE OFF");
        toggle.setChecked(false);

    }
}

How to temporarily exit Vim and go back

If you don't mind using your mouse a little bit:

  • Start your terminal,
  • select a file,
  • select Open Tab.

This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell and exit).

How do I activate C++ 11 in CMake?

For CMake 3.8 and newer you can use

target_compile_features(target PUBLIC cxx_std_11)

How To Set Text In An EditText

This is the solution in Kotlin

val editText: EditText = findViewById(R.id.main_et_name)
    editText.setText("This is a text.")

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

Android how to convert int to String?

Use Integer.toString(tmpInt) instead.

how to convert string into time format and add two hours

This will give you the time you want (eg: 21:31 PM)

//Add 2 Hours to just TIME
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
Date date2 = formatter.parse("19:31:51 PM");
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal2.add(Calendar.HOUR_OF_DAY, 2);
SimpleDateFormat printTimeFormat = new SimpleDateFormat("HH:mm a");
System.out.println(printTimeFormat.format(cal2.getTime())); 

C++ template constructor

Some points:

  • If you declare any constructor(including a templated one), the compiler will refrain from declaring a default constructor.
  • Unless you declare a copy-constructor (for class X one that takes X or X& or X const &) the compiler will generate the default copy-constructor.
  • If you provide a template constructor for class X which takes T const & or T or T& then the compiler will nevertheless generate a default non-templated copy-constructor, even though you may think that it shouldn't because when T = X the declaration matches the copy-constructor declaration.
  • In the latter case you may want to provide a non-templated copy-constructor along with the templated one. They will not conflict. When X is passed the nontemplated will be called. Otherwise the templated

HTH

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Example:

perfdb-# \df information_schema.*;

List of functions
        Schema      |        Name        | Result data type | Argument data types |  Type  
 information_schema | _pg_char_max_length   | integer | typid oid, typmod integer | normal
 information_schema | _pg_char_octet_length | integer | typid oid, typmod integer | normal
 information_schema | _pg_datetime_precision| integer | typid oid, typmod integer | normal
 .....
 information_schema | _pg_numeric_scale     | integer | typid oid, typmod integer | normal
 information_schema | _pg_truetypid         | oid     | pg_attribute, pg_type     | normal
 information_schema | _pg_truetypmod        | integer | pg_attribute, pg_type     | normal
(11 rows)

Temporarily disable all foreign key constraints

A good reference is given at : http://msdn.microsoft.com/en-us/magazine/cc163442.aspx under the section "Disabling All Foreign Keys"

Inspired from it, an approach can be made by creating a temporary table and inserting the constraints in that table, and then dropping the constraints and then reapplying them from that temporary table. Enough said here is what i am talking about

 SET NOCOUNT ON

    DECLARE @temptable TABLE(
       Id INT PRIMARY KEY IDENTITY(1, 1),
       FKConstraintName VARCHAR(255),
       FKConstraintTableSchema VARCHAR(255),
       FKConstraintTableName VARCHAR(255),
       FKConstraintColumnName VARCHAR(255),
       PKConstraintName VARCHAR(255),
       PKConstraintTableSchema VARCHAR(255),
       PKConstraintTableName VARCHAR(255),
       PKConstraintColumnName VARCHAR(255)    
    )

    INSERT INTO @temptable(FKConstraintName, FKConstraintTableSchema, FKConstraintTableName, FKConstraintColumnName)
    SELECT 
       KeyColumnUsage.CONSTRAINT_NAME, 
       KeyColumnUsage.TABLE_SCHEMA, 
       KeyColumnUsage.TABLE_NAME, 
       KeyColumnUsage.COLUMN_NAME 
    FROM 
       INFORMATION_SCHEMA.KEY_COLUMN_USAGE KeyColumnUsage
          INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TableConstraints
             ON KeyColumnUsage.CONSTRAINT_NAME = TableConstraints.CONSTRAINT_NAME
    WHERE
       TableConstraints.CONSTRAINT_TYPE = 'FOREIGN KEY'

    UPDATE @temptable SET
       PKConstraintName = UNIQUE_CONSTRAINT_NAME
    FROM 
       @temptable tt
          INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ReferentialConstraint
             ON tt.FKConstraintName = ReferentialConstraint.CONSTRAINT_NAME

    UPDATE @temptable SET
       PKConstraintTableSchema  = TABLE_SCHEMA,
       PKConstraintTableName  = TABLE_NAME
    FROM @temptable tt
       INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TableConstraints
          ON tt.PKConstraintName = TableConstraints.CONSTRAINT_NAME

    UPDATE @temptable SET
       PKConstraintColumnName = COLUMN_NAME
    FROM @temptable tt
       INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KeyColumnUsage
          ON tt.PKConstraintName = KeyColumnUsage.CONSTRAINT_NAME


    --Now to drop constraint:
    SELECT
       '
       ALTER TABLE [' + FKConstraintTableSchema + '].[' + FKConstraintTableName + '] 
       DROP CONSTRAINT ' + FKConstraintName + '

       GO'
    FROM
       @temptable

    --Finally to add constraint:
    SELECT
       '
       ALTER TABLE [' + FKConstraintTableSchema + '].[' + FKConstraintTableName + '] 
       ADD CONSTRAINT ' + FKConstraintName + ' FOREIGN KEY(' + FKConstraintColumnName + ') REFERENCES [' + PKConstraintTableSchema + '].[' + PKConstraintTableName + '](' + PKConstraintColumnName + ')

       GO'
    FROM
       @temptable

    GO

Eclipse and Windows newlines

To recursively remove the carriage returns (\r) from the CVS/* files in all child directories, run the following in a unix shell:

find ./ -wholename "\*CVS/[RE]\*" -exec dos2unix -q -o {} \;

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

What size do you use for varchar(MAX) in your parameter declaration?

If you do something like this:

    cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

size will be taken from "some large text".Length

This can be problematic when it's an output parameter, you get back no more characters then you put as input.

TreeMap sort by value

In Java 8:

LinkedHashMap<Integer, String> sortedMap = 
    map.entrySet().stream().
    sorted(Entry.comparingByValue()).
    collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                             (e1, e2) -> e1, LinkedHashMap::new));

Set Google Maps Container DIV width and height 100%

I just added inline style .
<div id="map_canvas" style="width:750px;height:484px;"></div>
And it worked for me .

Get the time of a datetime using T-SQL?

Assuming the title of your question is correct and you want the time:

SELECT CONVERT(char,GETDATE(),14) 

Edited to include millisecond.

curl: (6) Could not resolve host: application

In my case, putting space after colon was wrong.

# Not work
curl -H Content-Type: application/json ~
# OK
curl -H Content-Type:application/json ~

Height equal to dynamic width (CSS fluid layout)

width: 80vmin; height: 80vmin;

CSS does 80% of the smallest view, height or width

http://caniuse.com/#feat=viewport-units

Launch a shell command with in a python script, wait for the termination and return to the script

use spawn

import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

How to check if IEnumerable is null or empty?

Another way would be to get the Enumerator and call the MoveNext() method to see if there are any items:

if (mylist != null && mylist.GetEnumerator().MoveNext())
{
    // The list is not null or empty
}

This works for IEnumerable as well as IEnumerable<T>.

How do I restart a service on a remote machine in Windows?

You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.

If you wish to use the command line only, you can use

sc \\machine stop <service>

How to exit git log or git diff

Add following alias in the .bashrc file

git --no-pager log --oneline -n 10
  • --no-pager will encounter the (END) word
  • -n 10 will show only the last 10 commits
  • --oneline will show the commit message, ignore the author, date information

Disable Input fields in reactive form

If to use disabled form input elements (like suggested in correct answer how to disable input) validation for them will be also disabled, take attention for that!

(And if you are using on submit button like [disabled]="!form.valid"it will exclude your field from validation)

enter image description here

Recording video feed from an IP camera over a network

Why don't you consider www.cameraftp.com? it supports image upload and online viewer

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.name will stay there until the window is closed.

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider.

window.name has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that window.name can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

substring index range

Yes, the index starts at zero (0). The two arguments are startIndex and endIndex, where per the documentation:

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

See here for more information.

What underlies this JavaScript idiom: var self = this?

function Person(firstname, lastname) {
  this.firstname = firstname;

  this.lastname = lastname;
  this.getfullname = function () {
    return `${this.firstname}   ${this.lastname}`;
  };

  let that = this;
  this.sayHi = function() {
    console.log(`i am this , ${this.firstname}`);
    console.log(`i am that , ${that.firstname}`);
  };
}

let thisss = new Person('thatbetty', 'thatzhao');

let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};

thisss.sayHi.call(thatt);

Accessing JSON elements

Another alternative way using get method with requests:

import requests
wjdata = requests.get('url').json()
print wjdata.get('data').get('current_condition')[0].get('temp_C')

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

What is the effect of encoding an image in base64?

It will definitely cost you more space & bandwidth if you want to use base64 encoded images. However if your site has a lot of small images you can decrease the page loading time by encoding your images to base64 and placing them into html. In this way, the client browser wont need to make a lot of connections to the images, but will have them in html.

Correct way to delete cookies server-side

Sending the same cookie value with ; expires appended will not destroy the cookie.

Invalidate the cookie by setting an empty value and include an expires field as well:

Set-Cookie: token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT

Note that you cannot force all browsers to delete a cookie. The client can configure the browser in such a way that the cookie persists, even if it's expired. Setting the value as described above would solve this problem.

Format an Excel column (or cell) as Text in C#?

Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

Disclaimer: I own SpreadsheetGear LLC

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

.mp4 file not playing in chrome

I too had the same issue. I changed the codec to H264-MPEG-4 AVC and the videos started working in HTML5/Chrome.

Option selected in converter: H264-MPEG-4 AVC, Codec visible in VLC player: H264-MPEG-4 AVC (part 10) (avc1)

Hope it helps...

Run a JAR file from the command line and specify classpath

Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp or specify the main class. In your case it would contain lines like this:

Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar

Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar.

Then execute it with

java -jar MyJar.jar

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

Generate Controller and Model

laravel artisan does not support default model and view generation. check this provider https://github.com/JeffreyWay/Laravel-4-Generators to generate models, views, seeder etc.

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

Adding the "Clear" Button to an iPhone UITextField

you can add custom clear button and control the size and every thing using this:

UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
[clearButton setImage:img forState:UIControlStateNormal];
[clearButton setFrame:frame];
[clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside];

textField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever,    UITextFieldViewModeWhileEditing,   UITextFieldViewModeUnlessEditing
[textField setRightView:clearButton];

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

The case is like :

 mysql connects will localhost when network is not up.
 mysql cannot connect when network is up.

You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):

  1. Disconnect the network.
  2. Stop mysql service (if windows, try from services.msc window)
  3. Connect to network.
  4. Try to start the mysql and see if it starts correctly.
  5. Check for system logs anyways to be sure that there is no error in starting mysql service.
  6. If all goes well try connecting.
  7. If fails, try to do a telnet localhost 3306 and see what output it shows.
  8. Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.

This should ideally resolve the issue you are facing.

How to cast from List<Double> to double[] in Java?

High performance - every Double object wraps a single double value. If you want to store all these values into a double[] array, then you have to iterate over the collection of Double instances. A O(1) mapping is not possible, this should be the fastest you can get:

 double[] target = new double[doubles.size()];
 for (int i = 0; i < target.length; i++) {
    target[i] = doubles.get(i).doubleValue();  // java 1.4 style
    // or:
    target[i] = doubles.get(i);                // java 1.5+ style (outboxing)
 }

Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive method:

public static double[] toPrimitive(Double[] array) {
  if (array == null) {
    return null;
  } else if (array.length == 0) {
    return EMPTY_DOUBLE_ARRAY;
  }
  final double[] result = new double[array.length];
  for (int i = 0; i < array.length; i++) {
    result[i] = array[i].doubleValue();
  }
  return result;
}

(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )

By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[] from the list, then to unwrap the double values.

Is there a GUI design app for the Tkinter / grid geometry?

You have VisualTkinter also known as Visual Python. Development seems not active. You have sourceforge and googlecode sites. Web site is here.

On the other hand, you have PAGE that seems active and works in python 2.7 and py3k

As you indicate on your comment, none of these use the grid geometry. As far as I can say the only GUI builder doing that could probably be Komodo Pro GUI Builder which was discontinued and made open source in ca. 2007. The code was located in the SpecTcl repository.

It seems to install fine on win7 although has not used it yet. This is an screenshot from my PC:

enter image description here

By the way, Rapyd Tk also had plans to implement grid geometry as in its documentation says it is not ready 'yet'. Unfortunately it seems 'nearly' abandoned.