Programs & Examples On #Shoes

Shoes is a cross-platform toolkit for writing graphical apps easily and artfully using Ruby. Unlike most other GUI toolkits, Shoes is designed to be easy and straightforward without losing power.

could not extract ResultSet in hibernate

I faced the same problem after migrating a database from online server to localhost. The schema changed so I had to define the schema manually for each table:

@Entity
@Table(name = "ESBCORE_DOMAIN", schema = "SYS")

Check if the number is integer

In R, whether a number is numeric or integer can be determined by class function. Generally all numbers are stored as numeric and to explicitly define a number as integer we need to specify 'L' after the number.

Example:

x <- 1

class(x)

[1] "numeric"

x <- 1L

class(x)

[1] "integer"

I hope this is what was needed. Thanks :)

IsNull function in DB2 SQL?

In DB2 there is a function NVL(field, value if null).

Example:

SELECT ID, NVL(NAME, "Internal) AS NAME, NVL(PRICE,0) AS PRICE FROM PRODUCT WITH UR;

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Like thousands of people, I'm looking for this question:
Can run multiple queries simultaneously, and if there was one error, none would run I went to this page everywhere
But although the friends here gave good answers, these answers were not good for my problem
So I wrote a function that works well and has almost no problem with sql Injection.
It might be helpful for those who are looking for similar questions so I put them here to use

function arrayOfQuerys($arrayQuery)
{
    $mx = true;
    $conn->beginTransaction();
    try {
        foreach ($arrayQuery AS $item) {
            $stmt = $conn->prepare($item["query"]);
            $stmt->execute($item["params"]);
            $result = $stmt->rowCount();
            if($result == 0)
                $mx = false;
         }
         if($mx == true)
             $conn->commit();
         else
             $conn->rollBack();
    } catch (Exception $e) {
        $conn->rollBack();
        echo "Failed: " . $e->getMessage();
    }
    return $mx;
}

for use(example):

 $arrayQuery = Array(
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("aa1", 1)
    ),
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("bb1", 2)
    )
);
arrayOfQuerys($arrayQuery);

and my connection:

    try {
        $options = array(
            //For updates where newvalue = oldvalue PDOStatement::rowCount()   returns zero. You can use this:
            PDO::MYSQL_ATTR_FOUND_ROWS => true
        );
        $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password, $options);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo "Error connecting to SQL Server: " . $e->getMessage();
    }

Note:
This solution helps you to run multiple statement together,
If an incorrect a statement occurs, it does not execute any other statement

Creating virtual directories in IIS express

@Be.St.'s aprroach is true, but incomplete. I'm just copying his explanation with correcting the incorrect part.

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
   </application>
   <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Instead of adding a new application block, you should just add a new virtualDirectory element to the application parent element.

Edit - Visual Studio 2015

If you're looking for the applicationHost.config file and you're using VS2015 you'll find it in:

[solution_directory]/.vs/config/applicationHost.config

Create unique constraint with null columns

Create two partial indexes:

CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;

CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;

This way, there can only be one combination of (user_id, recipe_id) where menu_id IS NULL, effectively implementing the desired constraint.

Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id), you cannot base CLUSTER on a partial index, and queries without a matching WHERE condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).

If you need a complete index, you can alternatively drop the WHERE condition from favo_3col_uni_idx and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).

Aside: I advise not to use mixed case identifiers in PostgreSQL.

How can I select rows by range?

Following your clarification you're looking for limit:

SELECT * FROM `table` LIMIT 0, 10 

This will display the first 10 results from the database.

SELECT * FROM `table` LIMIT 5, 5 .

Will display 5-9 (5,6,7,8,9)

The syntax follows the pattern:

SELECT * FROM `table` LIMIT [row to start at], [how many to include] .

The SQL for selecting rows where a column is between two values is:

SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

See: http://www.w3schools.com/sql/sql_between.asp

If you want to go on the row number you can use rownum:

SELECT column_name(s)
FROM table_name
WHERE rownum 
BETWEEN x AND y

However we need to know which database engine you are using as rownum is different for most.

Create a new cmd.exe window from within another cmd.exe prompt

I also tried executing batch file that run daemon process/server at the end of CCNET task; The only way to make CruiseControl spawn an independent asynchronous process WITHOUT waiting for the end of process is:

  1. create a batch file to run the daemon process (server application)
  2. use task scheduler to run the batch file as CCNET task (using schtasks.exe)

    schtasks.exe /create /F /SC once /ST 08:50 /TN TaskName /TR "c:/path/to/batchFileName.bat"
    
    • 08:50 is the HH:MM time format

you might need to kill the process at the start of ccnet

PS: the selected answer using "start cmd.exe" does not work; a new command prompt is indeed spawned, but CCNET will wait for the spawned cmd to finish.

How to create a multiline UITextfield?

UITextField is specifically one-line only.

Your Google search is correct, you need to use UITextView instead of UITextField for display and editing of multiline text.

In Interface Builder, add a UITextView where you want it and select the "editable" box. It will be multiline by default.

SELECT * FROM in MySQLi

You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.

Access denied for user 'test'@'localhost' (using password: YES) except root user

Make sure the user has a localhost entry in the users table. That was the problem I was having. EX:

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

Process list on Linux via Python

I would use the subprocess module to execute the command ps with appropriate options. By adding options you can modify which processes you see. Lot's of examples on subprocess on SO. This question answers how to parse the output of ps for example:)

You can, as one of the example answers showed also use the PSI module to access system information (such as the process table in this example).

Adding Google Translate to a web site

Implementing Google translate html code is very easy. Use this code on your project, hope it will help you.

    <div id="google_translate_element"></div>
<script> 
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en'
  }, 'google_translate_element');
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> 

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.

npx command not found

if you are using macOS, use sudo command

sudo npm install -g npx

enter image description here

Java Map equivalent in C#

class Test
{
    Dictionary<int, string> entities;

    public string GetEntity(int code)
    {
        // java's get method returns null when the key has no mapping
        // so we'll do the same

        string val;
        if (entities.TryGetValue(code, out val))
            return val;
        else
            return null;
    }
}

Extending from two classes

Yea, as everyone else wrote, you cannot do multiple inheritance in Java. If you have two classes from which you'd like to use code, you'd typically just subclass one (say class A). For class B, you abstract the important methods of it to an interface BInterface (ugly name, but you get the idea), then say Main extends A implements BInterface. Inside, you can instantiate an object of class B and implement all methods of BInterface by calling the corresponding functions of B.

This changes the "is-a" relationship to a "has-a" relationship as your Main now is an A, but has a B. Depending on your use case, you might even make that change explicit by removing the BInterface from your A class and instead provide a method to access your B object directly.

AngularJS : When to use service instead of factory

The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.

To put it simply each one of these providers is a specialized version of the other, in this order: provider > factory > value / constant / service.

So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.

This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.

AngularJS providers, factories, services, etc are all the same thing
(source: simplygoodcode.com)

For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

Numpy where function multiple conditions

The accepted answer explained the problem well enough. However, the more Numpythonic approach for applying multiple conditions is to use numpy logical functions. In this case, you can use np.logical_and:

np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))

Losing scope when using ng-include

As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText" actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:

ng-include scope

To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:

 <form ng-submit="addLine(lineText)">

In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:

 <form ng-submit="addLine(lineText); lineText=''">

Function addLine() would thus become:

$scope.addLine = function(lineText) {
    $scope.chat.addLine(lineText);
    $scope.lines.push({
        text: lineText
    });
};

Fiddle.

Alternatives:

  • define an object property on HomeCtrl's $scope, and use that in the partial: ng-model="someObj.lineText; fiddle
  • not recommended, this is more of a hack: use $parent in the partial to create/access a lineText property on the HomeCtrl $scope:  ng-model="$parent.lineText"; fiddle

It is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I don't recommend using this in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.

default value for struct member in C

You can create a function for it:

typedef struct {
    int id;
    char name;
} employee;

void set_iv(employee *em);

int main(){
    employee em0; set_iv(&em0);
}

void set_iv(employee *em){
    (*em).id = 0;
    (*em).name = "none";
}

Using Intent in an Android application to show another activity

The issue was the OrderScreen Activity wasn't added to the AndroidManifest.xml. Once I added that as an application node, it worked properly.

<activity android:name=".OrderScreen" />

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

Procedure expects parameter which was not supplied

It is necessary to tell that a Stored Proc is being called:

comm.CommandType = CommandType.StoredProcedure;

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

Iterate over values of object

EcmaScript 2017 introduced Object.entries that allows you to iterate over values and keys. Documentation

var map = { key1 : 'value1', key2 : 'value2' }

for (let [key, value] of Object.entries(map)) {
    console.log(`${key}: ${value}`);
}

The result will be:

key1: value1
key2: value2

Generating HTML email body in C#

A commercial version which I use in production and allows for easy maintenance is LimiLabs Template Engine, been using it for 3+ years and allows me to make changes to the text template without having to update code (disclaimers, links etc..) - it could be as simple as

Contact templateData = ...; 
string html = Template
     .FromFile("template.txt")
     .DataFrom(templateData )
     .Render();

Worth taking a look at, like I did; after attempting various answers mentioned here.

Convert string to int if string is a number

Cast to long or cast to int, be aware of the following.

These functions are one of the view functions in Excel VBA that are depending on the system regional settings. So if you use a comma in your double like in some countries in Europe, you will experience an error in the US.

E.g., in european excel-version 0,5 will perform well with CDbl(), but in US-version it will result in 5. So I recommend to use the following alternative:

Public Function CastLong(var As Variant)

    ' replace , by .
    var = Replace(var, ",", ".")        

    Dim l As Long
    On Error Resume Next
    l = Round(Val(var))

    ' if error occurs, l will be 0
    CastLong = l

End Function

' similar function for cast-int, you can add minimum and maximum value if you like
' to prevent that value is too high or too low.
Public Function CastInt(var As Variant)

    ' replace , by .
    var = Replace(var, ",", ".")

    Dim i As Integer
    On Error Resume Next
    i = Round(Val(var))

    ' if error occurs, i will be 0
    CastInt = i

End Function

Of course you can also think of cases where people use commas and dots, e.g., three-thousand as 3,000.00. If you require functionality for these kind of cases, then you have to check for another solution.

How to copy only a single worksheet to another workbook using vba

Sub ActiveSheet_toDESKTOP_As_Workbook()

Dim Oldname As String
Dim MyRange As Range
Dim MyWS As String

