Programs & Examples On #Andromda

AndroMDA is a framework for creating components from case-models. Typically, it is used to generate Java components from UML models.

How to launch Safari and open URL from iOS app

Here one check is required that the url going to be open is able to open by device or simulator or not. Because some times (majority in simulator) i found it causes crashes.

Objective-C

NSURL *url = [NSURL URLWithString:@"some url"];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
   [[UIApplication sharedApplication] openURL:url];
}

Swift 2.0

let url : NSURL = NSURL(string: "some url")!
if UIApplication.sharedApplication().canOpenURL(url) {
     UIApplication.sharedApplication().openURL(url)
}

Swift 4.2

guard let url = URL(string: "some url") else {
    return
}
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

WPF MVVM ComboBox SelectedItem or SelectedValue not working

The type of the SelectedValuePath and the SelectedValue must be EXACTLY the same.

If for example the type of SelectedValuePath is Int16 and the type of the property that binds to SelectedValue is int it will not work.

I spend hours to find that, and that's why I am answering here after so much time the question was asked. Maybe another poor guy like me with the same problem can see it.

Multiple argument IF statement - T-SQL

Your code is valid (with one exception). It is required to have code between BEGIN and END.

Replace

--do some work

with

print ''

I think maybe you saw "END and not "AND"

How to increase time in web.config for executing sql query

I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:

  • DB connection string Connect Timeout
  • httpRuntime executionTimeout
  • basicHttpBinding binding closeTimeout
  • basicHttpBinding binding sendTimeout
  • basicHttpBinding binding receiveTimeout
  • basicHttpBinding binding openTimeout

Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.

I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.

Some code:

namespace ROS.WebService.Common
{
  using System;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;

  public static class DataAccess
  {
    public static string ConnectionString { get; private set; }

    static DataAccess()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
    }

    public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
    {
      using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
      {
        using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
        {
          foreach (var p in sqlParams) cmd.Parameters.Add(p);
          cmd.Connection.Open();
          return cmd.ExecuteNonQuery();
        }
      }
    }
  }
}

Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout

How to assign a select result to a variable?

I just had the same problem and...

declare @userId uniqueidentifier
set @userId = (select top 1 UserId from aspnet_Users)

or even shorter:

declare @userId uniqueidentifier
SELECT TOP 1 @userId = UserId FROM aspnet_Users

Update query PHP MySQL

Update a row or column of a table

$update = "UPDATE daily_patients SET queue_status = 'pending' WHERE doctor_id = $room_no and serial_number= $serial_num";

if ($con->query($update) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $con->error;
}

How to get all elements inside "div" that starts with a known text

var $list = $('#divname input[id^="q17_"]');   // get all input controls with id q17_

// once you have $list you can do whatever you want

var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {

    var id = $(this).prop("id");      // get id
    var cbx = '';
    if ($(this).is(':checkbox') || $(this).is(':radio')) {
        // Need to see if this control is checked
    }
    else { 
        // Nope, not a checked control - so do something else
    }

});

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

Sorry for digging up such an old thread, but there is a major error in the following reasoning:

RAII moves the responsibility of exception safety from the user of the object to the designer (and implementer) of the object. I would argue this is the correct place as you then only need to get exception safety correct once (in the design/implementation). By using finally you need to get exception safety correct every time you use an object.

More often than not, you have to deal with dynamically allocated objects, dynamic numbers of objects etc. Within the try-block, some code might create many objects (how many is determined at runtime) and store pointers to them in a list. Now, this is not an exotic scenario, but very common. In this case, you'd want to write stuff like

void DoStuff(vector<string> input)
{
  list<Foo*> myList;

  try
  {    
    for (int i = 0; i < input.size(); ++i)
    {
      Foo* tmp = new Foo(input[i]);
      if (!tmp)
        throw;

      myList.push_back(tmp);
    }

    DoSomeStuff(myList);
  }
  finally
  {
    while (!myList.empty())
    {
      delete myList.back();
      myList.pop_back();
    }
  }
}

Of course the list itself will be destroyed when going out of scope, but that wouldn't clean up the temporary objects you have created.

Instead, you have to go the ugly route:

void DoStuff(vector<string> input)
{
  list<Foo*> myList;

  try
  {    
    for (int i = 0; i < input.size(); ++i)
    {
      Foo* tmp = new Foo(input[i]);
      if (!tmp)
        throw;

      myList.push_back(tmp);
    }

    DoSomeStuff(myList);
  }
  catch(...)
  {
  }

  while (!myList.empty())
  {
    delete myList.back();
    myList.pop_back();
  }
}

Also: why is it that even managed lanuages provide a finally-block despite resources being deallocated automatically by the garbage collector anyway?

Hint: there's more you can do with "finally" than just memory deallocation.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.

Important note

Your code has a typo in your if statement in not exists(select...) part. Inner select statement has only one where condition while UserName condition is excluded from the not exists due to invalid brace completion. In any case you cave too many closing braces.

I assume this based on the fact that you're using two where conditions in update statement later on in your code.

Let's continue to my answer...

SQL Server 2008+ support MERGE statement

MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).

declare @clockDate date = '08/10/2012';
declare @userName = 'test';

merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
    update
    set BreakOut = getdate()
when not matched then
    insert (ClockDate, UserName, BreakOut)
    values (getdate(), source.UserName, getdate());

Difference between innerText, innerHTML and value?

In terms of MutationObservers, setting innerHTML generates a childList mutation due to the browsers removing the node and then adding a new node with the value of innerHTML.

If you set innerText, a characterData mutation is generated.

React: why child component doesn't update when prop changes

In my case I was updating a loading state that was passed down to a component. Within the Button the props.loading was coming through as expected (switching from false to true) but the ternary that showed a spinner wasn't updating.

I tried adding a key, adding a state that updated with useEffect() etc but none of the other answers worked.

What worked for me was changing this:

setLoading(true);
handleOtherCPUHeavyCode();

To this:

setLoading(true);
setTimeout(() => { handleOtherCPUHeavyCode() }, 1)

I assume it's because the process in handleOtherCPUHeavyCode is pretty heavy and intensive so the app freezes for a second or so. Adding the 1ms timeout allows the loading boolean to update and then the heavy code function can do it's work.

Convert MySQL to SQlite

Not every DB schema can be converted. MySQL is more complex and feature-rich than SQLite. However, if your schema is simple enough, you could dump it into an SQL file and try to import it / load it into an SQLite DB.

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

(Xcode 5) Well, after spending an hour I solved my issue. Even if you re-generate the provisioning file in Xcode 5, you should manually update your account. I only changed provisioning file in the Organizer tab that did not work, Xcode kept build with old provisioning file.

So go to

Xcode > Preferences > Accounts > View Details (Select your account)

Then refresh your provisioning files.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How can I store JavaScript variable output into a PHP variable?

You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).

With that in mind, the closest you could come is to use a PHP variable in your JS:

<?php
$a = 'foo'; // $a now holds PHP string foo
?>
<script>
    var a = '<?php echo $a; ?>'; //outputting string foo in context of JS
                                 //must wrap in quotes so that it is still string foo when JS does execute
                                 //when this DOES execute in the browser, PHP will have already completed all processing and exited
</script>
<?php
//do something else with $a
//JS still hasn't executed at this point
?>

As I stated, in this scenario the PHP (ALL of it) executes FIRST at the server, causing:

  1. a PHP variable $a to be created as string 'foo'
  2. the value of $a to be outputted in context of some JavaScript (which is not currently executing)
  3. more done with PHP's $a
  4. all output, including the JS with the var assignment, is sent to the browser.

As written, this results in the following being sent to the browser for execution (I removed the JS comments for clarity):

<script>
    var a = 'foo';
</script>

Then, and only then, will the JS start executing with its own variable a set to "foo" (at which point PHP is out of the picture).

In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.

Session state can only be used when enableSessionState is set to true either in a configuration

For SharePoint Can find the web config file in C:\inetpub\wwwroot\wss\VirtualDirectories\Sitecollection port number - and Make changes

 <system.web>
  <pages enableSessionState="true" /> 
 </system.web>

and using SharePoint Management Shell Run below Command

   Enable-SPSessionStateService -DefaultProvision

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">&laquo;Go back</a></p>";

Will go back one page.

echo "<p><a href=\"javascript:history.go(-2)\" title=\"Return to previous page\">&laquo;Go back</a></p>";

Will go back two pages.

twitter bootstrap navbar fixed top overlapping site

All you have to do is

@media (min-width: 980px) { body { padding-top: 40px; } } 

Counting the number of non-NaN elements in a numpy ndarray in Python

An alternative, but a bit slower alternative is to do it over indexing.

np.isnan(data)[np.isnan(data) == False].size

In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop 

The double use of np.isnan(data) and the == operator might be a bit overkill and so I posted the answer only for completeness.

How can I generate Javadoc comments in Eclipse?

You mean menu Project -> Generate Javadoc ?

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I accidentally turned on offline mode.

To disable it: in the Maven tool window, click The Toggle Offline Mode button.

enter image description here

How do I check if file exists in Makefile so I can delete it?

Missing a semicolon

if [ -a myApp ];
then
  rm myApp
fi

However, I assume you are checking for existence before deletion to prevent an error message. If so, you can just use rm -f myApp which "forces" delete, i.e. doesn't error out if the file didn't exist.

NPM clean modules

You can just delete the node_module directory

rm -rf node_modules/

How to hide/show div tags using JavaScript?

Use the following code:

function hide {
document.getElementById('div').style.display = "none";
}
function show {
document.getElementById('div').style.display = "block";
}

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

Count the number of all words in a string

The solution 7 does not give the correct result in the case there's just one word. You should not just count the elements in gregexpr's result (which is -1 if there where not matches) but count the elements > 0.

Ergo:

sapply(gregexpr("\\W+", str1), function(x) sum(x>0) ) + 1 

ESLint not working in VS Code?

In my case, I had the .eslintrc.json file inside the .vscode folder. Once I moved it out to the root folder, ESLint started working correctly.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

HQL "is null" And "!= null" on an Oracle column

That is a binary operator in hibernate you should use

is not null

Have a look at 14.10. Expressions

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

I had the same problem and I solved it as follows:

  1. check the node-sass version used in the current project

  2. go to node-sass release: "https://github.com/sass/node-sass/releases/tag/v@.@.@" (put your node-sass version here)

  3. check the Supported Environment table and see if your Node version exist in it

  4. if it is not, downgrade your node version to the latest version existing in the table

I know it's not the perfect solution but I didn't find anything else in my case.

How to drop a PostgreSQL database if there are active connections to it?

In PostgreSQL 9.2 and above, to disconnect everything except your session from the database you are connected to:

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
  AND pid <> pg_backend_pid();

In older versions it's the same, just change pid to procpid. To disconnect from a different database just change current_database() to the name of the database you want to disconnect users from.

You may want to REVOKE the CONNECT right from users of the database before disconnecting users, otherwise users will just keep on reconnecting and you'll never get the chance to drop the DB. See this comment and the question it's associated with, How do I detach all other users from the database.

If you just want to disconnect idle users, see this question.

