Programs & Examples On #Clojureql

ClojureQL is an alternative SQL library for Clojure.

Write output to a text file in PowerShell

The simplest way is to just redirect the output, like so:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt

> will cause the output file to be overwritten if it already exists.
>> will append new text to the end of the output file if it already exists.

Hashing a string with Sha256

The shortest and fastest way ever. Only 1 line!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

How to format a URL to get a file from Amazon S3?

Its actually formulated more like:

https://<bucket-name>.s3.amazonaws.com/<key>

See here

Inline <style> tags vs. inline css properties

Here's one aspect that could rule the difference:

If you change an element's style in JavaScript, you are affecting the inline style. If there's already a style there, you overwrite it permanently. But, if the style were defined in an external sheet or in a <style> tag, then setting the inline one to "" restores the style from that source.

How to create a directory using Ansible

Directory can be created using file module only, as directory is nothing but a file.

# create a directory if it doesn't exist
- file:
    path: /etc/some_directory
    state: directory
    mode: 0755
    owner: foo
    group: foo

Disable color change of anchor tag when visited

For those who are dynamically applying classes (i.e. active): Simply add a "div" tag inside the "a" tag with an href attribute:

<a href='your-link'>
  <div>
    <span>your link name</span>
  </div>
</a>

Multi-Column Join in Hibernate/JPA Annotations

This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key

i.e., one to one mapping based on 3 different columns

@Entity
@Table(name = "foo")
public class foo implements Serializable
{
    @Column(name="foocol1")
    private String foocol1;
    //add getter setter
    @Column(name="foocol2")
    private String foocol2;
    //add getter setter
    @Column(name="foocol3")
    private String foocol3;
    //add getter setter
    private Boo boo;
    private int id;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "brsitem_id", updatable = false)
    public int getId()
    {
        return this.id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @OneToOne
    @JoinColumns(
    {
        @JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
        @JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
        @JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
    }
    )
    public Boo getBoo()
    {
        return boo;
    }
    public void setBoo(Boo boo)
    {
        this.boo = boo;
    }
}





@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
    private int id;
    @Column(name="boocol1")
    private String boocol1;
    //add getter setter
    @Column(name="boocol2")
    private String boocol2;
    //add getter setter
    @Column(name="boocol3")
    private String boocol3;
    //add getter setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "item_id", updatable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
}

How to access random item in list?

I usually use this little collection of extension methods:

public static class EnumerableExtension
{
    public static T PickRandom<T>(this IEnumerable<T> source)
    {
        return source.PickRandom(1).Single();
    }

    public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
    {
        return source.Shuffle().Take(count);
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.OrderBy(x => Guid.NewGuid());
    }
}

For a strongly typed list, this would allow you to write:

var strings = new List<string>();
var randomString = strings.PickRandom();

If all you have is an ArrayList, you can cast it:

var strings = myArrayList.Cast<string>();

PHP sessions that have already been started

If you want a new one, then do session_destroy() before starting it. To check if its set before starting it, call session_status() :

$status = session_status();
if($status == PHP_SESSION_NONE){
    //There is no active session
    session_start();
}else
if($status == PHP_SESSION_DISABLED){
    //Sessions are not available
}else
if($status == PHP_SESSION_ACTIVE){
    //Destroy current and start new one
    session_destroy();
    session_start();
}

I would avoid checking the global $_SESSION instead of I am calling the session_status() method since PHP implemented this function explicitly to:

Expose session status via new function, session_status This is for (PHP >=5.4.0)

Cannot read property 'getContext' of null, using canvas

You don't have to include JQuery.

In the index.html:
<canvas id="canvas" width="640" height="480"></canvas><script src="javascript/game.js"> This should work without JQuery...

Edit: You should put the script tag IN the body tag...

Using Server.MapPath() inside a static field in ASP.NET MVC

Try HostingEnvironment.MapPath, which is static.

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

WPF: Setting the Width (and Height) as a Percentage Value

I use two methods for relative sizing. I have a class called Relative with three attached properties To, WidthPercent and HeightPercent which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.

The other approach is rather more cunning. Add a ViewBox where you want relative sizes inside, then inside that, add a Grid at width 100. Then if you add a TextBlock with width 10 inside that, it is obviously 10% of 100.

The ViewBox will scale the Grid according to whatever space it has been given, so if its the only thing on the page, then the Grid will be scaled out full width and effectively, your TextBlock is scaled to 10% of the page.

If you don't set a height on the Grid then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox else it will start scaling the height as well. You can probably work around this with a Stretch of UniformToFill.

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

How can I check if two segments intersect?

Here is C code to check if two points are on the opposite sides of the line segment. Using this code you can check if two segments intersect as well.

// true if points p1, p2 lie on the opposite sides of segment s1--s2
bool oppositeSide (Point2f s1, Point2f s2, Point2f p1, Point2f p2) {

//calculate normal to the segment
Point2f vec = s1-s2;
Point2f normal(vec.y, -vec.x); // no need to normalize

// vectors to the points
Point2f v1 = p1-s1;
Point2f v2 = p2-s1;

// compare signs of the projections of v1, v2 onto the normal
float proj1 = v1.dot(normal);
float proj2 = v2.dot(normal);
if (proj1==0 || proj2==0)
        cout<<"collinear points"<<endl;

return(SIGN(proj1) != SIGN(proj2));

}

Is there a way to cache GitHub credentials for pushing commits?

You can use credential helpers.

git config --global credential.helper 'cache --timeout=x'

where x is the number of seconds.

syntax for creating a dictionary into another dictionary in python

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

Why are static variables considered evil?

if I had to make 10,000 calls to a function within a class, I would be glad to make the method static and use a straightforward class.methodCall() on it instead of cluttering the memory with 10,000 instances of the class, Right?

You have to balance the need for encapsulating data into an object with a state, versus the need of simply computing the result of a function on some data.

Moreover statics reduce the inter-dependencies on the other parts of the code.

So does encapsulation. In large applications, statics tend to produce spaghetti code and don't easily allow refactoring or testing.

The other answers also provide good reasons against excessive use of statics.

Is System.nanoTime() completely useless?

No need to debate, just use the source. Here, SE 6 for Linux, make your own conclusions:

jlong os::javaTimeMillis() {
  timeval time;
  int status = gettimeofday(&time, NULL);
  assert(status != -1, "linux error");
  return jlong(time.tv_sec) * 1000  +  jlong(time.tv_usec / 1000);
}


jlong os::javaTimeNanos() {
  if (Linux::supports_monotonic_clock()) {
    struct timespec tp;
    int status = Linux::clock_gettime(CLOCK_MONOTONIC, &tp);
    assert(status == 0, "gettime error");
    jlong result = jlong(tp.tv_sec) * (1000 * 1000 * 1000) + jlong(tp.tv_nsec);
    return result;
  } else {
    timeval time;
    int status = gettimeofday(&time, NULL);
    assert(status != -1, "linux error");
    jlong usecs = jlong(time.tv_sec) * (1000 * 1000) + jlong(time.tv_usec);
    return 1000 * usecs;
  }
}

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x, it is not guaranteed at all:

>>> False = 5
>>> 0 == False
False

So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.

In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1, but on Python 3.x, this will always be the case, no matter what.

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

How to redirect both stdout and stderr to a file

Please use command 2>file Here 2 stands for file descriptor of stderr. You can also use 1 instead of 2 so that stdout gets redirected to the 'file'

How to change the Title of the window in Qt?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setWindowTitle("Main Page");
    w.show();
    return a.exec();
}

enter image description here

Apply a theme to an activity in Android?

To set it programmatically in Activity.java:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setTheme(R.style.MyTheme); // (for Custom theme)
  setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)

  this.setContentView(R.layout.myactivity);

To set in Application scope in Manifest.xml (all activities):

 <application
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To set in Activity scope in Manifest.xml (single activity):

  <activity
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To build a custom theme, you will have to declare theme in themes.xml file, and set styles in styles.xml file.

Reset ID autoincrement ? phpmyadmin

I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.

ALTER TABLE users DROP id

The above sql can be run via sql query or as php. This will delete the id column.

Then re add it again, via the code below:

ALTER TABLE  `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST

Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.

Why is list initialization (using curly braces) better than the alternatives?

It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.

Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.

Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)

UILabel with text of two different colors

Swift 4 and above: Inspired by anoop4real's solution, here's a String extension that can be used to generate text with 2 different colors.

extension String {

    func attributedStringForPartiallyColoredText(_ textToFind: String, with color: UIColor) -> NSMutableAttributedString {
        let mutableAttributedstring = NSMutableAttributedString(string: self)
        let range = mutableAttributedstring.mutableString.range(of: textToFind, options: .caseInsensitive)
        if range.location != NSNotFound {
            mutableAttributedstring.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
        }
        return mutableAttributedstring
    }
}

Following example changes color of asterisk to red while retaining original label color for remaining text.

label.attributedText = "Enter username *".attributedStringForPartiallyColoredText("*", with: #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1))

How to restart VScode after editing extension's config?

You can do the following

  1. Click on extensions
  2. Type Reload
  3. Then install

It will add a reload button on your right hand at the bottom of the vs code.

Returning IEnumerable<T> vs. IQueryable<T>

The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where(), Sum(), Count(), FirstOrDefault(), etc all have two versions: one that accepts functions and one that accepts expressions.

  • The IEnumerable version signature is: Where(Func<Customer, bool> predicate)

  • The IQueryable version signature is: Where(Expression<Func<Customer, bool>> predicate)

You've probably been using both of those without realizing it because both are called using identical syntax:

e.g. Where(x => x.City == "<City>") works on both IEnumerable and IQueryable

  • When using Where() on an IEnumerable collection, the compiler passes a compiled function to Where()

  • When using Where() on an IQueryable collection, the compiler passes an expression tree to Where(). An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.

Why bother with this expression tree thing? I just want Where() to filter my data. The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.

Oh, that sounds like a free performance boost, should I use AsQueryable() all over the place in that case? No, IQueryable is only useful if the underlying data provider can do something with it. Converting something like a regular List to IQueryable will not give you any benefit.

Laravel 5 PDOException Could Not Find Driver

It will depend of your php version. Check it running:

php -version

Now, according to your current version, run:

sudo apt-get install php7.2-mysql

How can I get the current page's full URL on a Windows/IIS server?

Maybe, because you are under IIS,

$_SERVER['PATH_INFO']

is what you want, based on the URLs you used to explain.

For Apache, you'd use $_SERVER['REQUEST_URI'].

Getting list of tables, and fields in each, in a database

Is this what you are looking for:

Using OBJECT CATALOG VIEWS

 SELECT T.name AS Table_Name ,
       C.name AS Column_Name ,
       P.name AS Data_Type ,
       P.max_length AS Size ,
       CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
FROM   sys.objects AS T
       JOIN sys.columns AS C ON T.object_id = C.object_id
       JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE  T.type_desc = 'USER_TABLE';

Using INFORMATION SCHEMA VIEWS

  SELECT TABLE_SCHEMA ,
       TABLE_NAME ,
       COLUMN_NAME ,
       ORDINAL_POSITION ,
       COLUMN_DEFAULT ,
       DATA_TYPE ,
       CHARACTER_MAXIMUM_LENGTH ,
       NUMERIC_PRECISION ,
       NUMERIC_PRECISION_RADIX ,
       NUMERIC_SCALE ,
       DATETIME_PRECISION
FROM   INFORMATION_SCHEMA.COLUMNS;

Reference : My Blog - http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/

C# ASP.NET Single Sign-On Implementation

There are several Identity providers with SSO support out of the box, also third-party** products.

** The only problem with third party products is that they charge per user/month, and it can be quite expensive.

Some of the tools available and with APIs for .NET are:

If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.

  • C#

    • IdentityServer3 (OAuth/OpenID protocols, OWIN/Katana)
    • IdentityServer4 (OAuth/OpenID protocols, ASP.NET Core)
    • OAuth 2.0 by Okta
  • Javascript

    • passport-openidconnect (node.js)
    • oidc-provider (node.js)
    • openid-client (node.js)
  • Python

    • pyoidc
    • Django OIDC Provider

I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.

Get current URL from IFRAME

I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:

    const iframeReference = document.getElementById("iframe_id");
    const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
    if (iframeUrl) {
        console.log("Voila: " + iframeUrl);
    } else {
        console.warn("iframe with id iframe_id not found");
    }

How to add shortcut keys for java code in eclipse

Type syso and ctrl + space for System.out.println()

Why can I not create a wheel in python?

Install the wheel package first:

pip install wheel

The documentation isn't overly clear on this, but "the wheel project provides a bdist_wheel command for setuptools" actually means "the wheel package...".

Add horizontal scrollbar to html table

I was running into the same issue. I discovered the following solution, which has only been tested in Chrome v31:

table {
    table-layout: fixed;
}

tbody {
    display: block;
    overflow: scroll;
}

Get docker container id from container name

  1. Get container Ids of running containers ::

    $docker ps -qf "name=IMAGE_NAME"
    
        -f: Filter output based on conditions provided
        -q: Only display numeric container IDs
    
  2. Get container Ids of all containers ::

    $docker ps -aqf "name=IMAGE_NAME"
    
        -a: all containers
    

Installing Java 7 on Ubuntu

Oracle as well as modern versions of Ubuntu have moved to newer versions of Java. The default for Ubuntu 20.04 is OpenJDK 11 which is good enough for most purposes.

If you really need it for running legacy programs, OpenJDK 8 is also available for Ubuntu 20.04 from the official repositories.

If you really need exactly Java 7, the best bet as of 2020 is to download a Zulu distribution. The easiest to install if you have root privileges is the .DEB version, otherwise download the .ZIP one.

https://www.azul.com/downloads/zulu-community/?version=java-7-lts&os=ubuntu&architecture=x86-64-bit&package=jdk

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

In my case the path of MySQL data folder had a special character "ç" and it make me get...

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist.

I'm have removed all special characters and everything works.

Django - Static file not found

If you've have added the django-storages module (to support uploading files to S3 in your django app for instance), and if like me you did not read correctly the documentation of this module, just remove this line from your settings.py:

STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

Otherwise it will cause your static assets to be looked NOT on your local machine but remotely in the S3 bucket, including admin panel CSS, and thus effectively breaking admin panel CSS.

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

I got same issue on Catalina mac. I also installed the R from the source in following diretory. ./Documents/R-4.0.3

Now from the terminal type

 ls -a 

and open

 vim .bash_profile 

type

export LANG="en_US.UTF-8"

save with :wq

then type

source .bash_profile 

and then open

./Documents/R-4.0.3/bin/R 
./Documents/R-4.0.3/bin/Rscript 

I always have to run "source /Users/yourComputerName/.bash_profile" before running R scripts.

How do I get currency exchange rates via an API such as Google Finance?

Yahoo has a YQL feature to get a whole bunch of currencies at once in XML or JSON. I've noticed the data is up to date by the minute where the ECB has day old data, and stops in the weekend.

http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys

Here is their query builder, where you can test a query and copy the url:

http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29

convert '1' to '0001' in JavaScript

Just to demonstrate the flexibility of javascript: you can use a oneliner for this

function padLeft(nr, n, str){
    return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
    return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5));       //=> '00023'
console.log((23).padLeft(5));     //=> '00023'
console.log((23).padLeft(5,' ')); //=> '   23'
console.log(padLeft(23,5,'>>'));  //=> '>>>>>>23'

If you want to use this for negative numbers also:

Number.prototype.padLeft = function (n,str) {
    return (this < 0 ? '-' : '') + 
            Array(n-String(Math.abs(this)).length+1)
             .join(str||'0') + 
           (Math.abs(this));
}
console.log((-23).padLeft(5));     //=> '-00023'

Alternative if you don't want to use Array:

number.prototype.padLeft = function (len,chr) {
 var self = Math.abs(this)+'';
 return (this<0 && '-' || '')+
         (String(Math.pow( 10, (len || 2)-self.length))
           .slice(1).replace(/0/g,chr||'0') + self);
}

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

Replace CRLF using powershell

For CMD one line LF-only:

powershell -NoProfile -command "((Get-Content 'prueba1.txt') -join \"`n\") + \"`n\" | Set-Content -NoNewline 'prueba1.txt'"

so you can create a .bat

Printing 2D array in matrix format

like so:

long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } };

var rowCount = arr.GetLength(0);
var colCount = arr.GetLength(1);
for (int row = 0; row < rowCount; row++)
{
    for (int col = 0; col < colCount; col++)               
        Console.Write(String.Format("{0}\t", arr[row,col]));
    Console.WriteLine();
} 

Calling dynamic function with dynamic number of parameters

You could use .apply()

You need to specify a this... I guess you could use the this within mainfunc.

function mainfunc (func)
{
    var args = new Array();
    for (var i = 1; i < arguments.length; i++)
        args.push(arguments[i]);

    window[func].apply(this, args);
}

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

Upgraded from EF5 to EF6 nuget a while back and kept encountering this issue. I'd temp fix it by updating the generated code to reference System.Data.Entity.Core.Objects, but after generation it would be changed back again (as expected since its generated).

This solved the problem for good:

http://msdn.microsoft.com/en-us/data/upgradeef6

If you have any models created with the EF Designer, you will need to update the code generation templates to generate EF6 compatible code. Note: There are currently only EF 6.x DbContext Generator templates available for Visual Studio 2012 and 2013.

  1. Delete existing code-generation templates. These files will typically be named <edmx_file_name>.tt and <edmx_file_name>.Context.tt and be nested under your edmx file in Solution Explorer. You can select the templates in Solution Explorer and press the Del key to delete them.
    Note: In Web Site projects the templates will not be nested under your edmx file, but listed alongside it in Solution Explorer.
    Note: In VB.NET projects you will need to enable 'Show All Files' to be able to see the nested template files.
  2. Add the appropriate EF 6.x code generation template. Open your model in the EF Designer, right-click on the design surface and select Add Code Generation Item...
    • If you are using the DbContext API (recommended) then EF 6.x DbContext Generator will be available under the Data tab.
      Note: If you are using Visual Studio 2012, you will need to install the EF 6 Tools to have this template. See Get Entity Framework for details.
    • If you are using the ObjectContext API then you will need to select the Online tab and search for EF 6.x EntityObject Generator.
  3. If you applied any customizations to the code generation templates you will need to re-apply them to the updated templates.

Download files from server php

If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.

How do I calculate r-squared using Python and Numpy?

From the numpy.polyfit documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function

E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + ... + p_1 * x + p_0

So you just need to calculate the R-squared for that fit. The wikipedia page on linear regression gives full details. You are interested in R^2 which you can calculate in a couple of ways, the easisest probably being

SST = Sum(i=1..n) (y_i - y_bar)^2
SSReg = Sum(i=1..n) (y_ihat - y_bar)^2
Rsquared = SSReg/SST

Where I use 'y_bar' for the mean of the y's, and 'y_ihat' to be the fit value for each point.

I'm not terribly familiar with numpy (I usually work in R), so there is probably a tidier way to calculate your R-squared, but the following should be correct

import numpy

# Polynomial Regression
def polyfit(x, y, degree):
    results = {}

    coeffs = numpy.polyfit(x, y, degree)

     # Polynomial Coefficients
    results['polynomial'] = coeffs.tolist()

    # r-squared
    p = numpy.poly1d(coeffs)
    # fit values, and mean
    yhat = p(x)                         # or [p(z) for z in x]
    ybar = numpy.sum(y)/len(y)          # or sum(y)/len(y)
    ssreg = numpy.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
    sstot = numpy.sum((y - ybar)**2)    # or sum([ (yi - ybar)**2 for yi in y])
    results['determination'] = ssreg / sstot

    return results

Sql script to find invalid email addresses

select
    email 
from loginuser where
patindex ('%[ &'',":;!+=\/()<>]*%', email) > 0  -- Invalid characters
or patindex ('[@.-_]%', email) > 0   -- Valid but cannot be starting character
or patindex ('%[@.-_]', email) > 0   -- Valid but cannot be ending character
or email not like '%@%.%'   -- Must contain at least one @ and one .
or email like '%..%'        -- Cannot have two periods in a row
or email like '%@%@%'       -- Cannot have two @ anywhere
or email like '%.@%' or email like '%@.%' -- Cant have @ and . next to each other
or email like '%.cm' or email like '%.co' -- Unlikely. Probably typos 
or email like '%.or' or email like '%.ne' -- Missing last letter

This worked for me. Had to apply rtrim and ltrim to avoid false positives.

Source: http://sevenwires.blogspot.com/2008/09/sql-how-to-find-invalid-email-in-sql.html

Postgres version:

select user_guid, user_guid email_address, creation_date, email_verified, active
from user_data where
length(substring (email_address from '%[ &'',":;!+=\/()<>]%')) > 0  -- Invalid characters
or length(substring (email_address from '[@.-_]%')) > 0   -- Valid but cannot be starting character
or length(substring (email_address from '%[@.-_]')) > 0   -- Valid but cannot be ending character
or email_address not like '%@%.%'   -- Must contain at least one @ and one .
or email_address like '%..%'        -- Cannot have two periods in a row
or email_address like '%@%@%'       -- Cannot have two @ anywhere
or email_address like '%.@%' or email_address like '%@.%' -- Cant have @ and . next to each other
or email_address like '%.cm' or email_address like '%.co' -- Unlikely. Probably typos 
or email_address like '%.or' or email_address like '%.ne' -- Missing last letter
;

'git status' shows changed files, but 'git diff' doesn't

TL;DR

Line ending issue:

  1. Change autocrlf setting to default true. I.e., checkout Windows-style line endings on Windows and commit Linux-style line endings on remote git repo:
    git config --global core.autocrlf true
    
  2. On a Windows mahcine, change all files in the repo to Windows-style:
    unix2dos **
    
  3. Git add all modified files and modified files will go:
    git add .
    git status
    

Background

  • Platform: Windows, WSL

I occassionally run into this issue that git status shows I have files modified while git diff shows nothing. This is most likely issue of line endings. I finally figured out how it always happen and share here to see if it can help others.

Root Cause

The reason I encounter this issue often is that I work on a Windows machine and interact with Git in WSL. Switching between linux and Windows setting can easily cause this end-of-line issue. Since line ending format used in OS differs:

  • Windows: \r\n
  • OSX / Linux: \n

Common Practice

When you install Git on your machine, it will ask you to choose line endings setting. Usually, the common practice is to use (commit) Linux-style line endings on your remote git repo and checkout Windows-style on your Windows machine. If you use default setting, this is what git do for you. enter image description here

This means if you have a shell script myScript.sh and bash script myScript.cmd in your repo, the scripts both exist with Linux-style ending in your remote git repo, and both exist with Windows-style ending on your Windows machine.

I used to checkout shell script file and use dos2unix to change the script line-ending in order to run the shell script in WSL. This is why I encounter the issue. Git keeps telling me my modification of line-ending has been changed and asks whether to commit the changes.

Solution

Use default line ending settings and if you change the line endings of some files (like use the dos2unix or dos2unix), drop the changings. If line-endings changes already exist and you would like to get rid of it, try git add them and the changes will go.

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

EDIT: the answer below would apply in most cases. OP however later mentioned that they could not edit anything other than the CSS file. But will leave this here so it may be of use to others.

enter image description here

The main consideration that others are neglecting is that OP has stated that they cannot modify the HTML.

You can target what you need in the DOM then add classes dynamically with javascript. Then style as you need.

In an example that I made, I targeted all <p> elements with jQuery and wrapped it with a div with a class of "colored"

$( "p" ).wrap( "<div class='colored'></div>" );

Then in my CSS i targeted the <p> and gave it the background color and changed to display: inline

.colored p {
    display: inline;
    background: green;
}

By setting the display to inline you lose some of the styling that it would normally inherit. So make sure that you target the most specific element and style the container to fit the rest of your design. This is just meant as a working starting point. Use carefully. Working demo on CodePen

How can I calculate the number of years between two dates?

Sleek foundation javascript function.

 function calculateAge(birthday) { // birthday is a date
   var ageDifMs = Date.now() - birthday;
   var ageDate = new Date(ageDifMs); // miliseconds from epoch
   return Math.abs(ageDate.getUTCFullYear() - 1970);
 }

Python Tkinter clearing a frame

pack_forget and grid_forget will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy method.

To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.

Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.

Assign a variable inside a Block to a variable outside a Block

Try __weak if you get any warning regarding retain cycle else use __block

Person *strongPerson = [Person new];
__weak Person *weakPerson = person;

Now you can refer weakPerson object inside block.

Run a controller function whenever a view is opened/shown

Following up on the answer and link from AlexMart, something like this works:

.controller('MyCtrl', function($scope) {
  $scope.$on('$ionicView.enter', function() {
     // Code you want executed every time view is opened
     console.log('Opened!')
  })
})

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

Selecting element by data attribute with jQuery

For people Googling and want more general rules about selecting with data-attributes:

$("[data-test]") will select any element that merely has the data attribute (no matter the value of the attribute). Including:

<div data-test=value>attributes with values</div>
<div data-test>attributes without values</div>

$('[data-test~="foo"]') will select any element where the data attribute contains foo but doesn't have to be exact, such as:

<div data-test="foo">Exact Matches</div>
<div data-test="this has the word foo">Where the Attribute merely contains "foo"</div>

$('[data-test="the_exact_value"]') will select any element where the data attribute exact value is the_exact_value, for example:

<div data-test="the_exact_value">Exact Matches</div>

but not

<div data-test="the_exact_value foo">This won't match</div>

Create comma separated strings C#?

Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.

Pros - More flexible than an array.

Cons - You can't pass a string containing a comma.

CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();

list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");

string s = list.ToString(); //Huey,Dewey,Louie

PHP: Return all dates between two dates in an array

// will return dates array
function returnBetweenDates( $startDate, $endDate ){
    $startStamp = strtotime(  $startDate );
    $endStamp   = strtotime(  $endDate );

    if( $endStamp > $startStamp ){
        while( $endStamp >= $startStamp ){

            $dateArr[] = date( 'Y-m-d', $startStamp );

            $startStamp = strtotime( ' +1 day ', $startStamp );

        }
        return $dateArr;    
    }else{
        return $startDate;
    }

}

returnBetweenDates( '2014-09-16', '2014-09-26' );

// print_r( returnBetweenDates( '2014-09-16', '2014-09-26' ) );

it will return array like below:

Array
(
    [0] => 2014-09-16
    [1] => 2014-09-17
    [2] => 2014-09-18
    [3] => 2014-09-19
    [4] => 2014-09-20
    [5] => 2014-09-21
    [6] => 2014-09-22
    [7] => 2014-09-23
    [8] => 2014-09-24
    [9] => 2014-09-25
    [10] => 2014-09-26
)

Show DialogFragment with animation growing from a point

Use decor view inside onStart in your dialog fragment

@Override
public void onStart() {
    super.onStart();


    final View decorView = getDialog()
            .getWindow()
            .getDecorView();

    decorView.animate().translationY(-100)
            .setStartDelay(300)
            .setDuration(300)
            .start();

}

Bundle ID Suffix? What is it?

The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.

It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.

An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:

com.awesomeapps.thebestapp

In this case the suffix is thebestapp.

How to center icon and text in a android button with width set to "fill parent"

I have seen solutions for aligning drawable at start/left but nothing for drawable end/right, so I came up with this solution. It uses dynamically calculated paddings for aligning drawable and text on both left and right side.

class IconButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyle) {

    init {
        maxLines = 1
    }

    override fun onDraw(canvas: Canvas) {
        val buttonContentWidth = (width - paddingLeft - paddingRight).toFloat()

        val textWidth = paint.measureText(text.toString())

        val drawable = compoundDrawables[0] ?: compoundDrawables[2]
        val drawableWidth = drawable?.intrinsicWidth ?: 0
        val drawablePadding = if (textWidth > 0 && drawable != null) compoundDrawablePadding else 0
        val bodyWidth = textWidth + drawableWidth.toFloat() + drawablePadding.toFloat()

        canvas.save()

        val padding = (buttonContentWidth - bodyWidth).toInt() / 2
        val leftOrRight = if (compoundDrawables[0] != null) 1 else -1
        setPadding(leftOrRight * padding, 0, -leftOrRight * padding, 0)

        super.onDraw(canvas)
        canvas.restore()
    }
}

It is important to set gravity in your layout to either "center_vertical|start" or "center_vertical|end" depending on where do you set the icon. For example:

<com.stackoverflow.util.IconButton
        android:id="@+id/cancel_btn"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableStart="@drawable/cancel"
        android:drawablePadding="@dimen/padding_small"
        android:gravity="center_vertical|start"
        android:text="Cancel" />

Only problem with this implementation is that button can only have single line of text, otherwise the area of the text fills the button and paddings will be 0.

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Modifying CSS class property values on the fly with JavaScript / jQuery

Why not just use a .class selector to modify the properties of every object in that class?

ie:

$('.myclass').css('color: red;');

How to output HTML from JSP <%! ... %> block?

All you need to do is pass the JspWriter object into your method as a parameter i.e.

void someOutput(JspWriter stream)

Then call it via:

<% someOutput(out) %>

The writer object is a local variable inside _jspService so you need to pass it into your utility method. The same would apply for all the other built in references (e.g. request, response, session).

A great way to see whats going on is to use Tomcat as your server and drill down into the 'work' directory for the '.java' file generated from your 'jsp' page. Alternatively in weblogic you can use the 'weblogic.jspc' page compiler to view the Java that will be generated when the page is requested.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

I resolved it by replacing Tomcat 8.5.* with Tomcat 7.0.* version.

What are libtool's .la file for?

It is a textual file that includes a description of the library.

It allows libtool to create platform-independent names.

For example, libfoo goes to:

Under Linux:

/lib/libfoo.so       # Symlink to shared object
/lib/libfoo.so.1     # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library

Under Cygwin:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # libtool library
/bin/cygfoo_1.dll    # DLL

Under Windows MinGW:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library
/bin/foo_1.dll       # DLL

So libfoo.la is the only file that is preserved between platforms by libtool allowing to understand what happens with:

  • Library dependencies
  • Actual file names
  • Library version and revision

Without depending on a specific platform implementation of libraries.

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

jsonify a SQLAlchemy result set in Flask

It's been a lot of times and there are lots of valid answers, but the following code block seems to work:

my_object = SqlAlchemyModel()
my_serializable_obj = my_object.__dict__
del my_serializable_obj["_sa_instance_state"]
print(jsonify(my_serializable_object))

I'm aware that this is not a perfect solution, nor as elegant as the others, however for those who want o quick fix, they might try this.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

How do I find out if a column exists in a VB.Net DataRow

You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".

Check that a variable is a number in UNIX shell

You can do that with simple test command.

$ test ab -eq 1 >/dev/null 2>&1
$ echo $?
2

$ test 21 -eq 1 >/dev/null 2>&1
$ echo $?
1