MyWS = ActiveCell.Parent.Name

    Application.DisplayAlerts = False 'hide confirmation from user
    Application.ScreenUpdating = False
    Oldname = ActiveSheet.Name
    'Sheets.Add(Before:=Sheets(1)).Name = "FirstSheet"
    
    'Get path for desktop of user PC
    Path = Environ("USERPROFILE") & "\Desktop"
    

    ActiveSheet.Cells.Copy
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "TransferSheet"
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.Copy
    
    'Create new workbook and past copied data in new workbook & save to desktop
    Workbooks.Add (xlWBATWorksheet)
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells(1, 1).Select
    ActiveWorkbook.ActiveSheet.Name = Oldname    '"report"
    ActiveWorkbook.SaveAs Filename:=Path & "\" & Oldname & " WS " & Format(CStr(Now()), "dd-mmm (hh.mm.ss AM/PM)") & ".xlsx"
    ActiveWorkbook.Close SaveChanges:=True

    
    Sheets("TransferSheet").Delete
    
    
   Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Worksheets(MyWS).Activate
    'MsgBox "Exported to Desktop"

End Sub

How to watch for array changes?

I fiddled around and came up with this. The idea is that the object has all the Array.prototype methods defined, but executes them on a separate array object. This gives the ability to observe methods like shift(), pop() etc. Although some methods like concat() won't return the OArray object. Overloading those methods won't make the object observable if accessors are used. To achieve the latter, the accessors are defined for each index within given capacity.

Performance wise... OArray is around 10-25 times slower compared to the plain Array object. For the capasity in a range 1 - 100 the difference is 1x-3x.

class OArray {
    constructor(capacity, observer) {

        var Obj = {};
        var Ref = []; // reference object to hold values and apply array methods

        if (!observer) observer = function noop() {};

        var propertyDescriptors = Object.getOwnPropertyDescriptors(Array.prototype);

        Object.keys(propertyDescriptors).forEach(function(property) {
            // the property will be binded to Obj, but applied on Ref!

            var descriptor = propertyDescriptors[property];
            var attributes = {
                configurable: descriptor.configurable,
                enumerable: descriptor.enumerable,
                writable: descriptor.writable,
                value: function() {
                    observer.call({});
                    return descriptor.value.apply(Ref, arguments);
                }
            };
            // exception to length
            if (property === 'length') {
                delete attributes.value;
                delete attributes.writable;
                attributes.get = function() {
                    return Ref.length
                };
                attributes.set = function(length) {
                    Ref.length = length;
                };
            }

            Object.defineProperty(Obj, property, attributes);
        });

        var indexerProperties = {};
        for (var k = 0; k < capacity; k++) {

            indexerProperties[k] = {
                configurable: true,
                get: (function() {
                    var _i = k;
                    return function() {
                        return Ref[_i];
                    }
                })(),
                set: (function() {
                    var _i = k;
                    return function(value) {
                        Ref[_i] = value;
                        observer.call({});
                        return true;
                    }
                })()
            };
        }
        Object.defineProperties(Obj, indexerProperties);

        return Obj;
    }
}

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

How to turn a String into a JavaScript function call?

Based on Nicolas Gauthier answer:

var strng = 'someobj.someCallback';
var data = 'someData';

var func = window;
var funcSplit = strng.split('.');
for(i = 0;i < funcSplit.length;i++){
   //We maybe can check typeof and break the bucle if typeof != function
   func = func[funcSplit[i]];
}
func(data);

How do I filter query objects by date range in Django?

Use

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])

Or if you are just trying to filter month wise:

Sample.objects.filter(date__year='2011', 
                      date__month='01')

Edit

As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

I got error "The DELETE statement conflicted with the REFERENCE constraint"

To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.

To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.

How to convert JSON to XML or XML to JSON?

I have used the below methods to convert the JSON to XML

List <Item> items;
public void LoadJsonAndReadToXML() {
  using(StreamReader r = new StreamReader(@ "E:\Json\overiddenhotelranks.json")) {
    string json = r.ReadToEnd();
    items = JsonConvert.DeserializeObject <List<Item>> (json);
    ReadToXML();
  }
}

And

public void ReadToXML() {
  try {
    var xEle = new XElement("Items",
      from item in items select new XElement("Item",
        new XElement("mhid", item.mhid),
        new XElement("hotelName", item.hotelName),
        new XElement("destination", item.destination),
        new XElement("destinationID", item.destinationID),
        new XElement("rank", item.rank),
        new XElement("toDisplayOnFod", item.toDisplayOnFod),
        new XElement("comment", item.comment),
        new XElement("Destinationcode", item.Destinationcode),
        new XElement("LoadDate", item.LoadDate)
      ));

    xEle.Save("E:\\employees.xml");
    Console.WriteLine("Converted to XML");
  } catch (Exception ex) {
    Console.WriteLine(ex.Message);
  }
  Console.ReadLine();
}

I have used the class named Item to represent the elements

public class Item {
  public int mhid { get; set; }
  public string hotelName { get; set; }
  public string destination { get; set; }
  public int destinationID { get; set; }
  public int rank { get; set; }
  public int toDisplayOnFod { get; set; }
  public string comment { get; set; }
  public string Destinationcode { get; set; }
  public string LoadDate { get; set; }
}

It works....

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

How to remove decimal values from a value of type 'double' in Java

String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose

The problem is two fold-

  1. To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
  2. Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.

saving a file (from stream) to disk using c#

For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.

Example (Assuming you already have a stream):

FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);    
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();

How to Publish Web with msbuild?

found two different solutions which worked in slightly different way:

1. This solution is inspired by the answer from alexanderb [link]. Unfortunately it did not work for us - some dll's were not copied to the OutDir. We found out that replacing ResolveReferences with Build target solves the problem - now all necessary files are copied into the OutDir location.

msbuild /target:Build;_WPPCopyWebApplication  /p:Configuration=Release;OutDir=C:\Tmp\myApp\ MyApp.csproj
Disadvantage of this solution was the fact that OutDir contained not only files for publish.

2. The first solution works well but not as we expected. We wanted to have the publish functionality as it is in Visual Studio IDE - i.e. only the files which should be published will be copied into the Output directory. As it has been already mentioned first solution copies much more files into the OutDir - the website for publish is then stored in _PublishedWebsites/{ProjectName} subfolder. The following command solves this - only the files for publish will be copied to desired folder. So now you have directory which can be directly published - in comparison with the first solution you will save some space on hard drive.

msbuild /target:Build;PipelinePreDeployCopyAllFilesToOneFolder /p:Configuration=Release;_PackageTempDir=C:\Tmp\myApp\;AutoParameterizationWebConfigConnectionStrings=false MyApp.csproj
AutoParameterizationWebConfigConnectionStrings=false parameter will guarantee that connection strings will not be handled as special artifacts and will be correctly generated - for more information see link.

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

QR Code encoding and decoding using zxing

If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103

I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.

How to do if-else in Thymeleaf?

<div th:switch="${user.role}"> 
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p> 
</div>


<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
<h2 th:if="${condition}">Hello!</h2>
<span th:unless="${condition}" class="xxx">Something else</span>
</div>

How do I append to a table in Lua

foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.

Python virtualenv questions

Yes basically this is what virtualenv do , and this is what the activate command is for, from the doc here:

activate script

In a newly created virtualenv there will be a bin/activate shell script, or a Scripts/activate.bat batch file on Windows.

This will change your $PATH to point to the virtualenv bin/ directory. Unlike workingenv, this is all it does; it's a convenience. But if you use the complete path like /path/to/env/bin/python script.py you do not need to activate the environment first. You have to use source because it changes the environment in-place. After activating an environment you can use the function deactivate to undo the changes.

The activate script will also modify your shell prompt to indicate which environment is currently active.

so you should just use activate command which will do all that for you:

> \path\to\env\bin\activate.bat

Switch firefox to use a different DNS than what is in the windows.host file

Go to options->Advanced->Network->Settings->Automatic proxy configuration url and enter 8.8.8.8 All you Mozilla traffic uses Google dns now.

Why is my Button text forced to ALL CAPS on Lollipop?

If you use appcompat-v7, you can subclass AppCompatButtonand setSupportAllCaps(false), then use this class for all your buttons.

/**
 * Light extension of {@link AppCompatButton} that overrides ALL CAPS transformation
 */
public class Button extends AppCompatButton {
    public Button(Context context, AttributeSet attrs) {
        super(context, attrs);
        setSupportAllCaps(false);
    }

    public Button(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setSupportAllCaps(false);
    }
}

See AppCompatButton#setSupportAllCaps(boolean) Android docs.

Angular 2 Scroll to bottom (Chat style)

After reading other solutions, the best solution I can think of, so you run only what you need is the following: You use ngOnChanges to detect the proper change

ngOnChanges() {
  if (changes.messages) {
      let chng = changes.messages;
      let cur  = chng.currentValue;
      let prev = chng.previousValue;
      if(cur && prev) {
        // lazy load case
        if (cur[0].id != prev[0].id) {
          this.lazyLoadHappened = true;
        }
        // new message
        if (cur[cur.length -1].id != prev[prev.length -1].id) {
          this.newMessageHappened = true;
        }
      }
    }

}

And you use ngAfterViewChecked to actually enforce the change before it renders but after the full height is calculated

ngAfterViewChecked(): void {
    if(this.newMessageHappened) {
      this.scrollToBottom();
      this.newMessageHappened = false;
    }
    else if(this.lazyLoadHappened) {
      // keep the same scroll
      this.lazyLoadHappened = false
    }
  }

If you are wondering how to implement scrollToBottom

@ViewChild('scrollWrapper') private scrollWrapper: ElementRef;
scrollToBottom(){
    try {
      this.scrollWrapper.nativeElement.scrollTop = this.scrollWrapper.nativeElement.scrollHeight;
    } catch(err) { }
  }

Hashing a file in Python

TL;DR use buffers to not use tons of memory.

We get to the crux of your problem, I believe, when we consider the memory implications of working with very large files. We don't want this bad boy to churn through 2 gigs of ram for a 2 gigabyte file so, as pasztorpisti points out, we gotta deal with those bigger files in chunks!

import sys
import hashlib

# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536  # lets read stuff in 64kb chunks!

md5 = hashlib.md5()
sha1 = hashlib.sha1()

with open(sys.argv[1], 'rb') as f:
    while True:
        data = f.read(BUF_SIZE)
        if not data:
            break
        md5.update(data)
        sha1.update(data)

print("MD5: {0}".format(md5.hexdigest()))
print("SHA1: {0}".format(sha1.hexdigest()))

What we've done is we're updating our hashes of this bad boy in 64kb chunks as we go along with hashlib's handy dandy update method. This way we use a lot less memory than the 2gb it would take to hash the guy all at once!

You can test this with:

$ mkfile 2g bigfile
$ python hashes.py bigfile
MD5: a981130cf2b7e09f4686dc273cf7187e
SHA1: 91d50642dd930e9542c39d36f0516d45f4e1af0d
$ md5 bigfile
MD5 (bigfile) = a981130cf2b7e09f4686dc273cf7187e
$ shasum bigfile
91d50642dd930e9542c39d36f0516d45f4e1af0d  bigfile

Hope that helps!

Also all of this is outlined in the linked question on the right hand side: Get MD5 hash of big files in Python


Addendum!

In general when writing python it helps to get into the habit of following pep-8. For example, in python variables are typically underscore separated not camelCased. But that's just style and no one really cares about those things except people who have to read bad style... which might be you reading this code years from now.

Reading integers from binary file in Python

An alternative method which does not make use of 'struct.unpack()' would be to use NumPy:

import numpy as np

f = open("file.bin", "r")
a = np.fromfile(f, dtype=np.uint32)

'dtype' represents the datatype and can be int#, uint#, float#, complex# or a user defined type. See numpy.fromfile.

Personally prefer using NumPy to work with array/matrix data as it is a lot faster than using Python lists.

Print the stack trace of an exception

If you are interested in a more compact stack trace with more information (package detail) that looks like:

  java.net.SocketTimeoutException:Receive timed out
    at j.n.PlainDatagramSocketImpl.receive0(Native Method)[na:1.8.0_151]
    at j.n.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)[^]
    at j.n.DatagramSocket.receive(DatagramSocket.java:812)[^]
    at o.s.n.SntpClient.requestTime(SntpClient.java:213)[classes/]
    at o.s.n.SntpClient$1.call(^:145)[^]
    at ^.call(^:134)[^]
    at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:124)[^]
    at o.s.f.RetryPolicy.call(RetryPolicy.java:105)[^]
    at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:59)[^]
    at o.s.n.SntpClient.requestTimeHA(SntpClient.java:134)[^]
    at ^.requestTimeHA(^:122)[^]
    at o.s.n.SntpClientTest.test2h(SntpClientTest.java:89)[test-classes/]
    at s.r.NativeMethodAccessorImpl.invoke0(Native Method)[na:1.8.0_151]

you can try to use Throwables.writeTo from the spf4j lib.

Javascript: Call a function after specific time period

Timeout:

setTimeout(() => {
   console.log('Hello Timeout!')
}, 3000);

Interval:

setInterval(() => {
   console.log('Hello Interval!')
}, 2000);

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

Get an array of list element contents in jQuery

var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"';

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

I use Ubuntu linux, and in my case the error was caused by incorrect statement syntax (which I found out by typing perror 150 at the terminal, which gives

MySQL error code 150: Foreign key constraint is incorrectly formed

Changing the syntax of the query from

alter table scale add constraint foreign key (year_id) references year.id;

to

alter table scale add constraint foreign key (year_id) references year(id);

fixed it.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

How to create a DateTime equal to 15 minutes ago?

only the below code in Python 3.7 worked for me

from datetime import datetime,timedelta    
print(datetime.now()-timedelta(seconds=900))

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>

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

I had a run in with the same problem. My application was also a Silverlight application and the service was being called from a class library with a custom UserControl that was being used in it.

The solution is simple. Copy the endpoint definitions from the config file (e.g. ServiceReferences.ClientConfig) of the class library to the config file of the silverlight application. I know you'd expect it to work without having to do this, but apparently someone in Redmond had a vacation that day.

How to set a dropdownlist item as selected in ASP.NET?

You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.

dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;

Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.

Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.

"Cannot have multiple items selected in a DropDownList"

Difference between thread's context class loader and normal classloader

There is an article on javaworld.com that explains the difference => Which ClassLoader should you use

(1)

Thread context classloaders provide a back door around the classloading delegation scheme.

Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

(2) from the same source:

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

Format date and time in a Windows batch script

Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):

@ECHO OFF
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _yyyy=%%L
      Set _mm=00%%J
      Set _dd=00%%G
      Set _hour=00%%H
      SET _minute=00%%I
      SET _second=00%%K
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%
      Set _hour=%_hour:~-2%
      Set _minute=%_minute:~-2%
      Set _second=%_second:~-2%

Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%
goto make_dump

:s_error
echo WMIC is not available, using default log filename
Set logtimestamp=_

:make_dump
set FILENAME=database_dump_%logtimestamp%.sql
...

Should I put input elements inside a label element?

A notable 'gotcha' dictates that you should never include more than one input element inside of a <label> element with an explicit "for" attribute, e.g:

<label for="child-input-1">
  <input type="radio" id="child-input-1"/>
  <span> Associate the following text with the selected radio button: </span>
  <input type="text" id="child-input-2"/>
</label>

While this may be tempting for form features in which a custom text value is secondary to a radio button or checkbox, the click-focus functionality of the label element will immediately throw focus to the element whose id is explicitly defined in its 'for' attribute, making it nearly impossible for the user to click into the contained text field to enter a value.

Personally, I try to avoid label elements with input children. It seems semantically improper for a label element to encompass more than the label itself. If you're nesting inputs in labels in order to achieve a certain aesthetic, you should be using CSS instead.

How to list all AWS S3 objects in a bucket using Java

As a slightly more concise solution to listing S3 objects when they might be truncated:

ListObjectsRequest request = new ListObjectsRequest().withBucketName(bucketName);
ObjectListing listing = null;

while((listing == null) || (request.getMarker() != null)) {
  listing = s3Client.listObjects(request);
  // do stuff with listing
  request.setMarker(listing.getNextMarker());
}

How to check whether input value is integer or float?

You can use Scanner Class to find whether a given number could be read as Int or Float type.

 import java.util.Scanner;
 public class Test {
     public static void main(String args[] ) throws Exception {

     Scanner sc=new Scanner(System.in);

     if(sc.hasNextInt())
         System.out.println("This input is  of type Integer");
     else if(sc.hasNextFloat())
         System.out.println("This input is  of type Float");
     else
         System.out.println("This is something else");
     }
}

React navigation goBack() and update parent state

is there a way to pass param from navigate.goback() and parent can listen to the params and update its state?

You can pass a callback function as parameter (as mentioned in other answers).

Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect):

ViewA.js

import React from "react";
import { Button, Text, View } from "react-native";

class ViewA extends React.Component {
  state = { selected: false };

  onSelect = data => {
    this.setState(data);
  };

  onPress = () => {
    this.props.navigate("ViewB", { onSelect: this.onSelect });
  };

  render() {
    return (
      <View>
        <Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
        <Button title="Next" onPress={this.onPress} />
      </View>
    );
  }
}

ViewB.js

import React from "react";
import { Button } from "react-native";

class ViewB extends React.Component {
  goBack() {
    const { navigation } = this.props;
    navigation.goBack();
    navigation.state.params.onSelect({ selected: true });
  }

  render() {
    return <Button title="back" onPress={this.goBack} />;
  }
}

Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617


Edit

For React Navigation v5

ViewB.js

import React from "react";
import { Button } from "react-native";

class ViewB extends React.Component {
  goBack() {
    const { navigation, route } = this.props;
    navigation.goBack();
    route.params.onSelect({ selected: true });
  }

  render() {
    return <Button title="back" onPress={this.goBack} />;
  }
}

Convert string to variable name in python

x='buffalo'    
exec("%s = %d" % (x,2))

After that you can check it by:

print buffalo

As an output you will see: 2

How to achieve pagination/table layout with Angular.js?

The best simple plug and play solution for pagination.

https://ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/#comment-1002

you would jus need to replace ng-repeat with custom directive.

<tr dir-paginate="user in userList|filter:search |itemsPerPage:7">
<td>{{user.name}}</td></tr>

Within the page u just need to add

<div align="center">
       <dir-pagination-controls
            max-size="100"
            direction-links="true"
            boundary-links="true" >
       </dir-pagination-controls>
</div>

In your index.html load

<script src="./js/dirPagination.js"></script>

In your module just add dependencies

angular.module('userApp',['angularUtils.directives.dirPagination']);

and thats all needed for pagination.

Might be helpful for someone.

How to import set of icons into Android Studio project

For custom images you created yourself, you can do without the plugin:

Right click on res folder, selecting New > Image Asset. browse image file. Select the largest image you have.

It will create all densities for you. Make sure you select an original image, not an asset studio image with an alpha, or you will semi-transpartent it twice.

How to send a "multipart/form-data" with requests in python?

Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:

var upload = multer().single('fieldName');

Regex: match everything but specific pattern

I need a regex able to match everything but except a string starting with index.php a specific pattern (specifically index.php and what follows, like index.php?id=2342343)

Use method Exec

_x000D_
_x000D_
    let match,_x000D_
        arr = [],_x000D_
        myRe = /([\s\S]+?)(?:index\.php\?id.+)/g;_x000D_
_x000D_
    var str = 'http://regular-viragenia/index.php?id=2342343';_x000D_
_x000D_
    while ((match = myRe.exec(str)) != null) {_x000D_
         arr.push(match[1]);_x000D_
    } _x000D_
    _x000D_
    console.log(arr);
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var myRe = /([\s\S]+?)(?:index\.php\?id=.+)/g;_x000D_
var str = 'http://regular-viragenia/index.php?id=2342343';_x000D_
var matches_array = myRe.exec(str);_x000D_
console.log(matches_array[1]);
_x000D_
_x000D_
_x000D_

OR OTHER MATCH

_x000D_
_x000D_
let match,_x000D_
            arr = [],_x000D_
            myRe = /index.php\?id=((?:(?!index)[\s\S])*)/g;_x000D_
_x000D_
        var str = 'http://regular-viragenia/index.php?id=2342343index.php?id=111index.php?id=222';_x000D_
_x000D_
        while ((match = myRe.exec(str)) != null) {_x000D_
             arr.push(match[1]);_x000D_
        } _x000D_
_x000D_
        console.log(arr);
_x000D_
_x000D_
_x000D_

socket programming multiple client to one server

For every client you need to start separate thread. Example:

public class ThreadedEchoServer {

    static final int PORT = 1978;

    public static void main(String args[]) {
        ServerSocket serverSocket = null;
        Socket socket = null;

        try {
            serverSocket = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();

        }
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                System.out.println("I/O error: " + e);
            }
            // new thread for a client
            new EchoThread(socket).start();
        }
    }
}

and

public class EchoThread extends Thread {
    protected Socket socket;

    public EchoThread(Socket clientSocket) {
        this.socket = clientSocket;
    }

