Programs & Examples On #Protocol handler

How do I create my own URL protocol? (e.g. so://...)

The portion with the HTTP://,FTP://, etc are called URI Schemes

You can register your own through the registry.

HKEY_CLASSES_ROOT/
  your-protocol-name/
    (Default)    "URL:your-protocol-name Protocol"
    URL Protocol ""
    shell/
      open/
        command/
          (Default) PathToExecutable

Sources: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml, http://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx

how to convert .java file to a .class file

From the command line, run

javac ClassName.java

How to get the data-id attribute?

var id = $(this).dataset.id

works for me!

how to enable sqlite3 for php?

Only use:

sudo apt-get install php5-sqlite

and later

sudo service apache2 restart

Get Hours and Minutes (HH:MM) from date

Another method using DATEPART built-in function:

SELECT cast(DATEPART(hour, GETDATE()) as varchar) + ':' + cast(DATEPART(minute, GETDATE()) as varchar)

Another Repeated column in mapping for entity error

The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:

@Column(nullable=false)
private Long customerId;

and also:

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer")
private Customer customer;

(and the same goes for productId/product).

You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId field, it's useless. And do the same for productId. If you want the customer ID of a sale, you just need to do this:

sale.getCustomer().getId()

Bash mkdir and subfolders

To create multiple sub-folders

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

startsWith() and endsWith() functions in PHP

I hope that the below answer may be efficient and also simple:

$content = "The main string to search";
$search = "T";
//For compare the begining string with case insensitive. 
if(stripos($content, $search) === 0) echo 'Yes';
else echo 'No';

//For compare the begining string with case sensitive. 
if(strpos($content, $search) === 0) echo 'Yes';
else echo 'No';

//For compare the ending string with case insensitive. 
if(stripos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';

//For compare the ending string with case sensitive. 
if(strpos(strrev($content), strrev($search)) === 0) echo 'Yes';
else echo 'No';

How can I turn a JSONArray into a JSONObject?

Can't you originally get the data as a JSONObject?

Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?

I'm not sure that it is possible to convert a JsonArray into a JsonObject.

I presume you are using the following from json.org

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

Multiple inputs with same name through POST in php

Change the names of your inputs:

<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum"  />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />

Then:

$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'

If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".

Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

Android Studio with Google Play Services

I've got this working after doing the following:

  • Have the google-play-services-lib as a module (note difference between module and project), then add the google-play-services.jar to your models "libs" directory.
  • After that add the jar to your build path through making a library or add the jar to another library. I generally have a single IDEA library which I add all my /libs/*.jar files to.
  • Add the library to your modules build path through Module Settings (F4).
  • Add the google-play-services-lib as a module dependency to your project.
  • Done!

Note: This doesn't give me the runtime exceptions either, it works.

How to find the path of Flutter SDK

If you have the flutter SDK installed.

Run:

flutter doctor -v

The first line will show the install path..

(if you don't have it installed go to the documentation)

How do I get the value of a registry key and ONLY the value using powershell

I'm not sure if this has been changed, or if it has something to do with which version of PS you're using, but using Andy's example, I can remove the -Name parameter and I still get the value of the reg item:

PS C:\> $key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
PS C:\> (Get-ItemProperty -Path $key).ProgramFilesDir
C:\Program Files


PS C:\> $psversiontable.psversion

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

Scikit-learn train_test_split with indices

Scikit learn plays really well with Pandas, so I suggest you use it. Here's an example:

In [1]: 
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
data = np.reshape(np.random.randn(20),(10,2)) # 10 training examples
labels = np.random.randint(2, size=10) # 10 labels

In [2]: # Giving columns in X a name
X = pd.DataFrame(data, columns=['Column_1', 'Column_2'])
y = pd.Series(labels)

In [3]:
X_train, X_test, y_train, y_test = train_test_split(X, y, 
                                                    test_size=0.2, 
                                                    random_state=0)

In [4]: X_test
Out[4]:

     Column_1    Column_2
2   -1.39       -1.86
8    0.48       -0.81
4   -0.10       -1.83

In [5]: y_test
Out[5]:

2    1
8    1
4    1
dtype: int32

You can directly call any scikit functions on DataFrame/Series and it will work.

Let's say you wanted to do a LogisticRegression, here's how you could retrieve the coefficients in a nice way:

In [6]: 
from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
model = model.fit(X_train, y_train)

# Retrieve coefficients: index is the feature name (['Column_1', 'Column_2'] here)
df_coefs = pd.DataFrame(model.coef_[0], index=X.columns, columns = ['Coefficient'])
df_coefs
Out[6]:
            Coefficient
Column_1    0.076987
Column_2    -0.352463

Android webview & localStorage

setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:

webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}

Encapsulation vs Abstraction?

NOTE: I am sharing this. It is not mean that here is not good answer but because I easily understood.

Answer:

When a class is conceptualized, what are the properties we can have in it given the context. If we are designing a class Animal in the context of a zoo, it is important that we have an attribute as animalType to describe domestic or wild. This attribute may not make sense when we design the class in a different context.

Similarly, what are the behaviors we are going to have in the class? Abstraction is also applied here. What is necessary to have here and what will be an overdose? Then we cut off some information from the class. This process is applying abstraction.

When we ask for difference between encapsulation and abstraction, I would say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept applied as part of inheritance and polymorphism.

Go here for more explanation about this topic.

Force encode from US-ASCII to UTF-8 (iconv)

People say you can't and I understand you may be frustrated when asking a question and getting such an answer.

If you really want it to show in UTF-8 instead of US ASCII then you need to do it in two steps.

First:

iconv -f us-ascii -t utf-16 yourfile > youfileinutf16.*

Second:

iconv -f utf-16le -t utf-8 yourfileinutf16 > yourfileinutf8.*

Then if you do a file -i, you'll see the new character set is UTF-8.

Dynamically create and submit form

Why don't you $.post or $.get directly?

GET requests:

$.get(url, data, callback);

POST requests:

$.post(url, data, callback);

Then you don't need a form, just send the data in your data object.

$.post("form2.html", {myField: "some value"}, function(){
  alert("done!");
});

Maven does not find JUnit tests to run

Many of these answers were quite useful to me in the past, but I would like to add an additional scenario that has cost me some time, as it may help others in the future:

Make sure that the test classes and methods are public.

My problem was that I was using an automatic test class/methods generation feature of my IDE (IntelliJ) and for some reason it created them as package-private. I find this to be easier to miss than one would expect.

Bitwise and in place of modulus operator

This only works for powers of two (and frequently only positive ones) because they have the unique property of having only one bit set to '1' in their binary representation. Because no other class of numbers shares this property, you can't create bitwise-and expressions for most modulus expressions.

String contains - ignore case

Try this

public static void main(String[] args)
{

    String original = "ABCDEFGHIJKLMNOPQ";
    String tobeChecked = "GHi";

    System.out.println(containsString(original, tobeChecked, true));        
    System.out.println(containsString(original, tobeChecked, false));

}

public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
    if (caseSensitive)
    {
        return original.contains(tobeChecked);

    }
    else
    {
        return original.toLowerCase().contains(tobeChecked.toLowerCase());
    }

}

How to save DataFrame directly to Hive?

You could use Hortonworks spark-llap library like this

import com.hortonworks.hwc.HiveWarehouseSession

df.write
  .format("com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector")
  .mode("append")
  .option("table", "myDatabase.myTable")
  .save()

Are parameters in strings.xml possible?

Yes, just format your strings in the standard String.format() way.

See the method Context.getString(int, Object...) and the Android or Java Formatter documentation.

In your case, the string definition would be:

<string name="timeFormat">%1$d minutes ago</string>

$on and $broadcast in angular

One thing you should know is $ prefix refers to an Angular Method, $$ prefixes refers to angular methods that you should avoid using.

below is an example template and its controllers, we'll explore how $broadcast/$on can help us achieve what we want.

<div ng-controller="FirstCtrl">
    <input ng-model="name"/> 
    <button ng-click="register()">Register </button>
</div>

<div ng-controller="SecondCtrl">
    Registered Name: <input ng-model="name"/> 
</div>

The controllers are

app.controller('FirstCtrl', function($scope){
    $scope.register = function(){

    }
});

app.controller('SecondCtrl', function($scope){

});

My question to you is how do you pass the name to the second controller when a user clicks register? You may come up with multiple solutions but the one we're going to use is using $broadcast and $on.

$broadcast vs $emit

Which should we use? $broadcast will channel down to all the children dom elements and $emit will channel the opposite direction to all the ancestor dom elements.

The best way to avoid deciding between $emit or $broadcast is to channel from the $rootScope and use $broadcast to all its children. Which makes our case much easier since our dom elements are siblings.

Adding $rootScope and lets $broadcast

app.controller('FirstCtrl', function($rootScope, $scope){
    $scope.register = function(){
        $rootScope.$broadcast('BOOM!', $scope.name)
    }
});

Note we added $rootScope and now we're using $broadcast(broadcastName, arguments). For broadcastName, we want to give it a unique name so we can catch that name in our secondCtrl. I've chosen BOOM! just for fun. The second arguments 'arguments' allows us to pass values to the listeners.

Receiving our broadcast

In our second controller, we need to set up code to listen to our broadcast

app.controller('SecondCtrl', function($scope){
  $scope.$on('BOOM!', function(events, args){
    console.log(args);
    $scope.name = args; //now we've registered!
  })
});

It's really that simple. Live Example

Other ways to achieve similar results

Try to avoid using this suite of methods as it is neither efficient nor easy to maintain but it's a simple way to fix issues you might have.

You can usually do the same thing by using a service or by simplifying your controllers. We won't discuss this in detail but I thought I'd just mention it for completeness.

Lastly, keep in mind a really useful broadcast to listen to is '$destroy' again you can see the $ means it's a method or object created by the vendor codes. Anyways $destroy is broadcasted when a controller gets destroyed, you may want to listen to this to know when your controller is removed.

Routing with multiple Get methods in ASP.NET Web API

There are lots of good answers already for this question. However nowadays Route configuration is sort of "deprecated". The newer version of MVC (.NET Core) does not support it. So better to get use to it :)

So I agree with all the answers which uses Attribute style routing. But I keep noticing that everyone repeated the base part of the route (api/...). It is better to apply a [RoutePrefix] attribute on top of the Controller class and don't repeat the same string over and over again.

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}

MySQL Insert query doesn't work with WHERE clause

Insert into = Adding rows to a table

Upate = update specific rows.

What would the where clause describe in your insert? It doesn't have anything to match, the row doesn't exist (yet)...

Map enum in JPA with fixed values?

This is now possible with JPA 2.1:

@Column(name = "RIGHT")
@Enumerated(EnumType.STRING)
private Right right;

Further details:

How to access POST form fields

I could find all parameters by using following code for both POST and GET requests.

var express = require('express');
var app = express();
const util = require('util');
app.post('/', function (req, res) {
    console.log("Got a POST request for the homepage");
    res.send(util.inspect(req.query,false,null));
})

How to format a number as percentage in R?

The tidyverse version is this:

> library(dplyr)
> library(scales)

> set.seed(1)
> m <- runif(5)
> dt <- as.data.frame(m)

> dt %>% mutate(perc=percent(m,accuracy=0.001))
          m    perc
1 0.2655087 26.551%
2 0.3721239 37.212%
3 0.5728534 57.285%
4 0.9082078 90.821%
5 0.2016819 20.168%

Looks tidy as usual.

Dropdownlist validation in Asp.net Using Required field validator

Add InitialValue="0" in Required field validator tag

 <asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID"
      Display="Dynamic" ValidationGroup="g1" runat="server"
      ControlToValidate="ControlID"
      InitialValue="0" ErrorMessage="ErrorMessage">
 </asp:RequiredFieldValidator>

Redirect parent window from an iframe action

or an alternative is the following (using document object)

parent.document.location.href = "http://example.com";

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:

Python 2.7 Deprecated in OSX 10.15 Catalina

Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")

https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes

Apple To Remove Python 2.7 in OSX 10.16

Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:

https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/

Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.

NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.

ScrollTo function in AngularJS

Thanks Andy for the example, this was very helpful. I ended implementing a slightly different strategy since I am developing a single-page scroll and did not want Angular to refresh when using the hashbang URL. I also want to preserve the back/forward action of the browser.

Instead of using the directive and the hash, I am using a $scope.$watch on the $location.search, and obtaining the target from there. This gives a nice clean anchor tag

<a ng-href="#/?scroll=myElement">My element</a>

I chained the watch code to the my module declaration in app.js like so:

.run(function($location, $rootScope) {
   $rootScope.$watch(function() { return $location.search() }, function(search) { 
     var scrollPos = 0;
     if (search.hasOwnProperty('scroll')) {
       var $target = $('#' + search.scroll);
       scrollPos = $target.offset().top;
     }   
     $("body,html").animate({scrollTop: scrollPos}, "slow");
   });
})

The caveat with the code above is that if you access by URL directly from a different route, the DOM may not be loaded in time for jQuery's $target.offset() call. The solution is to nest this code within a $viewContentLoaded watcher. The final code looks something like this:

.run(function($location, $rootScope) {
  $rootScope.$on('$viewContentLoaded', function() {
     $rootScope.$watch(function() { return $location.search() }, function(search) {
       var scrollPos = 0 
       if (search.hasOwnProperty('scroll')) {
         var $target = $('#' + search.scroll);
         var scrollPos = $target.offset().top;
       }
       $("body,html").animate({scrollTop: scrollPos}, "slow");                                                                                                                                                                    
     });  
   });    
 })

Tested with Chrome and FF

UICollectionView current visible cell index

This is old question but in my case...

- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    _m_offsetIdx = [m_cv indexPathForCell:m_cv.visibleCells.firstObject].row;
}

- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _m_offsetIdx = [m_cv indexPathForCell:m_cv.visibleCells.lastObject].row;
}

Circular gradient in android

<gradient
    android:centerColor="#c1c1c1"
    android:endColor="#4f4f4f"
    android:gradientRadius="400"
    android:startColor="#c1c1c1"
    android:type="radial" >
</gradient>

Best way to do a split pane in HTML

A good library is Shield UI - you can take a look at their flexible Splitter widget and the rest of the powerful components the framework offers.

how to avoid extra blank page at end while printing?

After struggling with various page-break settings and heights and a million various CSS rules on the body tag, I finally solved it over a year later.

I have a div which is supposed to be the only thing on the page which prints, but I was getting several blank pages after it. My body tag is set to visibility:hidden; but that wasn't enough. Vertically tall page elements still take up 'space'. So I added this in my print CSS rules:

#header, #menu, #sidebar{ height:1px; display:none;}

to target specific divs by their ids which contain tall page layout elements. I shrunk the height and then removed them from the layout. No more blank pages. Years later I'm happy to tell my client I cracked it. Hope this helps someone.

Select something that has more/less than x character

If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.

SELECT * 
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40)) 
FROM DATABASE')

When are static variables initialized?

From See Java Static Variable Methods:

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object.

Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.

What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.

In case of inner classes, they can not have static fields

An inner class is a nested class that is not explicitly or implicitly declared static.

...

Inner classes may not declare static initializers (§8.7) or member interfaces...

Inner classes may not declare static members, unless they are constant variables...

See JLS 8.1.3 Inner Classes and Enclosing Instances

final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.

final class Demo
{
    private final int x;
    private static final int z;  //must be initialized here.

    static 
    {
        z = 10;  //It can be initialized here.
    }

    public Demo(int x)
    {
        this.x=x;  //This is possible.
        //z=15; compiler-error - can not assign a value to a final variable z
    }
}

This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.

Increase bootstrap dropdown menu width

Add the following css class

.dropdown-menu {
    width: 300px !important;
    height: 400px !important;
}

Of course you can use what matches your need.

How to make primary key as autoincrement for Room Persistence lib

For example, if you have a users entity you want to store, with fields (firstname, lastname , email) and you want autogenerated id, you do this.

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerate = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

Room will then autogenerate and auto-increment the id field.

ORDER BY the IN value list

Lets get a visual impression about what was already said. For example you have a table with some tasks:

SELECT a.id,a.status,a.description FROM minicloud_tasks as a ORDER BY random();

 id |   status   |   description    
----+------------+------------------
  4 | processing | work on postgres
  6 | deleted    | need some rest
  3 | pending    | garden party
  5 | completed  | work on html

And you want to order the list of tasks by its status. The status is a list of string values:

(processing, pending,  completed, deleted)

The trick is to give each status value an interger and order the list numerical:

SELECT a.id,a.status,a.description FROM minicloud_tasks AS a
  JOIN (
    VALUES ('processing', 1), ('pending', 2), ('completed', 3), ('deleted', 4)
  ) AS b (status, id) ON (a.status = b.status)
  ORDER BY b.id ASC;

Which leads to:

 id |   status   |   description    
----+------------+------------------
  4 | processing | work on postgres
  3 | pending    | garden party
  5 | completed  | work on html
  6 | deleted    | need some rest

Credit @user80168

How to change status bar color to match app in Lollipop? [Android]

Just add this in you styles.xml. The colorPrimary is for the action bar and the colorPrimaryDark is for the status bar.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:colorPrimary">@color/primary</item>
    <item name="android:colorPrimaryDark">@color/primary_dark</item>
</style>

This picture from developer android explains more about color pallete. You can read more on this link.

enter image description here

getMinutes() 0-9 - How to display two digit numbers?

I usually use this piece of code :

var start = new Date(timestamp),
    startMinutes = start.getMinutes() < 10 ? '0' + start.getMinutes() : start.getMinutes();

It is quite similar to the @ogur accepted answer but does not concatenate an empty string in the case that 0 is not needed. Not sure it is better. Just an other way to do it !

Hibernate: hbm2ddl.auto=update in production?

We do it in a project running in production for months now and never had a problem so far. Keep in mind the 2 ingredients needed for this recipe:

  1. Design your object model with a backwards-compatibility approach, that is deprecate objects and attributes rather than removing/altering them. This means that if you need to change the name of an object or attribute, leave the old one as is, add the new one and write some kind of migration script. If you need to change an association between objects, if you already are in production, this means that your design was wrong in the first place, so try to think of a new way of expressing the new relationship, without affecting old data.

  2. Always backup the database prior to deployment.

My sense is - after reading this post - that 90% of the people taking part in this discussion are horrified just with the thought of using automations like this in a production environment. Some throw the ball at the DBA. Take a moment though to consider that not all production environments will provide a DBA and not many dev teams are able to afford one (at least for medium size projects). So, if we're talking about teams where everyone has to do everything, the ball is on them.

In this case, why not just try to have the best of both worlds? Tools like this are here to give a helping hand, which - with a careful design and plan - can help in many situations. And believe me, administrators may initially be hard to convince but if they know that the ball is not on their hands, they will love it.

Personally, I'd never go back to writing scripts by hand for extending any type of schema, but that's just my opinion. And after starting to adopt NoSQL schema-less databases recently, I can see that more than soon, all these schema-based operations will belong to the past, so you'd better start changing your perspective and look ahead.

How to change port number in vue-cli project

Another option if you're using vue cli 3 is to use a config file. Make a vue.config.js at the same level as your package.json and put a config like so:

module.exports = {
  devServer: {
    port: 3000
  }
}

Configuring it with the script:

npm run serve --port 3000

works great but if you have more config options I like doing it in a config file. You can find more info in the docs.

Sonar properties files

You have to specify the projectBaseDir if the module name doesn't match you module directory.

Since both your module are located in ".", you can simply add the following to your sonar-project properties:

module1.sonar.projectBaseDir=.
module2.sonar.projectBaseDir=.

Sonar will handle your modules as components of the project:

Result of Sonar analysis

EDIT

If both of your modules are located in the same source directory, define the same source folder for both and exclude the unwanted packages with sonar.exclusions:

module1.sonar.sources=src/main/java
module1.sonar.exclusions=app2code/**/*

module2.sonar.sources=src/main/java
module2.sonar.exclusions=app1code/**/*

More details about file exclusion

How to reset index in a pandas dataframe?

Another solutions are assign RangeIndex or range:

df.index = pd.RangeIndex(len(df.index))

df.index = range(len(df.index))

It is faster:

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())

In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop

In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop

In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop

How to pass a vector to a function?

found = binarySearch(first, last, search4, &random);

Notice the &.

Upgrade to python 3.8 using conda

Open Anaconda Prompt (base):

  1. Update conda:
conda update -n base -c defaults conda
  1. Create new environment with Python 3.8:
conda create -n python38 python=3.8
  1. Activate your new Python 3.8 environment:
conda activate python38
  1. Start Python 3.8:
python

Using JAXB to unmarshal/marshal a List<String>

User1's example worked well for me. But, as a warning, it won't work with anything other than simple String/Integer types, unless you add an @XmlSeeAlso annotation:

@XmlRootElement(name = "List")
@XmlSeeAlso(MovieTicket.class)
public class MovieTicketList {
    protected List<MovieTicket> list;

This works OK, although it prevents me from using a single generic list class across my entire application. It might also explain why this seemingly obvious class doesn't exist in the JAXB package.

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

http://jsfiddle.net/tVHYg/5/

.wrapper {
    background:#DDD;
    padding:1%;
    display:inline;
    height:20px;
}


span {
    width: 1%;
}

.contents {
    background:#c3c;
    overflow:hidden;
    white-space:nowrap;
    display:inline-block;
    width:0%;
}



.wrapper:hover .contents {
    -webkit-transition: width 1s ease-in-out;
    -moz-transition: width 1s ease-in-out;
    -o-transition: width 1s ease-in-out;
    transition: width 1s ease-in-out;

    width:90%;
}

Bash script plugin for Eclipse?

ShellEd

Solutions below how to install ShellEd don't work for me. A lot of error on dependencies. Found solution that works for me.

System:

Linux Lubuntu 12.04

IDE:

Eclipse Kepler

In Eclipse, go to Help > Install New Software

Click Add...

Add the following Location, http://download.eclipse.org/releases/kepler, and name it "Eclipse Kepler".

Click OK.

Select the newly-created Eclipse Kepler site.

Expand the Web, XML, Java EE and OSGi Enterprise Development section at the bottom. Select WST Server Adaptors.

Click Next, and install like usual.

Restart Eclipse

Then add ShellEd repo likewise as listed above: http://sourceforge.net/projects/shelled/files/shelled/update/

And install it.

Restart Eclipse.

Also worked in Eclipse Indigo as said here: http://docs.wraithmonster.com/install-shelled

Enjoy :)

FTP/SFTP access to an Amazon S3 Bucket

Update

S3 now offers a fully-managed SFTP Gateway Service for S3 that integrates with IAM and can be administered using aws-cli.


There are theoretical and practical reasons why this isn't a perfect solution, but it does work...

You can install an FTP/SFTP service (such as proftpd) on a linux server, either in EC2 or in your own data center... then mount a bucket into the filesystem where the ftp server is configured to chroot, using s3fs.

I have a client that serves content out of S3, and the content is provided to them by a 3rd party who only supports ftp pushes... so, with some hesitation (due to the impedance mismatch between S3 and an actual filesystem) but lacking the time to write a proper FTP/S3 gateway server software package (which I still intend to do one of these days), I proposed and deployed this solution for them several months ago and they have not reported any problems with the system.

As a bonus, since proftpd can chroot each user into their own home directory and "pretend" (as far as the user can tell) that files owned by the proftpd user are actually owned by the logged in user, this segregates each ftp user into a "subdirectory" of the bucket, and makes the other users' files inaccessible.


There is a problem with the default configuration, however.

Once you start to get a few tens or hundreds of files, the problem will manifest itself when you pull a directory listing, because ProFTPd will attempt to read the .ftpaccess files over, and over, and over again, and for each file in the directory, .ftpaccess is checked to see if the user should be allowed to view it.

You can disable this behavior in ProFTPd, but I would suggest that the most correct configuration is to configure additional options -o enable_noobj_cache -o stat_cache_expire=30 in s3fs:

-o stat_cache_expire (default is no expire)

specify expire time(seconds) for entries in the stat cache

Without this option, you'll make fewer requests to S3, but you also will not always reliably discover changes made to objects if external processes or other instances of s3fs are also modifying the objects in the bucket. The value "30" in my system was selected somewhat arbitrarily.

-o enable_noobj_cache (default is disable)

enable cache entries for the object which does not exist. s3fs always has to check whether file(or sub directory) exists under object(path) when s3fs does some command, since s3fs has recognized a directory which does not exist and has files or subdirectories under itself. It increases ListBucket request and makes performance bad. You can specify this option for performance, s3fs memorizes in stat cache that the object (file or directory) does not exist.

This option allows s3fs to remember that .ftpaccess wasn't there.


Unrelated to the performance issues that can arise with ProFTPd, which are resolved by the above changes, you also need to enable -o enable_content_md5 in s3fs.

-o enable_content_md5 (default is disable)

verifying uploaded data without multipart by content-md5 header. Enable to send "Content-MD5" header when uploading a object without multipart posting. If this option is enabled, it has some influences on a performance of s3fs when uploading small object. Because s3fs always checks MD5 when uploading large object, this option does not affect on large object.

This is an option which never should have been an option -- it should always be enabled, because not doing this bypasses a critical integrity check for only a negligible performance benefit. When an object is uploaded to S3 with a Content-MD5: header, S3 will validate the checksum and reject the object if it's corrupted in transit. However unlikely that might be, it seems short-sighted to disable this safety check.

Quotes are from the man page of s3fs. Grammatical errors are in the original text.

Git Bash doesn't see my PATH

Create a file in C:\Users\USERNAME which is called config.bashrc, containing:

PATH=$PATH:/c/Program\ Files\ \(x86\)/Application\ with\ space

Now move the file on the command line to the correct location:

mv config.bashrc .bashrc

java.lang.IllegalArgumentException: No converter found for return value of type

The issue occurred in my case because spring framework couldn't fetch the properties of nested objects. Getters/Setters is one way of solving. Making the properties public is another quick and dirty solution to validate if this is indeed the problem.

S3 limit to objects in a bucket

There are no limits to the number of objects you can store in your S3 bucket. AWS claims it to have unlimited storage. However, there are some limitations -

  1. By default, customers can provision up to 100 buckets per AWS account. However, you can increase your Amazon S3 bucket limit by visiting AWS Service Limits.
  2. An object can be 0 bytes to 5TB.
  3. The largest object that can be uploaded in a single PUT is 5 gigabytes
  4. For objects larger than 100 megabytes, customers should consider using the Multipart Upload capability.

That being said if you really have a lot of objects to be stored in S3 bucket consider randomizing your object name prefix to improve performance.

When your workload is a mix of request types, introduce some randomness to key names by adding a hash string as a prefix to the key name. By introducing randomness to your key names the I/O load will be distributed across multiple index partitions. For example, you can compute an MD5 hash of the character sequence that you plan to assign as the key and add 3 or 4 characters from the hash as a prefix to the key name.

More details - https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-performance-improve/

-- As of June 2018

throwing an exception in objective-c/cocoa

Since ObjC 2.0, Objective-C exceptions are no longer a wrapper for C's setjmp() longjmp(), and are compatible with C++ exception, the @try is "free of charge", but throwing and catching exceptions is way more expensive.

Anyway, assertions (using NSAssert and NSCAssert macro family) throw NSException, and that sane to use them as Ries states.

.NET HttpClient. How to POST string value?

You could do something like this

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:6740/api/Membership/exist");

req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";         
req.ContentLength = 6;

StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();

And then strReponse should contain the values returned by your webservice

How to change option menu icon in the action bar?

Use the example of Syed Raza Mehdi and add on the Application theme the name=actionOverflowButtonStyle parameter for compatibility.

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>

    <!-- For compatibility -->
    <item name="actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>

</style>

write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

Mathematical functions in Swift

For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.

Instead of floor(), round() and the rest of the rounding routines you can use rounded(_:):

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

These are currently available on Float and Double and it should be easy enough to convert to a CGFloat for example.

Instead of sqrt() there's the squareRoot() method on the FloatingPoint protocol. Again, both Float and Double conform to the FloatingPoint protocol:

let x = 4.0
let y = x.squareRoot()

For the trigonometric functions, the standard library can't help, so you're best off importing Darwin on the Apple platforms or Glibc on Linux. Fingers-crossed they'll be a neater way in the future.

#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

let x = 1.571
print(sin(x))
// Prints "~1.0"

android.widget.Switch - on/off event listener?

Use the following snippet to add a Switch to your layout via XML:

<Switch
     android:id="@+id/on_off_switch"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textOff="OFF"
     android:textOn="ON"/>

Then in your Activity's onCreate method, get a reference to your Switch and set its OnCheckedChangeListener:

Switch onOffSwitch = (Switch)  findViewById(R.id.on_off_switch); 
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Log.v("Switch State=", ""+isChecked);
}       

});