How to make MySQL handle UTF-8 properly

Set your database collation to UTF-8 then apply table collation to database default.

how to view the contents of a .pem certificate

Use the -printcert command like this:

keytool -printcert -file certificate.pem

What port number does SOAP use?

SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.

Appropriate datatype for holding percent values?

  • Hold as a decimal.
  • Add check constraints if you want to limit the range (e.g. between 0 to 100%; in some cases there may be valid reasons to go beyond 100% or potentially even into the negatives).
  • Treat value 1 as 100%, 0.5 as 50%, etc. This will allow any math operations to function as expected (i.e. as opposed to using value 100 as 100%).
  • Amend precision and scale as required (these are the two values in brackets columnName decimal(precision, scale). Precision says the total number of digits that can be held in the number, scale says how many of those are after the decimal place, so decimal(3,2) is a number which can be represented as #.##; decimal(5,3) would be ##.###.
  • decimal and numeric are essentially the same thing. However decimal is ANSI compliant, so always use that unless told otherwise (e.g. by your company's coding standards).

Example Scenarios

  • For your case (0.00% to 100.00%) you'd want decimal(5,4).
  • For the most common case (0% to 100%) you'd want decimal(3,2).
  • In both of the above, the check constraints would be the same

Example:

if object_id('Demo') is null
create table Demo
    (
        Id bigint not null identity(1,1) constraint pk_Demo primary key
        , Name nvarchar(256) not null constraint uk_Demo unique 
        , SomePercentValue decimal(3,2) constraint chk_Demo_SomePercentValue check (SomePercentValue between 0 and 1)
        , SomePrecisionPercentValue decimal(5,2) constraint chk_Demo_SomePrecisionPercentValue check (SomePrecisionPercentValue between 0 and 1)
    )

Further Reading:

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):

@using (Html.BeginForm("RemoveFromCart", "Cart")) {
                    @Html.Hidden("ProductId", line.Product.ProductID)
                    @Html.HiddenFor(x => x.ReturnUrl)
                    <input class="btn btn-sm btn-warning"
                           type="submit" value="Remove" />
                }

If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".

public ViewResult RemoveFromCart(int productId, string returnUrl){...}

If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.

*Adam Freeman (Apress - Pro ASP.Net MVC 5)

How to use jQuery with Angular?

You could also try to import it with the "InjectionToken". As described here: Use jQuery in Angular/Typescript without a type definition

You can simply inject the jQuery global instance and use it. For this you won't be needing any type definitions or typings.

import { InjectionToken } from '@angular/core';

export const JQ_TOKEN = new InjectionToken('jQuery');

export function jQueryFactory() {
    return window['jQuery'];
}

export const JQUERY_PROVIDER = [
    { provide: JQ_TOKEN, useFactory: jQueryFactory },
];

When set correctly in your app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

import { JQ_TOKEN } from './jQuery.service';

declare let jQuery: Object;

@NgModule({
    imports: [
        BrowserModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        { provide: JQ_TOKEN, useValue: jQuery }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

You can start using it in your components:

import { Component, Inject } from '@angular/core';
import { JQ_TOKEN } from './jQuery.service';

@Component({
    selector: "selector",
    templateUrl: 'somefile.html'
})
export class SomeComponent {
    constructor( @Inject(JQ_TOKEN) private $: any) { }

    somefunction() {
        this.$('...').doSomething();
    }
}

How to implement a FSM - Finite State Machine in Java

The heart of a state machine is the transition table, which takes a state and a symbol (what you're calling an event) to a new state. That's just a two-index array of states. For sanity and type safety, declare the states and symbols as enumerations. I always add a "length" member in some way (language-specific) for checking array bounds. When I've hand-coded FSM's, I format the code in row and column format with whitespace fiddling. The other elements of a state machine are the initial state and the set of accepting states. The most direct implementation of the set of accepting states is an array of booleans indexed by the states. In Java, however, enumerations are classes, and you can specify an argument "accepting" in the declaration for each enumerated value and initialize it in the constructor for the enumeration.

For the machine type, you can write it as a generic class. It would take two type arguments, one for the states and one for the symbols, an array argument for the transition table, a single state for the initial. The only other detail (though it's critical) is that you have to call Enum.ordinal() to get an integer suitable for indexing the transition array, since you there's no syntax for directly declaring an array with a enumeration index (though there ought to be).

To preempt one issue, EnumMap won't work for the transition table, because the key required is a pair of enumeration values, not a single one.

enum State {
    Initial( false ),
    Final( true ),
    Error( false );
    static public final Integer length = 1 + Error.ordinal();

    final boolean accepting;

    State( boolean accepting ) {
        this.accepting = accepting;
    }
}

enum Symbol {
    A, B, C;
    static public final Integer length = 1 + C.ordinal();
}

State transition[][] = {
    //  A               B               C
    {
        State.Initial,  State.Final,    State.Error
    }, {
        State.Final,    State.Initial,  State.Error
    }
};

Is there any way to set environment variables in Visual Studio Code?

I run vscode from my command line by navigating to the folder with the code and running

code .

If you do that all your bash/zsh variables are passed into vs code. You can update your .bashrc/.zshrc file or just do

export KEY=value

before opening it.

how to programmatically fake a touch event to a UIButton?

Swift 3:

self.btn.sendActions(for: .touchUpInside)

PDO closing connection

According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.

Show constraints on tables command

You can use this:

select
    table_name,column_name,referenced_table_name,referenced_column_name
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'my_database' 
    and table_name = 'my_table'

Or for better formatted output use this:

select
    concat(table_name, '.', column_name) as 'foreign key',  
    concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'my_database' 
    and table_name = 'my_table'

Convert string to BigDecimal in java

May I add something. If you are using currency you should use Scale(2), and you should probably figure out a round method.

Comparing object properties in c#

Update on Liviu's answer above - CompareObjects.DifferencesString has been deprecated.

This works well in a unit test:

CompareLogic compareLogic = new CompareLogic();
ComparisonResult result = compareLogic.Compare(object1, object2);
Assert.IsTrue(result.AreEqual);

Jquery- Get the value of first td in table

This should work:

$(".hit").click(function(){    
   var value=$(this).closest('tr').children('td:first').text();
   alert(value);    
});

Explanation:

  • .closest('tr') gets the nearest ancestor that is a <tr> element (so in this case the row where the <a> element is in).
  • .children('td:first') gets all the children of this element, but with the :first selector we reduce it to the first <td> element.
  • .text() gets the text inside the element

As you can see from the other answers, there is more than only one way to do this.

Why is Thread.Sleep so harmful

The problems with calling Thread.Sleep are explained quite succinctly here:

Thread.Sleep has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.

Thread.Sleep(n) means block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more than n milliseconds. The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be. So, Thread.Sleep is pointless for timing.

Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.

The preferred solution: WaitHandles

The most-made-mistake is using Thread.Sleep with a while-construct (demo and answer, nice blog-entry)

EDIT:
I would like to enhance my answer:

We have 2 different use-cases:

  1. We are waiting because we know a specific timespan when we should continue (use Thread.Sleep, System.Threading.Timer or alikes)

  2. We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!

My answer mainly covers use-case 2

Detailed 500 error message, ASP + IIS 7.5

Found it.

http://blogs.iis.net/ksingla/archive/2009/02/16/iis-7-5-updates-to-custom-errors-and-compression.aspx

run cmd as administrator, go to your system32\inetsrv folder and execute:

appcmd.exe set config -section:system.webServer/httpErrors -allowAbsolutePathsWhenDelegated:true

Now I can see detailed asp errors .

C# MessageBox dialog result

Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.

var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
switch (result)
{
    case DialogResult.Yes:
        SaveChanges();
        break;
    case DialogResult.No:
        Rollback();
        break;
    default:
        break;
}

Where can I find "make" program for Mac OS X Lion?

It appears you can install the command line tools without getting Xcode from Downloads for Apple Developers. It required me to login with my apple account.

Alternatively, once you install Xcode from the app store, you might notice the command line tools are not installed by default. Open Xcode, go to preferences, click to the "downloads" tab, and from there you can download and install command line tools.

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

In my case, it was Subversion, TortoiseSVN clinging to those files, so I just clicked on SVN in the Eclipse menu and then disconnect. Worked for me.

How to split a string and assign it to variables

Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

One side note:

The implicit unpacking happens for variadic functions in go:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)

Get file version in PowerShell

Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.

(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version

Truststore and Keystore Definitions

A keystore contains private keys, and the certificates with their corresponding public keys.

A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.

Angular 2 optional route parameter

You can define multiple routes with and without parameter:

@RouteConfig([
    { path: '/user/:id', component: User, name: 'User' },
    { path: '/user', component: User, name: 'Usernew' }
])

and handle the optional parameter in your component:

constructor(params: RouteParams) {
    var paramId = params.get("id");

    if (paramId) {
        ...
    }
}

See also the related github issue: https://github.com/angular/angular/issues/3525

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

The good practice is: Dispatch Groups

dispatch_group_t imageGroup = dispatch_group_create();

dispatch_group_enter(imageGroup);
[uploadImage executeWithCompletion:^(NSURL *result, NSError* error){
    // Image successfully uploaded to S3
    dispatch_group_leave(imageGroup);
}];

dispatch_group_enter(imageGroup);
[setImage executeWithCompletion:^(NSURL *result, NSError* error){
    // Image url updated
    dispatch_group_leave(imageGroup);
}];

dispatch_group_notify(imageGroup,dispatch_get_main_queue(),^{
    // We get here when both tasks are completed
});

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

#temp is materalized and CTE is not.

CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.

The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.

The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).

Preventing console window from closing on Visual Studio C/C++ Console application

You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

and this way the window would not close until you enter data for the a variable.

What is the difference between onBlur and onChange attribute in HTML?

onblur fires when a field loses focus, while onchange fires when that field's value changes. These events will not always occur in the same order, however.

In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE. However, if you press the enter key instead of tab, in Firefox it will fire onblur then onchange, while IE will usually fire in the original order. However, I've seen cases where IE will also fire blur first, so be careful. You can't assume that either the onblur or the onchange will happen before the other one.

Fill DataTable from SQL Server database

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

How to Check whether Session is Expired or not in asp.net

this way many people detect session has expired or not. the below code may help u.

protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

Create a new Ruby on Rails application using MySQL instead of SQLite

$ rails --help 

is always your best friend

usage:

$ rails new APP_PATH[options]

also note that options should be given after the application name

rails and mysql

$ rails new project_name -d mysql

rails and postgresql

$ rails new project_name -d postgresql

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

    String str1,str2;
    Scanner S=new Scanner(System.in);
    str1=S.nextLine();
    System.out.println(str1);
    str2=S.nextLine();
    str1=str1.concat(str2);
    System.out.println(str1.toLowerCase()); 

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

How to add conditional attribute in Angular 2?

You can use a better approach for someone writing HTML for an already existing scss.
html

[attr.role]="<boolean>"

scss

[role = "true"] { ... }

That way you don't need to <boolean> ? true : null every time.

How to Specify Eclipse Proxy Authentication Credentials?

Window ? Preferences ? General ? Network Connections then under "Proxy ByPass" click "Add Host" and enter the link from which you will be getting your third-party plugin; that's it bingo, now it should get the plugin no problem.

How to float 3 divs side by side using CSS?

I prefer this method, floats are poorly supported in older versions of IE (really?...)

.column-left{ position:absolute; left: 0px; width: 33.3%; background: red; }
.column-right{position:absolute; left:66.6%; width: 33.3%; background: green; }
.column-center{ position:absolute; left:33.3%; width: 33.3%; background: yellow; }

UPDATED : Of course, to use this technique and due to the absolute positioning you need to enclose the divs on a container and do a postprocessing to define the height of if, something like this:

jQuery(document).ready(function(){ 
    jQuery('.main').height( Math.max (
        jQuery('.column-left').height(),
        jQuery('.column??-right').height(),
        jQuery('.column-center').height())
    ); 
});

Not the most amazing thing in the world, but at least doesn't break on older IEs.

How to access private data members outside the class without making "friend"s?

In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!

class A {
     int iData;
};

int main ()
{
    A a;
    struct ATwin { int pubData; }; // define a twin class with public members
    reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value

    return 0;
}

Jenkins/Hudson - accessing the current build number?

I've just come across this question too and found out that if anytime the build number gets corrupt because of any error-triggered hard shutdown of the jenkins instance you can set back the build number manually by just editing the file nextBuildNumber (pathToJenkins\jobs\jobxyz\nextBuildNumber) and then make a reload by using the option
Reload Configuration from Disk from the Manage Jenkins View.

How to know user has clicked "X" or the "Close" button?

Assuming you're asking for WinForms, you may use the FormClosing() event. The event FormClosing() is triggered any time a form is to get closed.

To detect if the user clicked either X or your CloseButton, you may get it through the sender object. Try to cast sender as a Button control, and verify perhaps for its name "CloseButton", for instance.

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if (string.Equals((sender as Button).Name, @"CloseButton"))
        // Do something proper to CloseButton.
    else
        // Then assume that X has been clicked and act accordingly.
}

Otherwise, I have never ever needed to differentiate whether X or CloseButton was clicked, as I wanted to perform something specific on the FormClosing event, like closing all MdiChildren before closing the MDIContainerForm, or event checking for unsaved changes. Under these circumstances, we don't need, according to me, to differentiate from either buttons.

Closing by ALT+F4 will also trigger the FormClosing() event, as it sends a message to the Form that says to close. You may cancel the event by setting the

FormClosingEventArgs.Cancel = true. 

In our example, this would translate to be

e.Cancel = true.

Notice the difference between the FormClosing() and the FormClosed() events.

FormClosing occurs when the form received the message to be closed, and verify whether it has something to do before it is closed.

FormClosed occurs when the form is actually closed, so after it is closed.

Does this help?

How to read file from res/raw by name

Here are two approaches you can read raw resources using Kotlin.

You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.

Cheers mate

// R.raw.data_post

this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)

When do I need to use a semicolon vs a slash in Oracle SQL?

I wanted to clarify some more use between the ; and the /

In SQLPLUS:

  1. ; means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
  2. <newline> after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;), it means, store the statement to the buffer but do not run it.
  3. / after entering a statement into the buffer (with a blank <newline>) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.
  4. RUN or R is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement.
  5. / during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"

NOTE: Because ; are used for PL/SQL to end a statement ; cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:

END;
/

How can I format bytes a cell in Excel as KB, MB, GB etc?

Though Excel format conditions will only display 1 of 3 conditions related to number size (they code it as "positive; negative; zero; text" but I prefer to see it as : if isnumber and true; elseif isnumber and false; elseif number; elseif is text )

so to me the best answer is David's as well as Grastveit's comment for other regional format.

Here are the ones I use depending on reports I make.

[<1000000]#,##0.00," KB";[<1000000000]#,##0.00,," MB";#,##0.00,,," GB"

[>999999999999]#,##0.00,,,," TB";[>999999999]#,##0.00,,," GB";#.##0.00,," MB"

[<1000000]# ##0,00 " KB";[<1000000000]# ##0,00  " MB";# ##0,00   " GB"

[>999999999999]# ##0,00    " TB";[>999999999]# ##0,00   " GB";# ##0,00  " MB"

Take your pick!

UILabel - Wordwrap text

In Swift you would do it like this:

    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.numberOfLines = 0

(Note that the way the lineBreakMode constant works is different to in ObjC)

Convert Difference between 2 times into Milliseconds?

Many of the above mentioned solutions might suite different people.
I would like to suggest a slightly modified code than most accepted solution by "MusiGenesis".

DateTime firstTime = DateTime.Parse( TextBox1.Text );
DateTime secondTime = DateTime.Parse( TextBox2.Text );
double milDiff = secondTime.Subtract(firstTime).TotalMilliseconds;

Considerations:
- earlierTime.Subtract(laterTime) you will get a negative value.
- use int milDiff = (int)DateTime.Now.Subtract(StartTime).TotalMilliseconds; if you need integer value instead of double
- Same code can be used to get difference between two Date values and you may get .TotalDays or .TotalHours insteaf of .TotalMilliseconds

Creating custom function in React component

You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:

export default class Archive extends React.Component { 

    saySomething(something) {
        console.log(something);
    }

    handleClick(e) {
        this.saySomething("element clicked");
    }

    componentDidMount() {
        this.saySomething("component did mount");
    }

    render() {
        return <button onClick={this.handleClick.bind(this)} value="Click me" />;
    }
}

How can I get the current user directory?

May be this will be a good solution: taking in account whether this is Vista/Win7 or XP and without using environment variables:

string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
if ( Environment.OSVersion.Version.Major >= 6 ) {
    path = Directory.GetParent(path).ToString();
}

Though using the environment variable is much more clear.

Insert variable values in the middle of a string

Use String.Format

Pre C# 6.0

string data = "FlightA, B,C,D";
var str = String.Format("Hi We have these flights for you: {0}. Which one do you want?", data);

C# 6.0 -- String Interpolation

string data = "FlightA, B,C,D";
var str = $"Hi We have these flights for you: {data}. Which one do you want?";

http://www.informit.com/articles/article.aspx?p=2422807

MVC Return Partial View as JSON

You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

Render a view as a string

PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.

Using the code from the thread above, you would be able to use:

public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
    if (ModelState.IsValid)
    {
        if(Request.IsAjaxRequest())
            return PartialView("NotEvil", model);
        return View(model)
    }
    if(Request.IsAjaxRequest())
    {
        return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
    }
    return View(model);
}

How To Execute SSH Commands Via PHP

I would use phpseclib, a pure PHP SSH implementation. An example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

How to add a search box with icon to the navbar in Bootstrap 3?

You could use the segmented buttons example from Bootstrap 3:

<form action="" class="navbar-form navbar-right">
   <div class="input-group">
       <input type="Search" placeholder="Search..." class="form-control" />
       <div class="input-group-btn">
           <button class="btn btn-info">
           <span class="glyphicon glyphicon-search"></span>
           </button>
       </div>
   </div>
</form>

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

How can I see the raw SQL queries Django is running?

I've made a small snippet you can use:

from django.conf import settings
from django.db import connection


def sql_echo(method, *args, **kwargs):
    settings.DEBUG = True
    result = method(*args, **kwargs)
    for query in connection.queries:
        print(query)
    return result


# HOW TO USE EXAMPLE:
# 
# result = sql_echo(my_method, 'whatever', show=True)

It takes as parameters function (contains sql queryies) to inspect and args, kwargs needed to call that function. As the result it returns what function returns and prints SQL queries in a console.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

one of the approach if you want to get all user_id that satisfies all conditions is:

SELECT DISTINCT user_id FROM table WHERE ancestry IN ('England', '...', '...') GROUP BY user_id HAVING count(*) = <number of conditions that has to be satisfied> 

etc. If you need to take all user_ids that satisfies at least one condition, then you can do

SELECT DISTINCT user_id from table where ancestry IN ('England', 'France', ... , '...')

I am not aware if there is something similar to IN but that joins conditions with AND instead of OR

How to switch to the new browser window, which opens after click on the button?

Just to add to the content ...

To go back to the main window(default window) .

use driver.switchTo().defaultContent();

Remove a file from a Git repository without deleting it from the local filesystem

Ignore the files, remove the files from git, update git (for the removal).

Note : this does not deal with history for sensitive information.

This process definitely takes some undertanding of what is going on with git. Over time, having gained that, I've learned to do processes such as:

1) Ignore the files

  • Add or update the project .gitignore to ignore them - in many cases such as yours, the parent directory, e.g. log/ will be the regex to use.
  • commit and push that .gitignore file change (not sure if push needed mind you, no harm if done).