    public void run() {
        InputStream inp = null;
        BufferedReader brinp = null;
        DataOutputStream out = null;
        try {
            inp = socket.getInputStream();
            brinp = new BufferedReader(new InputStreamReader(inp));
            out = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            return;
        }
        String line;
        while (true) {
            try {
                line = brinp.readLine();
                if ((line == null) || line.equalsIgnoreCase("QUIT")) {
                    socket.close();
                    return;
                } else {
                    out.writeBytes(line + "\n\r");
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    }
}

You can also go with more advanced solution, that uses NIO selectors, so you will not have to create thread for every client, but that's a bit more complicated.

What does "Object reference not set to an instance of an object" mean?

If I have the class:

public class MyClass
{
   public void MyMethod()
   {

   }
}

and I then do:

MyClass myClass = null;
myClass.MyMethod();

The second line throws this exception becuase I'm calling a method on a reference type object that is null (I.e. has not been instantiated by calling myClass = new MyClass())

How to unzip gz file using Python

Maybe you want pass it to pandas also.

with gzip.open('features_train.csv.gz') as f:

    features_train = pd.read_csv(f)

features_train.head()

When & why to use delegates?

I consider delegates to be Anonymous Interfaces. In many cases you can use them whenever you need an interface with a single method, but you don't want the overhead of defining that interface.

PersistenceContext EntityManager injection NullPointerException

An entity manager can only be injected in classes running inside a transaction. In other words, it can only be injected in a EJB. Other classe must use an EntityManagerFactory to create and destroy an EntityManager.

Since your TestService is not an EJB, the annotation @PersistenceContext is simply ignored. Not only that, in JavaEE 5, it's not possible to inject an EntityManager nor an EntityManagerFactory in a JAX-RS Service. You have to go with a JavaEE 6 server (JBoss 6, Glassfish 3, etc).

Here's an example of injecting an EntityManagerFactory:

package com.test.service;

import java.util.*;
import javax.persistence.*;
import javax.ws.rs.*;

@Path("/service")
public class TestService {

    @PersistenceUnit(unitName = "test")
    private EntityManagerFactory entityManagerFactory;

    @GET
    @Path("/get")
    @Produces("application/json")
    public List get() {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            return entityManager.createQuery("from TestEntity").getResultList();
        } finally {
            entityManager.close();
        }
    }
}

The easiest way to go here is to declare your service as a EJB 3.1, assuming you're using a JavaEE 6 server.

Related question: Inject an EJB into JAX-RS (RESTful service)

one line if statement in php

The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well

function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();

deleting rows in numpy array

This is similar to your original approach, and will use less space than unutbu's answer, but I suspect it will be slower.

>>> import numpy as np
>>> p = np.array([[1.5, 0], [1.4,1.5], [1.6, 0], [1.7, 1.8]])
>>> p
array([[ 1.5,  0. ],
       [ 1.4,  1.5],
       [ 1.6,  0. ],
       [ 1.7,  1.8]])
>>> nz = (p == 0).sum(1)
>>> q = p[nz == 0, :]
>>> q
array([[ 1.4,  1.5],
       [ 1.7,  1.8]])

By the way, your line p.delete() doesn't work for me - ndarrays don't have a .delete attribute.

How to loop through an associative array and get the key?

If you use nested foreach() function, outer array's keys print again and again till inner array values end.

<?php 

$myArray = ['key_1' => ['value_1', 'value12'],
            'key_2' => ['value_2', 'value22'], 
            'key_3' => ['value_3', 'value32']
           ];

$keysOfMyArray = array_key($myArray);

for ($x = 0; $x < count($myArray); $x++){
       print "\t".$keysOfMyArray[$x]."\t\t".implode("\t\t",$myArray[$keysOfMyArray[$x]]."\n");
}

?>

ERROR 1049 (42000): Unknown database 'mydatabasename'

La Chi's answer works for me.

You can view his/her answer in the comment of zessx answer in this page. But I initially have a problem with it if you also do just tweak his/her answer like this: mysql -h localhost -u root -p -D mydatabase < mydatabase.sql.

Also I would suggest that in the mydatabase.sql portion you include the direct location of it in your computer like "C:\Users\username\desktop".

Thank you.

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Port 80

What I do on my cloud instances is I redirect port 80 to port 3000 with this command:

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000

Then I launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.

You should also edit your /etc/rc.local file and add that line minus the sudo. That will add the redirect when the machine boots up. You don't need sudo in /etc/rc.local because the commands there are run as root when the system boots.

Logs

Use the forever module to launch your Node.js with. It will make sure that it restarts if it ever crashes and it will redirect console logs to a file.

Launch on Boot

Add your Node.js start script to the file you edited for port redirection, /etc/rc.local. That will run your Node.js launch script when the system starts.

Digital Ocean & other VPS

This not only applies to Linode, but Digital Ocean, AWS EC2 and other VPS providers as well. However, on RedHat based systems /etc/rc.local is /ect/rc.d/local.

Convert a tensor to numpy array in Tensorflow?

You can use keras backend function.

import tensorflow as tf
from tensorflow.python.keras import backend 

sess = backend.get_session()
array = sess.run(< Tensor >)

print(type(array))

<class 'numpy.ndarray'>

I hope it helps!

Remove all multiple spaces in Javascript and replace with single space

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

How to detect IE11?

Use !(window.ActiveXObject) && "ActiveXObject" in window to detect IE11 explicitly.

To detect any IE (pre-Edge, "Trident") version, use "ActiveXObject" in window instead.

How can I perform static code analysis in PHP?

Online PHP lint

PHPLint

Unitialized variables check. Link 1 and 2 already seem to do this just fine, though.

I can't say I have used any of these intensively, though :)

Reset the Value of a Select Box

What worked for me was:

$('select option').each(function(){$(this).removeAttr('selected');});   

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Get bitcoin historical data

Scraping it to JSON with Node.js would be fun :)

https://github.com/f1lt3r/bitcoin-scraper

enter image description here

[
  [
    1419033600,  // Timestamp (1 for each minute of entire history)
    318.58,      // Open
    318.58,      // High
    318.58,      // Low
    318.58,      // Close
    0.01719605,  // Volume (BTC)
    5.478317609, // Volume (Currency)
    318.58       // Weighted Price (USD)
  ]
]

Dynamic Web Module 3.0 -- 3.1

If you want to use version 3.1 you need to use the following schema:

  • http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd

Note that 3.0 and 3.1 are different: in 3.1 there's no Sun mentioned, so simply changing 3_0.xsd to 3_1.xsd won't work.

This is how it should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">

</web-app>

Also, make sure you're depending on the latest versions in your pom.xml. That is,

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        ...
    </configuration>
</plugin>

and

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Finally, you should compile with Java 7 or 8:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
    </configuration>
</plugin>

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

I had a similar issue, I was sending a POST request (using RESTClient plugin for Firefox) with data in the request body and was receiving the same message.

In my case this happened because I was trying to use HTTPS protocol in a local tomcat instance where HTTPS was not configured.

Best way to store time (hh:mm) in a database

DATETIME start DATETIME end

I implore you to use two DATETIME values instead, labelled something like event_start and event_end.

Time is a complex business

Most of the world has now adopted the denery based metric system for most measurements, rightly or wrongly. This is good overall, because at least we can all agree that a g, is a ml, is a cubic cm. At least approximately so. The metric system has many flaws, but at least it's internationally consistently flawed.

With time however, we have; 1000 milliseconds in a second, 60 seconds to a minute, 60 minutes to an hour, 12 hours for each half a day, approximately 30 days per month which vary by the month and even year in question, each country has its time offset from others, the way time is formatted in each country vary.

It's a lot to digest, but the long and short of it is impossible for such a complex scenario to have a simple solution.

Some corners can be cut, but there are those where it is wiser not to

Although the top answer here suggests that you store an integer of minutes past midnight might seem perfectly reasonable, I have learned to avoid doing so the hard way.

The reasons to implement two DATETIME values are for an increase in accuracy, resolution and feedback.

These are all very handy for when the design produces undesirable results.

Am I storing more data than required?

It might initially appear like more information is being stored than I require, but there is a good reason to take this hit.

Storing this extra information almost always ends up saving me time and effort in the long-run, because I inevitably find that when somebody is told how long something took, they'll additionally want to know when and where the event took place too.

It's a huge planet

In the past, I have been guilty of ignoring that there are other countries on this planet aside from my own. It seemed like a good idea at the time, but this has ALWAYS resulted in problems, headaches and wasted time later on down the line. ALWAYS consider all time zones.

C#

A DateTime renders nicely to a string in C#. The ToString(string Format) method is compact and easy to read.

E.g.

new TimeSpan(EventStart.Ticks - EventEnd.Ticks).ToString("h'h 'm'm 's's'")

SQL server

Also if you're reading your database seperate to your application interface, then dateTimes are pleasnat to read at a glance and performing calculations on them are straightforward.

E.g.

SELECT DATEDIFF(MINUTE, event_start, event_end)

ISO8601 date standard

If using SQLite then you don't have this, so instead use a Text field and store it in ISO8601 format eg.

"2013-01-27T12:30:00+0000"

Notes:

  • This uses 24 hour clock*

  • The time offset (or +0000) part of the ISO8601 maps directly to longitude value of a GPS coordiate (not taking into account daylight saving or countrywide).

E.g.

TimeOffset=(±Longitude.24)/360 

...where ± refers to east or west direction.

It is therefore worth considering if it would be worth storing longitude, latitude and altitude along with the data. This will vary in application.

  • ISO8601 is an international format.

  • The wiki is very good for further details at http://en.wikipedia.org/wiki/ISO_8601.

  • The date and time is stored in international time and the offset is recorded depending on where in the world the time was stored.

In my experience there is always a need to store the full date and time, regardless of whether I think there is when I begin the project. ISO8601 is a very good, futureproof way of doing it.

Additional advice for free

It is also worth grouping events together like a chain. E.g. if recording a race, the whole event could be grouped by racer, race_circuit, circuit_checkpoints and circuit_laps.

In my experience, it is also wise to identify who stored the record. Either as a seperate table populated via trigger or as an additional column within the original table.

The more you put in, the more you get out

I completely understand the desire to be as economical with space as possible, but I would rarely do so at the expense of losing information.

A rule of thumb with databases is as the title says, a database can only tell you as much as it has data for, and it can be very costly to go back through historical data, filling in gaps.

The solution is to get it correct first time. This is certainly easier said than done, but you should now have a deeper insight of effective database design and subsequently stand a much improved chance of getting it right the first time.

The better your initial design, the less costly the repairs will be later on.

I only say all this, because if I could go back in time then it is what I'd tell myself when I got there.

#1062 - Duplicate entry for key 'PRIMARY'