How to compare datetime with only date in SQL Server

DON'T be tempted to do things like this:

Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'

This is a better way:

Select * from [User] U 
where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')

see: What does the word “SARGable” really mean?

EDIT + There are 2 fundamental reasons for avoiding use of functions on data in the where clause (or in join conditions).

  1. In most cases using a function on data to filter or join removes the ability of the optimizer to access an index on that field, hence making the query slower (or more "costly")
  2. The other is, for every row of data involved there is at least one calculation being performed. That could be adding hundreds, thousands or many millions of calculations to the query so that we can compare to a single criteria like 2014-02-07. It is far more efficient to alter the criteria to suit the data instead.

"Amending the criteria to suit the data" is my way of describing "use SARGABLE predicates"


And do not use between either.

the best practice with date and time ranges is to avoid BETWEEN and to always use the form:

WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable.

http://sqlmag.com/t-sql/t-sql-best-practices-part-2 (Itzik Ben-Gan)

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

I had the same problem in my tomcat server but when i check deeply i found that i add a new tag in my web.xml file and the server doesn't accept it so check your file to if any update happened then restart your tomcat and will be good .

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • Error in plot.new() : figure margins too large, Scatter plot

    Invoking dev.off() to make RStudio open up a new graphics device with default settings worked for me. HTH.

    Counting no of rows returned by a select query

    select COUNT(*)
    from Monitor as m
        inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
        group by m.Company_id
        having COUNT(m.Monitor_id)>=5
    

    Unlink of file Failed. Should I try again?

    In my case (Win8.1, TortoiseGit running), it was the process called "TortoiseSVN status cache" that was locking the file.

    Killing it allowed me to run "git gc" without any more problems. The above process is fired up by TortoiseGit, so there is no need to manually restart it.

    grep using a character vector with multiple patterns

    In addition to @Marek's comment about not including fixed==TRUE, you also need to not have the spaces in your regular expression. It should be "A1|A9|A6".

    You also mention that there are lots of patterns. Assuming that they are in a vector

    toMatch <- c("A1", "A9", "A6")
    

    Then you can create your regular expression directly using paste and collapse = "|".

    matches <- unique (grep(paste(toMatch,collapse="|"), 
                            myfile$Letter, value=TRUE))
    

    Using %f with strftime() in Python to get microseconds

    You can also get microsecond precision from the time module using its time() function.
    (time.time() returns the time in seconds since epoch. Its fractional part is the time in microseconds, which is what you want.)

    >>> from time import time
    >>> time()
    ... 1310554308.287459   # the fractional part is what you want.
    
    
    # comparision with strftime -
    >>> from datetime import datetime
    >>> from time import time
    >>> datetime.now().strftime("%f"), time()
    ... ('287389', 1310554310.287459)
    

    How to fix: "HAX is not working and emulator runs in emulation mode"

    Yes it should be fixed, HAXM isn't working.

    HAXM sometimes works; experience with HAXM is currently sporadic across platforms.

    For instance, I've got late 2009 iMac running 10.8.5 and i7 processor @2.8Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration on this iMac machine, API19 chokes out.

    I also have early 2013 MBP 15" Retina running 10.8.5 and i7 processor @2.7Ghz, Android SDK 22.6 with all the goodies updated this morning (03/05/14). API17 will build emulators with HAXM acceleration, API19 works great too.

    Ditto for my (personal) late 2013 MBP Retina 13" with dual-core i5 and Mavericks.

    There is something going on for virtualization at the chip level missing from older CPU's (even i7's) that the new API19 x86 images need for HAXM to work. If API19 is not working, give API17 or even 16 a try.

    How do you create a daemon in Python?

    80% of the time, when folks say "daemon", they only want a server. Since the question is perfectly unclear on this point, it's hard to say what the possible domain of answers could be. Since a server is adequate, start there. If an actual "daemon" is actually needed (this is rare), read up on nohup as a way to daemonize a server.

    Until such time as an actual daemon is actually required, just write a simple server.

    Also look at the WSGI reference implementation.

    Also look at the Simple HTTP Server.

    "Are there any additional things that need to be considered? " Yes. About a million things. What protocol? How many requests? How long to service each request? How frequently will they arrive? Will you use a dedicated process? Threads? Subprocesses? Writing a daemon is a big job.

    Infinite Recursion with Jackson JSON and Hibernate JPA issue

    There's now a Jackson module (for Jackson 2) specifically designed to handle Hibernate lazy initialization problems when serializing.

    https://github.com/FasterXML/jackson-datatype-hibernate

    Just add the dependency (note there are different dependencies for Hibernate 3 and Hibernate 4):

    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-hibernate4</artifactId>
      <version>2.4.0</version>
    </dependency>
    

    and then register the module when intializing Jackson's ObjectMapper:

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Hibernate4Module());
    

    Documentation currently isn't great. See the Hibernate4Module code for available options.

    Mockito matcher and array of primitives

    You can use Mockito.any() when arguments are arrays also. I used it like this:

    verify(myMock, times(0)).setContents(any(), any());
    

    The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

    when you add context:component-scan for the first time in an xml, the following needs to be added.

    xmlns:context="http://www.springframework.org/schema/context"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    

    How do I run Java .class files?

    This can mean a lot of things, but the most common one is that the class contained in the file doesn't have the same name as the file itself. So, check if your class is also called HelloWorld2.

    How to create a Calendar table for 100 years in Sql

     declare @date int
     WITH CTE_DatesTable
    AS
    (
      SELECT CAST('20000101' as date) AS [date]
      UNION ALL
      SELECT   DATEADD(dd, 1, [date])
      FROM CTE_DatesTable
      WHERE DATEADD(dd, 1, [date]) <= '21001231'
    )
    SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate   FROM CTE_DatesTable
    
    OPTION (MAXRECURSION 0);
    

    MSBUILD : error MSB1008: Only one project can be specified

    For future readers.

    I got this error because my specified LOG file had a space in it:

    BEFORE:

    /l:FileLogger,Microsoft.Build.Engine;logfile=c:\Folder With Spaces\My_Log.log
    

    AFTER: (which resolved it)

    /l:FileLogger,Microsoft.Build.Engine;logfile="c:\Folder With Spaces\My_Log.log"
    

    Playing sound notifications using Javascript?

    I wrote a small function that can do it, with the Web Audio API...

    var beep = function(duration, type, finishedCallback) {
    
        if (!(window.audioContext || window.webkitAudioContext)) {
            throw Error("Your browser does not support Audio Context.");
        }
    
        duration = +duration;
    
        // Only 0-4 are valid types.
        type = (type % 5) || 0;
    
        if (typeof finishedCallback != "function") {
            finishedCallback = function() {};   
        }
    
        var ctx = new (window.audioContext || window.webkitAudioContext);
        var osc = ctx.createOscillator();
    
        osc.type = type;
    
        osc.connect(ctx.destination);
        osc.noteOn(0);
    
        setTimeout(function() {
            osc.noteOff(0);
            finishedCallback();
        }, duration);
    
    };
    

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

    (I am new to Codeigniter, so I don't know if this is the best advice)

    I keep publicly available files in my public folder. It is logical for them to be there, and I don't want to use Codeigniter for something I don't need to use it for.

    The directory tree looks likes this:

    • /application/
    • /public/
    • /public/css/
    • /public/img/
    • /public/js/
    • /system/

    The only files I keep in /public/ are Codeigniter's index.php, and my .htaccess file:

    RewriteEngine On
    RewriteBase /
    
    RewriteRule ^css/ - [L]
    RewriteRule ^img/ - [L]
    RewriteRule ^js/ - [L]
    
    RewriteRule ^index.php(.*)$ - [L]
    RewriteRule ^(.*)$ /index.php?/$1 [L]
    

    How to execute raw SQL in Flask-SQLAlchemy app

    SQL Alchemy session objects have their own execute method:

    result = db.session.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})
    

    All your application queries should be going through a session object, whether they're raw SQL or not. This ensures that the queries are properly managed by a transaction, which allows multiple queries in the same request to be committed or rolled back as a single unit. Going outside the transaction using the engine or the connection puts you at much greater risk of subtle, possibly hard to detect bugs that can leave you with corrupted data. Each request should be associated with only one transaction, and using db.session will ensure this is the case for your application.

    Also take note that execute is designed for parameterized queries. Use parameters, like :val in the example, for any inputs to the query to protect yourself from SQL injection attacks. You can provide the value for these parameters by passing a dict as the second argument, where each key is the name of the parameter as it appears in the query. The exact syntax of the parameter itself may be different depending on your database, but all of the major relational databases support them in some form.

    Assuming it's a SELECT query, this will return an iterable of RowProxy objects.

    You can access individual columns with a variety of techniques:

    for r in result:
        print(r[0]) # Access by positional index
        print(r['my_column']) # Access by column name as a string
        r_dict = dict(r.items()) # convert to dict keyed by column names
    

    Personally, I prefer to convert the results into namedtuples:

    from collections import namedtuple
    
    Record = namedtuple('Record', result.keys())
    records = [Record(*r) for r in result.fetchall()]
    for r in records:
        print(r.my_column)
        print(r)
    

    If you're not using the Flask-SQLAlchemy extension, you can still easily use a session:

    import sqlalchemy
    from sqlalchemy.orm import sessionmaker, scoped_session
    
    engine = sqlalchemy.create_engine('my connection string')
    Session = scoped_session(sessionmaker(bind=engine))
    
    s = Session()
    result = s.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})
    

    Undefined symbols for architecture armv7

    In my case, I'd added a framework that must be using Objective C++. I found this post:

    XCode .m vs. .mm

    that explained how the main.m needed to be renamed to main.mm so that the Objective-C++ classes could be compiled, too.

    That fixed it for me.

    unexpected T_VARIABLE, expecting T_FUNCTION

    You cannot use function calls in a class construction, you should initialize that value in the constructor function.

    From the PHP Manual on class properties:

    This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

    A working code sample:

    <?php
        class UserDatabaseConnection
        {
            public $connection;
            public function __construct()
            {
                $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
            }
            public function lookupUser($username)
            {
                // rest of my code...
                // example usage (procedural way):
                $query = sqlite_exec($this->connection, "SELECT ...", $error);
                // object oriented way:
                $query = $this->connection->queryExec("SELECT ...", $error);
            }
        }
    
        $udb = new UserDatabaseConnection;
    ?>
    

    Depending on your needs, protected or private might be a better choice for $connection. That protects you from accidentally closing or messing with the connection.

    What is the C# equivalent of friend?

    There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!

    Example: To be placed in AssemblyInfo.cs

    [assembly: InternalsVisibleTo("OtherAssembly")]
    

    How can I change my Cygwin home folder after installation?

    Change your HOME environment variable.

    on XP, its right-click My Computer >> Properties >> Advanced >> Environment Variables >> User Variables for >> [select variable HOME] >> edit

    How do I return the SQL data types from my query?

    This will give you everything column property related.

    SELECT * INTO TMP1
    FROM ( SELECT TOP 1 /* rest of your query expression here */ );
    
    SELECT o.name AS obj_name, TYPE_NAME(c.user_type_id) AS type_name, c.*  
    FROM sys.objects AS o   
    JOIN sys.columns AS c  ON o.object_id = c.object_id  
    WHERE o.name = 'TMP1';
    
    DROP TABLE TMP1;
    

    How to remove all CSS classes using jQuery/JavaScript?

    $("#item").removeClass();
    

    Calling removeClass with no parameters will remove all of the item's classes.


    You can also use (but is not necessarily recommended, the correct way is the one above):

    $("#item").removeAttr('class');
    $("#item").attr('class', '');
    $('#item')[0].className = '';
    

    If you didn't have jQuery, then this would be pretty much your only option:

    document.getElementById('item').className = '';
    

    How to vertically align text in input type="text"?

    Put it in a div tag seems to be the only way to FORCE that:

    <div style="vertical-align: middle"><div><input ... /></div></div>
    

    May be other tags like span works as like div do.

    Visual Studio 2015 doesn't have cl.exe

    For me that have Visual Studio 2015 this works:
    Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
    You can now execute your command in it, for example: cl /?

    GROUP BY without aggregate function

    You're experiencing a strict requirement of the GROUP BY clause. Every column not in the group-by clause must have a function applied to reduce all records for the matching "group" to a single record (sum, max, min, etc).

    If you list all queried (selected) columns in the GROUP BY clause, you are essentially requesting that duplicate records be excluded from the result set. That gives the same effect as SELECT DISTINCT which also eliminates duplicate rows from the result set.

    Best way to serialize/unserialize objects in JavaScript?

    The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.

    var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";
    

    then you can call

    eval("(" + person + ")") 
    

    , and you will get back your function in the json object.

    Batch not-equal (inequality) operator

    Try:

    if not "asdf" == "fdas" echo asdf
    

    That works for me on Windows XP (I get the same error as you for the code you posted).

    Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

    As an improvement to both Praveen and Tony, I use an override:

    public partial class MyDatabaseEntities : DbContext
    {
        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                            validationErrors.Entry.Entity.GetType().FullName,
                            validationError.PropertyName,
                            validationError.ErrorMessage);
                    }
                }
    
                throw;  // You can also choose to handle the exception here...
            }
        }
    }
    

    using jquery $.ajax to call a PHP function

    You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.

    Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).

    C++ auto keyword. Why is it magic?

    This functionality hasn't been there your whole life. It's been supported in Visual Studio since the 2010 version. It's a new C++11 feature, so it's not exclusive to Visual Studio and is/will be portable. Most compilers support it already.

    Replace new line/return with space using regex

    You May use first split and rejoin it using white space. it will work sure.

    String[] Larray = L.split("[\\n]+");
    L = "";
    for(int i = 0; i<Larray.lengh; i++){
       L = L+" "+Larray[i];  
    }
    

    Use 'import module' or 'from module import'?

    I was answering a similar question post but the poster deleted it before i could post. Here is one example to illustrate the differences.

    Python libraries may have one or more files (modules). For exmaples,

    package1
      |-- __init__.py
    

    or

    package2
      |-- __init__.py
      |-- module1.py
      |-- module2.py
    

    We can define python functions or classes inside any of the files based design requirements.

    Let's define

    1. func1() in __init__.py under mylibrary1, and
    2. foo() in module2.py under mylibrary2.

    We can access func1() using one of these methods

    import package1
    
    package1.func1()
    

    or

    import package1 as my
    
    my.func1()
    

    or

    from package1 import func1
    
    func1()
    

    or

    from package1 import *
    
    func1()
    

    We can use one of these methods to access foo():

    import package2.module2
    
    package2.module2.foo()
    

    or

    import package2.module2 as mod2
    
    mod2.foo()
    

    or

    from package2 import module2
    
    module2.foo()
    

    or

    from package2 import module2 as mod2
    
    mod2.foo()
    

    or

    from package2.module2 import *
    
    foo()
    

    apache mod_rewrite is not working or not enabled

    Try setting: "AllowOverride All".

    How to re import an updated package while in Python Interpreter?

    dragonfly's answer worked for me (python 3.4.3).

    import sys
    del sys.modules['module_name']
    

    Here is a lower level solution :

    exec(open("MyClass.py").read(), globals())
    

    How do I read an image file using Python?

    The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

    from PIL import Image
    jpgfile = Image.open("picture.jpg")
    
    print(jpgfile.bits, jpgfile.size, jpgfile.format)
    

    Rails: How to run `rails generate scaffold` when the model already exists?

    I had this challenge when working on a Rails 6 API application in Ubuntu 20.04.

    I had already existing models, and I needed to generate corresponding controllers for the models and also add their allowed attributes in the controller params.

    Here's how I did it:

    I used the rails generate scaffold_controller to get it done.

    I simply ran the following commands:

    rails generate scaffold_controller School name:string logo:json motto:text address:text
    
    rails generate scaffold_controller Program name:string logo:json school:references
    

    This generated the corresponding controllers for the models and also added their allowed attributes in the controller params, including the foreign key attributes.

    create  app/controllers/schools_controller.rb
    invoke  test_unit
    create    test/controllers/schools_controller_test.rb
    
    create  app/controllers/programs_controller.rb
    invoke  test_unit
    create    test/controllers/programs_controller_test.rb
    

    That's all.

    I hope this helps

    How do I use itertools.groupby()?

    WARNING:

    The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using

    for x in list(groupby(range(10))):
        print(list(x[1]))
    

    will produce:

    []
    []
    []
    []
    []
    []
    []
    []
    []
    [9]
    

    Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,

    def groupbylist(*args, **kwargs):
        return [(k, list(g)) for k, g in groupby(*args, **kwargs)]
    

    and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.

    Best way to save a trained model in PyTorch?

    A common PyTorch convention is to save models using either a .pt or .pth file extension.

    Save/Load Entire Model Save:

    path = "username/directory/lstmmodelgpu.pth"
    torch.save(trainer, path)
    
    

    Load:

    Model class must be defined somewhere

    model = torch.load(PATH)
    model.eval()
    

    String.Format not work in TypeScript

    You can declare it yourself quite easily:

    interface StringConstructor {
        format: (formatString: string, ...replacement: any[]) => string;
    }
    
    String.format('','');
    

    This is assuming that String.format is defined elsewhere. e.g. in Microsoft Ajax Toolkit : http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx

    insert data into database using servlet and jsp in eclipse

    Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.

    Use of ~ (tilde) in R programming Language

    The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

    The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


    Other common uses of formula objects in R

    The lattice package uses them to specify the variables to plot.
    The ggplot2 package uses them to specify panels for plotting.
    The dplyr package uses them for non-standard evaulation.

    What are NDF Files?

    Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

    Source: MSDN: Understanding Files and Filegroups

    The recommended file name extension for secondary data files is .ndf, but this is not enforced.

    How I can check whether a page is loaded completely or not in web driver?

    Here is how I would fix it, using a code snippet to give you a basic idea:

    public class IFrame1 extends LoadableComponent<IFrame1> {
    
        private RemoteWebDriver driver;
    
        @FindBy(id = "iFrame1TextFieldTestInputControlID" ) public WebElement iFrame1TextFieldInput;
        @FindBy(id = "iFrame1TextFieldTestProcessButtonID" ) public WebElement copyButton;
    
        public IFrame1( RemoteWebDriver drv ) {
            super();
            this.driver = drv;
            this.driver.switchTo().defaultContent();
            waitTimer(1, 1000);
            this.driver.switchTo().frame("BodyFrame1");
            LOGGER.info("IFrame1 constructor...");
        }
    
        @Override
        protected void isLoaded() throws Error {        
            LOGGER.info("IFrame1.isLoaded()...");
            PageFactory.initElements( driver, this );
            try {
                assertTrue( "Page visible title is not yet available.", 
                        driver.findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1")
                        .getText().equals("iFrame1 Test") );
            } catch ( NoSuchElementException e) {
                LOGGER.info("No such element." );
                assertTrue("No such element.", false);
            }
        }
    
        /**
         * Method: load
         * Overidden method from the LoadableComponent class.
         * @return  void
         * @throws  null
         */
        @Override
        protected void load() {
            LOGGER.info("IFrame1.load()...");
            Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
                    .withTimeout(30, TimeUnit.SECONDS)
                    .pollingEvery(5, TimeUnit.SECONDS)
                    .ignoring( NoSuchElementException.class ) 
                    .ignoring( StaleElementReferenceException.class ) ;
            wait.until( ExpectedConditions.presenceOfElementLocated( 
                    By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1") ) );
        }
    ....
    

    Export to csv/excel from kibana

    I totally missed the export button at the bottom of each visualization. As for read only access...Shield from Elasticsearch might be worth exploring.

    Java, return if trimmed String in List contains String

    String search = "A";
    for(String s : myList)
        if(s.contains(search)) return true;
    return false;
    

    This will iterate over each string in the list, and check if it contains the string you're looking for. If it's only spaces you want to trap for, you can do this:

    String search = "A";
    for(String s : myList)
        if(s.replaceAll(" ","").contains(search)) return true;
    return false;
    

    which will first replace spaces with empty strings before searching. Additionally, if you just want to trim the string first, you can do:

    String search = "A";
    for(String s : myList)
        if(s.trim().contains(search)) return true;
    return false;
    

    How to convert a .eps file to a high quality 1024x1024 .jpg?

    Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

    Row count where data exists

    lastrow = Sheet1.Range("A#").End(xlDown).Row
    

    This is more easy to determine the row count.
    Make sure you declare the right variable when it comes to larger rows.
    By the way the '#' sign must be a number where you want to start the row count.

    How to keep two folders automatically synchronized?

    Just simple modification of @silgon answer:

    while true; do 
      inotifywait -r -e modify,create,delete /directory
      rsync -avz /directory /target
    done
    

    (@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)

    Java, "Variable name" cannot be resolved to a variable

    public void setHoursWorked(){
        hoursWorked = hours;
    }
    

    You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.

    How can I center text (horizontally and vertically) inside a div block?

    This works for me (tested OK!):

    HTML:

    <div class="mydiv">
        <p>Item to be centered!</p>
    </div>
    

    CSS:

    .mydiv {
        height: 100%; /* Or other */
        position: relative;
    }
    
    .mydiv p {
        margin: 0;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-right: -50%;
        transform: translate(-50%, -50%); /* To compensate own width and height */
    }
    

    You can choose other values than 50%. For example, 25% to center at 25% of parent.

    How to sort a data frame by date

    Assuming your data frame is named d,

    d[order(as.Date(d$V3, format="%d/%m/%Y")),]
    

    Read my blog post, Sorting a data frame by the contents of a column, if that doesn't make sense.

    How to apply a function to two columns of Pandas dataframe

    There is a clean, one-line way of doing this in Pandas:

    df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)
    

    This allows f to be a user-defined function with multiple input values, and uses (safe) column names rather than (unsafe) numeric indices to access the columns.

    Example with data (based on original question):

    import pandas as pd
    
    df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})
    mylist = ['a', 'b', 'c', 'd', 'e', 'f']
    
    def get_sublist(sta,end):
        return mylist[sta:end+1]
    
    df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)
    

    Output of print(df):

      ID  col_1  col_2      col_3
    0  1      0      1     [a, b]
    1  2      2      4  [c, d, e]
    2  3      3      5  [d, e, f]
    

    If your column names contain spaces or share a name with an existing dataframe attribute, you can index with square brackets:

    df['col_3'] = df.apply(lambda x: f(x['col 1'], x['col 2']), axis=1)
    

    C++ array initialization

    Note that the '=' is optional in C++11 universal initialization syntax, and it is generally considered better style to write :

    char myarray[ARRAY_SIZE] {0}
    

    Java Process with Input/Output Stream

    You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

    Are nested try/except blocks in Python a good programming practice?

    A good and simple example for nested try/except could be the following:

    import numpy as np
    
    def divide(x, y):
        try:
            out = x/y
        except:
            try:
                out = np.inf * x / abs(x)
            except:
                out = np.nan
        finally:
            return out
    
    

    Now try various combinations and you will get the correct result:

    divide(15, 3)
    # 5.0
    
    divide(15, 0)
    # inf
    
    divide(-15, 0)
    # -inf
    
    divide(0, 0)
    # nan
    
    

    (Of course, we have NumPy, so we don't need to create this function.)

    How to generate components in a specific folder with Angular CLI?

    ng g c component-name

    For specify custom location: ng g c specific-folder/component-name

    here component-name will be created inside specific-folder.

    Similarl approach can be used for generating other components like directive, pipe, service, class, guard, interface, enum, module, etc.

    Calling a rest api with username and password - how to

    You can also use the RestSharp library for example

    var userName = "myuser";
    var password = "mypassword";
    var host = "170.170.170.170:333";
    var client = new RestClient("https://" + host + "/method1");            
    client.Authenticator = new HttpBasicAuthenticator(userName, password);            
    var request = new RestRequest(Method.POST); 
    request.AddHeader("Accept", "application/json");
    request.AddHeader("Cache-Control", "no-cache");
    request.AddHeader("Content-Type", "application/json");            
    request.AddParameter("application/json","{}",ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
    

    cannot redeclare block scoped variable (typescript)

    In my case (using IntelliJ) File - Invalidate Caches / Restart... did the trick.

    Unnamed/anonymous namespaces vs. static functions

    From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.

    But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it might be doing when it accepts it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.

    Append TimeStamp to a File Name

    you can use:

    Stopwatch.GetTimestamp();
    

    pip broke. how to fix DistributionNotFound error?

    I was facing the similar problem in OSx. My stacktrace was saying

    raise DistributionNotFound(req)
    pkg_resources.DistributionNotFound: setuptools>=11.3
    

    Then I did the following

    sudo pip install --upgrade setuptools
    

    This solved the problem for me. Hope someone will find this useful.

    How to check whether a string is Base64 encoded or not

    If you are using Java, you can actually use commons-codec library

    import org.apache.commons.codec.binary.Base64;
    
    String stringToBeChecked = "...";
    boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());
    

    [UPDATE 1] Deprecation Notice Use instead

    Base64.isBase64(value);

       /**
         * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
         * method treats whitespace as valid.
         *
         * @param arrayOctet
         *            byte array to test
         * @return {@code true} if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
         *         {@code false}, otherwise
         * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
         */
        @Deprecated
        public static boolean isArrayByteBase64(final byte[] arrayOctet) {
            return isBase64(arrayOctet);
        }
    

    jQuery - on change input text

    This technique is working for me:

    $('#myInputFieldId').bind('input',function(){ 
                   alert("Hello");
        });
    

    Note that according to this JQuery doc, "on" is recommended rather than bind in newer versions.

    How eliminate the tab space in the column in SQL Server 2008

    Use the Below Code for that

    UPDATE Table1 SET Column1 = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column1, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))`
    

    How to check if a subclass is an instance of a class at runtime?

    Maybe I'm missing something, but wouldn't this suffice:

    if (view instanceof B) {
        // this view is an instance of B
    }
    

    Replace console output in Python

    I wrote this a while ago and really happy with it. Feel free to use it.

    It takes an index and total and optionally title or bar_length. Once done, replaces the hour glass with a check-mark.

    ? Calculating: [¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦] 18.0% done

    ? Calculating: [¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦] 100.0% done

    I included an example that can be run to test it.

    import sys
    import time
    
    def print_percent_done(index, total, bar_len=50, title='Please wait'):
        '''
        index is expected to be 0 based index. 
        0 <= index < total
        '''
        percent_done = (index+1)/total*100
        percent_done = round(percent_done, 1)
    
        done = round(percent_done/(100/bar_len))
        togo = bar_len-done
    
        done_str = '¦'*int(done)
        togo_str = '¦'*int(togo)
    
        print(f'\t?{title}: [{done_str}{togo_str}] {percent_done}% done', end='\r')
    
        if round(percent_done) == 100:
            print('\t?')
    
    
    r = 50
    for i in range(r):
        print_percent_done(i,r)
        time.sleep(.02)
    

    I also have a version with responsive progress bar depending on the terminal width using shutil.get_terminal_size() if that is of interest.

    List of swagger UI alternatives

    Yes, there are a few of them.

    Hosted solutions that support swagger:

    Check the following articles for more details:

    Get most recent file in a directory on Linux

    Shorted variant based on dmckee's answer:

    ls -t | head -1
    

    FIX CSS <!--[if lt IE 8]> in IE

        <!--[if IE]>
        <style type='text/css'>
        #header ul#h-menu li a{font-weight:normal!important}
        </style>
        <![endif]-->
    

    will apply that style in all versions of IE.

    How do I call an Angular.js filter with multiple arguments?

    In templates, you can separate filter arguments by colons.

    {{ yourExpression | yourFilter: arg1:arg2:... }}
    

    From Javascript, you call it as

    $filter('yourFilter')(yourExpression, arg1, arg2, ...)
    

    There is actually an example hidden in the orderBy filter docs.


    Example:

    Let's say you make a filter that can replace things with regular expressions:

    myApp.filter("regexReplace", function() { // register new filter
    
      return function(input, searchRegex, replaceRegex) { // filter arguments
    
        return input.replace(RegExp(searchRegex), replaceRegex); // implementation
    
      };
    });
    

    Invocation in a template to censor out all digits:

    <p>{{ myText | regexReplace: '[0-9]':'X' }}</p>
    

    How do I append to a table in Lua

    I'd personally make use of the table.insert function:

    table.insert(a,"b");
    

    This saves you from having to iterate over the whole table therefore saving valuable resources such as memory and time.

    Getting "Cannot call a class as a function" in my React Project

    Looks like there're no single case when this error appears.

    Happened to me when I didn't declare constructor in statefull component.

    class MyComponent extends Component {
    
        render() {
            return <div>Test</div>;
        }
    }
    

    instead of

    class MyComponent extends Component {
    
        constructor(props) {
            super(props);
        }
    
        render() {
            return <div>Test</div>;
        }
    }
    

    Cannot run emulator in Android Studio

    In my case (Windows 10) the reason was that I dared to unzip the android sdk into non default folder. When I moved it to the default one c:/Users/[username]/AppData/Local/Android/Sdk and changed the paths in Android Studio and System Variables, it started to work.

    How to check a string against null in java?

    There are two ways to do it..Say String==null or string.equals()..

    public class IfElse {
    
        public int ifElseTesting(String a){
            //return null;
            return (a== null)? 0: a.length();
        }
    
    }
    
    public class ShortCutifElseTesting {
    
        public static void main(String[] args) {
    
            Scanner scanner=new Scanner(System.in);
            System.out.println("enter the string please:");
            String a=scanner.nextLine();
            /*
            if (a.equals(null)){
                System.out.println("you are not correct");
            }
            else if(a.equals("bangladesh")){
                System.out.println("you are right");
            }
            else
                System.out.println("succesful tested");
    
            */
            IfElse ie=new IfElse();
            int result=ie.ifElseTesting(a);
            System.out.println(result);
    
        }
    
    }
    

    Check this example..Here is an another example of shortcut version of If Else..

    Load image from resources

    You can do this using the ResourceManager:

    public bool info(string channel)
    {
       object o = Properties.Resources.ResourceManager.GetObject(channel);
       if (o is Image)
       {
           channelPic.Image = o as Image;
           return true;
       }
       return false;
    }
    

    Where to put Gradle configuration (i.e. credentials) that should not be committed?

    If you have user specific credentials ( i.e each developer might have different username/password ) then I would recommend using the gradle-properties-plugin.

    1. Put defaults in gradle.properties
    2. Each developer overrides with gradle-local.properties ( this should be git ignored ).

    This is better than overriding using $USER_HOME/.gradle/gradle.properties because different projects might have same property names.

    inverting image in Python with OpenCV

    Alternatively, you could invert the image using the bitwise_not function of OpenCV:

    imagem = cv2.bitwise_not(imagem)
    

    I liked this example.

    How to find EOF through fscanf?

    fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

    So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

    You should check for EOF when you call fscanf, not check the array slot for EOF.

    How do you discover model attributes in Rails?

    For Schema related stuff

    Model.column_names         
    Model.columns_hash         
    Model.columns 
    

    For instance variables/attributes in an AR object

    object.attribute_names                    
    object.attribute_present?          
    object.attributes
    

    For instance methods without inheritance from super class

    Model.instance_methods(false)
    

    Validate email with a regex in jQuery

    function mailValidation(val) {
        var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    
        if (!expr.test(val)) {
            $('#errEmail').text('Please enter valid email.');
        }
        else {
            $('#errEmail').hide();
        }
    }
    

    How to insert the current timestamp into MySQL database using a PHP insert query

    Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

    You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

    $update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";
    

    How can I make a float top with CSS?

    This works for me:

    margin-bottom: auto;
    

    A formula to copy the values from a formula to another column

    You can use =A4, in case A4 is having long formula

    Use :hover to modify the css of another class?

    It's not possible in CSS at the moment, unless you want to select a child or sibling element (trivial and described in other answers here).

    For all other cases you'll need JavaScript. jQuery and frameworks like Angular can tackle this problem with relative ease.

    [Edit]

    With the new CSS (4) selector :has(), you'll be able to target parent elements/classes, making a CSS-Only solution viable in the near future!

    How to find NSDocumentDirectory in Swift?

    More convenient Swift 3 method:

    let documentsUrl = FileManager.default.urls(for: .documentDirectory, 
                                                 in: .userDomainMask).first!
    

    Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

    there might be a problem at your web hosting company from where you are testing the secure communication for gateway, that they might not allow you to do that.

    also there might be a username, password that must be provided before connecting to remote host.

    or your IP might need to be in the list of approved IP for the remote server for communication to initiate.

    How to tell which commit a tag points to in Git?

    Even though this is pretty old, I thought I would point out a cool feature I just found for listing tags with commits:

    git log --decorate=full
    

    It will show the branches which end/start at a commit, and the tags for commits.

    Change URL parameters

    Here is a simple solution using the query-string library.

    const qs = require('query-string')
    function addQuery(key, value) {
      const q = qs.parse(location.search)
      const url = qs.stringifyUrl(
        {
          url: location.pathname,
          query: {
          ...q,
          [key]: value,
          },
        },
        { skipEmptyString: true }
      );
      window.location.href = url
      // if you are using Turbolinks
      // add this: Turbolinks.visit(url)
    }
    // Usage
    addQuery('page', 2)
    

    If you are using react without react-router

    export function useAddQuery() {
      const location = window.location;
      const addQuery = useCallback(
        (key, value) => {
          const q = qs.parse(location.search);
          const url = qs.stringifyUrl(
            {
              url: location.pathname,
              query: {
                ...q,
                [key]: value,
              },
            },
            { skipEmptyString: true }
          );
          window.location.href = url
        },
        [location]
      );
    
      return { addQuery };
    }
    // Usage
    const { addQuery } = useAddQuery()
    addQuery('page', 2)
    

    If you are using react with react-router

    export function useAddQuery() {
      const location = useLocation();
      const history = useHistory();
    
      const addQuery = useCallback(
        (key, value) => {
          let pathname = location.pathname;
          let searchParams = new URLSearchParams(location.search);
          searchParams.set(key, value);
          history.push({
            pathname: pathname,
            search: searchParams.toString()
          });
        },
        [location, history]
      );
    
      return { addQuery };
    }
    
    // Usage
    const { addQuery } = useAddQuery()
    addQuery('page', 2)
    

    PS: qs is the import from query-string module.

    MIPS: Integer Multiplication and Division

    To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

    The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

    E.g.:

    li $a0, 5
    li $a1, 3
    mult $a0, $a1
    mfhi $a2 # 32 most significant bits of multiplication to $a2
    mflo $v0 # 32 least significant bits of multiplication to $v0
    

    To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

    E.g.:

    div $a0, $a1
    mfhi $a2 # remainder to $a2
    mflo $v0 # quotient to $v0
    

    How do you append to a file?

    You need to open the file in append mode, by setting "a" or "ab" as the mode. See open().

    When you open with "a" mode, the write position will always be at the end of the file (an append). You can open with "a+" to allow reading, seek backwards and read (but all writes will still be at the end of the file!).

    Example:

    >>> with open('test1','wb') as f:
            f.write('test')
    >>> with open('test1','ab') as f:
            f.write('koko')
    >>> with open('test1','rb') as f:
            f.read()
    'testkoko'
    

    Note: Using 'a' is not the same as opening with 'w' and seeking to the end of the file - consider what might happen if another program opened the file and started writing between the seek and the write. On some operating systems, opening the file with 'a' guarantees that all your following writes will be appended atomically to the end of the file (even as the file grows by other writes).


    A few more details about how the "a" mode operates (tested on Linux only). Even if you seek back, every write will append to the end of the file:

    >>> f = open('test','a+') # Not using 'with' just to simplify the example REPL session
    >>> f.write('hi')
    >>> f.seek(0)
    >>> f.read()
    'hi'
    >>> f.seek(0)
    >>> f.write('bye') # Will still append despite the seek(0)!
    >>> f.seek(0)
    >>> f.read()
    'hibye'
    

    In fact, the fopen manpage states:

    Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded the call:

    fseek(stream, 0, SEEK_END);
    

    Old simplified answer (not using with):

    Example: (in a real program use with to close the file - see the documentation)

    >>> open("test","wb").write("test")
    >>> open("test","a+b").write("koko")
    >>> open("test","rb").read()
    'testkoko'
    

    invalid conversion from 'const char*' to 'char*'

    string::c.str() returns a string of type const char * as seen here

    A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str());

    While the above may work, it is undefined behaviour, and unsafe.

    Here's a nicer solution using templates:

    char * my_argument = const_cast<char*> ( ...c_str() );
    

    Play sound file in a web-page in the background

    Though this might be too late to comment but here's the working code for problems such as yours.

    <div id="player">
        <audio autoplay hidden>
         <source src="link/to/file/file.mp3" type="audio/mpeg">
                    If you're reading this, audio isn't supported. 
        </audio>
    </div>
    

    Configuring user and password with Git Bash

    If you are a Mac user and have keychain enabled, you to need to remove the authorization information that is stored in the keychain:

    - Open up Keychain access
    - Click "All items" under category in the left-hand column
    - Search for git
    - Delete all git entries.
    

    Then you should change your username and email from the terminal using git config:

    $ git config --global user.name "Bob"
    
    $ git config --global user.email "[email protected]"
    

    Now if you try to push to the repository you will be asked for a username and password. Enter the login credentials you are trying to switch to. This problem normally pops up if you signed into GitHub on a browser using a different username and password or previously switched accounts on your terminal.

    Left-pad printf with spaces

    I use this function to indent my output (for example to print a tree structure). The indent is the number of spaces before the string.

    void print_with_indent(int indent, char * string)
    {
        printf("%*s%s", indent, "", string);
    }
    

    Docker compose, running containers in net:host

    Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode when using the v2 YAML format.

    How can I clear the input text after clicking

    I would recommend to use this since I have the same issue which got fixed.

    $('input:text').focus(
        function(){
            $(this).val('');
        });
    

    Arduino error: does not name a type?

    Don't know it this is your problem but it was mine.

    Void setup() does not name a type

    BUT

    void setup() is ok.

    I found that the sketch I copied for another project was full of 'wrong case' letters. Onc efixed, it ran smoothly.emphasized text

    How can I convert a PFX certificate file for use with Apache on a linux server?

    Took some tooling around but this is what I ended up with.

    Generated and installed a certificate on IIS7. Exported as PFX from IIS

    Convert to pkcs12

    openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
    

    NOTE: While converting PFX to PEM format, openssl will put all the Certificates and Private Key into a single file. You will need to open the file in Text editor and copy each Certificate & Private key(including the BEGIN/END statements) to its own individual text file and save them as certificate.cer, CAcert.cer, privateKey.key respectively.

    -----BEGIN PRIVATE KEY-----
    Saved as certificate.key
    -----END PRIVATE KEY-----
    
    -----BEGIN CERTIFICATE-----
    Saved as certificate.crt
    -----END CERTIFICATE-----
    

    Added to apache vhost w/ Webmin.

    Copying an array of objects into another array in javascript

    The key things here are

    1. The entries in the array are objects, and
    2. You don't want modifications to an object in one array to show up in the other array.

    That means we need to not just copy the objects to a new array (or a target array), but also create copies of the objects.

    If the destination array doesn't exist yet...

    ...use map to create a new array, and copy the objects as you go:

    const newArray = sourceArray.map(obj => /*...create and return copy of `obj`...*/);
    

    ...where the copy operation is whatever way you prefer to copy objects, which varies tremendously project to project based on use case. That topic is covered in depth in the answers to this question. But for instance, if you only want to copy the objects but not any objects their properties refer to, you could use spread notation (ES2015+):

    const newArray = sourceArray.map(obj => ({...obj}));
    

    That does a shallow copy of each object (and of the array). Again, for deep copies, see the answers to the question linked above.

    Here's an example using a naive form of deep copy that doesn't try to handle edge cases, see that linked question for edge cases:

    _x000D_
    _x000D_
    function naiveDeepCopy(obj) {
        const newObj = {};
        for (const key of Object.getOwnPropertyNames(obj)) {
            const value = obj[key];
            if (value && typeof value === "object") {
                newObj[key] = {...value};
            } else {
                newObj[key] = value;
            }
        }
        return newObj;
    }
    const sourceArray = [
        {
            name: "joe",
            address: {
                line1: "1 Manor Road",
                line2: "Somewhere",
                city: "St Louis",
                state: "Missouri",
                country: "USA",
            },
        },
        {
            name: "mohammed",
            address: {
                line1: "1 Kings Road",
                city: "London",
                country: "UK",
            },
        },
        {
            name: "shu-yo",
        },
    ];
    const newArray = sourceArray.map(naiveDeepCopy);
    // Modify the first one and its sub-object
    newArray[0].name = newArray[0].name.toLocaleUpperCase();
    newArray[0].address.country = "United States of America";
    console.log("Original:", sourceArray);
    console.log("Copy:", newArray);
    _x000D_
    .as-console-wrapper {
        max-height: 100% !important;
    }
    _x000D_
    _x000D_
    _x000D_

    If the destination array exists...

    ...and you want to append the contents of the source array to it, you can use push and a loop:

    for (const obj of sourceArray) {
        destinationArray.push(copy(obj));
    }
    

    Sometimes people really want a "one liner," even if there's no particular reason for it. If you refer that, you could create a new array and then use spread notation to expand it into a single push call:

    destinationArray.push(...sourceArray.map(obj => copy(obj)));
    

    How to set base url for rest in spring boot?

    Since this is the first google hit for the problem and I assume more people will search for this. There is a new option since Spring Boot '1.4.0'. It is now possible to define a custom RequestMappingHandlerMapping that allows to define a different path for classes annotated with @RestController

    A different version with custom annotations that combines @RestController with @RequestMapping can be found at this blog post

    @Configuration
    public class WebConfig {
    
        @Bean
        public WebMvcRegistrationsAdapter webMvcRegistrationsHandlerMapping() {
            return new WebMvcRegistrationsAdapter() {
                @Override
                public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                    return new RequestMappingHandlerMapping() {
                        private final static String API_BASE_PATH = "api";
    
                        @Override
                        protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
                            Class<?> beanType = method.getDeclaringClass();
                            if (AnnotationUtils.findAnnotation(beanType, RestController.class) != null) {
                                PatternsRequestCondition apiPattern = new PatternsRequestCondition(API_BASE_PATH)
                                        .combine(mapping.getPatternsCondition());
    
                                mapping = new RequestMappingInfo(mapping.getName(), apiPattern,
                                        mapping.getMethodsCondition(), mapping.getParamsCondition(),
                                        mapping.getHeadersCondition(), mapping.getConsumesCondition(),
                                        mapping.getProducesCondition(), mapping.getCustomCondition());
                            }
    
                            super.registerHandlerMethod(handler, method, mapping);
                        }
                    };
                }
            };
        }
    }
    

    PowerShell - Start-Process and Cmdline Switches

    I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)

    cmd /C "$msbuild $args" >> $outputfile

    Android TabLayout Android Design

    I've just managed to setup new TabLayout, so here are the quick steps to do this (????)?*:???

    1. Add dependencies inside your build.gradle file:

      dependencies {
          compile 'com.android.support:design:23.1.1'
      }
      
    2. Add TabLayout inside your layout

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
      
          <android.support.v7.widget.Toolbar
              android:id="@+id/toolbar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="?attr/colorPrimary"/>
      
          <android.support.design.widget.TabLayout
              android:id="@+id/tab_layout"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>
      
          <android.support.v4.view.ViewPager
              android:id="@+id/pager"
              android:layout_width="match_parent"
              android:layout_height="match_parent"/>
      
      </LinearLayout>
      
    3. Setup your Activity like this:

      import android.os.Bundle;
      import android.support.design.widget.TabLayout;
      import android.support.v4.app.Fragment;
      import android.support.v4.app.FragmentManager;
      import android.support.v4.app.FragmentPagerAdapter;
      import android.support.v4.view.ViewPager;
      import android.support.v7.app.AppCompatActivity;
      import android.support.v7.widget.Toolbar;
      
      public class TabLayoutActivity extends AppCompatActivity {
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_pull_to_refresh);
      
              Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
              TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
              ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
      
              if (toolbar != null) {
                  setSupportActionBar(toolbar);
              }
      
              viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
              tabLayout.setupWithViewPager(viewPager);
          }
      
          public class SectionPagerAdapter extends FragmentPagerAdapter {
      
              public SectionPagerAdapter(FragmentManager fm) {
                  super(fm);
              }
      
              @Override
              public Fragment getItem(int position) {
                  switch (position) {
                      case 0:
                          return new FirstTabFragment();
                      case 1:
                      default:
                          return new SecondTabFragment();
                  }
              }
      
              @Override
              public int getCount() {
                  return 2;
              }
      
              @Override
              public CharSequence getPageTitle(int position) {
                  switch (position) {
                      case 0:
                          return "First Tab";
                      case 1:
                      default:
                          return "Second Tab";
                  }
              }
          }
      
      }
      

    How to Apply Gradient to background view of iOS Swift App

    if you want to use HEX instead of RGBA, just drag a new empty .swift and add below mentioned code:

         import UIKit
    
        extension UIColor {
            convenience init(rgba: String) {
                var red:   CGFloat = 0.0
                var green: CGFloat = 0.0
                var blue:  CGFloat = 0.0
                var alpha: CGFloat = 1.0
    
                if rgba.hasPrefix("#") {
                    let index   = advance(rgba.startIndex, 1)
                    let hex     = rgba.substringFromIndex(index)
                    let scanner = NSScanner(string: hex)
                    var hexValue: CUnsignedLongLong = 0
                    if scanner.scanHexLongLong(&hexValue) {
                        switch (count(hex)) {
                        case 3:
                            red   = CGFloat((hexValue & 0xF00) >> 8)       / 15.0
                            green = CGFloat((hexValue & 0x0F0) >> 4)       / 15.0
                            blue  = CGFloat(hexValue & 0x00F)              / 15.0
                        case 4:
                            red   = CGFloat((hexValue & 0xF000) >> 12)     / 15.0
                            green = CGFloat((hexValue & 0x0F00) >> 8)      / 15.0
                            blue  = CGFloat((hexValue & 0x00F0) >> 4)      / 15.0
                            alpha = CGFloat(hexValue & 0x000F)             / 15.0
                        case 6:
                            red   = CGFloat((hexValue & 0xFF0000) >> 16)   / 255.0
                            green = CGFloat((hexValue & 0x00FF00) >> 8)    / 255.0
                            blue  = CGFloat(hexValue & 0x0000FF)           / 255.0
                        case 8:
                            red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
                            green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                            blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
                            alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
                        default:
                            print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
                        }
                    } else {
                        println("Scan hex error")
                    }
                } else {
                    print("Invalid RGB string, missing '#' as prefix")
                }
                self.init(red:red, green:green, blue:blue, alpha:alpha)
            }
    }
    

    similarly, drag another empty .swift file and add below mentioned code:

        class Colors {
        let colorTop = UIColor(rgba: "##8968CD").CGColor
        let colorBottom = UIColor(rgba: "#5D478B").CGColor
    
        let gl: CAGradientLayer
    
        init() {
            gl = CAGradientLayer()
            gl.colors = [ colorTop, colorBottom]
            gl.locations = [ 0.0, 1.0]
        }
    }
    

    after that in view controller, under class instantiate your 'Color' class like this:

    let colors = Colors()
    

    add a new function:

    func refresh() {
            view.backgroundColor = UIColor.clearColor()
            var backgroundLayer = colors.gl
            backgroundLayer.frame = view.frame
            view.layer.insertSublayer(backgroundLayer, atIndex: 0)
        }
    

    state that function in viewDidLoad:

    refresh()
    

    you're done :)) using HEX is way too easy if compared to RGBA. :D

    Fatal error: Call to a member function bind_param() on boolean

    You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.

    The name 'InitializeComponent' does not exist in the current context

    For those who find this on the internet. Check the Windows.csproj file if the compilation is there. There should be 2 entries

    <Page Include="YourFile.xaml">
      <SubType>Designer</SubType>
      <Generator>MSBuild:Compile</Generator>
    </Page>
    
    <Compile Include="YourFile.xaml.cs">
      <DependentUpon>YourFile.xaml</DependentUpon>
    </Compile>
    

    Intellij reformat on file save

    If you're developing in Flutter, there's a new experimental option as of 5/1/2018 that allows you to format code on save. Settings

    How do you do relative time in Rails?

    What about

    30.seconds.ago
    2.days.ago
    

    Or something else you were shooting for?

    sql delete statement where date is greater than 30 days

    Although the DATEADD is probably the most transparrent way of doing this, it is worth noting that simply getdate()-30 will also suffice.

    Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:

    SELECT * 
    FROM Results 
    WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)
    

    How to get time (hour, minute, second) in Swift 3 using NSDate?

    In Swift 3.0 Apple removed 'NS' prefix and made everything simple. Below is the way to get hour, minute and second from 'Date' class (NSDate alternate)

    let date = Date()
    let calendar = Calendar.current
    
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)
    print("hours = \(hour):\(minutes):\(seconds)")
    

    Like these you can get era, year, month, date etc. by passing corresponding.

    How to set enum to null

    If this is C#, it won't work: enums are value types, and can't be null.

    The normal options are to add a None member:

    public enum Color
    {
      None,
      Red,
      Green,
      Yellow
    }
    
    Color color = Color.None;
    

    ...or to use Nullable:

    Color? color = null;
    

    Encrypt and decrypt a password in Java

    Here is the algorithm I use to crypt with MD5.It returns your crypted output.

       public class CryptWithMD5 {
       private static MessageDigest md;
    
       public static String cryptWithMD5(String pass){
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] passBytes = pass.getBytes();
            md.reset();
            byte[] digested = md.digest(passBytes);
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<digested.length;i++){
                sb.append(Integer.toHexString(0xff & digested[i]));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CryptWithMD5.class.getName()).log(Level.SEVERE, null, ex);
        }
            return null;
    
    
       }
    }
    

    You cannot decrypt MD5, but you can compare outputs since if you put the same string in this method it will have the same crypted output.If you want to decrypt you need to use the SHA.You will never use decription for a users password.For that always use MD5.That exception is pretty redundant.It will never throw it.

    Text vertical alignment in WPF TextBlock

    The TextBlock doesn't support vertical text alignment.

    I work around this by wrapping the text block with a Grid and setting HorizontalAlignment="Stretch" and VerticalAlignment="Center".

    Like this:

    <Grid>
        <TextBlock 
            HorizontalAlignment="Stretch"
            VerticalAlignment="Center"
            Text="Your text" />
    </Grid>
    

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

    I ran into this recently and eventually found that this was caused by a network timeout from the endpoint we were hitting. Fortunately for us we were able to increase the timeout duration.

    To verify this was our issue (and actually not an issue with net http), I made the same request with curl and confirmed that the request was being terminated.

    How to kill all processes with a given partial name?

    Found the best way to do it for a server which does not support pkill

    kill -9 $(ps ax | grep My_pattern| fgrep -v grep | awk '{ print $1 }')
    

    You do not have to loop.

    How to remove "index.php" in codeigniter's path

    Step 1 :

    Add this in htaccess file

    <IfModule mod_rewrite.c> 
    RewriteEngine On 
    #RewriteBase / 
    
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^ index.php [QSA,L] 
    </IfModule>
    

    Step 2 :

    Remove index.php in codeigniter config

    $config['base_url'] = ''; 
    $config['index_page'] = '';
    

    Step 3 :

    Allow overriding htaccess in Apache Configuration (Command)

    sudo nano /etc/apache2/apache2.conf and edit the file & change to

    AllowOverride All
    

    for www folder

    Step 4 :

    Enabled apache mod rewrite (Command)

    sudo a2enmod rewrite

    Step 5 :

    Restart Apache (Command)

    sudo /etc/init.d/apache2 restart
    

    How to display a jpg file in Python?

    Don't forget to include

    import Image
    

    In order to show it use this :

    Image.open('pathToFile').show()
    

    Comparing Dates in Oracle SQL

    Conclusion,

    to_char works in its own way

    So,

    Always use this format YYYY-MM-DD for comparison instead of MM-DD-YY or DD-MM-YYYY or any other format

    Add border-bottom to table row <tr>

    I found when using this method that the space between the td elements caused a gap to form in the border, but have no fear...

    One way around this:

    <tr>
        <td>
            Example of normal table data
        </td>
    
        <td class="end" colspan="/* total number of columns in entire table*/">
            /* insert nothing in here */ 
        </td>
    </tr>
    

    With the CSS:

    td.end{
        border:2px solid black;
    }
    

    How to fill in proxy information in cntlm config file?

    Once you generated the file, and changed your password, you can run as below,

    cntlm -H
    

    Username will be the same. it will ask for password, give it, then copy the PassNTLMv2, edit the cntlm.ini, then just run the following

    cntlm -v
    

    Send File Attachment from Form Using phpMailer and PHP

    Try:

    if (isset($_FILES['uploaded_file']) &&
        $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
        $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                             $_FILES['uploaded_file']['name']);
    }
    

    Basic example can also be found here.

    The function definition for AddAttachment is:

    public function AddAttachment($path,
                                  $name = '',
                                  $encoding = 'base64',
                                  $type = 'application/octet-stream')
    

    Function is not defined - uncaught referenceerror

    How about removing the onclick attribute and adding an ID:

    <input type="image" src="btn.png" alt="" id="img-clck" />
    

    And your script:

    $(document).ready(function(){
        function codeAddress() {
            var address = document.getElementById("formatedAddress").value;
            geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                }
            });
        }
        $("#img-clck").click(codeAddress);
    });
    

    This way if you need to change the function name or whatever no need to touch the html.

    Copying text outside of Vim with set mouse=a enabled

    Compilation settings that vim was compiled with, are part of the issue. vim --version shows these.

    In OSX, the default vim has -clipboard But you need +clipboard

    On osx you can and apparently generally should, use macvim. You can do brew cask install macvim That one has +clipboard.

    Them you'll have two vims.

    ~$ ls -l /usr/bin/vim   <--- default vim
    -rwxr-xr-x  1 root  wheel  1745984 15 Jul  2017 /usr/bin/vim
    
    ~$ ls -l /usr/local/bin/vim   <-- macvim, installed recently via that mentioned brew line. 
    lrwxr-xr-x  1 apple  admin  42 16 May 23:32 /usr/local/bin/vim -> /Applications/MacVim.app/Contents/bin/mvim
    ~$ 
    

    running vim will run macvim 'cos /usr/local/bin should be before /usr/bin in the path, though you can check with which vim.

    running vim(to run macvim), is fine but you may want to map vi to macvim 'cos otherwise running vi stays at the default vim! You can rewrite or delete(with rm) and recreate the vi sym link, with ln. And to do that without an 'operation not permitted" error, you have to (temporarily) disable SIL. https://apple.stackexchange.com/questions/208478/how-do-i-disable-system-integrity-protection-sip-aka-rootless-on-macos-os-x .

    macvim has +clipboard as shown by vim --version

    Here is a working ~/.vim/vimrc with just the required lines.

    :set mouse=a
    :map <leader>c "+y
    :map <leader>v "+p
    

    The default leader key is backslash.

    I read a suggestion that one should use the leader key.. (certainly control has many keys already in use, so the suggestion was to not use control. I don't know if that applies to command key too, but anyhow).

    With that mentioned mapping, \c will do "+y which will copy from the register known as +, to the clipboard. And \v will paste from the register known as +.

    So that's a copy/paste that works between windows.

    Another OS may require "* rather than "+

    PHP Get Site URL Protocol - http vs https

    Because testing port number is not a good practice according to me, my solution is:

    define('HTTPS', isset($_SERVER['HTTPS']) && filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN));
    

    The HTTPSconstant returns TRUE if $_SERVER['HTTPS'] is set and equals to "1", "true", "on" or "yes". Returns FALSE otherwise.

    Posting array from form

    If you want everything in your post to be as $Variables you can use something like this:

    foreach($_POST as $key => $value) { eval("$" . $key . " = " . $value"); }

    Should you always favor xrange() over range()?

    • range(): range(1, 10) returns a list from 1 to 10 numbers & hold whole list in memory.
    • xrange(): Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is lightly faster than range() and more memory efficient. xrange() object like an iterator and generates the numbers on demand (Lazy Evaluation).
    In [1]: range(1,10)
    Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    In [2]: xrange(10)
    Out[2]: xrange(10)
    
    In [3]: print xrange.__doc__
    Out[3]: xrange([start,] stop[, step]) -> xrange object
    

    range() does the same thing as xrange() used to do in Python 3 and there is not term xrange() exist in Python 3. range() can actually be faster in some scenario if you iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects.

    WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

    I had a similar situation, but the client config was using a basicHttpBinding. The issue turned out to be that the service was using SOAP 1.2 and you can't specify SOAP 1.2 in a basicHttpBinding. I modified the client config to use a customBinding instead and everything worked. Here are the details of my customBinding for reference. The service I was trying to consume was over HTTPS using UserNameOverTransport.

    <customBinding>
        <binding name="myBindingNameHere" sendTimeout="00:03:00">
            <security authenticationMode="UserNameOverTransport" includeTimestamp="false">
                <secureConversationBootstrap />
            </security>
            <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
                  messageVersion="Soap12" writeEncoding="utf-8">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
            </textMessageEncoding>
            <httpsTransport manualAddressing="false" maxBufferPoolSize="4194304"
                  maxReceivedMessageSize="4194304" allowCookies="false" authenticationScheme="Basic"
                  bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                  keepAliveEnabled="true" maxBufferSize="4194304" proxyAuthenticationScheme="Anonymous"
                  realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
                  useDefaultWebProxy="true" requireClientCertificate="false" />
        </binding>
    </customBinding>
    

    Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

    If you have two lists that have the predicted and actual values; as it appears you do, you can pass them to a function that will calculate TP, FP, TN, FN with something like this:

    def perf_measure(y_actual, y_hat):
        TP = 0
        FP = 0
        TN = 0
        FN = 0
    
        for i in range(len(y_hat)): 
            if y_actual[i]==y_hat[i]==1:
               TP += 1
            if y_hat[i]==1 and y_actual[i]!=y_hat[i]:
               FP += 1
            if y_actual[i]==y_hat[i]==0:
               TN += 1
            if y_hat[i]==0 and y_actual[i]!=y_hat[i]:
               FN += 1
    
        return(TP, FP, TN, FN)
    

    From here I think you will be able to calculate rates of interest to you, and other performance measure like specificity and sensitivity.

    Javascript to display the current date and time

    Try this:

    var d = new Date(),
        minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
        hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
        ampm = d.getHours() >= 12 ? 'pm' : 'am',
        months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
        days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
    return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
    

    DEMO