$ test 1 -eq 1 >/dev/null 2>&1
$ echo $?
0

So if the exit status is either 0 or 1 then it is a integer , but if the exis status is 2 then it is not a number.

Python concatenate text files

If you have a lot of files in the directory then glob2 might be a better option to generate a list of filenames rather than writing them by hand.

import glob2

filenames = glob2.glob('*.txt')  # list of all .txt files in the directory

with open('outfile.txt', 'w') as f:
    for file in filenames:
        with open(file) as infile:
            f.write(infile.read()+'\n')

How to set "style=display:none;" using jQuery's attr method?

Please try below code for it :

$('#msform').fadeOut(50);

$('#msform').fadeIn(50);

ValueError: all the input arrays must have same number of dimensions

The reason why you get your error is because a "1 by n" matrix is different from an array of length n.

I recommend using hstack() and vstack() instead. Like this:

import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:]                    # last column of that matrix.

result = np.hstack((a,b))       # stack them horizontally like this:
#array([[ 0,  1,  2,  3,  4,  5,  6,  7,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15, 15],
#       [16, 17, 18, 19, 20, 21, 22, 23, 23],
#       [24, 25, 26, 27, 28, 29, 30, 31, 31]])

Notice the repeated "7, 15, 23, 31" column. Also, notice that I used a[:,-1:] instead of a[:,-1]. My version generates a column:

array([[7],
       [15],
       [23],
       [31]])

Instead of a row array([7,15,23,31])


Edit: append() is much slower. Read this answer.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

To acheive dynamic filtering follow the link - https://iamvickyav.medium.com/spring-boot-dynamically-ignore-fields-while-converting-java-object-to-json-e8d642088f55

  1. Add the @JsonFilter("Filter name") annotation to the model class.

  2. Inside the controller function add the code:-

    SimpleBeanPropertyFilter simpleBeanPropertyFilter =
            SimpleBeanPropertyFilter.serializeAllExcept("id", "dob"); 
    
    FilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter("Filter name", simpleBeanPropertyFilter);
    
    List<User> userList = userService.getAllUsers();
    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userList);
    mappingJacksonValue.setFilters(filterProvider);
    
    return mappingJacksonValue;
    
  3. make sure the return type is MappingJacksonValue.

Convert NSData to String?

I believe your "P" as the dataWithBytes param

NSData *keydata = [NSData dataWithBytes:P length:len];

should be "buf"

NSData *keydata = [NSData dataWithBytes:buf length:len];

since i2d_PrivateKey puts the pointer to the output buffer p at the end of the buffer and waiting for further input, and buf is still pointing to the beginning of your buffer.

The following code works for me where pkey is a pointer to an EVP_PKEY:

unsigned char *buf, *pp;
int len = i2d_PrivateKey(pkey, NULL);
buf = OPENSSL_malloc(len); 
pp = buf;
i2d_PrivateKey(pkey, &pp);

NSData* pkeyData = [NSData dataWithBytes:(const void *)buf length:len];
DLog(@"Private key in hex (%d): %@", len, pkeyData);