  1. Make sure PRIMARY KEY was selected AUTO_INCREMENT.
  2. Just enable Auto increment by :
    ALTER TABLE [table name] AUTO_INCREMENT = 1
  3. When you execute the insert command you have to skip this key.

C# Convert a Base64 -> byte[]

I've written an extension method for this purpose:

public static byte[] FromBase64Bytes(this byte[] base64Bytes)
{
    string base64String = Encoding.UTF8.GetString(base64Bytes, 0, base64Bytes.Length);
    return Convert.FromBase64String(base64String);
}

Call it like this:

byte[] base64Bytes = .......
byte[] regularBytes = base64Bytes.FromBase64Bytes();

I hope it helps someone.

Removing single-quote from a string in php

Using your current str_replace method:

$FileName = str_replace("'", "", $UserInput);

While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.

With str_replace, you could even have an array of strings you want to remove entirely:

$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example

$FileName = str_replace( $remove, "", $UserInput );

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

I've had the same problem with indigo and a project that needs to generate Java sources from XSD.
I could fix it by supplying the missing life-cycle mapping, as described on this page

What's the most efficient way to test two integer ranges for overlap?

My case is different. i want check two time ranges overlap. there should not be a unit time overlap. here is Go implementation.

    func CheckRange(as, ae, bs, be int) bool {
    return (as >= be) != (ae > bs)
    }

Test cases

if CheckRange(2, 8, 2, 4) != true {
        t.Error("Expected 2,8,2,4 to equal TRUE")
    }

    if CheckRange(2, 8, 2, 4) != true {
        t.Error("Expected 2,8,2,4 to equal TRUE")
    }

    if CheckRange(2, 8, 6, 9) != true {
        t.Error("Expected 2,8,6,9 to equal TRUE")
    }

    if CheckRange(2, 8, 8, 9) != false {
        t.Error("Expected 2,8,8,9 to equal FALSE")
    }

    if CheckRange(2, 8, 4, 6) != true {
        t.Error("Expected 2,8,4,6 to equal TRUE")
    }

    if CheckRange(2, 8, 1, 9) != true {
        t.Error("Expected 2,8,1,9 to equal TRUE")
    }

    if CheckRange(4, 8, 1, 3) != false {
        t.Error("Expected 4,8,1,3 to equal FALSE")
    }

    if CheckRange(4, 8, 1, 4) != false {
        t.Error("Expected 4,8,1,4 to equal FALSE")
    }

    if CheckRange(2, 5, 6, 9) != false {
        t.Error("Expected 2,5,6,9 to equal FALSE")
    }

    if CheckRange(2, 5, 5, 9) != false {
        t.Error("Expected 2,5,5,9 to equal FALSE")
    }

you can see there is XOR pattern in boundary comparison

HTML tag inside JavaScript

here's how to incorporate variables and html tags in document.write also note how you can simply add text between the quotes

document.write("<h1>System Paltform: ", navigator.platform, "</h1>");

Simplest way to detect a mobile device in PHP

function isMobile(){
   if(defined(isMobile))return isMobile;
   @define(isMobile,(!($HUA=@trim(@$_SERVER['HTTP_USER_AGENT']))?0:
   (
      preg_match('/(android|bb\d+|meego).+mobile|silk|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i'
      ,$HUA)
   ||
      preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i'
      ,$HUA)
   )
   ));
}

echo isMobile()?1:0;
// OR
echo isMobile?1:0;

PHP - how to create a newline character?

_x000D_
_x000D_
You Can Try This._x000D_
<?php_x000D_
   $content = str_replace(PHP_EOL, "<br>", $your_content);_x000D_
 ?>_x000D_
 _x000D_
<p><?php echo($content); ?></p>
_x000D_
_x000D_
_x000D_

Amazon S3 boto - how to create a folder?

Use this:

import boto3
s3 = boto3.client('s3')
bucket_name = "YOUR-BUCKET-NAME"
directory_name = "DIRECTORY/THAT/YOU/WANT/TO/CREATE" #it's name of your folders
s3.put_object(Bucket=bucket_name, Key=(directory_name+'/'))

git rebase fatal: Needed a single revision

Check that you spelled the branch name correctly. I was rebasing a story branch (i.e. branch_name) and forgot the story part. (i.e. story/branch_name) and then git spit this error at me which didn't make much sense in this context.

Implement Stack using Two Queues

import java.util.*;

/**
 *
 * @author Mahmood
 */
public class StackImplUsingQueues {

    Queue<Integer> q1 = new LinkedList<Integer>();
    Queue<Integer> q2 = new LinkedList<Integer>();

    public int pop() {
        if (q1.peek() == null) {
            System.out.println("The stack is empty, nothing to return");
            int i = 0;
            return i;
        } else {
            int pop = q1.remove();
            return pop;
        }
    }

    public void push(int data) {

        if (q1.peek() == null) {
            q1.add(data);
        } else {
            for (int i = q1.size(); i > 0; i--) {
                q2.add(q1.remove());
            }
            q1.add(data);
            for (int j = q2.size(); j > 0; j--) {
                q1.add(q2.remove());
            }

        }
    }

    public static void main(String[] args) {
        StackImplUsingQueues s1 = new StackImplUsingQueues();
        //       Stack s1 = new Stack();
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        s1.push(5);
        s1.push(6);
        s1.push(7);
        s1.push(8);
        s1.push(9);
        s1.push(10);
        // s1.push(6);
        System.out.println("1st = " + s1.pop());
        System.out.println("2nd = " + s1.pop());
        System.out.println("3rd = " + s1.pop());
        System.out.println("4th = " + s1.pop());
        System.out.println("5th = " + s1.pop());
        System.out.println("6th = " + s1.pop());
        System.out.println("7th = " + s1.pop());
        System.out.println("8th = " + s1.pop());
        System.out.println("9th = " + s1.pop());
        System.out.println("10th= " + s1.pop());
    }
}

How should I copy Strings in Java?

Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...

So you can copy as in your first example without any problem :

String s = "hello";
String backup_of_s = s;
s = "bye";

How to resolve a Java Rounding Double issue

I would modify the example above as follows:

import java.math.BigDecimal;

BigDecimal premium = new BigDecimal("1586.6");
BigDecimal netToCompany = new BigDecimal("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

This way you avoid the pitfalls of using string to begin with. Another alternative:

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf(158660, 2);
BigDecimal netToCompany = BigDecimal.valueOf(70875, 2);
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

I think these options are better than using doubles. In webapps numbers start out as strings anyways.

Intellij reformat on file save

I thought there was something like that in IntelliJ, but I can't find it. The only clean-up that happens at save is that white space at the ends of lines is removed. I thought I had to specify that behavior at one point, but I don't see anything related at this point.

How do I sort a table in Excel if it has cell references in it?

Best way is to keep your reference data on one side of the sheet and all the formulas on the other side of the sheet. then leave a blank column between them (hide it if you want) an then you'll be sorting only the reference data keeping the Formula references pointing always at the same place. Downside is Excel will recalc everytime you sort.

Google Chrome: This setting is enforced by your administrator

Try to use this solution:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome

Run regedit, Delete the key, then restart Chrome.

Effective way to find any file's Encoding

Check this.

UDE

This is a port of Mozilla Universal Charset Detector and you can use it like this...

public static void Main(String[] args)
{
    string filename = args[0];
    using (FileStream fs = File.OpenRead(filename)) {
        Ude.CharsetDetector cdet = new Ude.CharsetDetector();
        cdet.Feed(fs);
        cdet.DataEnd();
        if (cdet.Charset != null) {
            Console.WriteLine("Charset: {0}, confidence: {1}", 
                 cdet.Charset, cdet.Confidence);
        } else {
            Console.WriteLine("Detection failed.");
        }
    }
}

How to delete object from array inside foreach loop?

Be careful with the main answer.

with

[['id'=>1,'cat'=>'vip']
,['id'=>2,'cat'=>'vip']
,['id'=>3,'cat'=>'normal']

and calling the function

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'cat' && $value == 'vip'){
            //delete this particular object from the $array
            unset($array[$elementKey]);
        } 
    }
}

it returns

[2=>['id'=>3,'cat'=>'normal']

instead of

[0=>['id'=>3,'cat'=>'normal']

It is because unset does not re-index the array.

It reindexes. (if we need it)

$result=[];
foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        $found=false;
        if($valueKey === 'cat' && $value === 'vip'){
            $found=true;
            $break;
        } 
        if(!$found) {
           $result[]=$element;
        }
    }
}

Check if space is in a string

Use this:

word = raw_input("Please enter a single word : ")
while True:
    if " " in word:
        word = raw_input("Please enter a single word : ")
    else:
        print "Thanks"
        break

Optimistic vs. Pessimistic locking

One use case for optimistic locking is to have your application use the database to allow one of your threads / hosts to 'claim' a task. This is a technique that has come in handy for me on a regular basis.

The best example I can think of is for a task queue implemented using a database, with multiple threads claiming tasks concurrently. If a task has status 'Available', 'Claimed', 'Completed', a db query can say something like "Set status='Claimed' where status='Available'. If multiple threads try to change the status in this way, all but the first thread will fail because of dirty data.

Note that this is a use case involving only optimistic locking. So as an alternative to saying "Optimistic locking is used when you don't expect many collisions", it can also be used where you expect collisions but want exactly one transaction to succeed.

npm install errors with Error: ENOENT, chmod

I think your compiled coffee script is missing from the published npm package. Try writing a prepublish command.

Location of Django logs and errors

Setup https://docs.djangoproject.com/en/dev/topics/logging/ and then these error's will echo where you point them. By default they tend to go off in the weeds so I always start off with a good logging setup before anything else.

Here is a really good example for a basic setup: https://ian.pizza/b/2013/04/16/getting-started-with-django-logging-in-5-minutes/

Edit: The new link is moved to: https://github.com/ianalexander/ianalexander/blob/master/content/blog/getting-started-with-django-logging-in-5-minutes.html

Git - Ignore node_modules folder everywhere

Add below line to your .gitignore