2) Remove the files from git (only).

  • Now remove the files from git (only) with git remove --cached some_dir/
  • Check that they still remain locally (they should!).

3) Add and commit that change (essentially this is a change to "add" deleting stuff, despite the otherwise confusing "add" command!)

  • git add .
  • git commit -m"removal"

MVC Calling a view from a different controller

To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.

public class CommentsController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}

and

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.

WCF Service, the type provided as the service attribute values…could not be found

I had the same problem. Make sure you include assembly name in Factory property in your .svc file. Maybe you need to clean IIS cache if you had renamed project assembly name.

How can I get the count of line in a file in an efficient way?

This solution is about 3.6× faster than the top rated answer when tested on a file with 13.8 million lines. It simply reads the bytes into a buffer and counts the \n characters. You could play with the buffer size, but on my machine, anything above 8KB didn't make the code faster.

private int countLines(File file) throws IOException {
    int lines = 0;

    FileInputStream fis = new FileInputStream(file);
    byte[] buffer = new byte[BUFFER_SIZE]; // BUFFER_SIZE = 8 * 1024
    int read;

    while ((read = fis.read(buffer)) != -1) {
        for (int i = 0; i < read; i++) {
            if (buffer[i] == '\n') lines++;
        }
    }

    fis.close();

    return lines;
}

Android SeekBar setOnSeekBarChangeListener