You can use an online converter to convert your binary data into base 64 (http://tomeko.net/online_tools/hex_to_base64.php?lang=en) and compare it to the private key in your cert file after using the following command and checking the output of mypkey.pem:

openssl pkcs12 -in myCert.p12 -nocerts -nodes -out mypkey.pem

I referenced your question and this EVP function site for my answer.

Bootstrap: add margin/padding space between columns

Just add 'justify-content-around' class. that would automatically add gap between 2 divs.

Documentation: https://getbootstrap.com/docs/4.1/layout/grid/#horizontal-alignment

Sample:

<div class="row justify-content-around">
    <div class="col-4">
      One of two columns
    </div>
    <div class="col-4">
      One of two columns
    </div>
</div>

How do I get bit-by-bit data from an integer value in C?

Using std::bitset

int value = 123;
std::bitset<sizeof(int)> bits(value);
std::cout <<bits.to_string();

UICollectionView auto scroll to cell at IndexPath

this seemed to work for me, its similar to another answer but has some distinct differences:

- (void)viewDidLayoutSubviews
{     
   [self.collectionView layoutIfNeeded];
   NSArray *visibleItems = [self.collectionView indexPathsForVisibleItems];
   NSIndexPath *currentItem = [visibleItems objectAtIndex:0];
   NSIndexPath *nextItem = [NSIndexPath indexPathForItem:someInt inSection:currentItem.section];

   [self.collectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}

Implementing multiple interfaces with Java - is there a way to delegate?

Unfortunately: NO.

We're all eagerly awaiting the Java support for extension methods

git stash -> merge stashed change with current changes

The way I do this is to git add this first then git stash apply <stash code>. It's the most simple way.

Pip - Fatal error in launcher: Unable to create process using '"'

My solution is to run twine upload over the python -m argument.

So just use python -m:

python -m twine upload dist/*

How can I match a string with a regex in Bash?

A Function To Do This

extract () {
  if [ -f $1 ] ; then
      case $1 in
          *.tar.bz2)   tar xvjf $1    ;;
          *.tar.gz)    tar xvzf $1    ;;
          *.bz2)       bunzip2 $1     ;;
          *.rar)       rar x $1       ;;
          *.gz)        gunzip $1      ;;
          *.tar)       tar xvf $1     ;;
          *.tbz2)      tar xvjf $1    ;;
          *.tgz)       tar xvzf $1    ;;
          *.zip)       unzip $1       ;;
          *.Z)         uncompress $1  ;;
          *.7z)        7z x $1        ;;
          *)           echo "don't know '$1'..." ;;
      esac
  else
      echo "'$1' is not a valid file!"
  fi
}

Other Note

In response to Aquarius Power in the comment above, We need to store the regex on a var

The variable BASH_REMATCH is set after you match the expression, and ${BASH_REMATCH[n]} will match the nth group wrapped in parentheses ie in the following ${BASH_REMATCH[1]} = "compressed" and ${BASH_REMATCH[2]} = ".gz"

if [[ "compressed.gz" =~ ^(.*)(\.[a-z]{1,5})$ ]]; 
then 
  echo ${BASH_REMATCH[2]} ; 
else 
  echo "Not proper format"; 
fi

(The regex above isn't meant to be a valid one for file naming and extensions, but it works for the example)

convert HTML ( having Javascript ) to PDF using JavaScript

You can do it using a jquery,

Use this code to link the button...

$(document).ready(function() {
    $("#button_id").click(function() {
        window.print();
        return false;
    });
});

This link may be also helpful: jQuery Print HTML Pdf Page Options Link

PL/pgSQL checking if a row exists

Use count(*)

declare 
   cnt integer;
begin
  SELECT count(*) INTO cnt
  FROM people
  WHERE person_id = my_person_id;

IF cnt > 0 THEN
  -- Do something
END IF;

Edit (for the downvoter who didn't read the statement and others who might be doing something similar)

The solution is only effective because there is a where clause on a column (and the name of the column suggests that its the primary key - so the where clause is highly effective)

Because of that where clause there is no need to use a LIMIT or something else to test the presence of a row that is identified by its primary key. It is an effective way to test this.

How to add hyperlink in JLabel?

Use a JEditorPane with a HyperlinkListener.

How to test valid UUID/GUID?

Beside Gambol's answer that will do the job in nearly all cases, all answers given so far missed that the grouped formatting (8-4-4-4-12) is not mandatory to encode GUIDs in text. It's used extremely often but obviously also a plain chain of 32 hexadecimal digits can be valid.[1] regexenh:

/^[0-9a-f]{8}-?[0-9a-f]{4}-?[1-5][0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$/i

[1] The question is about checking variables, so we should include the user-unfriendly form as well.

How do I make entire div a link?

You need to assign display: block; property to the wrapping anchor. Otherwise it won't wrap correctly.

<a style="display:block" href="http://justinbieber.com">
  <div class="xyz">My div contents</div>
</a>

How to use subList()

I've implemented and tested this one; it should cover most bases:

public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
    int size = list.size();
    if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
        return Collections.emptyList();
    }

    fromIndex = Math.max(0, fromIndex);
    toIndex = Math.min(size, toIndex);

    return list.subList(fromIndex, toIndex);
}

How to initialize log4j properly?

The fix for me was to put "log4j.properties" into the "src" folder.

Could not find a version that satisfies the requirement tensorflow

Looks like the problem is with Python 3.8. Use Python 3.7 instead. Steps I took to solve this.

  • Created a python 3.7 environment with conda
  • List item Installed rasa using pip install rasa within the environment.

Worked for me.

iFrame onload JavaScript event

Your code is correct. Just test to ensure it is being called like:

<script>
function doIt(){
  alert("here i am!");
  __doPostBack('ctl00$ctl00$bLogout','')
}
</script>

<iframe onload="doIt()"></iframe>

How to run ssh-add on windows?

In order to run ssh-add on Windows one could install git using choco install git. The ssh-add command is recognized once C:\Program Files\Git\usr\bin has been added as a PATH variable and the command prompt has been restarted:

C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)

C:\Users\user\Desktop\repository> 

How to connect to a MySQL Data Source in Visual Studio

Right Click the Project in Solution Explorer and click Manage NuGet Packages

Search for MySql.Data package, when you find it click on Install

Here is the sample controller which connects to MySql database using the mysql package. We mainly make use of MySqlConnection connection object.

 public class HomeController : Controller
{
    public ActionResult Index()
    {
        List<employeemodel> employees = new List<employeemodel>();
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            string query = "SELECT EmployeeId, Name, Country FROM Employees";
            using (MySqlCommand cmd = new MySqlCommand(query))
            {
                cmd.Connection = con;
               con.Open();
                using (MySqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        employees.Add(new EmployeeModel
                        {
                            EmployeeId = Convert.ToInt32(sdr["EmployeeId"]),
                            Name = sdr["Name"].ToString(),
                            Country = sdr["Country"].ToString()
                        });
                    }
                }
                con.Close();
            }
        }

        return View(employees);
    }
}

What is the difference between exit and return?

the return statement exits from the current function and exit() exits from the program

they are the same when used in main() function

also return is a statement while exit() is a function which requires stdlb.h header file

C# MessageBox dialog result

This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:

//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

// If the no button was pressed ... 
if (result == DialogResult.No)
{
    ...
}

Hope it helps

How do I display a decimal value to 2 decimal places?

None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01

Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.

then rounding to ensure we do not have more than 2 d.p.

Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)

6.665m.ToString() -> "6.67"

6.6m.ToString() -> "6.60"

Maven project version inheritance - do I have to specify the parent version?

Since Maven 3.5.0 you can use the ${revision} placeholder for that. The use is documented here: Maven CI Friendly Versions.

In short the parent pom looks like this (quoted from the Apache documentation):

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>18</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-parent</artifactId>
  <name>First CI Friendly</name>
  <version>${revision}</version>
  ...
  <properties>
    <revision>1.0.0-SNAPSHOT</revision>
  </properties>
  <modules>
    <module>child1</module>
    ..
  </modules>
</project>

and the child pom like this

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.maven.ci</groupId>
    <artifactId>ci-parent</artifactId>
    <version>${revision}</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-child</artifactId>
   ...
</project>

You also have to use the Flatten Maven Plugin to generate pom documents with the dedicated version number included for deployment. The HowTo is documented in the linked documentation.

Also @khmarbaise wrote a nice blob post about this feature: Maven: POM Files Without a Version in It?

sys.argv[1], IndexError: list index out of range

sys.argv represents the command line options you execute a script with.

sys.argv[0] is the name of the script you are running. All additional options are contained in sys.argv[1:].

You are attempting to open a file that uses sys.argv[1] (the first argument) as what looks to be the directory.

Try running something like this:

python ConcatenateFiles.py /tmp

Redirect on select option in select box

I'd strongly suggest moving away from inline JavaScript, to something like the following:

function redirect(goto){
    var conf = confirm("Are you sure you want to go elswhere?");
    if (conf && goto != '') {
        window.location = goto;
    }
}

var selectEl = document.getElementById('redirectSelect');

selectEl.onchange = function(){
    var goto = this.value;
    redirect(goto);

};

JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.

In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.

Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

How to disable sort in DataGridView?

For extending control functionality like this, I like to use extension methods so that it can be reused easily. Here is a starter extensions file that contains an extension to disable sorting on a datagridview.

To use it, just include it in your project and call like this

myDatagridView.DisableSorting()

In my case, I added this line of code in the DataBindingComplete eventhandler of the DataGridView where I wanted sorting disabled

Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms

Public Module Extensions

<Extension()>
Public Sub DisableSorting(datagrid As DataGridView)
    For index = 0 To datagrid.Columns.Count - 1
        datagrid.Columns(index).SortMode = DataGridViewColumnSortMode.NotSortable
    Next
End Sub


End Module

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Ruby get object keys as array

An alternative way if you need something more (besides using the keys method):

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }

obviously you would only do that if you want to manipulate the array while retrieving it..

Best way to repeat a character in C#

In all versions of .NET, you can repeat a string thus:

public static string Repeat(string value, int count)
{
    return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
}

To repeat a character, new String('\t', count) is your best bet. See the answer by @CMS.

html table cell width for different rows

with 5 columns and colspan, this is possible (click here) (but doesn't make much sense to me):

<table width="100%" border="1" bgcolor="#ffffff">
    <colgroup>
        <col width="25%">
        <col width="25%">
        <col width="25%">
        <col width="5%">
        <col width="20%">
    </colgroup>
    <tr>
        <td>25</td>
        <td colspan="2">50</td>
        <td colspan="2">25</td>     
    </tr>
    <tr>
        <td colspan="2">50</td>
        <td colspan="2">30</td>
        <td>20</td>
    </tr>
</table>

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

Redirect stderr to stdout in C shell

What about just

xxx >& /dev/stdout

???

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

Use getActivity().getSupportFragmentManager()

Most efficient way to get table row count

If it's only about getting the number of records (rows) I'd suggest using:

SELECT TABLE_ROWS
FROM information_schema.tables 
WHERE table_name='the_table_you_want' -- Can end here if only 1 DB 
  AND table_schema = DATABASE();      -- See comment below if > 1 DB

(at least for MySQL) instead.

Is there a Google Chrome-only CSS hack?

Sure is:

@media screen and (-webkit-min-device-pixel-ratio:0)
{ 
    #element { properties:value; } 
}

And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/

Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.

Also, these hacks may not be future proof.

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

CSS3 Transition - Fade out effect

This is the working code for your question.
Enjoy Coding....

<html>
   <head>

      <style>

         .animated {
            background-color: green;
            background-position: left top;
            padding-top:95px;
            margin-bottom:60px;
            -webkit-animation-duration: 10s;animation-duration: 10s;
            -webkit-animation-fill-mode: both;animation-fill-mode: both;
         }

         @-webkit-keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         @keyframes fadeOut {
            0% {opacity: 1;}
            100% {opacity: 0;}
         }

         .fadeOut {
            -webkit-animation-name: fadeOut;
            animation-name: fadeOut;
         }
      </style>

   </head>
   <body>

      <div id="animated-example" class="animated fadeOut"></div>

   </body>
</html>

Attach IntelliJ IDEA debugger to a running Java process

Also I use Tomcat GUI app (in my case: C:\tomcat\bin\Tomcat9w.bin).

  • Go to Java tab:

    enter image description here

  • Set your Java properties, for example:

    Java virtual machine

    C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll

    Java virtual machine

    C:\tomcat\bin\bootstrap.jar;C:\tomcat\bin\tomcat-juli.jar

    Java Options:

    -Dcatalina.home=C:\tomcat

    -Dcatalina.base=C:\tomcat

    -Djava.io.tmpdir=C:\tomcat\temp

    -Djava.util.logging.config.file=C:\tomcat\conf\logging.properties

    -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000

    Java 9 options:

    --add-opens=java.base/java.lang=ALL-UNNAMED

    --add-opens=java.base/java.io=ALL-UNNAMED

    --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED

How to compile for Windows on Linux with gcc/g++?

I've used mingw on Linux to make Windows executables in C, I suspect C++ would work as well.

I have a project, ELLCC, that packages clang and other things as a cross compiler tool chain. I use it to compile clang (C++), binutils, and GDB for Windows. Follow the download link at ellcc.org for pre-compiled binaries for several Linux hosts.

jQuery: enabling/disabling datepicker

try

$("#from").datepicker().datepicker('disable');

No provider for Http StaticInjectorError

You would need also to import the HttpClientModule from Angular '@angular/common/http' into your main AppModule for making HTTP requests.

app.module.ts

import { HttpClientModule } from '@angular/common/http';
import { ServiceService } from '../../../services/service.service';

@NgModule({
   imports: [
       HttpClientModule
   ],
   providers: [
       ServiceService
   ]
})
export class AppModule {...}

jQuery: How can I show an image popup onclick of the thumbnail?

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

How to add Google Maps Autocomplete search box?

<input id="autocomplete" placeholder="Enter your address" type="text"/>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://mapenter code heres.googleapis.com/maps/api/js?key=AIzaSyC7vPqKI7qjaHCE1SPg6i_d1HWFv1BtODo&libraries=places"></script>
<script type="text/javascript">
    function initialize() {

        new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')), {
            types: ['geocode']
        });
    }

    initialize();

</script>

Android Activity without ActionBar

Please find the default theme in styles.xml

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

And change parent this way

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

findAll() in yii

Use the below code. This should work.

$comments = EmailArchive::find()->where(['email_id' => $id])->all();

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

First of all, it is a waste of an executor slot to wrap the build step in node. Your upstream executor will just be sitting idle for no reason.

Second, from a multibranch project, you can use the environment variable BRANCH_NAME to make logic conditional on the current branch.

Third, the job parameter takes an absolute or relative job name. If you give a name without any path qualification, that would refer to another job in the same folder, which in the case of a multibranch project would mean another branch of the same repository.

Thus what you meant to write is probably

if (env.BRANCH_NAME == 'master') {
    build '../other-repo/master'
}

Java converting Image to BufferedImage

From a Java Game Engine:

/**
 * Converts a given Image into a BufferedImage
 *
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
public static BufferedImage toBufferedImage(Image img)
{
    if (img instanceof BufferedImage)
    {
        return (BufferedImage) img;
    }

    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}

Error in plot.window(...) : need finite 'xlim' values

This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.

For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'

Div with margin-left and width:100% overflowing on the right side

<div style="width:100%;">
    <div style="margin-left:45px;">
       <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>

Is there a way to get a collection of all the Models in your Rails app?

To avoid pre-load all Rails, you can do this:

Dir.glob("#{Rails.root}/app/models/**/*.rb").each {|f| require_dependency(f) }

require_dependency(f) is the same that Rails.application.eager_load! uses. This should avoid already required file errors.

Then you can use all kind of solutions to list AR models, like ActiveRecord::Base.descendants

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

CSS blur on background image but not on content

Add another div or img to your main div and blur that instead. jsfiddle

.blur {
    background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
    background-size:cover;
    -webkit-filter: blur(13px);
    -moz-filter: blur(13px);
    -o-filter: blur(13px);
    -ms-filter: blur(13px);
    filter: blur(13px);
    position:absolute;
    width:100%;
    height:100%;
}

How to get the index with the key in Python dictionary?

No, there is no straightforward way because Python dictionaries do not have a set ordering.

From the documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

In other words, the 'index' of b depends entirely on what was inserted into and deleted from the mapping before:

>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}

As of Python 2.7, you could use the collections.OrderedDict() type instead, if insertion order is important to your application.

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, which allows using aggregation operators such as $addFields, which outputs all existing fields from the input documents and newly added fields:

var new_info = { param2: "val2_new", param3: "val3_new" }

// { some_key: { param1: "val1", param2: "val2", param3: "val3" } }
// { some_key: { param1: "val1", param2: "val2"                 } }
db.collection.update({}, [{ $addFields: { some_key: new_info } }], { multi: true })
// { some_key: { param1: "val1", param2: "val2_new", param3: "val3_new" } }
// { some_key: { param1: "val1", param2: "val2_new", param3: "val3_new" } }
  • The first part {} is the match query, filtering which documents to update (in this case all documents).

  • The second part [{ $addFields: { some_key: new_info } }] is the update aggregation pipeline:

    • Note the squared brackets signifying the use of an aggregation pipeline.
    • Since this is an aggregation pipeline, we can use $addFields.
    • $addFields performs exactly what you need: updating the object so that the new object will overlay / merge with the existing one:
    • In this case, { param2: "val2_new", param3: "val3_new" } will be merged into the existing some_key by keeping param1 untouched and either add or replace both param2 and param3.
  • Don't forget { multi: true }, otherwise only the first matching document will be updated.

Linq to Entities - SQL "IN" clause

An alternative method to BenAlabaster answer

First of all, you can rewrite the query like this:

var matches = from Users in people
        where Users.User_Rights == "Admin" ||
              Users.User_Rights == "Users" || 
              Users.User_Rights == "Limited"
        select Users;

Certainly this is more 'wordy' and a pain to write but it works all the same.

So if we had some utility method that made it easy to create these kind of LINQ expressions we'd be in business.

with a utility method in place you can write something like this:

var matches = ctx.People.Where(
        BuildOrExpression<People, string>(
           p => p.User_Rights, names
        )
);

This builds an expression that has the same effect as:

var matches = from p in ctx.People
        where names.Contains(p.User_Rights)
        select p;

But which more importantly actually works against .NET 3.5 SP1.

Here is the plumbing function that makes this possible:

public static Expression<Func<TElement, bool>> BuildOrExpression<TElement, TValue>(
        Expression<Func<TElement, TValue>> valueSelector, 
        IEnumerable<TValue> values
    )
{     
    if (null == valueSelector) 
        throw new ArgumentNullException("valueSelector");

    if (null == values)
        throw new ArgumentNullException("values");  

    ParameterExpression p = valueSelector.Parameters.Single();

    if (!values.Any())   
        return e => false;

    var equals = values.Select(value =>
        (Expression)Expression.Equal(
             valueSelector.Body,
             Expression.Constant(
                 value,
                 typeof(TValue)
             )
        )
    );
   var body = equals.Aggregate<Expression>(
            (accumulate, equal) => Expression.Or(accumulate, equal)
    ); 

   return Expression.Lambda<Func<TElement, bool>>(body, p);
}

I'm not going to try to explain this method, other than to say it essentially builds a predicate expression for all the values using the valueSelector (i.e. p => p.User_Rights) and ORs those predicates together to create an expression for the complete predicate

Source: http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

javascript: optional first argument in function

Or you also can differentiate by what type of content you got. Options used to be an object the content is used to be a string, so you could say:

if ( typeof content === "object" ) {
  options = content;
  content = null;
}

Or if you are confused with renaming, you can use the arguments array which can be more straightforward:

if ( arguments.length === 1 ) {
  options = arguments[0];
  content = null;
}

Mixing a PHP variable with a string literal

You can use {} arround your variable, to separate it from what's after:

echo "{$test}y"

As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.

How to close Android application?

by calling finish(); in OnClick button or on menu

case R.id.menu_settings:

      finish();
     return true;

Remove characters before character "."

A couple of methods that, if the char does not exists, return the original string.

This one cuts the string after the first occurrence of the pivot:

public static string truncateStringAfterChar(string input, char pivot){         
    int index = input.IndexOf(pivot);   
    if(index >= 0) {
        return input.Substring(index + 1);          
    }           
    return input;       
}

This one instead cuts the string after the last occurrence of the pivot:

public static string truncateStringAfterLastChar(string input, char pivot){         
    return input.Split(pivot).Last();   
}

Run Excel Macro from Outside Excel Using VBScript From Command Line

I tried the above methods but I got the "macro cannot be found" error. This is final code that worked!

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True

  ' Import Add-Ins
xlApp.Workbooks.Open "C:\<pathOfXlaFile>\MyMacro.xla"
xlApp.AddIns("MyMacro").Installed = True

'
Open Excel workbook
Set xlBook = xlApp.Workbooks.Open("<pathOfXlsFile>\MyExcel.xls", 0, True)

' Run Macro
xlApp.Run "Sheet1.MyMacro"

xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Quit

In my case, MyMacro happens to be under Sheet1, thus Sheet1.MyMacro.

Android - How to download a file from a webserver

Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }

    /**
     * Showing Dialog
     * */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