*/node_modules/*

This will ignore all node_modules in your current directory as well as subdirectory.

IIS: Where can I find the IIS logs?

Enabling Tracing may be a better alternative to the Windows Event Log. This gave me the information I needed to fix my own WebService.

How to define partitioning of DataFrame?

I was able to do this using RDD. But I don't know if this is an acceptable solution for you. Once you have the DF available as an RDD, you can apply repartitionAndSortWithinPartitions to perform custom repartitioning of data.

Here is a sample I used:

class DatePartitioner(partitions: Int) extends Partitioner {

  override def getPartition(key: Any): Int = {
    val start_time: Long = key.asInstanceOf[Long]
    Objects.hash(Array(start_time)) % partitions
  }

  override def numPartitions: Int = partitions
}

myRDD
  .repartitionAndSortWithinPartitions(new DatePartitioner(24))
  .map { v => v._2 }
  .toDF()
  .write.mode(SaveMode.Overwrite)

Force “landscape” orientation mode

It is now possible with the HTML5 webapp manifest. See below.


Original answer:

You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.

You can detect the device orientation with CSS3 media queries like this:

@media screen and (orientation:portrait) {
    // CSS applied when the device is in portrait mode
}

@media screen and (orientation:landscape) {
    // CSS applied when the device is in landscape mode
}

Or by binding a JavaScript orientation change event like this:

document.addEventListener("orientationchange", function(event){
    switch(window.orientation) 
    {  
        case -90: case 90:
            /* Device is in landscape mode */
            break; 
        default:
            /* Device is in portrait mode */
    }
});

Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.

As explained on html5rocks.com, you can now force the orientation mode using a manifest.json file.

You need to include those line into the json file:

{
    "display":      "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
    "orientation":  "landscape", /* Could be "landscape" or "portrait" */
    ...
}

And you need to include the manifest into your html file like this:

<link rel="manifest" href="manifest.json">

Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.

google chrome extension :: console.log() from background page?

To answer your question directly, when you call console.log("something") from the background, this message is logged, to the background page's console. To view it, you may go to chrome://extensions/ and click on that inspect view under your extension.

When you click the popup, it's loaded into the current page, thus the console.log should show log message in the current page.

C# : Passing a Generic Object

You're missing at least a couple of things:

  • Unless you're using reflection, the type arguments need to be known at compile-time, so you can't use

    PrintGeneric<test2.GetType()>
    

    ... although in this case you don't need to anyway

  • PrintGeneric doesn't know anything about T at the moment, so the compiler can't find a member called T

Options:

  • Put a property in the ITest interface, and change PrintGeneric to constrain T:

    public void PrintGeneric<T>(T test) where T : ITest
    {
        Console.WriteLine("Generic : " + test.PropertyFromInterface);
    }
    
  • Put a property in the ITest interface and remove the generics entirely:

    public void PrintGeneric(ITest test)
    {
        Console.WriteLine("Property : " + test.PropertyFromInterface);
    }
    
  • Use dynamic typing instead of generics if you're using C# 4

What is this Javascript "require"?

Alright, so let's first start with making the distinction between Javascript in a web browser, and Javascript on a server (CommonJS and Node).

Javascript is a language traditionally confined to a web browser with a limited global context defined mostly by what came to be known as the Document Object Model (DOM) level 0 (the Netscape Navigator Javascript API).

Server-side Javascript eliminates that restriction and allows Javascript to call into various pieces of native code (like the Postgres library) and open sockets.

Now require() is a special function call defined as part of the CommonJS spec. In node, it resolves libraries and modules in the Node search path, now usually defined as node_modules in the same directory (or the directory of the invoked javascript file) or the system-wide search path.

To try to answer the rest of your question, we need to use a proxy between the code running in the the browser and the database server.

Since we are discussing Node and you are already familiar with how to run a query from there, it would make sense to use Node as that proxy.

As a simple example, we're going to make a URL that returns a few facts about a Beatle, given a name, as JSON.

/* your connection code */

var express = require('express');
var app = express.createServer();
app.get('/beatles/:name', function(req, res) {
    var name = req.params.name || '';
    name = name.replace(/[^a-zA_Z]/, '');
    if (!name.length) {
        res.send({});
    } else {
        var query = client.query('SELECT * FROM BEATLES WHERE name =\''+name+'\' LIMIT 1');
        var data = {};
        query.on('row', function(row) {
            data = row;
            res.send(data);
        });
    };
});
app.listen(80, '127.0.0.1');

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

How to automatically allow blocked content in IE?

You have two options:

  1. Use a Mark of the Web. This will enable a single html page to load. It See here for details. To do this, add the following to your web page below the doctype and above the html tag:

    <!-- saved from url=(0014)about:internet -->

  2. Disable this feature. To do so go to Internet Options->Advanced->Security->Allow Active Content... Then close IE. When you restart IE, it will not give you this error.

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

Random number from a range in a Bash Script

The simplest general way that comes to mind is a perl one-liner:

perl -e 'print int(rand(65000-2000)) + 2000'

You could always just use two numbers:

PORT=$(($RANDOM + ($RANDOM % 2) * 32768))

You still have to clip to your range. It's not a general n-bit random number method, but it'll work for your case, and it's all inside bash.

If you want to be really cute and read from /dev/urandom, you could do this:

od -A n -N 2 -t u2 /dev/urandom

That'll read two bytes and print them as an unsigned int; you still have to do your clipping.

How to run a cronjob every X minutes?

In a crontab file, the fields are:

  • minute of the hour.
  • hour of the day.
  • day of the month.
  • month of the year.
  • day of the week.

So:

10 * * * * blah

means execute blah at 10 minutes past every hour.

If you want every five minutes, use either:

*/5 * * * * blah

meaning every minute but only every fifth one, or:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah

for older cron executables that don't understand the */x notation.

If it still seems to be not working after that, change the command to something like:

date >>/tmp/debug_cron_pax.txt

and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron daemon.

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

Force index use in Oracle

If you think the performance of the query will be better using the index, how could you force the query to use the index?

First you would of course verify that the index gave a better result for returning the complete data set, right?

The index hint is the key here, but the more up to date way of specifying it is with the column naming method rather than the index naming method. In your case you would use:

select /*+ index(table_name (column_having_index)) */ *
from   table_name
where  column_having_index="some value"; 

In more complex cases you might ...

select /*+ index(t (t.column_having_index)) */ *
from   my_owner.table_name t,
       ...
where  t.column_having_index="some value"; 

With regard to composite indexes, I'm not sure that you need to specify all columns, but it seems like a good idea. See the docs here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#autoId18 on multiple index_specs and use of index_combine for multiple indexes, and here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABGFHCH for the specification of multiple columns in the index_spec.

Java ArrayList of Doubles

You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:

new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));

If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:

new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));

Named parameters in JDBC

Plain vanilla JDBC does not support named parameters.

If you are using DB2 then using DB2 classes directly:

  1. Using named parameter markers with PreparedStatement objects
  2. Using named parameter markers with CallableStatement objects

Merging dictionaries in C#

The trivial solution would be:

using System.Collections.Generic;
...
public static Dictionary<TKey, TValue>
    Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)
{
    var result = new Dictionary<TKey, TValue>();
    foreach (var dict in dictionaries)
        foreach (var x in dict)
            result[x.Key] = x.Value;
    return result;
}

Generate ER Diagram from existing MySQL database, created for CakePHP

Use MySQL Workbench. create SQL dump file of your database

Follow below steps:

  1. Click File->Import->Reverse Engineer MySQL Create Script
  2. Click Browse and select your SQL create script.
  3. Make Sure "Place Imported Objects on a diagram" is checked.
  4. Click Execute Button.
  5. You are done.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

I faced similar issue with Spring MVC application. I used < mvc:resources > tag to resolve this issue.

Please find the following link having more details.

http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/

Session variables not working php

Just talked to the hosting service, it was an issue at their end. he said " your account session.save_path was not set as a result issue arise. I set it for you now."

And it works fine after that :)

How to split a line into words separated by one or more spaces in bash?

If you already have your line of text in a variable $LINE, then you should be able to say

for L in $LINE; do
   echo $L;
done

How to adjust layout when soft keyboard appears

Add this line into Manifiest File:

android:windowSoftInputMode="adjustResize"

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

github markdown colspan

You can use HTML tables on GitHub (but not on StackOverflow)

<table>
  <tr>
    <td>One</td>
    <td>Two</td>
  </tr>
  <tr>
    <td colspan="2">Three</td>
  </tr>
</table>

Becomes

HTML table output

Deserializing a JSON file with JavaScriptSerializer()

Create a sub-class User with an id field and screen_name field, like this:

public class User
{
    public string id { get; set; }
    public string screen_name { get; set; }
}

public class Response {

    public string id { get; set; }
    public string text { get; set; }
    public string url { get; set; }
    public string width { get; set; }
    public string height { get; set; }
    public string size { get; set; }
    public string type { get; set; }
    public string timestamp { get; set; }
    public User user { get; set; }
}

Remove Project from Android Studio

The location of SDK is incorrect, the name of one filer is with place this is creating an issue. By removing that space issue will be resolved. old SDK location:

C:\Users\At Tech\AppData\Local\Android\Sdk

new SDK location:

F:\AndroidSDK\Sdk

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

The answer of the user load step worked for me. Sometimes is need edit the file in /etc/mysql/my.cnf add line to client

[client]
password = your_mysql_root_password
port  = 3306
host  = 127.0.0.1
socket  = /var/lib/mysql/mysql.sock

Java character array initializer

Instead of above way u can achieve the solution simply by following method..

public static void main(String args[]) {
    String ini = "Hi there";
    for (int i = 0; i < ini.length(); i++) {
        System.out.print(" " + ini.charAt(i));
    }
}

How to unblock with mysqladmin flush hosts

You should put it into command line in windows.

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

For network login use the following command:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

Extracting the last n characters from a string in R

I used the following code to get the last character of a string.

    substr(output, nchar(stringOfInterest), nchar(stringOfInterest))

You can play with the nchar(stringOfInterest) to figure out how to get last few characters.

Return Boolean Value on SQL Select Statement

Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.

SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)

How do I align a label and a textarea?

Use vertical-align:middle in your CSS.

<table>
    <tr>
       <td style="vertical-align:middle">Description:</td>
       <td><textarea></textarea></td>
    </tr>
</table>

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

Efficient way to remove keys with empty strings from a dict

It can get even shorter than BrenBarn's solution (and more readable I think)

{k: v for k, v in metadata.items() if v}

Tested with Python 2.7.3.

Iterate through a HashMap

for (Map.Entry<String, String> item : hashMap.entrySet()) {
    String key = item.getKey();
    String value = item.getValue();
}

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

Count the number of occurrences of each letter in string

You can use the following code.

main()
{
    int i = 0,j=0,count[26]={0};
    char ch = 97;
    char string[100]="Hello how are you buddy ?";
    for (i = 0; i < 100; i++)
    {
        for(j=0;j<26;j++)
            {
            if (tolower(string[i]) == (ch+j))
                {
                    count[j]++;
                }
        }
    }
    for(j=0;j<26;j++)
        {

            printf("\n%c -> %d",97+j,count[j]);

    }

}

Hope this helps.

How to obtain the last path segment of a URI

If you are using Java 8 and you want the last segment in a file path you can do.

Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();