Override all methods

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {


    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {


    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {


    }

How to convert byte array to string and vice versa?

This one works for me up to android Q:

You can use the following method to convert o hex string to string

    public static String hexToString(String hex) {
    StringBuilder sb = new StringBuilder();
    char[] hexData = hex.toCharArray();
    for (int count = 0; count < hexData.length - 1; count += 2) {
        int firstDigit = Character.digit(hexData[count], 16);
        int lastDigit = Character.digit(hexData[count + 1], 16);
        int decimal = firstDigit * 16 + lastDigit;
        sb.append((char)decimal);
    }
    return sb.toString();
}

with the following to convert a byte array to a hex string

    public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

Maven: mvn command not found

  1. Run 'path' in command prompt and ensure that the maven installation directory is listed.
  2. Ensure the maven is installed in 'C:\Program Files\Maven'.

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

How to read data from java properties file using Spring Boot

i would suggest the following way:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

SSH SCP Local file to Remote in Terminal Mac Os X

Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.

So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:

Using scp, copy file to a directory in the remote user's account, for example the Documents directory:

scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents

Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:

ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www

What is the difference between UTF-8 and Unicode?

They're not the same thing - UTF-8 is a particular way of encoding Unicode.

There are lots of different encodings you can choose from depending on your application and the data you intend to use. The most common are UTF-8, UTF-16 and UTF-32 s far as I know.

overlay two images in android to set an imageview

You can use the code below to solve the problem or download demo here

Create two functions to handle each.

First, the canvas is drawn and the images are drawn on top of each other from point (0,0)

On button click

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

Function to create an overlay.

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

    Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(firstImage, 0f, 0f, null);
    canvas.drawBitmap(secondImage, 10, 10, null);
    return result;
}

Read more

Adding a custom header to HTTP request using angular.js

Basic authentication using HTTP POST method:

$http({
    method: 'POST',
    url: '/API/authenticate',
    data: 'username=' + username + '&password=' + password + '&email=' + email,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

...and GET method call with header:

$http({
    method: 'GET',
    url: '/books',
    headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

Java for loop multiple variables

change this line

for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){ 

to

for(int a = 0, b = 1; a<cards.length-1, b=a+1; a++){

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

Declaring and initializing a string array in VB.NET

Public Function TestError() As String()
     Return {"foo", "bar"}
End Function

Works fine for me and should work for you, but you may need allow using implicit declarations in your project. I believe this is turning off Options strict in the Compile section of the program settings.

Since you are using VS 2008 (VB.NET 9.0) you have to declare create the new instance

New String() {"foo", "Bar"}

Plotting multiple lines, in different colors, with pandas dataframe

You can use this code to get your desire output

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df

  color  x   y
0   red  0   0
1   red  1   1
2   red  2   2
3  blue  3   9
4  blue  4  16
5  blue  5  25

To plot graph

a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)

plt.show()

Output The output result will look like this

Assign multiple values to array in C

If you are doing these same assignments a lot in your program and want a shortcut, the most straightforward solution might be to just add a function

static inline void set_coordinates(
        GLfloat coordinates[static 8],
        GLfloat c0, GLfloat c1, GLfloat c2, GLfloat c3,
        GLfloat c4, GLfloat c5, GLfloat c6, GLfloat c7)
{
    coordinates[0] = c0;
    coordinates[1] = c1;
    coordinates[2] = c2;
    coordinates[3] = c3;
    coordinates[4] = c4;
    coordinates[5] = c5;
    coordinates[6] = c6;
    coordinates[7] = c7;
}

and then simply call

GLfloat coordinates[8];
// ...
set_coordinates(coordinates, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);

Is it .yaml or .yml?

EDIT:

So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet?

This question could be:

  1. A request for advice; or

  2. A natural expression of that particular emotion which is experienced, while one is observing that some official recommendation is being disregarded—prominently, or even predominantly.

People differ in their predilection for following:

  1. Official advice; or

  2. The preponderance of practice.

Of course, I am unlikely to influence you, regarding which of these two paths you prefer to take!

In what follows (and, in the spirit of science), I merely make an hypothesis, about what (merely as a matter of fact) led the majority of people to use the 3-letter extension. And, I focus on efficient causes.

By this, I do not intend moral exhortation. As you may recall, the fact that something is, does not imply that it should be.

Whatever your personal inclination, be it to follow one path or the other, I do not object.

(End of edit.)

The suggestion, that this preference (in real life usage) was caused by a 8.3 character DOS-ish limitation, IMO is a red herring (erroneous and misleading).

As of August, 2016, the Google search counts for YML and YAML were approximately 6,000,000 and 4,100,000 (to two digits of precision). Furthermore, the "YAML" count was unfairly high because it included mention of the language by name, beyond its use as an extension.

As of July, 2018, the Google's search counts for YML and YAML were approximately 8,100,000 and 4,100,000 (again, to two digits of precision). So, in the last two years, YML has essentially doubled in popularity, but YAML has stayed the same.

Another cultural measure is websites which attempt to explain file extensions. For example, on the FilExt website (as of July, 2018), the page for YAML results in: "Ooops! The FILEXT.com database does not have any information on file extension .YAML."

Whereas, it has an entry for YML, which gives: "YAML...uses a text file and organizes it into a format which is Human-readable. 'database.yml' is a typical example when YAML is used by Ruby on Rails to connect to a database."

As of November, 2014, Wikipedia's article on extension YML still stated that ".yml" is "the file extension for the YAML file format" (emphasis added). Its YAML article lists both extensions, without expressing a preference.

The extension ".yml" is sufficiently clear, is more brief (thus easier to type and recognize), and is much more common.

Of course, both of these extensions could be viewed as abbreviations of a long, possible extension, ".yamlaintmarkuplanguage". But programmers (and users) don't want to type all of that!

Instead, we programmers (and users) want to type as little as possible, and still yet be unambiguous and clear. And we want to see what kind of file it is, as quickly as possible, without reading a longer word. Typing just how many characters accomplishes both of these goals? Isn't the answer three (3)? In other words, YML?

Wikipedia's Category:Filename_extensions page lists entries for .a, .o and .Z. Somehow, it missed .c and .h (used by the C language). These example single-letter extensions help us to see that extensions should be as long as necessary, but no longer (to half-quote Albert Einstein).

Instead, notice that, in general, few extensions start with "Y". Commonly, on the other hand, the letter X is used for a great variety of meanings including "cross," "extensible," "extreme," "variable," etc. (e.g. in XML). So starting with "Y" already conveys much information (in terms of information theory), whereas starting with "X" does not.

Linguistically speaking, therefore, the acronym "XML" has (in a way) only two informative letters ("M" and "L"). "YML", instead, has three informative letters ("M", "L" and "Y"). Indeed, the existing set of acronyms beginning with Y seems extremely small. By implication, this is why a four letter YAML file extension feels greatly overspecified.

Perhaps this is why we see in practice that the "linguistic" pressure (in natural use) to lengthen the abbreviation in question to four (4) characters is weak, and the "linguistic" pressure to shorten this abbreviation to three (3) characters is strong.

Purely as a result, probably, of these factors (and not as an official endorsement), I would note that the YAML.org website's latest news item (from November, 2011) is all about a project written in JavaScript, JS-YAML, which, itself, internally prefers to use the extension ".yml".

The above-mentioned factors may have been the main ones; nevertheless, all the factors (known or unknown) have resulted in the abbreviated, three (3) character extension becoming the one in predominant use for YAML—despite the inventors' preference.

".YML" seems to be the de facto standard. Yet the same inventors were perceptive and correct, about the world's need for a human-readable data language. And we should thank them for providing it.

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

If you are using Ubuntu, Python has already been downloaded on your PC. so, go to -> ctrl + alt + s -> search interpreter -> go to project interpreter than select Python 3.6 in the dropdown menu.

Edit: If there is no Python interpreter in drop-down menu, you should click the gear icon that on the right of the drop-down menu --> add --> select an interpreter.

(on PyCharm 2018.2.4 Community Edition)

How to reset the use/password of jenkins on windows?

I created a new user with "admin" and new password on the installation steps. But after sometime, i wanted to sign in again and that password was showing incorrect, so i used the initial password again to login.

The initial password can be found in the below location:-

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

try this method

JavaScript isset() equivalent

This simple solution works, but not for deep object check.

function isset(str) {
    return window[str] !== undefined;
}

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

Post an object as data using Jquery Ajax

Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType or dataType, like this:

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: data0,

    success: function(data)
    {
        alert('Done');
    }
});

Switch tabs using Selenium WebDriver with Java

With Selenium 2.53.1 using firefox 47.0.1 as the WebDriver in Java: no matter how many tabs I opened, "driver.getWindowHandles()" would only return one handle so it was impossible to switch between tabs.

Once I started using Chrome 51.0, I could get all handles. The following code show how to access multiple drivers and multiple tabs within each driver.

// INITIALIZE TWO DRIVERS (THESE REPRESENT SEPARATE CHROME WINDOWS)
driver1 = new ChromeDriver();
driver2 = new ChromeDriver();

// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
   driver1.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
   // SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
   Thread.sleep(100);

// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs1 = new ArrayList<String> (driver1.getWindowHandles());

// REPEAT FOR THE SECOND DRIVER (SECOND CHROME BROWSER WINDOW)

// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
   driver2.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
   // SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
   Thread.sleep(100);

// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs2 = new ArrayList<String> (driver1.getWindowHandles());

// NOW PERFORM DESIRED TASKS WITH FIRST BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
   driver1.switchTo().window(tabs1.get(ii));
   // LOGIC FOR THAT DRIVER'S CURRENT TAB
}

// PERFORM DESIRED TASKS WITH SECOND BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
   drvier2.switchTo().window(tabs2.get(ii));
   // LOGIC FOR THAT DRIVER'S CURRENT TAB
}

Hopefully that gives you a good idea of how to manipulate multiple tabs in multiple browser windows.

How to send email to multiple recipients using python smtplib?

It works for me.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email protected]'
recipients = '[email protected],[email protected]'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())

When to use Comparable and Comparator

Comparable should be used when you compare instances of the same class.

Comparator can be used to compare instances of different classes.

Comparable is implemented by the class which needs to define a natural ordering for its objects. For example, String implements Comparable.

In case a different sorting order is required, then, implement comparator and define its own way of comparing two instances.

What is the proper way to re-attach detached objects in Hibernate?

I went back to the JavaDoc for org.hibernate.Session and found the following:

Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Any instance returned by a get() or load() method is persistent. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

Thus update(), saveOrUpdate(), lock(), replicate() and merge() are the candidate options.

update(): Will throw an exception if there is a persistent instance with the same identifier.

saveOrUpdate(): Either save or update

lock(): Deprecated

replicate(): Persist the state of the given detached instance, reusing the current identifier value.

merge(): Returns a persistent object with the same identifier. The given instance does not become associated with the session.

Hence, lock() should not be used straightway and based on the functional requirement one or more of them can be chosen.

How to get back to the latest commit after checking out a previous commit?

If you have a branch different than master, one easy way is to check out that branch, then check out master. Voila, you are back at the tip of master. There's probably smarter ways...

Boolean operators && and ||

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.

Add comma to numbers every three digits

2016 Answer:

Javascript has this function, so no need for Jquery.

yournumber.toLocaleString("en");

Multiple conditions in a C 'for' loop

There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to && or ||.

Make new column in Panda dataframe by adding values from other columns

Concerning n00b's comment: "I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"

I was getting the same error. In my case it was because I was trying to perform the column addition on a dataframe that was created like this:

df_b = df[['colA', 'colB', 'colC']]

instead of:

df_c = pd.DataFrame(df, columns=['colA', 'colB', 'colC'])

df_b is a copy of a slice from df
df_c is an new dataframe. So

df_c['colD'] = df['colA'] + df['colB']+ df['colC']

will add the columns and won't raise any warning. Same if .sum(axis=1) is used.

My docker container has no internet

Just adding this here in case someone runs into this issue within a virtualbox container running docker. I reconfigured the virtualbox network to bridged instead of nat, and the problem went away.

How can I make all images of different height and width the same via CSS?

Set height and width parameters in CSS file