How do I pass multiple parameters in Objective-C?

Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.

In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:

NSString *obj = @"Hello, World!";
int index = 5;

[array insertObject:obj atIndex:index];

This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.

Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:

  • + (id)numberWithBool:(BOOL)value;
  • + (id)numberWithFloat:(float)value;
  • + (id)numberWithDouble:(double)value;

In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.

Swift: Testing optionals for nil

One of the most direct ways to use optionals is the following:

Assuming xyz is of optional type, like Int? for example.

if let possXYZ = xyz {
    // do something with possXYZ (the unwrapped value of xyz)
} else {
    // do something now that we know xyz is .None
}

This way you can both test if xyz contains a value and if so, immediately work with that value.

With regards to your compiler error, the type UInt8 is not optional (note no '?') and therefore cannot be converted to nil. Make sure the variable you're working with is an optional before you treat it like one.

Receiving JSON data back from HTTP request

If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.

The HttpClient class documentation includes this example:

  HttpClient client = new HttpClient();
  HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
  response.EnsureSuccessStatusCode();
  string responseBody = await response.Content.ReadAsStringAsync();

Adding Image to xCode by dragging it from File

For xCode 10, first you need to add the image in your assetsCatalogue and then type this:

let imageView = UIImageView(image: #imageLiteral(resourceName: "type the name of your image here..."))

For beginners, let imageView is the name of the UIImageView object we are about to create.

An example for embedding an image into a viewControler file would look like this:

import UIKit

class TutorialViewCotroller: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let imageView = UIImageView(image: #imageLiteral(resourceName: "intoImage"))
        view.addSubview(imageView)
    }
}

Please notice that I did not use any extension for the image file name, as in my case it is a group of images.

How to remove a branch locally?

The Github application for Windows shows all remote branches of a repository. If you have deleted the branch locally with $ git branch -d [branch_name], the remote branch still exists in your Github repository and will appear regardless in the Windows Github application.

If you want to delete the branch completely (remotely as well), use the above command in combination with $ git push origin :[name_of_your_new_branch]. Warning: this command erases all existing branches and may cause loss of code. Be careful, I do not think this is what you are trying to do.

However every time you delete the local branch changes, the remote branch will still appear in the application. If you do not want to keep making changes, just ignore it and do not click, otherwise you may clone the repository. If you had any more questions, please let me know.

ASP.NET Custom Validator Client side & Server Side validation not firing

Use this:

<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>

To validate an empty field.

You don't need to add 2 validators !

How do I copy an object in Java?

public class MyClass implements Cloneable {

private boolean myField= false;
// and other fields or objects

public MyClass (){}

@Override
public MyClass clone() throws CloneNotSupportedException {
   try
   {
       MyClass clonedMyClass = (MyClass)super.clone();
       // if you have custom object, then you need create a new one in here
       return clonedMyClass ;
   } catch (CloneNotSupportedException e) {
       e.printStackTrace();
       return new MyClass();
   }

  }
}

and in your code:

MyClass myClass = new MyClass();
// do some work with this object
MyClass clonedMyClass = myClass.clone();

Convert SVG to image (JPEG, PNG, etc.) in the browser

There are several ways to convert SVG to PNG using the Canvg library.

In my case, I needed to get the PNG blob from inline SVG.

The library documentation provides an example (see OffscreenCanvas example).

But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)

However, there is another way that will work in Firefox too.

const el = document.getElementById("some-svg"); //this is our inline SVG

var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;

const svg = new XMLSerializer().serializeToString(el); //convert SVG to string

//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();

let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

For the last line thanks to this answer

XAMPP, Apache - Error: Apache shutdown unexpectedly

I solved the problem with stopping the service "Web Deployment Agent Service". Open: System -> Computer Management -> Services -> Web Deployment Agent Service. Stop this service and starting XAMPP works. I think this is a service by MS Webmatrix.

(German: Systemsteuerung -> System und Sicherheit -> Verwaltung -> Dienste -> Webbereitstellungs-Agent-Dienst)

How to unzip gz file using Python

import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in:
    with open('file.txt', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

Usage of __slots__?

Quoting Jacob Hallen:

The proper use of __slots__ is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. [This use of __slots__ eliminates the overhead of one dict for every object.] While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.

Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.

Making CPython smart enough to handle saving space without __slots__ is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).

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)

How can I wait for a thread to finish with .NET?

Here's a simple example that waits for a tread to finish, within the same class. It also makes a call to another class in the same namespace. I included the "using" statements so it can execute as a Windows Forms form as long as you create button1.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace ClassCrossCall
{

    public partial class Form1 : Form
    {
        int number = 0; // This is an intentional problem, included
                        // for demonstration purposes
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.Text = "Initialized";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "Clicked";
            button1.Refresh();
            Thread.Sleep(400);
            List<Task> taskList = new List<Task>();
            taskList.Add(Task.Factory.StartNew(() => update_thread(2000)));
            taskList.Add(Task.Factory.StartNew(() => update_thread(4000)));
            Task.WaitAll(taskList.ToArray());
            worker.update_button(this, number);
        }

        public void update_thread(int ms)
        {
            // It's important to check the scope of all variables
            number = ms; // This could be either 2000 or 4000. Race condition.
            Thread.Sleep(ms);
        }
    }

    class worker
    {
        public static void update_button(Form1 form, int number)
        {
            form.button1.Text = $"{number}";
        }
    }
}

Numpy - add row to array

If no calculations are necessary after every row, it's much quicker to add rows in python, then convert to numpy. Here are timing tests using python 3.6 vs. numpy 1.14, adding 100 rows, one at a time:

import numpy as np 
from time import perf_counter, sleep

def time_it():
    # Compare performance of two methods for adding rows to numpy array
    py_array = [[0, 1, 2], [0, 2, 0]]
    py_row = [4, 5, 6]
    numpy_array = np.array(py_array)
    numpy_row = np.array([4,5,6])
    n_loops = 100

    start_clock = perf_counter()
    for count in range(0, n_loops):
       numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
    duration = perf_counter() - start_clock
    print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))

    start_clock = perf_counter()
    for count in range(0, n_loops):
        py_array.append(py_row) # .15 micros
    numpy_array = np.array(py_array) # 43.9 micros       
    duration = perf_counter() - start_clock
    print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
    sleep(15)

#time_it() prints:

numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row

So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack's poor performance under those circumstances. If you don't need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.

Provide schema while reading csv file as a dataframe

Thanks to the answer by @Nulu, it works for pyspark with minimal tweaking

from pyspark.sql.types import LongType, StringType, StructField, StructType, BooleanType, ArrayType, IntegerType

customSchema = StructType(Array(
    StructField("project", StringType, true),
    StructField("article", StringType, true),
    StructField("requests", IntegerType, true),
    StructField("bytes_served", DoubleType, true)))