If you have a url such as http://base_path/some_segment/id you can do.

final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

Calculate the display width of a string in Java

I personally was searching for something to let me compute the multiline string area, so I could determine if given area is big enough to print the string - with preserving specific font.

private static Hashtable hash = new Hashtable();
private Font font;
private LineBreakMeasurer lineBreakMeasurer;
private int start, end;

public PixelLengthCheck(Font font) {
    this.font = font;
}

public boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {
    AttributedString attributedString = new AttributedString(textToMeasure, hash);
    attributedString.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator attributedCharacterIterator =
            attributedString.getIterator();
    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();

    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
            new FontRenderContext(null, false, false));

    float width = (float) areaToFit.width;
    float height = 0;
    lineBreakMeasurer.setPosition(start);

    while (lineBreakMeasurer.getPosition() < end) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
        height += textLayout.getAscent();
        height += textLayout.getDescent() + textLayout.getLeading();
    }

    boolean res = height <= areaToFit.getHeight();

    return res;
}

SQL Server - INNER JOIN WITH DISTINCT

select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;

hope this helps

Navigation bar show/hide

Here is a very quick and simple solution:

self.navigationController.hidesBarsOnTap = YES;

This will work on single tap instead of double tap. Also it will change the behavior for the navigation controller even after pushing or popping the current view controller.

You can always modify this behavior in your controller within the viewWillAppear: and viewWillDisappear: actions if you would like to set the behavior only for a single view controller.

Here is the documentation:

Set CFLAGS and CXXFLAGS options using CMake

On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")

It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.

Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS

Temporarily switch working copy to a specific Git commit

In addition to the other answers here showing you how to git checkout <the-hash-you-want> it's worth knowing you can switch back to where you were using:

git checkout @{-1}

This is often more convenient than:

git checkout what-was-that-original-branch-called-again-question-mark

As you might anticipate, git checkout @{-2} will take you back to the branch you were at two git checkouts ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.


Sadly for productivity, git checkout @{1} does not take you to the branch you will be on in future, which is a shame.

WCF service startup error "This collection already contains an address with scheme http"

In my case root cause of this issue was multiple http bindings defined at parent web site i.e. InetMgr->Sites->Mysite->properties->EditBindings. I deleted one http binding which was not required and problem got resolved.

Extract regression coefficient values

The package broom comes in handy here (it uses the "tidy" format).

tidy(mg) will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).

Example from broom's github repo:

lmfit <- lm(mpg ~ wt, mtcars)
require(broom)    
tidy(lmfit)

      term estimate std.error statistic   p.value
1 (Intercept)   37.285   1.8776    19.858 8.242e-19
2          wt   -5.344   0.5591    -9.559 1.294e-10

is.data.frame(tidy(lmfit))
[1] TRUE

ActionLink htmlAttributes

@Html.ActionLink("display name", "action", "Contorller"
    new { id = 1 },Html Attribute=new {Attribute1="value"})

Proper way to make HTML nested list?

I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.

Why javascript getTime() is not a function?

For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.

I was facing this error because I tried to compare two dates using the following Method

var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator

However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.

Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime() method was simply not added to the prototype.

Solution

In this case, recreating a date-Object based on your dates will fix the issue.

var res = new Date(dat1).getTime() > new Date(dat2).getTime()

Edit:

I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.

The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.

class Details {
    description: string;
    date: Date;
    score: number;
    approved: boolean;

    constructor(data: any) {
      Object.assign(this, data);
    }
}

and to perform the mapping:

public getDetails(id: number): Promise<Details> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details/${id}`)
               .map(response => new Details(response.json()))
               .toPromise();
}

for arrays use:

public getDetails(): Promise<Details[]> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details`)
               .map(response => {
                   const array = JSON.parse(response.json()) as any[];
                   const details = array.map(data => new Details(data));
                   return details;
               })
               .toPromise();
}

For credits and further information about this topic follow the link.

How to run Java program in terminal with external library JAR

  1. you can set your classpath in the in the environment variabl CLASSPATH. in linux, you can add like CLASSPATH=.:/full/path/to/the/Jars, for example ..........src/external and just run in side ......src/Report/

Javac Reporter.java

java Reporter

Similarily, you can set it in windows environment variables. for example, in Win7

Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila

How to print (using cout) a number in binary form?

If you want to display the bit representation of any object, not just an integer, remember to reinterpret as a char array first, then you can print the contents of that array, as hex, or even as binary (via bitset):

#include <iostream>
#include <bitset>
#include <climits>

template<typename T>
void show_binrep(const T& a)
{
    const char* beg = reinterpret_cast<const char*>(&a);
    const char* end = beg + sizeof(a);
    while(beg != end)
        std::cout << std::bitset<CHAR_BIT>(*beg++) << ' ';
    std::cout << '\n';
}
int main()
{
    char a, b;
    short c;
    a = -58;
    c = -315;
    b = a >> 3;
    show_binrep(a);
    show_binrep(b);
    show_binrep(c);
    float f = 3.14;
    show_binrep(f);
}

Note that most common systems are little-endian, so the output of show_binrep(c) is not the 1111111 011000101 you expect, because that's not how it's stored in memory. If you're looking for value representation in binary, then a simple cout << bitset<16>(c) works.

How do I convert a number to a numeric, comma-separated formatted string?

remove the commas with a replace and convert:

CONVERT(INT,REPLACE([varName],',',''))

where varName is the name of the variable that has numeric values in it with commas

Check if string begins with something?

Have a look at JavaScript substring() method.

How to change the minSdkVersion of a project?

Create a new AVD with the AVD Manager and set the Target to API Level 7. Try running your application with that AVD. Additionally, make sure that your min sdk in your Manifest file is at least set to 7.

Use JavaScript to place cursor at end of text in text input element

While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.

The solution that works cross browser and for all input types is rather simple:

  • get and store the value of input in a variable
  • focus the input
  • set the value of input to the stored value

That way the cursor is at the end of the input element.
So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):

$('.foo').click(function() {
    element_selector = $(this).attr('data-focus-element');
    $focus = $(element_selector);
    value = $focus.val();
    $focus.focus();
    $focus.val(value);
});

Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.

How to return first 5 objects of Array in Swift?

The Prefix function is definitely the most efficient way of solving this problem, but you can also use for-in loops like the following:

let array = [1,2,3,4,5,6,7,8,9]
let maxNum = 5
var iterationNumber = 0
var firstNumbers = [Int()]
if array.count > maxNum{
  for i in array{
    iterationNumber += 1
    if iterationNumber <= maxNum{
      firstNumbers.append(i)
    }
  }
  firstNumbers.remove(at: 0)
  print(firstNumbers)
} else {
  print("There were not \(maxNum) items in the array.")
}

This solution takes up many lines of code but checks to see if there are enough items in the array to carry out the program, then continues and solves the problem. This solution uses many basic functions including array.count, which returns the amount of items in the array, not the position of last item in the array. It also uses array.append, which adds things onto the end of the array. Lastly, it uses array.remove, which removes the array's item that has a specified position.

I have tested it it and it works for at least swift 5.

Execution failed app:processDebugResources Android Studio

This worked for me just by restarting android studio 2 times :D. I'm using Android Studio 2.1.

Typescript Type 'string' is not assignable to type

Typescript 3.4 introduces the new 'const' assertion

You can now prevent literal types (eg. 'orange' or 'red') being 'widened' to type string with a so-called const assertion.

You will be able to do:

let fruit = 'orange' as const;  // or...
let fruit = <const> 'orange';

And then it won't turn itself into a string anymore - which is the root of the problem in the question.