_x000D_
_x000D_
.ImageStyle{_x000D_
_x000D_
    max-height: 17vw;_x000D_
    min-height: 17vw;_x000D_
    max-width:17vw;_x000D_
    min-width: 17vw;_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

Apply pandas function to column to create multiple new columns?

I have a more complicated situation, the dataset has a nested structure:

import json
data = '{"TextID":{"0":"0038f0569e","1":"003eb6998d","2":"006da49ea0"},"Summary":{"0":{"Crisis_Level":["c"],"Type":["d"],"Special_Date":["a"]},"1":{"Crisis_Level":["d"],"Type":["a","d"],"Special_Date":["a"]},"2":{"Crisis_Level":["d"],"Type":["a"],"Special_Date":["a"]}}}'
df = pd.DataFrame.from_dict(json.loads(data))
print(df)

output:

        TextID                                            Summary
0  0038f0569e  {'Crisis_Level': ['c'], 'Type': ['d'], 'Specia...
1  003eb6998d  {'Crisis_Level': ['d'], 'Type': ['a', 'd'], 'S...
2  006da49ea0  {'Crisis_Level': ['d'], 'Type': ['a'], 'Specia...

The Summary column contains dict objects, so I use apply with from_dict and stack to extract each row of dict:

df2 = df.apply(
    lambda x: pd.DataFrame.from_dict(x[1], orient='index').stack(), axis=1)
print(df2)

output:

    Crisis_Level Special_Date Type     
                0            0    0    1
0            c            a    d  NaN
1            d            a    a    d
2            d            a    a  NaN

Looks good, but missing the TextID column. To get TextID column back, I've tried three approach:

  1. Modify apply to return multiple columns:

    df_tmp = df.copy()
    
    df_tmp[['TextID', 'Summary']] = df.apply(
        lambda x: pd.Series([x[0], pd.DataFrame.from_dict(x[1], orient='index').stack()]), axis=1)
    print(df_tmp)
    

    output:

        TextID                                            Summary
    0  0038f0569e  Crisis_Level  0    c
    Type          0    d
    Spec...
    1  003eb6998d  Crisis_Level  0    d
    Type          0    a
        ...
    2  006da49ea0  Crisis_Level  0    d
    Type          0    a
    Spec...
    

    But this is not what I want, the Summary structure are flatten.

  2. Use pd.concat:

    df_tmp2 = pd.concat([df['TextID'], df2], axis=1)
    print(df_tmp2)
    

    output:

        TextID (Crisis_Level, 0) (Special_Date, 0) (Type, 0) (Type, 1)
    0  0038f0569e                 c                 a         d       NaN
    1  003eb6998d                 d                 a         a         d
    2  006da49ea0                 d                 a         a       NaN
    

    Looks fine, the MultiIndex column structure are preserved as tuple. But check columns type:

    df_tmp2.columns
    

    output:

    Index(['TextID', ('Crisis_Level', 0), ('Special_Date', 0), ('Type', 0),
        ('Type', 1)],
        dtype='object')
    

    Just as a regular Index class, not MultiIndex class.

  3. use set_index:

    Turn all columns you want to preserve into row index, after some complicated apply function and then reset_index to get columns back:

    df_tmp3 = df.set_index('TextID')
    
    df_tmp3 = df_tmp3.apply(
        lambda x: pd.DataFrame.from_dict(x[0], orient='index').stack(), axis=1)
    
    df_tmp3 = df_tmp3.reset_index(level=0)
    print(df_tmp3)
    

    output:

        TextID Crisis_Level Special_Date Type     
                            0            0    0    1
    0  0038f0569e            c            a    d  NaN
    1  003eb6998d            d            a    a    d
    2  006da49ea0            d            a    a  NaN
    

    Check the type of columns

    df_tmp3.columns
    

    output:

    MultiIndex(levels=[['Crisis_Level', 'Special_Date', 'Type', 'TextID'], [0, 1, '']],
            codes=[[3, 0, 1, 2, 2], [2, 0, 0, 0, 1]])
    

So, If your apply function will return MultiIndex columns, and you want to preserve it, you may want to try the third method.

Calculate difference in keys contained in two Python dictionaries

Based on ghostdog74's answer,

dicta = {"a":1,"d":2}
dictb = {"a":5,"d":2}

for value in dicta.values():
    if not value in dictb.values():
        print value

will print differ value of dicta

Which UUID version to use?

If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.

UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).

To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:

chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)

How to show the last queries executed on MySQL?

If you don't feel like changing your MySQL configuration you could use an SQL profiler like "Neor Profile SQL" http://www.profilesql.com .

Convert Uri to String and String to Uri

This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.

   /**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

Using Git with Visual Studio

I've looked into this a bit at work (both with Subversion and Git). Visual Studio actually has a source control integration API to allow you to integrate third-party source control solutions into Visual Studio. However, most folks don't bother with it for a couple of reasons.

The first is that the API pretty much assumes you are using a locked-checkout workflow. There are a lot of hooks in it that are either way expensive to implement, or just flat out make no sense when you are using the more modern edit-merge workflow.

The second (which is related) is that when you are using the edit-merge workflow that both Subversion and Git encourage, you don't really need Visual Studio integration. The main killer thing about SourceSafe's integration with Visual Studio is that you (and the editor) can tell at a glance which files you own, which must be checked out before you can edit, and which you cannot check out even if you want to. Then it can help you do whatever revision-control voodoo you need to do when you want to edit a file. None of that is even part of a typical Git workflow.

When you are using Git (or SVN typically), your revision-control interactions all take place either before your development session, or after it (once you have everything working and tested). At that point it really isn't too much of a pain to use a different tool. You aren't constantly having to switch back and forth.

C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

Implement an input with a mask

You can also try my implementation, which doesn't have delay after each key press when typing the contents, and has full support for backspace and delete.

You can try it online: https://jsfiddle.net/qmyo6a1h/1/

    <html>
    <style>
    input{
      font-family:'monospace';
    }
    </style>
    <body>
      <input type="text" id="phone" placeholder="123-5678-1234" title="123-5678-1234" input-mask="___-____-____">
      <input type="button" onClick="showValue_phone()" value="Show Value" />
      <input type="text" id="console_phone" />
      <script>
        function InputMask(element) {
          var self = this;

          self.element = element;

          self.mask = element.attributes["input-mask"].nodeValue;

          self.inputBuffer = "";

          self.cursorPosition = 0;

          self.bufferCursorPosition = 0;

          self.dataLength = getDataLength();

          function getDataLength() {
            var ret = 0;

            for (var i = 0; i < self.mask.length; i++) {
              if (self.mask.charAt(i) == "_") {
                ret++;
              }
            }

            return ret;
          }

          self.keyEventHandler = function (obj) {
            obj.preventDefault();

            self.updateBuffer(obj);
            self.manageCursor(obj);
            self.render();
            self.moveCursor();
          }

          self.updateBufferPosition = function () {
            var selectionStart = self.element.selectionStart;
            self.bufferCursorPosition = self.displayPosToBufferPos(selectionStart);
            console.log("self.bufferCursorPosition==" + self.bufferCursorPosition);
          }

          self.onClick = function () {
            self.updateBufferPosition();
          }

          self.updateBuffer = function (obj) {
            if (obj.keyCode == 8) {
              self.inputBuffer = self.inputBuffer.substring(0, self.bufferCursorPosition - 1) + self.inputBuffer.substring(self.bufferCursorPosition);
            }
            else if (obj.keyCode == 46) {
              self.inputBuffer = self.inputBuffer.substring(0, self.bufferCursorPosition) + self.inputBuffer.substring(self.bufferCursorPosition + 1);
            }
            else if (obj.keyCode >= 37 && obj.keyCode <= 40) {
              //do nothing on cursor keys.
            }
            else {
              var selectionStart = self.element.selectionStart;
              var bufferCursorPosition = self.displayPosToBufferPos(selectionStart);
              self.inputBuffer = self.inputBuffer.substring(0, bufferCursorPosition) + String.fromCharCode(obj.which) + self.inputBuffer.substring(bufferCursorPosition);
              if (self.inputBuffer.length > self.dataLength) {
                self.inputBuffer = self.inputBuffer.substring(0, self.dataLength);
              }
            }
          }

          self.manageCursor = function (obj) {
            console.log(obj.keyCode);
            if (obj.keyCode == 8) {
              self.bufferCursorPosition--;
            }
            else if (obj.keyCode == 46) {
              //do nothing on delete key.
            }
            else if (obj.keyCode >= 37 && obj.keyCode <= 40) {
              if (obj.keyCode == 37) {
                self.bufferCursorPosition--;
              }
              else if (obj.keyCode == 39) {
                self.bufferCursorPosition++;
              }
            }
            else {
              var bufferCursorPosition = self.displayPosToBufferPos(self.element.selectionStart);
              self.bufferCursorPosition = bufferCursorPosition + 1;
            }
          }

          self.setCursorByBuffer = function (bufferCursorPosition) {
            var displayCursorPos = self.bufferPosToDisplayPos(bufferCursorPosition);
            self.element.setSelectionRange(displayCursorPos, displayCursorPos);
          }

          self.moveCursor = function () {
            self.setCursorByBuffer(self.bufferCursorPosition);
          }

          self.render = function () {
            var bufferCopy = self.inputBuffer;
            var ret = {
              muskifiedValue: ""
            };

            var lastChar = 0;

            for (var i = 0; i < self.mask.length; i++) {
              if (self.mask.charAt(i) == "_" &&
                bufferCopy) {
                ret.muskifiedValue += bufferCopy.charAt(0);
                bufferCopy = bufferCopy.substr(1);
                lastChar = i;
              }
              else {
                ret.muskifiedValue += self.mask.charAt(i);
              }
            }

            self.element.value = ret.muskifiedValue;

          }

          self.preceedingMaskCharCount = function (displayCursorPos) {
            var lastCharIndex = 0;
            var ret = 0;

            for (var i = 0; i < self.element.value.length; i++) {
              if (self.element.value.charAt(i) == "_"
                || i > displayCursorPos - 1) {
                lastCharIndex = i;
                break;
              }
            }

            if (self.mask.charAt(lastCharIndex - 1) != "_") {
              var i = lastCharIndex - 1;
              while (self.mask.charAt(i) != "_") {
                i--;
                if (i < 0) break;
                ret++;
              }
            }

            return ret;
          }

          self.leadingMaskCharCount = function (displayIndex) {
            var ret = 0;

            for (var i = displayIndex; i >= 0; i--) {
              if (i >= self.mask.length) {
                continue;
              }
              if (self.mask.charAt(i) != "_") {
                ret++;
              }
            }

            return ret;
          }

          self.bufferPosToDisplayPos = function (bufferIndex) {
            var offset = 0;
            var indexInBuffer = 0;

            for (var i = 0; i < self.mask.length; i++) {
              if (indexInBuffer > bufferIndex) {
                break;
              }

              if (self.mask.charAt(i) != "_") {
                offset++;
                continue;
              }

              indexInBuffer++;
            }
            var ret = bufferIndex + offset;

            return ret;
          }

          self.displayPosToBufferPos = function (displayIndex) {
            var offset = 0;
            var indexInBuffer = 0;

            for (var i = 0; i < self.mask.length && i <= displayIndex; i++) {
              if (indexInBuffer >= self.inputBuffer.length) {
                break;
              }

              if (self.mask.charAt(i) != "_") {
                offset++;
                continue;
              }

              indexInBuffer++;
            }

            return displayIndex - offset;
          }

          self.getValue = function () {
            return this.inputBuffer;
          }
          self.element.onkeypress = self.keyEventHandler;
          self.element.onclick = self.onClick;
        }

        function InputMaskManager() {
          var self = this;

          self.instances = {};

          self.add = function (id) {
            var elem = document.getElementById(id);
            var maskInstance = new InputMask(elem);
            self.instances[id] = maskInstance;
          }

          self.getValue = function (id) {
            return self.instances[id].getValue();
          }

          document.onkeydown = function (obj) {
            if (obj.target.attributes["input-mask"]) {
              if (obj.keyCode == 8 ||
                obj.keyCode == 46 ||
                (obj.keyCode >= 37 && obj.keyCode <= 40)) {

                if (obj.keyCode == 8 || obj.keyCode == 46) {
                  obj.preventDefault();
                }

                //needs to broadcast to all instances here:
                var keys = Object.keys(self.instances);
                for (var i = 0; i < keys.length; i++) {
                  if (self.instances[keys[i]].element.id == obj.target.id) {
                    self.instances[keys[i]].keyEventHandler(obj);
                  }
                }
              }
            }
          }
        }

        //Initialize an instance of InputMaskManager and
        //add masker instances by passing in the DOM ids
        //of each HTML counterpart.
        var maskMgr = new InputMaskManager();
        maskMgr.add("phone");

        function showValue_phone() {
          //-------------------------------------------------------__Value_Here_____
          document.getElementById("console_phone").value = maskMgr.getValue("phone");
        }
      </script>
    </body>

    </html>

How to set time to a date object in java

Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")

Docker remove <none> TAG images

docker system prune will do the trick, it removes

- all stopped containers
- all networks not used by at least one container
- all dangling images
- all dangling build cache

But use it, with the caution!

jQuery form input select by id

Why not just:

$('#b').click(function () {
    var val = $(this).val(); 
})

Or if you don't click it (and I guess you won't) and you will use submit button, you can use prev() function either.

Chrome extension: accessing localStorage in content script

Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

One downside is that it is asynchronous.

https://developer.chrome.com/extensions/storage.html

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

import java.lang.*;
import java.io.*;
public class rupee
{
public static void main(String[] args)throws  IOException
{

int len=0,revnum=0,i,dup=0,j=0,k=0;
int gvalue;
 String[] ones={"one","Two","Three","Four","Five","Six","Seven","Eight","Nine","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen",""};
String[] twos={"Ten","Twenty","Thirty","Fourty","fifty","Sixty","Seventy","eighty","Ninety",""};
System.out.println("\n Enter value");
InputStreamReader b=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(b);
gvalue=Integer.parseInt(br.readLine());
if(gvalue==10)

   System.out.println("Ten");

else if(gvalue==100)

  System.out.println("Hundred");

else if(gvalue==1000)
  System.out.println("Thousand");

dup=gvalue;
for(i=0;dup>0;i++)
{
  revnum=revnum*10+dup%10;
  len++;
  dup=dup/10;
}
while(j<len)
{
 if(gvalue<10)
 {
  System.out.println(ones[gvalue-1]);
 }
else if(gvalue>10&&gvalue<=19)
 {
  System.out.println(ones[gvalue-2]);
  break;
 }
else if(gvalue>19&&gvalue<100)
 {
   k=gvalue/10;
   gvalue=gvalue%10;
   System.out.println(twos[k-1]);
 }
else if(gvalue>100&&gvalue<1000)
 {
   k=gvalue/100;
   gvalue=gvalue%100;
   System.out.println(ones[k-1] +"Hundred");
 }
else if(gvalue>=1000&&gvalue<9999)
 {
   k=gvalue/1000;
   gvalue=gvalue%1000;
   System.out.println(ones[k-1]+"Thousand");
}
else if(gvalue>=11000&&gvalue<=19000)
 {
  k=gvalue/1000;
  gvalue=gvalue%1000;
  System.out.println(twos[k-2]+"Thousand");
 }      
else if(gvalue>=12000&&gvalue<100000)
{
 k=gvalue/10000;
     gvalue=gvalue%10000;
 System.out.println(ones[gvalue-1]);
}
else
{
 System.out.println("");
    }
j++;
}
}
}

Align <div> elements side by side

Beware float: left

…there are many ways to align elements side-by-side.

Below are the most common ways to achieve two elements side-by-side…

Demo: View/edit all the below examples on Codepen


Basic styles for all examples below…

Some basic css styles for parent and child elements in these examples:

.parent {
  background: mediumpurple;
  padding: 1rem;
}
.child {
  border: 1px solid indigo;
  padding: 1rem;
}

float:left

Using the float solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)

html

<div class='parent'>
  <div class='child float-left-child'>A</div>
  <div class='child float-left-child'>B</div>
</div>

css

.float-left-child {
  float: left;
}

display:inline-block

html

<div class='parent'>
  <div class='child inline-block-child'>A</div>
  <div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

Note: the space between these two child elements can be removed, by removing the space between the div tags:

display:inline-block (no space)

html

<div class='parent'>
  <div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

display:flex

html

<div class='parent flex-parent'>
  <div class='child flex-child'>A</div>
  <div class='child flex-child'>B</div>
</div>

css

.flex-parent {
  display: flex;
}
.flex-child {
  flex: 1;
}

display:inline-flex

html

<div class='parent inline-flex-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.inline-flex-parent {
  display: inline-flex;
}

display:grid

html

<div class='parent grid-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.grid-parent {
  display: grid;
  grid-template-columns: 1fr 1fr
}

Binding objects defined in code-behind

You can try x:Reference trick

<Window ... x:Name="myWindow"><ListBox ItemsSource="{Binding Items, Source={x:Reference myWindow}}" /></Window>

'Java' is not recognized as an internal or external command

Assume, Java/JDK is installed to the folder: C:\Program Files\Java:

Java/JDK installation path

Follow the steps:

  1. Goto Control Panel ? System ? Advanced system settings ? Advanced ? Environment variables (Win+Pause/Break for System in Control Panel)
  2. In the System variables section click on New…
  3. In Variable name write: JAVA_HOME
  4. In Variable value write: C:\Program Files\Java\bin, press OK: Add JAVA_HOME
  5. In the System variables section double click on Path
  6. Press New and write C:\Program Files\Java\bin, press OK: Add Java Path
  7. In Environment variables window press OK
  8. Restart/Run cmd.exe and write: java --version: Java version CMD

How to extract closed caption transcript from YouTube video?

You can view/copy/download a timecoded xml file of a youtube's closed captions file by accessing

http://video.google.com/timedtext?lang=[LANGUAGE]&v=[YOUTUBE VIDEO IDENTIFIER]

For example http://video.google.com/timedtext?lang=pt&v=WSVKbw7LC2w

NOTE: this method does not download autogenerated closed captions, even if you get the language right (maybe there's a special code for autogenerated languages).

Table scroll with HTML and CSS

Works only in Chrome but it can be adapted to other modern browsers. Table falls back to common table with scroll bar in other brws. Uses CSS3 FLEX property.

http://jsfiddle.net/4SUP8/1/

<table border="1px" class="flexy">
    <caption>Lista Sumnjivih vozila:</caption>
    <thead>
        <tr>
            <td>Opis Sumnje</td>
        <td>Registarski<br>broj vozila</td>
        <td>Datum<br>Vreme</td>
        <td>Brzina<br>(km/h)</td>
        <td>Lokacija</td>
        <td>Status</td>
        <td>Akcija</td>
        </tr>
    </thead>
    <tbody>

        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>

        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>

        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>


        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>

    </tbody>
</table>

Style (CSS 3):

caption {
    display: block;
    line-height: 3em;
    width: 100%;
    -webkit-align-items: stretch;
    border: 1px solid #eee;
}

       .flexy {
            display: block;
            width: 90%;
            border: 1px solid #eee;
            max-height: 320px;
            overflow: auto;
        }

        .flexy thead {
            display: -webkit-flex;
            -webkit-flex-flow: row;
        }

        .flexy thead tr {
            padding-right: 15px;
            display: -webkit-flex;
            width: 100%;
            -webkit-align-items: stretch;
        }

        .flexy tbody {
            display: -webkit-flex;
            height: 100px;
            overflow: auto;
            -webkit-flex-flow: row wrap;
        }
        .flexy tbody tr{
            display: -webkit-flex;
            width: 100%;
        }

        .flexy tr td {
            width: 15%;
        }

How to assign execute permission to a .sh file in windows to be executed in linux

This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.

What are the benefits to marking a field as `readonly` in C#?

I don't believe there are any performance gains from using a readonly field. It's simply a check to ensure that once the object is fully constructed, that field cannot be pointed to a new value.

However "readonly" is very different from other types of read-only semantics because it's enforced at runtime by the CLR. The readonly keyword compiles down to .initonly which is verifiable by the CLR.

The real advantage of this keyword is to generate immutable data structures. Immutable data structures by definition cannot be changed once constructed. This makes it very easy to reason about the behavior of a structure at runtime. For instance, there is no danger of passing an immutable structure to another random portion of code. They can't changed it ever so you can program reliably against that structure.

Here is a good entry about one of the benefits of immutability: Threading

How to modify list entries during for loop?

In short, to do modification on the list while iterating the same list.

list[:] = ["Modify the list" for each_element in list "Condition Check"]

example:

list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]

Default FirebaseApp is not initialized

Make sure to add to your root-level build.gradle

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.3.2'
    }
}

Then, in your module level Gradle file (usually the app/build.gradle), add the 'apply plugin' line at the bottom of the file to enable the Gradle plugin:

apply plugin: 'com.android.application'

android {
  // ...
}

dependencies {
  // ...
  implementation 'com.google.firebase:firebase-core:9.6.1'
  // Getting a "Could not find" error? Make sure you have
  // the latest Google Repository in the Android SDK manager
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

As said in documentation. I had exception as in a question above when forgot to add this in my gradle files.

Dynamic function name in javascript?

If you want to have a dynamic function like the __call function in PHP, you could use Proxies.

const target = {};

const handler = {
  get: function (target, name) {
    return (myArg) => {
      return new Promise(resolve => setTimeout(() => resolve('some' + myArg), 600))
    }
  }
};

const proxy = new Proxy(target, handler);

(async function() {
  const result = await proxy.foo('string')
  console.log('result', result) // 'result somestring' after 600 ms
})()

Calculate difference between 2 date / times in Oracle SQL

You may also try this:

select to_char(to_date('1970-01-01 00:00:00', 'yyyy-mm-dd hh24:mi:ss')+(end_date - start_date),'hh24:mi:ss')
       as run_time from some_table;

It displays time in more human readable form, like: 00:01:34. If you need also days you may simply add DD to last formatting string.

Convert an integer to a byte array

Adding this option for dealing with basic uint8 to byte[] conversion

foo := 255 // 1 - 255
ufoo := uint16(foo) 
far := []byte{0,0}
binary.LittleEndian.PutUint16(far, ufoo)
bar := int(far[0]) // back to int
fmt.Println("foo, far, bar : ",foo,far,bar)

output : foo, far, bar : 255 [255 0] 255

How can I check if a URL exists via PHP?

$url = 'http://google.com';
$not_url = 'stp://google.com';

if (@file_get_contents($url)): echo "Found '$url'!";
else: echo "Can't find '$url'.";
endif;
if (@file_get_contents($not_url)): echo "Found '$not_url!";
else: echo "Can't find '$not_url'.";
endif;

// Found 'http://google.com'!Can't find 'stp://google.com'.

Export to CSV via PHP

pre-made code attached here. you can use it by just copying and pasting in your code:

https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv

How can I get last characters of a string

Last 5

_x000D_
_x000D_
var id="ctl03_Tabs1";_x000D_
var res = id.charAt(id.length-5)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

Last

_x000D_
_x000D_
   _x000D_
 var id="ctl03_Tabs1";_x000D_
 var res = id.charAt(id.length-1)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

Change the content of a div based on selection from dropdown menu

here is a jsfiddle with an example of showing/hiding div's via a select.

HTML:

<div id="option1" class="group">asdf</div>
<div id="option2" class="group">kljh</div>
<div id="option3" class="group">zxcv</div>
<div id="option4" class="group">qwerty</div>
<select id="selectMe">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>
</select>

jQuery:

$(document).ready(function () {
  $('.group').hide();
  $('#option1').show();
  $('#selectMe').change(function () {
    $('.group').hide();
    $('#'+$(this).val()).show();
  })
});

How to set a default row for a query that returns no rows?

One table scan method using a left join from defaults to actuals:

CREATE TABLE [stackoverflow-285666] (k int, val varchar(255))

INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-1')
INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-2')
INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-3')
INSERT  INTO [stackoverflow-285666]
VALUES  (2, '2-1')
INSERT  INTO [stackoverflow-285666]
VALUES  (2, '2-2')

DECLARE @k AS int
SET @k = 0

WHILE @k < 3
    BEGIN
        SELECT  @k AS k
               ,COALESCE(ActualValue, DefaultValue) AS [Value]
        FROM    (
                 SELECT 'DefaultValue' AS DefaultValue
                ) AS Defaults
        LEFT JOIN (
                   SELECT   val AS ActualValue
                   FROM     [stackoverflow-285666]
                   WHERE    k = @k
                  ) AS [Values]
                ON 1 = 1

        SET @k = @k + 1
    END

DROP TABLE [stackoverflow-285666]

Gives output:

k           Value
----------- ------------
0           DefaultValue

k           Value
----------- ------------
1           1-1
1           1-2
1           1-3

k           Value
----------- ------------
2           2-1
2           2-2

Regex for not empty and not whitespace

Most regular expression engines support "counter part" escape sequences. That is, for \s (white-space) there's its counter part \S (non-white-space).

Using this, you can check, if there is at least one non-white-space character with ^\S+$.

PCRE for PHP has several of these escape sequences.

CreateProcess error=2, The system cannot find the file specified

I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

I got an error. But if I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

everything was OK.

Is this a good way to clone an object in ES6?

Following on from the answer by @marcel I found some functions were still missing on the cloned object. e.g.

function MyObject() {
  var methodAValue = null,
      methodBValue = null

  Object.defineProperty(this, "methodA", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    },
    enumerable: true
  });

  Object.defineProperty(this, "methodB", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    }
  });
}

where on MyObject I could clone methodA but methodB was excluded. This occurred because it is missing

enumerable: true

which meant it did not show up in

for(let key in item)

Instead I switched over to

Object.getOwnPropertyNames(item).forEach((key) => {
    ....
  });

which will include non-enumerable keys.

I also found that the prototype (proto) was not cloned. For that I ended up using

if (obj.__proto__) {
  copy.__proto__ = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
}

PS: Frustrating that I could not find a built in function to do this.

Multi-dimensional arraylist or list in C#?

If you want to modify this I'd go with either of the following:

List<string[]> results;

-- or --

List<List<string>> results;

depending on your needs...

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

Where can I find my Facebook application id and secret key?

From 2018:

Go to Settings -> Basic -> App Secret (type your password and you're ready to go).

jQuery - Illegal invocation

In my case (using webpack 4) within an anonymous function, that I was using as a callback.

I had to use window.$.ajax() instead of $.ajax() despite having:

import $ from 'jquery';
window.$ = window.jQuery = $;

Smooth scroll to specific div on click

Ned Rockson basically answers this question. However there is a fatal flaw within his solution. When the targeted element is closer to the bottom of the page than the viewport-height, the function doesn't reach its exit statement and traps the user on the bottom of the page. This is simply solved by limiting the iteration count.

var smoothScroll = function(elementId) {
    var MIN_PIXELS_PER_STEP = 16;
    var MAX_SCROLL_STEPS = 30;
    var target = document.getElementById(elementId);
    var scrollContainer = target;
    do {
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do {
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
                                 (targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);

    var iterations = 0;
    var stepFunc = function() {
        if(iterations > MAX_SCROLL_STEPS){
            return;
        }
        scrollContainer.scrollTop =
            Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);

        if (scrollContainer.scrollTop >= targetY) {
            return;
        }

        window.requestAnimationFrame(stepFunc);
    };

    window.requestAnimationFrame(stepFunc);
}

CASE .. WHEN expression in Oracle SQL

Of course...

select case substr(status,1,1) -- you're only interested in the first character.
            when 'a' then 'Active'
            when 'i' then 'Inactive'
            when 't' then 'Terminated'
       end as statustext
  from stage.tst

However, there's a few worrying things about this schema. Firstly if you have a column that means something, appending a number onto the end it not necessarily the best way to go. Also, depending on the number of status' you have you might want to consider turning this column into a foreign key to a separate table.


Based on your comment you definitely want to turn this into a foreign key. For instance

create table statuses ( -- Not a good table name :-)
    status varchar2(10)
  , description varchar2(10)
  , constraint pk_statuses primary key (status)
    )

create table tst (
    id number
  , status varchar2(10)
  , constraint pk_tst primary key (id)
  , constraint fk_tst foreign key (status) references statuses (status)
    )

Your query then becomes

select a.status, b.description
  from tst a
  left outer join statuses b
    on a.status = b.status

Here's a SQL Fiddle to demonstrate.

How do I read a date in Excel format in Python?

xlrd.xldate_as_tuple is nice, but there's xlrd.xldate.xldate_as_datetime that converts to datetime as well.

import xlrd
wb = xlrd.open_workbook(filename)
xlrd.xldate.xldate_as_datetime(41889, wb.datemode)
=> datetime.datetime(2014, 9, 7, 0, 0)

Button Center CSS

Consider adding this to your CSS to resolve the problem:

.btn {
  width: 20%;
  margin-left: 40%;
  margin-right: 30%;
}

Run javascript function when user finishes typing instead of on key up?

The chosen answer above does not work.

Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.

The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won't happen if your input is empty.

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on keyup, start the countdown
$('#myInput').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#myInput').val()) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

And the same code in vanilla JavaScript solution:

//setup before functions
let typingTimer;                //timer identifier
let doneTypingInterval = 5000;  //time in ms (5 seconds)
let myInput = document.getElementById('myInput');

//on keyup, start the countdown
myInput.addEventListener('keyup', () => {
    clearTimeout(typingTimer);
    if (myInput.value) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

This solution does use ES6 but it's not necessary here. Just replace let with var and the arrow function with a regular function.

What is the maximum possible length of a .NET string?

The max length of a string on my machine is 1,073,741,791.

You see, Strings aren't limited by integer as is commonly believed.

Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed.

Now, here's something you're welcome to try yourself.

Create a new C# console app in Visual Studio and then copy/paste the main method here:

static void Main(string[] args)
{
    Console.WriteLine("String test, by Nicholas John Joseph Taylor");

    Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.");

    Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string.");

    Console.WriteLine("\nThe test starts ...now:\n");

    int Length = 0;

    string s = "";

    int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.

    LoopPoint:

    // Make a string appendage the length of the value of Increment

    StringBuilder StringAppendage = new StringBuilder();

    for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)
    {
        StringAppendage.Append("0");

    }

    // Repeatedly append string appendage until an out of memory exception is thrown.

    try
    {
        if (Increment > 0)
            while (Length < int.MaxValue)
            {
                Length += Increment;

                s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment

                Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));

            }

    }
    catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.
    {
        Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Length -= Increment;

        Increment /= 10;

        Console.WriteLine("After decimation, the value of Increment is " + Increment + ".");

    }
    catch (Exception ex2)
    {
        Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Console.WriteLine("Press a key to continue...");

        Console.ReadKey();

    }

    if (Increment > 0)
    {
        goto LoopPoint;

    }

    Console.WriteLine("Test complete.");

    Console.WriteLine("\nThe max length of a string is " + s.Length + ".");

    Console.WriteLine("\nPress any key to continue.");

    Console.ReadKey();

}

My results were as follows:

String test, by Nicholas John Joseph Taylor

Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then.

This is a quickish test to narrow down results to find the max supported length of a string.

The test starts ...now:

s.Length = 1000000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000.

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete.

The max length of a string is 1073741791.

Press any key to continue.

The max length of a string on my machine is 1073741791.

I'd appreciate it very much if people could post their results as a comment below.

It will be interesting to learn if people get the same or different results.

How to see the changes in a Git commit?

From the man page for git-diff(1):

git diff [options] [<commit>] [--] [<path>…]
git diff [options] --cached [<commit>] [--] [<path>…]
git diff [options] <commit> <commit> [--] [<path>…]
git diff [options] <blob> <blob>
git diff [options] [--no-index] [--] <path> <path>

Use the 3rd one in the middle:

git diff [options] <parent-commit> <commit>

Also from the same man page, at the bottom, in the Examples section:

$ git diff HEAD^ HEAD      <3>

Compare the version before the last commit and the last commit.

Admittedly it's worded a little confusingly, it would be less confusing as

Compare the most recent commit with the commit before it.

Set bootstrap modal body height by percentage

This worked for me

.modal-dialog,
.modal-content {
    /* 80% of window height */
    height: 80%;
}

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;
}