pagecount = sc.read.format("com.databricks.spark.csv")
         .option("delimiter"," ")
         .option("quote","")
         .option("header", "false")
         .schema(customSchema)
         .load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")

Find the number of columns in a table

SELECT TABLE_SCHEMA
    , TABLE_NAME
    , number = COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_SCHEMA, TABLE_NAME;

This one worked for me.

Depend on a branch or tag using a git URL in a package.json?

If you want to use devel or feature branch, or you haven’t published a certain package to the NPM registry, or you can’t because it’s a private module, then you can point to a git:// URI instead of a version number in your package.json:

"dependencies": {
   "public": "git://github.com/user/repo.git#ref",
   "private": "git+ssh://[email protected]:user/repo.git#ref"
}

The #ref portion is optional, and it can be a branch (like master), tag (like 0.0.1) or a partial or full commit id.

Select multiple columns by labels in pandas

Just pick the columns you want directly....

df[['A','E','I','C']]

Styling a input type=number

UPDATE 17/03/2017

Original solution won't work anymore. The spinners are part of shadow dom. For now just to hide in chrome use:

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
  -webkit-appearance: none;_x000D_
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

or to always show:

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

You can try the following but keep in mind that works only for Chrome:

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    cursor:pointer;_x000D_
    display:block;_x000D_
    width:8px;_x000D_
    color: #333;_x000D_
    text-align:center;_x000D_
    position:relative;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before,_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
    content: "^";_x000D_
    position:absolute;_x000D_
    right: 0;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:before {_x000D_
    top:0px;_x000D_
}_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button:after {_x000D_
    bottom:0px;_x000D_
    -webkit-transform: rotate(180deg);_x000D_
}
_x000D_
<input type="number" />
_x000D_
_x000D_
_x000D_

access key and value of object using *ngFor

Thought of adding an answer for Angular 8:

For looping you can do:

<ng-container *ngFor="let item of BATCH_FILE_HEADERS | keyvalue: keepOriginalOrder">
   <th nxHeaderCell>{{'upload.bulk.headings.'+item.key |translate}}</th>
</ng-container>

Also if you need the above array to keep the original order then declare this inside your class:

public keepOriginalOrder = (a, b) => a.key;

HTML text input field with currency symbol

Try This

_x000D_
_x000D_
<label style="position: relative; left:15px;">$</label>
<input type="text" style="text-indent: 15px;">
_x000D_
_x000D_
_x000D_

How do I import/include MATLAB functions?

Solution for Windows

Go to File --> Set Path and add the folder containing the functions as Matlab files. (At least for Matlab 2007b on Vista)

How to pick a new color for each plotted line within a figure in matplotlib?

As Ciro's answer notes, you can use prop_cycle to set a list of colors for matplotlib to cycle through. But how many colors? What if you want to use the same color cycle for lots of plots, with different numbers of lines?

One tactic would be to use a formula like the one from https://gamedev.stackexchange.com/a/46469/22397, to generate an infinite sequence of colors where each color tries to be significantly different from all those that preceded it.

Unfortunately, prop_cycle won't accept infinite sequences - it will hang forever if you pass it one. But we can take, say, the first 1000 colors generated from such a sequence, and set it as the color cycle. That way, for plots with any sane number of lines, you should get distinguishable colors.

Example:

from matplotlib import pyplot as plt
from matplotlib.colors import hsv_to_rgb
from cycler import cycler

# 1000 distinct colors:
colors = [hsv_to_rgb([(i * 0.618033988749895) % 1.0, 1, 1])
          for i in range(1000)]
plt.rc('axes', prop_cycle=(cycler('color', colors)))

for i in range(20):
    plt.plot([1, 0], [i, i])

plt.show()

Output:

Graph output by the code above

Now, all the colors are different - although I admit that I struggle to distinguish a few of them!

How to change a TextView's style at runtime

Depending on which style you want to set, you have to use different methods. TextAppearance stuff has its own setter, TypeFace has its own setter, background has its own setter, etc.

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

How to use graphics.h in codeblocks?

If you want to use Codeblocks and Graphics.h,you can use Codeblocks-EP(I used it when I was learning C in college) then you can try

Codeblocks-EP http://codeblocks.codecutter.org/

In Codeblocks-EP , [File]->[New]->[Project]->[WinBGIm Project]

Codeblocks-EP WinBGIm Project Graphics.h

It has templates for WinBGIm projects installed and all the necessary libraries pre-installed.

OR try this https://stackoverflow.com/a/20321173/5227589

Show/Hide Multiple Divs with Jquery

If they fall into logical groups, I would probably go with the class approach already listed here.

Many people seem to forget that you can actually select several items by id in the same jQuery selector, as well:

$("#div1, #div2, #div3").show();

Where 'div1', 'div2', and 'div3' are all id attributes on various divs you want to show at once.

What is a good practice to check if an environmental variable exists or not?

Use the first; it directly tries to check if something is defined in environ. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and only use it for a comparison.

You're trying to see if something is present in environ, why would you get just to compare it and then toss it away?

That's exactly what getenv does:

Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.

(this also means your check could just be if getenv("FOO"))

you don't want to get it, you want to check for it's existence.

Either way, getenv is just a wrapper around environ.get but you don't see people checking for membership in mappings with:

from os import environ
if environ.get('Foo') is not None:

To summarize, use:

if "FOO" in os.environ:
    pass

if you just want to check for existence, while, use getenv("FOO") if you actually want to do something with the value you might get.

Rotation of 3D vector?

Here is an elegant method using quaternions that are blazingly fast; I can calculate 10 million rotations per second with appropriately vectorised numpy arrays. It relies on the quaternion extension to numpy found here.

Quaternion Theory: A quaternion is a number with one real and 3 imaginary dimensions usually written as q = w + xi + yj + zk where 'i', 'j', 'k' are imaginary dimensions. Just as a unit complex number 'c' can represent all 2d rotations by c=exp(i * theta), a unit quaternion 'q' can represent all 3d rotations by q=exp(p), where 'p' is a pure imaginary quaternion set by your axis and angle.

We start by converting your axis and angle to a quaternion whose imaginary dimensions are given by your axis of rotation, and whose magnitude is given by half the angle of rotation in radians. The 4 element vectors (w, x, y, z) are constructed as follows:

import numpy as np
import quaternion as quat

v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian

vector = np.array([0.] + v)
rot_axis = np.array([0.] + axis)
axis_angle = (theta*0.5) * rot_axis/np.linalg.norm(rot_axis)

First, a numpy array of 4 elements is constructed with the real component w=0 for both the vector to be rotated vector and the rotation axis rot_axis. The axis angle representation is then constructed by normalizing then multiplying by half the desired angle theta. See here for why half the angle is required.

Now create the quaternions v and qlog using the library, and get the unit rotation quaternion q by taking the exponential.

vec = quat.quaternion(*v)
qlog = quat.quaternion(*axis_angle)
q = np.exp(qlog)

Finally, the rotation of the vector is calculated by the following operation.

v_prime = q * vec * np.conjugate(q)

print(v_prime) # quaternion(0.0, 2.7491163, 4.7718093, 1.9162971)

Now just discard the real element and you have your rotated vector!

v_prime_vec = v_prime.imag # [2.74911638 4.77180932 1.91629719] as a numpy array

Note that this method is particularly efficient if you have to rotate a vector through many sequential rotations, as the quaternion product can just be calculated as q = q1 * q2 * q3 * q4 * ... * qn and then the vector is only rotated by 'q' at the very end using v' = q * v * conj(q).

This method gives you a seamless transformation between axis angle <---> 3d rotation operator simply by exp and log functions (yes log(q) just returns the axis-angle representation!). For further clarification of how quaternion multiplication etc. work, see here

Java client certificates over HTTPS/SSL

I use the Apache commons HTTP Client package to do this in my current project and it works fine with SSL and a self-signed cert (after installing it into cacerts like you mentioned). Please take a look at it here:

http://hc.apache.org/httpclient-3.x/tutorial.html

http://hc.apache.org/httpclient-3.x/sslguide.html

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,

  1. jquery-1.7.1.min.js
  2. jquery.unobtrusive-ajax.min.js

Only these two are enough for performing Ajax operation.

How to set caret(cursor) position in contenteditable element (div)?

I refactored @Liam's answer. I put it in a class with static methods, I made its functions receive an element instead of an #id, and some other small tweaks.

This code is particularly good for fixing the cursor in a rich text box that you might be making with <div contenteditable="true">. I was stuck on this for several days before arriving at the below code.

edit: His answer and this answer have a bug involving hitting enter. Since enter doesn't count as a character, the cursor position gets messed up after hitting enter. If I am able to fix the code, I will update my answer.

edit2: Save yourself a lot of headaches and make sure your <div contenteditable=true> is display: inline-block. This fixes some bugs related to Chrome putting <div> instead of <br> when you press enter.

How To Use

let richText = document.getElementById('rich-text');
let offset = Cursor.getCurrentCursorPosition(richText);
// do stuff to the innerHTML, such as adding/removing <span> tags
Cursor.setCurrentCursorPosition(offset, richText);
richText.focus();

Code

// Credit to Liam (Stack Overflow)
// https://stackoverflow.com/a/41034697/3480193
class Cursor {
    static getCurrentCursorPosition(parentElement) {
        var selection = window.getSelection(),
            charCount = -1,
            node;
        
        if (selection.focusNode) {
            if (Cursor._isChildOf(selection.focusNode, parentElement)) {
                node = selection.focusNode; 
                charCount = selection.focusOffset;
                
                while (node) {
                    if (node === parentElement) {
                        break;
                    }

                    if (node.previousSibling) {
                        node = node.previousSibling;
                        charCount += node.textContent.length;
                    } else {
                        node = node.parentNode;
                        if (node === null) {
                            break;
                        }
                    }
                }
            }
        }
        
        return charCount;
    }
    