/** and /* in Java Comments

The first is Javadoc comments. They can be processed by the javadoc tool to generate the API documentation for your classes. The second is a normal block comment.

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

Squash the first two commits in Git?

You could use rebase interactive to modify the last two commits before they've been pushed to a remote

git rebase HEAD^^ -i

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

The accepted answer seems not adequate in several situations.

To check whether the localStorage or sessionStorage are supported, I use the following snippet from MDN.

function storageAvailable(type) {
    var storage;
    try {
        storage = window[type];
        var x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return e instanceof DOMException && (
            // everything except Firefox
            e.code === 22 ||
            // Firefox
            e.code === 1014 ||
            // test name field too, because code might not be present
            // everything except Firefox
            e.name === 'QuotaExceededError' ||
            // Firefox
            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
            // acknowledge QuotaExceededError only if there's something already stored
            (storage && storage.length !== 0);
    }
}

Use this snippet like this, and fallback to, for example, using cookie:

if (storageAvailable('localStorage')) {
  // Yippee! We can use localStorage awesomeness
}
else {
  // Too bad, no localStorage for us
  document.cookie = key + "=" + encodeURIComponent(value) + expires + "; path=/";
}

I have made the fallbackstorage package which uses this snippet to check for the storage availability and fallback to a manually implemented MemoryStorage.

import {getSafeStorage} from 'fallbackstorage'

getSafeStorage().setItem('test', '1') // always work

ORA-01031: insufficient privileges when selecting view

Q. When is the "with grant option" required ?

A. when you have a view executed from a third schema.

Example: schema DSDSW has a view called view_name

a) that view selects from a table in another schema  (FDR.balance)
b) a third shema  X_WORK  tries to select  from that view

Typical grants: grant select on dsdw.view_name to dsdw_select_role; grant dsdw_select_role to fdr;

But: fdr gets select count(*) from dsdw.view_name; ERROR at line 1: ORA-01031: insufficient privileges

issue the grant:

grant select on fdr.balance to dsdw with grant option;

now fdr: select count(*) from dsdw.view_name; 5 rows

Passing a Bundle on startActivity()?

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);


Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key)

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

How to create a TextArea in Android

Use TextView inside a ScrollView to display messages with any no.of lines. User can't edit the text in this view as in EditText.

I think this is good for your requirement. Try it once.

You can change the default color and text size in XML file only if you want to fix them as below:

<TextView 
    android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="100px"
    android:textColor="#f00"
    android:textSize="25px"
    android:typeface="serif"
    android:textStyle="italic"/>

or if you want to change dynamically whenever you want use as below:

TextView textarea = (TextView)findViewById(R.id.tv);  // tv is id in XML file for TextView
textarea.setTextSize(20);
textarea.setTextColor(Color.rgb(0xff, 0, 0));
textarea.setTypeface(Typeface.SERIF, Typeface.ITALIC);

LaTeX: remove blank page after a \part or \chapter

Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.

Derived from book.cls

\def\@endpart{\vfil\newpage
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}

It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.

\makeatletter
\renewcommand\@endpart{\vfil
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}
\makeatother

Switch statement with returns -- code correctness

I personally tend to lose the breaks. Possibly one source of this habit is from programming window procedures for Windows apps:

LRESULT WindowProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_SIZE:
            return sizeHandler (...);
        case WM_DESTROY:
            return destroyHandler (...);
        ...
    }

    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

I personally find this approach a lot simpler, succinct and flexible than declaring a return variable set by each handler, then returning it at the end. Given this approach, the breaks are redundant and therefore should go - they serve no useful purpose (syntactically or IMO visually) and only bloat the code.

Renaming columns in Pandas

One line or Pipeline solutions

I'll focus on two things:

  1. OP clearly states

    I have the edited column names stored it in a list, but I don't know how to replace the column names.

    I do not want to solve the problem of how to replace '$' or strip the first character off of each column header. OP has already done this step. Instead I want to focus on replacing the existing columns object with a new one given a list of replacement column names.

  2. df.columns = new where new is the list of new columns names is as simple as it gets. The drawback of this approach is that it requires editing the existing dataframe's columns attribute and it isn't done inline. I'll show a few ways to perform this via pipelining without editing the existing dataframe.


Setup 1
To focus on the need to rename of replace column names with a pre-existing list, I'll create a new sample dataframe df with initial column names and unrelated new column names.

df = pd.DataFrame({'Jack': [1, 2], 'Mahesh': [3, 4], 'Xin': [5, 6]})
new = ['x098', 'y765', 'z432']

df

   Jack  Mahesh  Xin
0     1       3    5
1     2       4    6

Solution 1
pd.DataFrame.rename

It has been said already that if you had a dictionary mapping the old column names to new column names, you could use pd.DataFrame.rename.

d = {'Jack': 'x098', 'Mahesh': 'y765', 'Xin': 'z432'}
df.rename(columns=d)

   x098  y765  z432
0     1     3     5
1     2     4     6

However, you can easily create that dictionary and include it in the call to rename. The following takes advantage of the fact that when iterating over df, we iterate over each column name.

# Given just a list of new column names
df.rename(columns=dict(zip(df, new)))

   x098  y765  z432
0     1     3     5
1     2     4     6

This works great if your original column names are unique. But if they are not, then this breaks down.


Setup 2
Non-unique columns

df = pd.DataFrame(
    [[1, 3, 5], [2, 4, 6]],
    columns=['Mahesh', 'Mahesh', 'Xin']
)
new = ['x098', 'y765', 'z432']

df

   Mahesh  Mahesh  Xin
0       1       3    5
1       2       4    6

Solution 2
pd.concat using the keys argument

First, notice what happens when we attempt to use solution 1:

df.rename(columns=dict(zip(df, new)))

   y765  y765  z432
0     1     3     5
1     2     4     6

We didn't map the new list as the column names. We ended up repeating y765. Instead, we can use the keys argument of the pd.concat function while iterating through the columns of df.

pd.concat([c for _, c in df.items()], axis=1, keys=new) 

   x098  y765  z432
0     1     3     5
1     2     4     6

Solution 3
Reconstruct. This should only be used if you have a single dtype for all columns. Otherwise, you'll end up with dtype object for all columns and converting them back requires more dictionary work.

Single dtype

pd.DataFrame(df.values, df.index, new)

   x098  y765  z432
0     1     3     5
1     2     4     6

Mixed dtype

pd.DataFrame(df.values, df.index, new).astype(dict(zip(new, df.dtypes)))

   x098  y765  z432
0     1     3     5
1     2     4     6

Solution 4
This is a gimmicky trick with transpose and set_index. pd.DataFrame.set_index allows us to set an index inline, but there is no corresponding set_columns. So we can transpose, then set_index, and transpose back. However, the same single dtype versus mixed dtype caveat from solution 3 applies here.

Single dtype

df.T.set_index(np.asarray(new)).T

   x098  y765  z432
0     1     3     5
1     2     4     6

Mixed dtype

df.T.set_index(np.asarray(new)).T.astype(dict(zip(new, df.dtypes)))

   x098  y765  z432
0     1     3     5
1     2     4     6

Solution 5
Use a lambda in pd.DataFrame.rename that cycles through each element of new.
In this solution, we pass a lambda that takes x but then ignores it. It also takes a y but doesn't expect it. Instead, an iterator is given as a default value and I can then use that to cycle through one at a time without regard to what the value of x is.

df.rename(columns=lambda x, y=iter(new): next(y))

   x098  y765  z432
0     1     3     5
1     2     4     6

And as pointed out to me by the folks in sopython chat, if I add a * in between x and y, I can protect my y variable. Though, in this context I don't believe it needs protecting. It is still worth mentioning.

df.rename(columns=lambda x, *, y=iter(new): next(y))

   x098  y765  z432
0     1     3     5
1     2     4     6

How to check if variable is array?... or something array-like

If you are using foreach inside a function and you are expecting an array or a Traversable object you can type hint that function with:

function myFunction(array $a)
function myFunction(Traversable)

If you are not using foreach inside a function or you are expecting both you can simply use this construct to check if you can iterate over the variable:

if (is_array($a) or ($a instanceof Traversable))

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

I had this problem and then I ran "apache_start.bat" the error in german told me there was a problem with line 51 in httpd-ssl.conf which is

SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5

What I did was comment lines 163 (ssl module) and 522 (httpd-ssl.conf include) in httpd.conf; I don't need ssl for development, so that solved it for me.

Celery Received unregistered task of type (run example)

I encountered this problem as well, but it is not quite the same, so just FYI. Recent upgrades causes this error message due to this decorator syntax.

ERROR/MainProcess] Received unregistered task of type 'my_server_check'.

@task('my_server_check')

Had to be change to just

@task()

No clue why.

How do I count unique visitors to my site?

I have edited the "Best answer" code, though I found a useful thing that was missing. This is will also track the ip of a user if they are using a Proxy or simply if the server has nginx installed as a proxy reverser.

I added this code to his script at the top of the function:

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

Afther that I edited his code.

Find the line that says the following:

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

and replace it with this:

$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $adresseip. $vst_id;

This will work.

Here is the full code if anything happens:

<?php

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
$adresseip = getRealIpAddr();

// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result

Haven't tested this on the Sql script yet.

Limit length of characters in a regular expression?

Limit the length of characters in a regular expression? ^[a-z]{6,15}$'

Limit length of characters or Numbers in a regular expression? ^[a-z | 0-9]{6,15}$'

Set value to currency in <input type="number" />

Add step="0.01" to the <input type="number" /> parameters:

<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />

Demo: http://jsfiddle.net/uzbjve2u/

But the Dollar sign must stay outside the textbox... every non-numeric or separator charachter will be cropped automatically.

Otherwise you could use a classic textbox, like described here.

SQL command to display history of queries

(Linux) Open your Terminal ctrl+alt+t run the command

 cat ~/.mysql_history

you will get all the previous mysql query history enjoy :)

Binding List<T> to DataGridView in WinForm

After adding new item to persons add:

myGrid.DataSource = null;
myGrid.DataSource = persons;

Scatter plots in Pandas/Pyplot: How to plot by category

You can also try Altair or ggpot which are focused on declarative visualisations.

import numpy as np
import pandas as pd
np.random.seed(1974)

# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))

Altair code

from altair import Chart
c = Chart(df)
c.mark_circle().encode(x='x', y='y', color='label')

enter image description here

ggplot code

from ggplot import *
ggplot(aes(x='x', y='y', color='label'), data=df) +\
geom_point(size=50) +\
theme_bw()

enter image description here

Best implementation for Key Value Pair Data Structure?

Just one thing to add to this (although I do think you have already had your question answered by others). In the interests of extensibility (since we all know it will happen at some point) you may want to check out the Composite Pattern This is ideal for working with "Tree-Like Structures"..

Like I said, I know you are only expecting one sub-level, but this could really be useful for you if you later need to extend ^_^

Disable Proximity Sensor during call

If you have LineageOS 7.1.2 (and have root), try this solution from XDA.


After having tried all the solutions proposed here, none of which worked for my Nexus 4 (mako), I found one on XDA that solves the problem with the Android dialer (but not with other apps). Basically I downloaded a recompiled version of the Dialer.apk file, which simply ignores the proximity sensor and behaves in the same way as the stock dialer app does.

Rename /system/priv-app/Dialer/Dialer.apk to something, then place the downloaded file to that folder. After reboot, I had to install the new dialer manually (simply by clicking on it). So now the original app is replaced, and the calls should be handled by this new one.

[Downside: the new way to answer a call is by pulling down the status bar and clicking 'Answer' (or 'Dismiss'), the usual slider is missing. Also, you'll need to repeat this every time your Android updates to a newer version.]

How do I pull my project from github?

Since you have wiped out your computer and want to checkout your project again, you could start by doing the below initial settings:

git config --global user.name "Your Name"
git config --global user.email [email protected]

Login to your github account, go to the repository you want to clone, and copy the URL under "Clone with HTTPS".

You can clone the remote repository by using HTTPS, even if you had setup SSH the last time:

git clone https://github.com/username/repo-name.git

NOTE:

If you had setup SSH for your remote repository previously, you will have to add that key to the known hosts ssh file on your PC; if you don't and try to do git clone [email protected]:username/repo-name.git, you will see an error similar to the one below:

Cloning into 'repo-name'...
The authenticity of host 'github.com (192.30.255.112)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXDoJWGl7E1IGOCspZomTxdCARLviMw6E5SY8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'github.com,192.30.255.112' (RSA) to the list of known hosts.
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Using HTTPS is a easier than SSH in this case.

SELECT INTO using Oracle

Use:

create table new_table_name 
as
select column_name,[more columns] from Existed_table;

Example:

create table dept
as
select empno, ename from emp;

If the table already exists:

insert into new_tablename select columns_list from Existed_table;

How to write log base(2) in c/c++

All the above answers are correct. This answer of mine below can be helpful if someone needs it. I have seen this requirement in many questions which we are solving using C.

log2 (x) = logy (x) / logy (2)

However, if you are using C language and you want the result in integer, you can use the following:

int result = (int)(floor(log(x) / log(2))) + 1;

Hope this helps.

Rails 4 - Strong Parameters - Nested Objects

As odd as it sound when you want to permit nested attributes you do specify the attributes of nested object within an array. In your case it would be

Update as suggested by @RafaelOliveira

params.require(:measurement)
      .permit(:name, :groundtruth => [:type, :coordinates => []])

On the other hand if you want nested of multiple objects then you wrap it inside a hash… like this

params.require(:foo).permit(:bar, {:baz => [:x, :y]})


Rails actually have pretty good documentation on this: http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

For further clarification, you could look at the implementation of permit and strong_parameters itself: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247