Fiddle: http://jsfiddle.net/mehmetatas/18dpgqpb/2/

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How to access parent Iframe from JavaScript

Once id of iframe is set, you can access iframe from inner document as shown below.

var iframe = parent.document.getElementById(frameElement.id);

Works well in IE, Chrome and FF.

Why is it string.join(list) instead of list.join(string)?

This was discussed in the String methods... finally thread in the Python-Dev achive, and was accepted by Guido. This thread began in Jun 1999, and str.join was included in Python 1.6 which was released in Sep 2000 (and supported Unicode). Python 2.0 (supported str methods including join) was released in Oct 2000.

  • There were four options proposed in this thread:
    • str.join(seq)
    • seq.join(str)
    • seq.reduce(str)
    • join as a built-in function
  • Guido wanted to support not only lists, tuples, but all sequences/iterables.
  • seq.reduce(str) is difficult for new-comers.
  • seq.join(str) introduces unexpected dependency from sequences to str/unicode.
  • join() as a built-in function would support only specific data types. So using a built in namespace is not good. If join() supports many datatypes, creating optimized implementation would be difficult, if implemented using the __add__ method then it's O(n²).
  • The separator string (sep) should not be omitted. Explicit is better than implicit.

There are no other reasons offered in this thread.

Here are some additional thoughts (my own, and my friend's):

  • Unicode support was coming, but it was not final. At that time UTF-8 was the most likely about to replace UCS2/4. To calculate total buffer length of UTF-8 strings it needs to know character coding rule.
  • At that time, Python had already decided on a common sequence interface rule where a user could create a sequence-like (iterable) class. But Python didn't support extending built-in types until 2.2. At that time it was difficult to provide basic iterable class (which is mentioned in another comment).

Guido's decision is recorded in a historical mail, deciding on str.join(seq):

Funny, but it does seem right! Barry, go for it...
--Guido van Rossum

Getting the encoding of a Postgres database

Method 1:

If you're already logged in to the db server, just copy and paste this.

SHOW SERVER_ENCODING;

Result:

  server_encoding 
-----------------  
UTF8

For Client encoding :

 SHOW CLIENT_ENCODING;

Method 2:

Again if you are already logged in, use this to get the list based result

\l 

Getting checkbox values on submit

//retrive check box and gender value
$gender=$row['gender'];
$chkhobby=$row['chkhobby'];
<tr>
    <th>GENDER</th>
    <td>
            Male<input type="radio" name="gender" value="1" <?php echo ($gender== '1') ?  "checked" : "" ;  ?>/>
            Female<input type="radio" name="gender" value="0" <?php echo ($gender== '0') ?  "checked" : "" ;  ?>/>

    </td>
</tr>
<tr>
    <th>Hobbies</th>
    <td>
        <pre><?php //print_r($row);

            $hby = @explode(",",$row['chkhobby']);
            //print_r($hby);
        ?></pre>
        read<input id="check_1" type="checkbox" name="chkhobby[]" value="read" <?php if(in_array("read",$hby)){?> checked="checked"<?php }?>>
        write<input id="check_2" type="checkbox" name="chkhobby[]" value="write" <?php if(in_array("write",$hby)){?> checked="checked"<?php }?>>
        play<input id="check_4" type="checkbox" name="chkhobby[]" value="play" <?php if(in_array("play",$hby)){?> checked="checked"<?php }?>>


    </td>
    </tr>
//update
$gender=$_POST['gender'];
$chkhobby = implode(',', $_POST['chkhobby']);

How to get changes from another branch

You are almost there :)