    static setCurrentCursorPosition(chars, element) {
        if (chars >= 0) {
            var selection = window.getSelection();
            
            let range = Cursor._createRange(element, { count: chars });

            if (range) {
                range.collapse(false);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
    }
    
    static _createRange(node, chars, range) {
        if (!range) {
            range = document.createRange()
            range.selectNode(node);
            range.setStart(node, 0);
        }

        if (chars.count === 0) {
            range.setEnd(node, chars.count);
        } else if (node && chars.count >0) {
            if (node.nodeType === Node.TEXT_NODE) {
                if (node.textContent.length < chars.count) {
                    chars.count -= node.textContent.length;
                } else {
                    range.setEnd(node, chars.count);
                    chars.count = 0;
                }
            } else {
                for (var lp = 0; lp < node.childNodes.length; lp++) {
                    range = Cursor._createRange(node.childNodes[lp], chars, range);

                    if (chars.count === 0) {
                    break;
                    }
                }
            }
        } 

        return range;
    }
    
    static _isChildOf(node, parentElement) {
        while (node !== null) {
            if (node === parentElement) {
                return true;
            }
            node = node.parentNode;
        }

        return false;
    }
}

How to insert values in two dimensional array programmatically?

In case you don't know in advance how many elements you will have to handle it might be a better solution to use collections instead (https://en.wikipedia.org/wiki/Java_collections_framework). It would be possible also to create a new bigger 2-dimensional array, copy the old data over and insert the new items there, but the collection framework handles this for you automatically.

In this case you could use a Map of Strings to Lists of Strings:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyClass {
    public static void main(String args[]) {
        Map<String, List<String>> shades = new HashMap<>();

        ArrayList<String> shadesOfGrey = new ArrayList<>();
        shadesOfGrey.add("lightgrey");
        shadesOfGrey.add("dimgray");
        shadesOfGrey.add("sgi gray 92");

        ArrayList<String> shadesOfBlue = new ArrayList<>();
        shadesOfBlue.add("dodgerblue 2");
        shadesOfBlue.add("steelblue 2");
        shadesOfBlue.add("powderblue");

        ArrayList<String> shadesOfYellow = new ArrayList<>();
        shadesOfYellow.add("yellow 1");
        shadesOfYellow.add("gold 1");
        shadesOfYellow.add("darkgoldenrod 1");

        ArrayList<String> shadesOfRed = new ArrayList<>();
        shadesOfRed.add("indianred 1");
        shadesOfRed.add("firebrick 1");
        shadesOfRed.add("maroon 1");

        shades.put("greys", shadesOfGrey);
        shades.put("blues", shadesOfBlue);
        shades.put("yellows", shadesOfYellow);
        shades.put("reds", shadesOfRed);

        System.out.println(shades.get("greys").get(0)); // prints "lightgrey"
    }
}

Not Able To Debug App In Android Studio

What worked for me in Android Studio 3.2.1

Was:

RUN -> Attach debugger to Android Process --> com.my app

How can I display a tooltip message on hover using jQuery?

As recommended qTip and other projects are quite old I recommend using qTip2 as it is most up-to-date.

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

How can I select records ONLY from yesterday?

to_char(tran_date, 'yyyy-mm-dd') = to_char(sysdate-1, 'yyyy-mm-dd')

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Using DataBinding and setting background to the edittext with resources from the drawable folder causes the exception.

<EditText
                            android:background="@drawable/rectangle"
                            android:imeOptions="flagNoExtractUi"
                            android:layout_width="match_parent"
                            android:layout_height="45dp"
                            android:hint="Enter Your Name"
                            android:gravity="center"
                            android:textColorHint="@color/hintColor"
                            android:singleLine="true"
                            android:id="@+id/etName"
                            android:inputType="textCapWords"
                            android:text="@={viewModel.model.name}"
                            android:fontFamily="@font/avenir_roman"/>

Solution

I just change the background from android:background="@drawable/rectangle" to android:background="@null"

Clean and Rebuild the Project.

In C#, why is String a reference type that behaves like a value type?

How can you tell string is a reference type? I'm not sure that it matters how it is implemented. Strings in C# are immutable precisely so that you don't have to worry about this issue.

Mysql command not found in OS X 10.7

Maybe I'll help someone else. None of the above answers worked for Catalina. Finally, this solved the problem

echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> /Users/$(whoami)/.bash_profile

Of course, you have to change for the version of mysql you have installed

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

Prevent BODY from scrolling when a modal is opened

You could try setting body size to window size with overflow: hidden when modal is open

Your project contains error(s), please fix it before running it

Simply Deleted my debug certificate under ~/.android/debug.keystore and Project->Clean did solve the problem.

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Sorry, brief moment of synapse failure. Here's the real answer.

require 'date'

Time.at(seconds_since_epoch_integer).to_datetime

Brief example (this takes into account the current system timezone):

$ date +%s
1318996912

$ irb

ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
 => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> 

Further update (for UTC):

ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
 => #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>

Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..) outperforms DateTime.strptime(..) (update: added more benchmarks).

# ~ % ruby -v
#  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]

irb(main):038:0> Benchmark.measure do
irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
irb(main):040:2*     DateTime.strptime(s, '%s')
irb(main):041:2>   end
irb(main):042:1> end

=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>

irb(main):044:0> Benchmark.measure do
irb(main):045:1>   [1318996912, 1318496912].each do |i|
irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
irb(main):047:2>   end
irb(main):048:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

irb(main):050:0* Benchmark.measure do
irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
irb(main):052:2*     Time.at(s.to_i).to_datetime
irb(main):053:2>   end
irb(main):054:1> end

=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>

irb(main):056:0* Benchmark.measure do
irb(main):057:1*   [1318996912, 1318496912].each do |i|
irb(main):058:2*     Time.at(i).to_datetime
irb(main):059:2>   end
irb(main):060:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

Display alert message and redirect after click on accept

echo "<script>
window.location.href='admin/ahm/panel';
alert('There are no fields to generate a report');
</script>";

Try out this way it works...

First assign the window with the new page where the alert box must be displayed then show the alert box.

Populating spinner directly in the layout xml

Define this in your String.xml file and name the array what you want, such as "Weight"

<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>

and this code in your layout.xml

<Spinner 
        android:id="@+id/fromspin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:entries="@array/Weight"
 />

In your java file, getActivity is used in fragment; if you write that code in activity, then remove getActivity.

a = (Spinner) findViewById(R.id.fromspin);

 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
                R.array.weight, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        a.setAdapter(adapter);
        a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
                    if (!b.getText().toString().isEmpty()) {
                        float value1 = Float.parseFloat(b.getText().toString());
                        float kg = value1;
                        c.setText(Float.toString(kg));
                        float gram = value1 * 1000;
                        d.setText(Float.toString(gram));
                        float carat = value1 * 5000;
                        e.setText(Float.toString(carat));
                        float ton = value1 / 908;
                        f.setText(Float.toString(ton));
                    }

                }



            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        // Inflate the layout for this fragment
        return v;
    }

Angularjs - Pass argument to directive

You can try like below:

app.directive("directive_name", function(){
return {
    restrict:'E',
    transclude:true,
    template:'<div class="title"><h2>{{title}}</h3></div>',
    scope:{
      accept:"="
    },
    replace:true
  };
})

it sets up a two-way binding between the value of the 'accept' attribute and the parent scope.

And also you can set two way data binding with property: '='

For example, if you want both key and value bound to the local scope you would do:

  scope:{
    key:'=',
    value:'='
  },

For more info, https://docs.angularjs.org/guide/directive

So, if you want to pass an argument from controller to directive, then refer this below fiddle

http://jsfiddle.net/jaimem/y85Ft/7/

Hope it helps..

How do you change the server header returned by nginx?

It’s very simple: Add these lines to server section:

server_tokens off;
more_set_headers 'Server: My Very Own Server';

How to use log4net in Asp.net core 2.0

I am porting a .Net Framework console app to .Net Core and found a similar issue with log files not getting created under certain circumstances.

When using "CreateRepository" there appears to be a difference between .net framework and .net standard.

Under .Net Framework this worked to create a unique Log instance with it's own filename using the same property from log4net.config

GlobalContext.Properties["LogName"] = LogName;
var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository);

Under .Net Standard this didn't work and if you turn on tracing you see it can't find the configuration file ".config". It wasn't loading the previous known configuration. Once I added the configuration to the configurator it still didn't log, while not complaining about it either.

To get it working under .Net Standard with similar behavior as before, this is what I did.

var loggerRepository = LogManager.CreateRepository(LogName);
XmlConfigurator.Configure(loggerRepository,new FileInfo("log4net.config"));
var hierarchy = (Hierarchy) loggerRepository;
var appender = (RollingFileAppender)hierarchy.Root.GetAppender("RollingLogFileAppender");
appender.File = Path.Combine(Directory.GetCurrentDirectory(), "logs", $"{LogName}.log");

I didn't want to create a configuration file for every repo, so this works. Perhaps there is a better way to get the .Net Framework behavior as before and if there is please let me know below.

Close Window from ViewModel

Here is a simple example using the MVVM Light Messenger instead of an event. The view model sends a close message when a button is clicked:

    public MainViewModel()
    {
        QuitCommand = new RelayCommand(ExecuteQuitCommand);
    }

    public RelayCommand QuitCommand { get; private set; }

    private void ExecuteQuitCommand() 
    {
        Messenger.Default.Send<CloseMessage>(new CloseMessage());
    }

Then it is received in the code behind of the window.

    public Main()
    {   
        InitializeComponent();
        Messenger.Default.Register<CloseMessage>(this, HandleCloseMessage);
    }

    private void HandleCloseMessage(CloseMessage closeMessage)
    {
        Close();
    }

Python how to write to a binary file?

You can use the following code example using Python 3 syntax:

from struct import pack
with open("foo.bin", "wb") as file:
  file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))

Here is shell one-liner:

python -c $'from struct import pack\nwith open("foo.bin", "wb") as file: file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))'

How to read Excel cell having Date with Apache POI?

For reading date cells this method has proven to be robust so far:

private LocalDate readCellAsDate(final Row row, final int pos) {
    if (pos == -1) {
        return null;
    }
    final Cell cell = row.getCell(pos - 1);
    if (cell != null) {
        cell.setCellType(CellType.NUMERIC);
    } else {
        return null;
    }
    if (DateUtil.isCellDateFormatted(cell)) {
        try {
            return cell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } catch (final NullPointerException e) {
            logger.error(e.getMessage());
            return null;
        }
    }
    return null;
}

How to sort 2 dimensional array by column value?

If you want to sort based on first column (which contains number value), then try this:

arr.sort(function(a,b){
  return a[0]-b[0]
})

If you want to sort based on second column (which contains string value), then try this:

arr.sort(function(a,b){
  return a[1].charCodeAt(0)-b[1].charCodeAt(0)
})

P.S. for the second case, you need to compare between their ASCII values.

Hope this helps.

Get value from SimpleXMLElement Object

You can also use the magic method __toString()

$xml->code[0]->lat->__toString()