All that is left is to

git checkout featurex
git merge our-team

This will merge our-team into featurex.

The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

I had a similar problem while moving from Visual Studio 2013 to Visual Studio 2015 on a MVC project.

Deleting the whole .vs solution worked as a charm as Johan J v Rensburg pointed out.

List of special characters for SQL LIKE clause

For SQL Server, from http://msdn.microsoft.com/en-us/library/ms179859.aspx :

  • % Any string of zero or more characters.

    WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title.

  • _ Any single character.

    WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).

  • [ ] Any single character within the specified range ([a-f]) or set ([abcdef]).

    WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.

  • [^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

    WHERE au_lname LIKE 'de[^l]%' all author last names starting with de and where the following letter is not l.

Return the characters after Nth character in a string

If your numbers are always 4 digits long:

=RIGHT(A1,LEN(A1)-5) //'0001 Baseball' returns Baseball

If the numbers are variable (i.e. could be more or less than 4 digits) then:

=RIGHT(A1,LEN(A1)-FIND(" ",A1,1)) //'123456 Baseball’ returns Baseball

Convert JSONArray to String Array

I do post an answer here for the question here that was closed even though the asnwers here helped, but were not sufficient.

So, this is in order to get a json array to a String[] using jsonsimple.

According to the (marvelous) decode examples and docs, JSONArrays are java List, so we can access List methods.

From there, is it possible to transform it to a String[] with the following:

    JSONObject assemblingTags = (JSONObject) obj.get("assembling-tags");
    JSONArray aTagsList = (JSONArray) assemblingTags.get("list");
    String[] tagsList = (String[]) aTagsList.stream().toArray(String[]::new);

Scroll Automatically to the Bottom of the Page

If you want to scroll entire page to the bottom:

var scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;

See the sample on JSFiddle

If you want to scroll an element to the bottom:

function gotoBottom(id){
   var element = document.getElementById(id);
   element.scrollTop = element.scrollHeight - element.clientHeight;
}

And that's how it works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

UPDATE: Latest versions of Chrome (61+) and Firefox does not support scrolling of body, see: https://dev.opera.com/articles/fixing-the-scrolltop-bug/

PostgreSQL unnest() with element number

unnest2() as exercise

Older versions before pg v8.4 need a user-defined unnest(). We can adapt this old function to return elements with an index:

CREATE FUNCTION unnest2(anyarray)
  RETURNS setof record  AS
$BODY$
  SELECT $1[i], i
  FROM   generate_series(array_lower($1,1),
                         array_upper($1,1)) i;
$BODY$ LANGUAGE sql IMMUTABLE;

Spring Boot @autowired does not work, classes in different package

By default, in Spring boot applications, component scan is done inside the package where your main class resides. any bean which is outside the package will not the created and thus gives the above mentioned exception.

Solution: you could either move the beans to the main spring boot class(which is not a good approach) or create a seperate configutation file and import it:

@Import({CustomConfigutation1.class, CustomConfiguration2.class})
@SpringBootpplication
public class BirthdayApplication {

public static void main(String [] args) {
    springApplication.run(BirthdayApplication.class, args );
}

}

Add beans to these CustomConfiguration files.

MySQL direct INSERT INTO with WHERE clause

you can use UPDATE command.

UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id

Editing hosts file to redirect url?

hosts file:

1.2.3.4 google.com

1.2.3.4 - ip of your server.

Run script on the server for redirecting users to url that you want.

Socket send and receive byte array

Try this, it's working for me.

Sender:

byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

dOut.writeInt(message.length); // write length of the message
dOut.write(message);           // write the message


Receiver:

Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());

int length = dIn.readInt();                    // read length of incoming message
if(length>0) {
    byte[] message = new byte[length];
    dIn.readFully(message, 0, message.length); // read the message
}

Rendering raw html with reactjs

I used this library called Parser. It worked for what I needed.

import React, { Component } from 'react';    
import Parser from 'html-react-parser';

class MyComponent extends Component {
  render() {
    <div>{Parser(this.state.message)}</div>
  }
};

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

Try the following steps:

  1. Open Services window (open "run box" and type services.msc).

  2. Looking for SQL services (with SQL prefix).

  3. Start them (if cannot start. Goto step 4).

  4. Right_click to each service -> Properties -> Change to tab "Log on"-> choise log on as "Local ..." -> 0K. Then start SQL services again.

Try Open SQL and connect database.

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

sql query distinct with Row_Number

Question is too old and my answer might not add much but here are my two cents for making query a little useful:

;WITH DistinctRecords AS (
    SELECT  DISTINCT [col1,col2,col3,..] 
    FROM    tableName 
    where   [my condition]
), 
serialize AS (
   SELECT
    ROW_NUMBER() OVER (PARTITION BY [colNameAsNeeded] ORDER BY  [colNameNeeded]) AS Sr,*
    FROM    DistinctRecords 
)
SELECT * FROM serialize 

Usefulness of using two cte's lies in the fact that now you can use serialized record much easily in your query and do count(*) etc very easily.

DistinctRecords will select all distinct records and serialize apply serial numbers to distinct records. after wards you can use final serialized result for your purposes without clutter.

Partition By might not be needed in most cases

Remove querystring from URL

2nd Update: In attempt to provide a comprehensive answer, I am benchmarking the three methods proposed in the various answers.

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
var i;

// Testing the substring method
i = 0;
console.time('10k substring');
while (i < 10000) {
    testURL.substring(0, testURL.indexOf('?'));
    i++;
}
console.timeEnd('10k substring');

// Testing the split method
i = 0;
console.time('10k split');
while (i < 10000) {
    testURL.split('?')[0]; 
    i++;
}
console.timeEnd('10k split');

// Testing the RegEx method
i = 0;
var re = new RegExp("[^?]+");
console.time('10k regex');
while (i < 10000) {
    testURL.match(re)[0]; 
    i++;
}
console.timeEnd('10k regex');

Results in Firefox 3.5.8 on Mac OS X 10.6.2:

10k substring:  16ms
10k split:      25ms
10k regex:      44ms

Results in Chrome 5.0.307.11 on Mac OS X 10.6.2:

10k substring:  14ms
10k split:      20ms
10k regex:      15ms

Note that the substring method is inferior in functionality as it returns a blank string if the URL does not contain a querystring. The other two methods would return the full URL, as expected. However it is interesting to note that the substring method is the fastest, especially in Firefox.


1st UPDATE: Actually the split() method suggested by Robusto is a better solution that the one I suggested earlier, since it will work even when there is no querystring:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.split('?')[0];    // Returns: "/Products/List"

var testURL2 = '/Products/List';
testURL2.split('?')[0];    // Returns: "/Products/List"

Original Answer:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?'));    // Returns: "/Products/List"

Python 3 print without parenthesis

I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.

Try it out on Regexr.com, doesn't work in NP++(?):

find:     (?<=print)( ')(.*)(')
replace: ('$2')

for variables:

(?<=print)( )(.*)(\n)
('$2')\n

for label and variable:

(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n

Disable Required validation attribute under certain circumstances

You can remove all validation off a property with the following in your controller action.

ModelState.Remove<ViewModel>(x => x.SomeProperty);

@Ian's comment regarding MVC5

The following is still possible

ModelState.Remove("PropertyNameInModel");

Bit annoying that you lose the static typing with the updated API. You could achieve something similar to the old way by creating an instance of HTML helper and using NameExtensions Methods.

C# : "A first chance exception of type 'System.InvalidOperationException'"

The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this

HTML to PDF with Node.js

Package

I used html-pdf

Easy to use and allows not only to save pdf as file, but also pipe pdf content to a WriteStream (so I could stream it directly to Google Storage to save there my reports).

Using css + images

It takes css into account. The only problem I faced - it ignored my images. The solution I found was to replace url in src attrribute value by base64, e.g.

<img src="data:image/png;base64,iVBOR...kSuQmCC">

You can do it with your code or to use one of online converters, e.g. https://www.base64-image.de/

Compile valid html code from html fragment + css

  1. I had to get a fragment of my html document (I just appiled .html() method on jQuery selector).
  2. Then I've read the content of the relevant css file.

Using this two values (stored in variables html and css accordingly) I've compiled a valid html code using Template string

var htmlContent = `
<!DOCTYPE html>
<html>
  <head>
    <style>
      ${css}
    </style>
  </head>
  <body id=direct-sellers-bill>
    ${html}
  </body>
</html>`

and passed it to create method of html-pdf.