Programs & Examples On #Asp.net authorization

TypeScript and array reduce function

It's actually the JavaScript array reduce function rather than being something specific to TypeScript.

As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

Here's an example which sums up the values of an array:

_x000D_
_x000D_
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
_x000D_
_x000D_

The snippet should produce 6.

input file appears to be a text format dump. Please use psql

For me when i try to restore from remote host i used

psql -U username -p 5432 -h 10.10.10.1 -d database < db.dump

worked fine. And if not remote just following command worked.

psql -d database < db.dump

What's "this" in JavaScript onclick?

The value of event handler attributes such as onclick should just be JavaScript, without any "javascript:" prefix. The javascript: pseudo-protocol is used in a URL, for example:

<a href="javascript:func(this)">here</a>

You should use the onclick="func(this)" form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol "this" will refer to the window object rather than the <a> element.

How do you copy a record in a SQL table but swap out the unique id of the new row?

Here is how I did it using ASP classic and couldn't quite get it to work with the answers above and I wanted to be able to copy a product in our system to a new product_id and needed it to be able to work even when we add in more columns to the table.

Cn.Execute("CREATE TEMPORARY TABLE temprow AS SELECT * FROM product WHERE product_id = '12345'")
Cn.Execute("UPDATE temprow SET product_id = '34567'")
Cn.Execute("INSERT INTO product SELECT * FROM temprow")
Cn.Execute("DELETE temprow")
Cn.Execute("DROP TABLE temprow")

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is @Ben's answer updated for use with Ember...note you have to use Ember.get because context is passed in as a String.

Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
  var ret = "";
  var newContext = Ember.get(this, context);
  for(var prop in newContext)
  {
    if (newContext.hasOwnProperty(prop)) {
      ret = ret + options.fn({property:prop,value:newContext[prop]});
    }
  }
  return ret;
});

Template:

{{#eachProperty object}}
  {{key}}: {{value}}<br/>
{{/eachProperty }}

Why docker container exits immediately

I added read shell statement at the end. This keeps the main process of the container - startup shell script - running.

How to use System.Net.HttpClient to post a complex type?

This is the code I wound up with, based upon the other answers here. This is for an HttpPost that receives and responds with complex types:

Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(
                       strMyHttpPostURL,
                       new MyComplexObject { Param1 = param1, Param2 = param2}).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
                    //debug:
                    //String s = response.Result.Content.ReadAsStringAsync().Result;
                    MyOtherComplexType moct = (MyOtherComplexType)JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result, typeof(MyOtherComplexType));

Can we overload the main method in Java?

yes we can overload main method. main method must not be static main method.

Removing double quotes from variables in batch file creates problems with CMD environment

Your conclusion (1) sounds wrong. There must be some other factor at play.

The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.

E.g.:

set cmd=%~1
set params=%~2 %~3

"%cmd%" %params%

Note the quotes around %cmd%. Without them, path with spaces won't work.

If you could post your entire batch code, maybe more specific answer could be made.

How to make all controls resize accordingly proportionally when window is maximized?

In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.

Here are some that do not resize their contents (I'm guessing that you are using one or more of these):

StackPanel
WrapPanel
Canvas
TabControl

Here are some that do resize their contents:

Grid
UniformGrid
DockPanel

Therefore, it is almost always preferable to use a Grid instead of a StackPanel unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid to not size its inner controls... it all depends on your Grid.RowDefinition and Grid.ColumnDefinition settings:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
        <RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
        <RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
    </Grid.RowDefinitions>
</Grid>

You can find out more about the Grid control from the Grid Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.

Further resizing can be achieved using the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties. The default value of these properties is Stretch which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.

UPDATE >>>

In response to the questions in your comment:

Use the Grid.RowDefinition and Grid.ColumnDefinition settings to organise a basic structure first... it is common to add Grid controls into the cells of outer Grid controls if need be. You can also use the Grid.ColumnSpan and Grid.RowSpan properties to enable controls to span multiple columns and/or rows of a Grid.

It is most common to have at least one row/column with a Height/Width of "*" which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.

There is no Auto setting that you can use on the controls in the cells, but this is just as well, because we want the Grid to size the controls for us... therefore, we don't want to set the Height or Width of these controls at all.

The point that I made about the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties was just to let you know of their existence... as their default value is already Stretch, you don't generally need to set them explicitly.

The Margin property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin property to suit your needs.

state machines tutorials

I prefer using function pointers over gigantic switch statements, but in contrast to qrdl's answer I normally don't use explicit return codes or transition tables.

Also, in most cases you'll want a mechanism to pass along additional data. Here's an example state machine:

#include <stdio.h>

struct state;
typedef void state_fn(struct state *);

struct state
{
    state_fn * next;
    int i; // data
};

state_fn foo, bar;

void foo(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = bar;
}

void bar(struct state * state)
{
    printf("%s %i\n", __func__, ++state->i);
    state->next = state->i < 10 ? foo : 0;
}

int main(void)
{
    struct state state = { foo, 0 };
    while(state.next) state.next(&state);
}

What is the difference between Cloud Computing and Grid Computing?

There are a lot of good answers to this question already but another way to take a look at it is the cloud (ala Amazon's AWS) is good for interactive use cases and the grid (ala High Performance Computing) is good for batch use cases.

Cloud is interactive in that you can get resources on demand via self service. The code you run on VMs in the cloud, such as the Apache web server, can server clients interactively.

Grid is batch in that you submit jobs to a job queue after obtaining the credentials from some HPC authority to do so. The code you run on the grid waits in that queue until there are sufficient resources to execute it.

There are good use cases for both styles of computing.

How to zip a file using cmd line?

Not exactly zipping, but you can compact files in Windows with the compact command:

compact /c /s:<directory or file>

And to uncompress:

compact /u /s:<directory or file>

NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)

JavaScript isset() equivalent

This is a pretty bulletproof solution for testing if a variable exists :

var setOrNot = typeof variable !== typeof undefined ? true : false;

Unfortunately, you cannot simply encapsulate it in a function.

You might think of doing something like this :

function isset(variable) {
    return typeof variable !== typeof undefined ? true : false;
}

However, this will produce a reference error if variable variable has not been defined, because you cannot pass along a non-existing variable to a function :

Uncaught ReferenceError: foo is not defined

On the other hand, it does allow you to test whether function parameters are undefined :

var a = '5';

var test = function(x, y) {
    console.log(isset(x));
    console.log(isset(y));
};

test(a);

// OUTPUT :
// ------------
// TRUE
// FALSE

Even though no value for y is passed along to function test, our isset function works perfectly in this context, because y is known in function test as an undefined value.

Parse String to Date with Different Format in Java

Convert a string date to java.sql.Date

String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

You can also use this stored procedure if you only want to truncate all tables in a specific schema:

-- =============================================
-- Author:      Ben de Ridder
-- Create date: 20160513
-- Description: Truncate all tables in schema
-- =============================================
CREATE PROCEDURE TruncateAllTablesInSchema
    @schema nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @table nVARCHAR(255)

    DECLARE db_cursor CURSOR FOR 
        select t.name
          from sys.tables t inner join
               sys.schemas s on 
                    t.schema_id=s.schema_id
         where s.name=@schema
         order by 1

    OPEN db_cursor   

    FETCH NEXT FROM db_cursor INTO @table   

    WHILE @@FETCH_STATUS = 0   
    BEGIN   
           declare @sql nvarchar(1000)

           set @sql = 'truncate table [' + @schema + '].[' + @table + ']'

           exec sp_sqlexec @sql

           FETCH NEXT FROM db_cursor INTO @table   
    END   

    CLOSE db_cursor   
    DEALLOCATE db_cursor 

END
GO

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

I had the EXACT same issue as the OP. My configuration and situation were identical. I finally narrowed it down to being an issue in WCFStorm after creating a service reference in a test project in Visual Studio and confirming that the service was working. In Storm you need to click on the "Config" settings option (NOT THE "Client Config"). After clicking on that, click on the "Security" tab on the dialog that pops up. Make sure "Authentication Type" is set to "None" (The default is "Windows Authentication"). Presto, it works! I always test out my methods in WCFStorm as I'm building them out, but have never tried using it to connect to one that has already been set up on SSL. Hope this helps someone!

No templates in Visual Studio 2017

NOTE: this topic is about installation issues with MS project templates.

I came here via a search in Google, I was looking for a missing Template option in Visual Studio 2017 File menu: in VS-2015, it was Export to Template and I used it to add my own standard Project Items.

Meanwhile, I found an answer.. my issue was not related to default templates and it does not need install things. The option Export to Template has been moved to the VS-2017 Project menu !

How to use \n new line in VB msgbox() ...?

This work for me: MessageBox.Show("YourString" & vbcrlf & "YourNewLineString")

Deleting an object in C++

saveLeaves(vec,msh);
I'm assuming takes the msh pointer and puts it inside of vec. Since msh is just a pointer to the memory, if you delete it, it will also get deleted inside of the vector.

Comparing two arrays & get the values which are not common

Look at Compare-Object

Compare-Object $a1 $b1 | ForEach-Object { $_.InputObject }

Or if you would like to know where the object belongs to, then look at SideIndicator:

$a1=@(1,2,3,4,5,8)
$b1=@(1,2,3,4,5,6)
Compare-Object $a1 $b1

Converting a UNIX Timestamp to Formatted Date String

Assuming you are using PHP5.3 then the modern way of handling dates is via the native DateTime class. To get the current time you can just call

$currentTime = new DateTime();

To create a DateTime object from a specific timestamp (i.e. not now)

$currentTime = DateTime::createFromFormat( 'U', $timestamp );

To get a formatted string you can then call

$formattedString = $currentTime->format( 'c' );

See the manual page here

Ruby get object keys as array

Like taro said, keys returns the array of keys of your Hash:

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

You'll find all the different methods available for each class.

If you don't know what you're dealing with:

 puts my_unknown_variable.class.to_s

This will output the class name.

How do I set a checkbox in razor view?

you set AllowRating property to true from your controller or model

      @Html.CheckBoxFor(m => m.AllowRating, new { @checked =Model.AllowRating })

How to call webmethod in Asp.net C#

There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.

Script example:

$.ajax({
    type: "POST",
    url: '/Default.aspx/TestMethod',
    data: '{message: "HAI" }',
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        console.log(data);
    },
    failure: function (response) {
        alert(response.d);
    }
});

WebMethod example:

[WebMethod]
public static string TestMethod(string message)
{
     return "The message" + message;
}

HTML5 form required attribute. Set custom validation message?

It's very simple to control custom messages with the help of the HTML5 oninvalid event

Here is the code:

User ID 
<input id="UserID"  type="text" required 
       oninvalid="this.setCustomValidity('User ID is a must')">

Seconds CountDown Timer

Use Timer for this

   private System.Windows.Forms.Timer timer1; 
   private int counter = 60;
   private void btnStart_Click_1(object sender, EventArgs e)
   {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 1000; // 1 second
        timer1.Start();
        lblCountDown.Text = counter.ToString();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter--;
        if (counter == 0)
            timer1.Stop();
        lblCountDown.Text = counter.ToString();
    }

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

Change below path in httpd.conf file to your setup. This will fix the issue.

Define SRVROOT "C:\Apache24"   
ServerRoot "${SRVROOT}"

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

When you use angular.js for handling events, you should use ng-keydown for preventing pause in developer in chrome.

How can one use multi threading in PHP applications

You could simulate threading. PHP can run background processes via popen (or proc_open). Those processes can be communicated with via stdin and stdout. Of course those processes can themselves be a php program. That is probably as close as you'll get.

What is the Swift equivalent of isEqualToString in Objective-C?

Use == operator instead of isEqual

Comparing Strings

Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.

String Equality

Two String values are considered equal if they contain exactly the same characters in the same order:

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.

For more read official documentation of Swift (search Comparing Strings).

error: request for member '..' in '..' which is of non-class type

I ran into a case where I got that error message and had

Foo foo(Bar());

and was basically trying to pass in a temporary Bar object to the Foo constructor. Turns out the compiler was translating this to

Foo foo(Bar(*)());

that is, a function declaration whose name is foo that returns a Foo that takes in an argument -- a function pointer returning a Bar with 0 arguments. When passing in temporaries like this, better to use Bar{} instead of Bar() to eliminate ambiguity.

Disable submit button when form invalid with AngularJS

If you are using Reactive Forms you can use this:

<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>

Cygwin Make bash command not found

I had the same problem and it was due to several installations of cygwin.

Check the link (the icon) that you click on to start the terminal. In case it does not point to the directory of your updated cygwin installation, you have the wrong installation of cygwin. When updating, double check the location of cygwin, and start exactly this instance of cygwin.

Python interpreter error, x takes no arguments (1 given)

Python implicitly passes the object to method calls, but you need to explicitly declare the parameter for it. This is customarily named self:

def updateVelocity(self):

Set color of TextView span in Android

Here's a Kotlin Extension Function I have for this

    fun TextView.setColouredSpan(word: String, color: Int) {
        val spannableString = SpannableString(text)
        val start = text.indexOf(word)
        val end = text.indexOf(word) + word.length
        try {
            spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text = spannableString
        } catch (e: IndexOutOfBoundsException) {
         println("'$word' was not not found in TextView text")
    }
}

Use it after you have set your text to the TextView like so

private val blueberry by lazy { getColor(R.color.blueberry) }

textViewTip.setColouredSpan("Warning", blueberry)

How do I import modules or install extensions in PostgreSQL 9.1+?

Postgrseql 9.1 provides for a new command CREATE EXTENSION. You should use it to install modules.

Modules provided in 9.1 can be found here.. The include,

adminpack , auth_delay , auto_explain , btree_gin , btree_gist
, chkpass , citext , cube , dblink , dict_int
, dict_xsyn , dummy_seclabel , earthdistance , file_fdw , fuzzystrmatch
, hstore , intagg , intarray , isn , lo
, ltree , oid2name , pageinspect , passwordcheck , pg_archivecleanup
, pgbench , pg_buffercache , pgcrypto , pg_freespacemap , pgrowlocks
, pg_standby , pg_stat_statements , pgstattuple , pg_test_fsync , pg_trgm
, pg_upgrade , seg , sepgsql , spi , sslinfo , tablefunc
, test_parser , tsearch2 , unaccent , uuid-ossp , vacuumlo
, xml2

If for instance you wanted to install earthdistance, simply use this command:

CREATE EXTENSION earthdistance;

If you wanted to install an extension with a hyphen in its name, like uuid-ossp, you need to enclose the extension name in double quotes:

CREATE EXTENSION "uuid-ossp";

Displaying all table names in php from MySQL database

Queries should look like :

SHOW TABLES

SHOW TABLES FROM mydatabase

SHOW TABLES FROM mydatabase LIKE "tab%"

Things from the MySQL documentation in square brackets [] are optional.

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

What is the difference between Sessions and Cookies in PHP?

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.

Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.

Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.

How do C++ class members get initialized if I don't do it explicitly?

First, let me explain what a mem-initializer-list is. A mem-initializer-list is a comma-separated list of mem-initializers, where each mem-initializer is a member name followed by (, followed by an expression-list, followed by a ). The expression-list is how the member is constructed. For example, in

static const char s_str[] = "bodacydo";
class Example
{
private:
    int *ptr;
    string name;
    string *pname;
    string &rname;
    const string &crname;
    int age;

public:
    Example()
        : name(s_str, s_str + 8), rname(name), crname(name), age(-4)
    {
    }
};

the mem-initializer-list of the user-supplied, no-arguments constructor is name(s_str, s_str + 8), rname(name), crname(name), age(-4). This mem-initializer-list means that the name member is initialized by the std::string constructor that takes two input iterators, the rname member is initialized with a reference to name, the crname member is initialized with a const-reference to name, and the age member is initialized with the value -4.

Each constructor has its own mem-initializer-list, and members can only be initialized in a prescribed order (basically the order in which the members are declared in the class). Thus, the members of Example can only be initialized in the order: ptr, name, pname, rname, crname, and age.

When you do not specify a mem-initializer of a member, the C++ standard says:

If the entity is a nonstatic data member ... of class type ..., the entity is default-initialized (8.5). ... Otherwise, the entity is not initialized.

Here, because name is a nonstatic data member of class type, it is default-initialized if no initializer for name was specified in the mem-initializer-list. All other members of Example do not have class type, so they are not initialized.

When the standard says that they are not initialized, this means that they can have any value. Thus, because the above code did not initialize pname, it could be anything.

Note that you still have to follow other rules, such as the rule that references must always be initialized. It is a compiler error to not initialize references.

WMI "installed" query different from add/remove programs list?

In order to build a more-or-less reliable list of applications that appear in the "Programs and Feautres" in the Control Panel, you have to consider that not all applications were installed using MSI. WMI only provides the ones installed with MSI.

Here is a short summary of what I've found out:

MSI applications always have a Product Code (GUID) subkey under HKLM\...\Uninstall and/or under HKLM\...\Installer\UserData\S-1-5-18\Products. In addition, they may have a key that looks like HKLM\...\Uninstall\NotAGuid.

Non-MSI applications do not have a product code, and therefore have keys like HKLM\...\Uninstall\NotAGuid or HKCU\...\Uninstall\NotAGuid.

C++/CLI Converting from System::String^ to std::string

I spent hours trying to convert a windows form listbox ToString value to a standard string so that I could use it with fstream to output to a txt file. My Visual Studio didn't come with marshal header files which several answers I found said to use. After so much trial and error I finally found a solution to the problem that just uses System::Runtime::InteropServices:

void MarshalString ( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars = 
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

//this is the code to use the function:
scheduleBox->SetSelected(0,true);
string a = "test";
String ^ c = gcnew String(scheduleBox->SelectedItem->ToString());
MarshalString(c, a);
filestream << a;

And here is the MSDN page with the example: http://msdn.microsoft.com/en-us/library/1b4az623(v=vs.80).aspx

I know it's a pretty simple solution but this took me HOURS of troubleshooting and visiting several forums to finally find something that worked.

How to use GROUP_CONCAT in a CONCAT in MySQL

IF OBJECT_ID('master..test') is not null Drop table test

CREATE TABLE test (ID INTEGER, NAME VARCHAR (50), VALUE INTEGER );
INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);

select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = _a.name for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc

My table name is test , and for concatination I use the For XML Path('') syntax. The stuff function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )

character_expression Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

start Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.

length Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.

HTTP Error 500.19 and error code : 0x80070021

Got precisely the same error and came to this question. As @SpaceBison mentioned in comments, this answer describes the solution - https://stackoverflow.com/a/12867753/404099. I spotted it too late and it misses some steps. This is what worked for me:

Windows Server 2012, IIS 8.5. Should work for other versions too.

  • Go to server manager, click add roles and features
  • In the roles section choose: Web Server
    • Under Security sub-section choose everything (I excluded digest, IP restrictions and URL authorization as we don't use them)
    • Under Application Development choose .NET Extensibility 4.5, ASP.NET 4.5 and both ISAPI entries
  • In the features section choose: NET 3.5, .NET 4.5, ASP.NET 4.5
  • In the web server section choose: Web Server (all), Management Tools (IIS Management Console and Management Service), Windows Authentication - if you are using any of it

Simulating Button click in javascript

try this

document.getElementById("datapicker").addEventListener("submit", function())

How do I find the time difference between two datetime objects in python?

To just find the number of days: timedelta has a 'days' attribute. You can simply query that.

>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13

Removing duplicate rows in Notepad++

None worked for me.

A solution is:

Replace

^(.*)\s+(\r?\n\1\s+)+$

with

\1

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object and test the $_.CreationTime:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
    Where-Object { $_.CreationTime -ge "03/01/2013" -and $_.CreationTime -le "03/31/2013" }

How can I validate google reCAPTCHA v2 using javascript/jQuery?

_x000D_
_x000D_
if (typeof grecaptcha !== 'undefined' && $("#dvCaptcha").length > 0 && $("#dvCaptcha").html() == "") {_x000D_
                dvcontainer = grecaptcha.render('dvCaptcha', {_x000D_
                    'sitekey': ReCaptchSiteKey,_x000D_
                    'expired-callback' :function (response){_x000D_
                        recaptch.reset();_x000D_
                        c_responce = null;_x000D_
                    },_x000D_
                    'callback': function (response) {_x000D_
                        $("[id*=txtCaptcha]").val(c_responce);_x000D_
                        $("[id*=rfvCaptcha]").hide();_x000D_
                        c_responce = response;_x000D_
_x000D_
                    }_x000D_
                });_x000D_
            }_x000D_
            _x000D_
            function callonanybuttonClick(){_x000D_
             _x000D_
                if (c_responce == null) {_x000D_
                    $("[id*=txtCaptcha]").val("");_x000D_
                    $("[id*=rfvCaptcha]").show();_x000D_
_x000D_
                    return false;_x000D_
                }_x000D_
                else {_x000D_
                    $("[id*=txtCaptcha]").val(c_responce);_x000D_
                    $("[id*=rfvCaptcha]").hide();_x000D_
                    return true;_x000D_
                }_x000D_
            _x000D_
}
_x000D_
<div id="dvCaptcha" class="captchdiv"></div>_x000D_
    <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />_x000D_
    <label id="rfvCaptcha" style="color:red;display:none;font-weight:normal;">Captcha validation is required.</label>
_x000D_
_x000D_
_x000D_

Captcha validation is required.

How to get the IP address of the server on which my C# application is running on?

And this is to get all local IPs in csv format in VB.NET

Imports System.Net
Imports System.Net.Sockets

Function GetIPAddress() As String
    Dim ipList As List(Of String) = New List(Of String)
    Dim host As IPHostEntry
    Dim localIP As String = "?"
    host = Dns.GetHostEntry(Dns.GetHostName())
    For Each ip As IPAddress In host.AddressList
        If ip.AddressFamily = AddressFamily.InterNetwork Then
            localIP = ip.ToString()
            ipList.Add(localIP)
        End If
    Next
    Dim ret As String = String.Join(",", ipList.ToArray)
    Return ret
End Function

How to use Boost in Visual Studio 2010

Here is how I was able to use Boost:

  1. Download and extract the zip version of Boost libraries.
  2. Run bootstrap.bat file and then run bjam.exe.
  3. Wait for roughly 30 minutes or so.
  4. Create a new project in Visual Studio.
  5. Go to project-->properties-->Linker-->General-->Additional Library Directories and add boost/stage/lib directory to it.
  6. Go to project-->properties-->C/C++-->General-->Additional Include Directories and add boost directory to it.

You will be able to build your project without any errors !

How to add anchor tags dynamically to a div in Javascript?

I recommend that you use jQuery for this, as it makes the process much easier. Here are some examples using jQuery:

$("div#id").append('<a href="' + url + '">' + text + '</a>');

If you need a list though, as in a <ul>, you can do this:

$("div#id").append('<ul>');
var ul = $("div#id > ul");

ul.append('<li><a href="' + url + '">' + text + '</a></li>');

How to get UTC+0 date in Java 8?

In Java8 you use the new Time API, and convert an Instant in to a ZonedDateTime Using the UTC TimeZone

#if DEBUG vs. Conditional("DEBUG")

It really depends on what you're going for:

  • #if DEBUG: The code in here won't even reach the IL on release.
  • [Conditional("DEBUG")]: This code will reach the IL, however calls to the method will be omitted unless DEBUG is set when the caller is compiled.

Personally I use both depending on the situation:

Conditional("DEBUG") Example: I use this so that I don't have to go back and edit my code later during release, but during debugging I want to be sure I didn't make any typos. This function checks that I type a property name correctly when trying to use it in my INotifyPropertyChanged stuff.

[Conditional("DEBUG")]
[DebuggerStepThrough]
protected void VerifyPropertyName(String propertyName)
{
    if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        Debug.Fail(String.Format("Invalid property name. Type: {0}, Name: {1}",
            GetType(), propertyName));
}

You really don't want to create a function using #if DEBUG unless you are willing to wrap every call to that function with the same #if DEBUG:

#if DEBUG
    public void DoSomething() { }
#endif

    public void Foo()
    {
#if DEBUG
        DoSomething(); //This works, but looks FUGLY
#endif
    }

versus:

[Conditional("DEBUG")]
public void DoSomething() { }

public void Foo()
{
    DoSomething(); //Code compiles and is cleaner, DoSomething always
                   //exists, however this is only called during DEBUG.
}

#if DEBUG example: I use this when trying to setup different bindings for WCF communication.

#if DEBUG
        public const String ENDPOINT = "Localhost";
#else
        public const String ENDPOINT = "BasicHttpBinding";
#endif

In the first example, the code all exists, but is just ignored unless DEBUG is on. In the second example, the const ENDPOINT is set to "Localhost" or "BasicHttpBinding" depending on if DEBUG is set or not.


Update: I am updating this answer to clarify an important and tricky point. If you choose to use the ConditionalAttribute, keep in mind that calls are omitted during compilation, and not runtime. That is:

MyLibrary.dll

[Conditional("DEBUG")]
public void A()
{
    Console.WriteLine("A");
    B();
}

[Conditional("DEBUG")]
public void B()
{
    Console.WriteLine("B");
}

When the library is compiled against release mode (i.e. no DEBUG symbol), it will forever have the call to B() from within A() omitted, even if a call to A() is included because DEBUG is defined in the calling assembly.

How to make a .jar out from an Android Studio project

  • Open build.gradle for library project enter image description here

  • Write two tasks in build.gradle -- deleteJar and createJar and add rule createJar.dependsOn(deleteJar, build) enter image description here

The code from above:

task deleteJar(type: Delete) {
    delete 'libs/jars/logmanagementlib.jar'
}           

task createJar(type: Copy) {
    from('build/intermediates/bundles/release/')
    into('libs/jars/')
    include('classes.jar')
    rename('classes.jar', 'logmanagementlib.jar')
}

createJar.dependsOn(deleteJar, build)
  • Expand gradle panel from right and open all tasks under yourlibrary->others. You will see two new tasks there -- createJar and deleteJar enter image description here

  • Double click on createJar enter image description here

  • Once the task run successfully, get your generated jar from path mentioned in createJar task i.e. libs/xxxx.jar enter image description here

  • copy the newly generated jar into your required project's lib folder-->right click-->select "add as library"

Find row in datatable with specific id

DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(r => Convert.ToInt32(r["ID"]) == 5);
if (dataRow != null)
{
    // code
}

If it is a typed DataSet:

MyDatasetType.MyDataTableRow dataRow = dataSet.MyDataTable.FirstOrDefault(r => r.ID == 5);
if (dataRow != null)
{
    // code
}

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, it is asking for the application/executable that is capable of creating Javadoc. There is a javadoc executable inside the jdk's bin folder.

How to run a JAR file

Before run the jar check Main-Class: classname is available or not in MANIFEST.MF file. MANIFEST.MF is present in jar.

java -jar filename.jar

Hexadecimal string to byte array in C

I found this question by Googling for the same thing. I don't like the idea of calling sscanf() or strtol() since it feels like overkill. I wrote a quick function which does not validate that the text is indeed the hexadecimal presentation of a byte stream, but will handle odd number of hex digits:

uint8_t tallymarker_hextobin(const char * str, uint8_t * bytes, size_t blen)
{
   uint8_t  pos;
   uint8_t  idx0;
   uint8_t  idx1;

   // mapping of ASCII characters to hex values
   const uint8_t hashmap[] =
   {
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //  !"#$%&'
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ()*+,-./
     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 01234567
     0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 89:;<=>?
     0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // @ABCDEFG
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // HIJKLMNO
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // PQRSTUVW
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // XYZ[\]^_
     0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // `abcdefg
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // hijklmno
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pqrstuvw
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // xyz{|}~.
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........
     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  // ........
   };

   bzero(bytes, blen);
   for (pos = 0; ((pos < (blen*2)) && (pos < strlen(str))); pos += 2)
   {
      idx0 = (uint8_t)str[pos+0];
      idx1 = (uint8_t)str[pos+1];
      bytes[pos/2] = (uint8_t)(hashmap[idx0] << 4) | hashmap[idx1];
   };

   return(0);
}

Change bundle identifier in Xcode when submitting my first app in IOS

Just change Product Name in your project's build settings. This will change the bundle identifier with no need to manually touch xcode configuration files.

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

I like to use hash keys when dealing verification links. I would recommend using the microtime and hashing that using MD5 since there should be no reason why the keys should be the same since it hashes based off of the microtime.

  1. $key = md5(rand());
  2. $key = md5(microtime());

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

In my case this was caused by not committing my conflict resolution.

The problem was caused by running the git pull command. Changes in the origin led to conflicts with my local repo, which I resolved. However, I did not commit them. The solution at this point is to commit the changes (git commit the resolved file)

If you have also modified some files since resolving the conflict, the git status command will show the local modifications as unstaged local modifications and merge resolution as staged local modifications. This can be properly resolved by committing changes from the merge first by git commit, then adding and committing the unstaged changes as usual (e.g. by git commit -a).

How to export non-exportable private key from store

This worked for me on Windows Server 2012 - I needed to export a non-exportable certificate to setup another ADFS server and this did the trick. Remember to use the jailbreak instructions above i.e.:

crypto::certificates /export /systemstore:CERT_SYSTEM_STORE_LOCAL_MACHINE

month name to month number and vice versa in python

One more:

def month_converter(month):
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    return months.index(month) + 1

CSS opacity only to background color, not the text on it?

Use:

background:url("location of image"); // Use an image with opacity

This method will work in all browsers.

How should strace be used?

strace lists all system calls done by the process it's applied to. If you don't know what system calls mean, you won't be able to get much mileage from it.

Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is actually attempting to do, as distinct from what you expected it to.

Convert date to another timezone in JavaScript

Having looked around a lot including links from this page i found this great article, using moment timezone:

https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/

To summarise it:

Get the user's timezone

var tz = moment.tz.guess();
console.info('Timezone: ' + tz);

Returns eg: Timezone: Europe/London

Set the default user timezone

moment.tz.setDefault(tz);

Set custom timezone

moment.tz.setDefault('America/Los_Angeles');

Convert date / time to local timezone, assumes original date/time is in UTC

moment.utc('2016-12-25 07:00').tz(tz).format('ddd, Do MMMM YYYY, h:mma');

Returns: Sun, 25th December 2016, 7:00am

Convert date/time to LA Time

moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');

Returns: Sat, 24th December 2016, 11:00pm

Convert from LA time to London

moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );

Returns: Sun, 25th December 2016, 3:00pm

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Try the following:

if ((select VisitCount from PageImage where PID=@pid and PageNumber=5) is NULL)
begin
    update PageImage
    set VisitCount=1
    where PID=@pid and PageNumber=@pageno
end 
else
begin
    update PageImage 
    set VisitCount=VisitCount+1
    where PID=@pid and PageNumber=@pageno
end

How to update multiple columns in single update statement in DB2

I know it's an old question, but I just had to find solution for multiple rows update where multiple records had to updated with different values based on their IDs and I found that I can use a a scalar-subselect:

UPDATE PROJECT
  SET DEPTNO =
        (SELECT WORKDEPT FROM EMPLOYEE
           WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
  WHERE RESPEMP='000030'

(with WHERE optional, of course)

Also, I found that it is critical to specify that no NULL values would not be used in this update (in case not all records in first table have corresponding record in the second one), this way:

UPDATE PROJECT
  SET DEPTNO =
        (SELECT WORKDEPT FROM EMPLOYEE
           WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
  WHERE RESPEMP IN (SELECT EMPNO FROM EMPLOYEE)

Source: https://www.ibm.com/support/knowledgecenter/ssw_i5_54/sqlp/rbafyupdatesub.htm

How do I check if string contains substring?

Like this:

if (str.indexOf("Yes") >= 0)

...or you can use the tilde operator:

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)

Or:

if (/yes/i.test(str))

How to enable ASP classic in IIS7.5

So it turns out that if I add the Handler Mappings on the Website and Application level, everything works beautifully. I was only adding them on the server level, thus IIS did not know to map the asp pages to the IsapiModule.

So to resolve this issue, go to the website you want to add your application to, then double click on Handler Mappings. Click "Add Script Map" and enter in the following information:

RequestPath: *.asp
Executable: C:\Windows\System32\inetsrv\asp.dll
Name: Classic ASP (this can be anything you want it to be

How to make external HTTP requests with Node.js

node-http-proxy is a great solution as was suggested by @hross above. If you're not deadset on using node, we use NGINX to do the same thing. It works really well with node. We use it for example to process SSL requests before forwarding them to node. It can also handle cacheing and forwarding routes. Yay!

sql server convert date to string MM/DD/YYYY

As of SQL Server 2012+, you can use FORMAT(value, format [, culture ])

Where the format param takes any valid standard format string or custom formatting string

Example:

SELECT FORMAT(GETDATE(), 'MM/dd/yyyy')

Further Reading:

How to Batch Rename Files in a macOS Terminal?

try this

for i in *.png ; do mv "$i" "${i/remove_me*.png/.png}" ; done

Here is another way:

for file in Name*.png; do mv "$file" "01_$file"; done

Linker command failed with exit code 1 - duplicate symbol __TMRbBp

If you're using Ionic and the Push and Console plugins that's the problem. Remove the cordova console plugin (which is deprecated) and the error will disappear.

The linker error is saying that a library is duplicated which is, in fact, true because the console plugin is already in cordova-ios 4.5+

It took me a couple of hours to figure this out!

Looping over elements in jQuery

I have used the following before:

var my_form = $('#form-id');
var data = {};

$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
    function() {
        var name = $(this).attr('name');
        var val = $(this).val();

        if (!data.hasOwnProperty(name)) {
            data[name] = new Array;
        }

        data[name].push(val);
    }
);

This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.

Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.

Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).

Parse JSON String into a Particular Object Prototype in JavaScript

The current answers contain a lot of hand-rolled or library code. This is not necessary.

  1. Use JSON.parse('{"a":1}') to create a plain object.

  2. Use one of the standardized functions to set the prototype:

    • Object.assign(new Foo, { a: 1 })
    • Object.setPrototypeOf({ a: 1 }, Foo.prototype)

Android emulator failed to allocate memory 8

Go to edit Android Virtual Devices and change the 1024 Under Memory Options to 768. If it still doesn't work, keep going lower and lower.

JPA 2.0, Criteria API, Subqueries, In Expressions

Late resurrection.

Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:

SELECT e 
FROM Employee e 
WHERE e IN (SELECT emp
              FROM Project p JOIN p.employees emp 
             WHERE p.name = :project)

Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:

SELECT e 
FROM Employee e 
WHERE e.id IN (SELECT emp.id
                 FROM Project p JOIN p.employees emp 
                WHERE p.name = :project)

Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);

Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);

sq.select(sqEmp.get(Employee_.id)).where(
        cb.equal(project.get(Project_.name), 
        cb.parameter(String.class, "project")));

c.select(emp).where(
        cb.in(emp.get(Employee_.id)).value(sq));

TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();

Is <img> element block level or inline level?

Whenever you insert an image it just takes the width that the image has originally. You can add any other html element next to it and you will see that it will allow it. That makes image an "inline" element.

Import Script from a Parent Directory

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
    +-- __init__.py
    +-- moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

How to Display Multiple Google Maps per page with API V3

OP wanted two specific maps, but if you'd like to have a dynamic number of maps on one page (for instance a list of retailer locations) you need to go another route. The standard implementation of Google maps API defines the map as a global variable, this won't work with a dynamic number of maps. Here's my code to solve this without global variables:

function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var mapOptions = {
            zoom: 14,
            center: results[0].geometry.location,
            disableDefaultUI: true
        };
        var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});
}

Just pass the ID and address of each map to the function to plot the map and mark the address.

How to set the context path of a web application in Tomcat 7.0

In Tomcat 9.0, I only have to change the following in the server.xml

<Context docBase="web" path="/web" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

to

<Context docBase="web" path="" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

Docker how to change repository name or rename image?

docker tag CURRENT_IMAGE_NAME DESIRED_IMAGE_NAME

How to add multiple jar files in classpath in linux

You use the -classpath argument. You can use either a relative or absolute path. What that means is you can use a path relative to your current directory, OR you can use an absolute path that starts at the root /.

Example:

bash$ java -classpath path/to/jar/file MyMainClass

In this example the main function is located in MyMainClass and would be included somewhere in the jar file.

For compiling you need to use javac

Example:

bash$ javac -classpath path/to/jar/file MyMainClass.java

You can also specify the classpath via the environment variable, follow this example:

bash$ export CLASSPATH="path/to/jar/file:path/tojar/file2"
bash$ javac MyMainClass.java

For any normally complex java project you should look for the ant script named build.xml

Last element in .each() set

A shorter answer from here, adapted to this question:

var arr = $('.requiredText');
arr.each(function(index, item) {
   var is_last_item = (index == (arr.length - 1));
});

Just for completeness.

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

If you are using version 2.2 and above of Android Studio then in Android Studio use Build ? Analyze APK then select AndroidManifest.xml file.

Managing SSH keys within Jenkins for Git

This works for me if you have config and the private key file in the /Jenkins/.ssh/ you need to chown (change owner) for these 2 files then restart jenkins in order for the jenkins instance to read these 2 files.

Pass in an array of Deferreds to $.when()

When calling multiple parallel AJAX calls, you have two options for handling the respective responses.

  1. Use Synchronous AJAX call/ one after another/ not recommended
  2. Use Promises' array and $.when which accepts promises and its callback .done gets called when all the promises are return successfully with respective responses.

Example

_x000D_
_x000D_
function ajaxRequest(capitalCity) {_x000D_
   return $.ajax({_x000D_
        url: 'https://restcountries.eu/rest/v1/capital/'+capitalCity,_x000D_
        success: function(response) {_x000D_
        },_x000D_
        error: function(response) {_x000D_
          console.log("Error")_x000D_
        }_x000D_
    });_x000D_
}_x000D_
$(function(){_x000D_
   var capitalCities = ['Delhi', 'Beijing', 'Washington', 'Tokyo', 'London'];_x000D_
   $('#capitals').text(capitalCities);_x000D_
_x000D_
   function getCountryCapitals(){ //do multiple parallel ajax requests_x000D_
      var promises = [];   _x000D_
      for(var i=0,l=capitalCities.length; i<l; i++){_x000D_
            var promise = ajaxRequest(capitalCities[i]);_x000D_
            promises.push(promise);_x000D_
      }_x000D_
  _x000D_
      $.when.apply($, promises)_x000D_
        .done(fillCountryCapitals);_x000D_
   }_x000D_
  _x000D_
   function fillCountryCapitals(){_x000D_
        var countries = [];_x000D_
        var responses = arguments;_x000D_
        for(i in responses){_x000D_
            console.dir(responses[i]);_x000D_
            countries.push(responses[i][0][0].nativeName)_x000D_
        }  _x000D_
        $('#countries').text(countries);_x000D_
   }_x000D_
  _x000D_
   getCountryCapitals()_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
  <h4>Capital Cities : </h4> <span id="capitals"></span>_x000D_
  <h4>Respective Country's Native Names : </h4> <span id="countries"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to share my Docker-Image without using the Docker-Hub?

Sending a docker image to a remote server can be done in 3 simple steps:

  1. Locally, save docker image as a .tar:
docker save -o <path for created tar file> <image name>
  1. Locally, use scp to transfer .tar to remote

  2. On remote server, load image into docker:

docker load -i <path to docker image tar file>

What's the difference between the atomic and nonatomic attributes?

The default is atomic, this means it does cost you performance whenever you use the property, but it is thread safe. What Objective-C does, is set a lock, so only the actual thread may access the variable, as long as the setter/getter is executed.

Example with MRC of a property with an ivar _internal:

[_internal lock]; //lock
id result = [[value retain] autorelease];
[_internal unlock];
return result;

So these last two are the same:

@property(atomic, retain) UITextField *userName;

@property(retain) UITextField *userName; // defaults to atomic

On the other hand does nonatomic add nothing to your code. So it is only thread safe if you code security mechanism yourself.

@property(nonatomic, retain) UITextField *userName;

The keywords doesn't have to be written as first property attribute at all.

Don't forget, this doesn't mean that the property as a whole is thread-safe. Only the method call of the setter/getter is. But if you use a setter and after that a getter at the same time with 2 different threads, it could be broken too!

How to automatically generate N "distinct" colors?

This OpenCV function uses the HSV color model to generate n evenly distributed colors around the 0<=H<=360º with maximum S=1.0 and V=1.0. The function outputs the BGR colors in bgr_mat:

void distributed_colors (int n, cv::Mat_<cv::Vec3f> & bgr_mat) {
  cv::Mat_<cv::Vec3f> hsv_mat(n,CV_32F,cv::Vec3f(0.0,1.0,1.0));
  double step = 360.0/n;
  double h= 0.0;
  cv::Vec3f value;
  for (int i=0;i<n;i++,h+=step) {
    value = hsv_mat.at<cv::Vec3f>(i);
    hsv_mat.at<cv::Vec3f>(i)[0] = h;
  }
  cv::cvtColor(hsv_mat, bgr_mat, CV_HSV2BGR);
  bgr_mat *= 255;
}

afxwin.h file is missing in VC++ Express Edition

Including the header afxwin.h signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:

  1. Download and install the Windows Driver Kit.

  2. Select menu Tools > Options… > Projects and Solutions > VC++ Directories.

  3. In the drop-down menu Show directories for select Include files.

  4. Add the following paths (replace $(WDK_directory) with the directory where you installed Windows Driver Kit in the first step):

    $(WDK_directory)\inc\mfc42
    $(WDK_directory)\inc\atl30
    

  5. In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory) like before):

    $(WDK_directory)\lib\mfc\i386
    $(WDK_directory)\lib\atl\i386
    

  6. In the $(WDK_directory)\inc\mfc42\afxwin.inl file, edit the following lines (starting from 1033):

    _AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    to

    _AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    In other words, add BOOL after _AFXWIN_INLINE.

How to color the Git console?

Well, if you are not satisfied with the default setting, you can use ANSI escape code to help you set the color, and if you want to modify some text, you can write bash to help you. see as below:

Eaxmplae

# .gitconfig

[alias]
    st-color = "!f() { \
        echo -n -e '\\033[38;2;255;0;01m\\033[4m' ;\
        git status -s | grep ' D' | \
        sed -e 's/^ ./DELETE:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[48;2;128;128;128m' ;\
        echo -n -e '\\033[38;2;0;255;01m' ;\
        git status -s | grep ' [AM]' | \
        sed -e 's/^ ./NEW OR MODIFY:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[38;2;255;0;255m' ;\
        echo Rename ;\
        git status -s | grep 'R ' | \
        sed -e 's/^..//' ; \
        echo -n -e '\\033[m' ;\
    }; f"

demo

enter image description here

Explanation

  1. you can write the long script on .gitconfig use the syntax as below:

    [alias]
        your-cmd = !f() { \
            \
        }; f"
    
  2. echo -n -e (see more echo)

    • -n = Do not output a trailing newline.
    • -e Enable interpretation of the following backslash-escaped
  3. \\033[38;2;255;0;0m\\033[4m (see more SGR parameters)

    • \\033[38;2;255;0;0m : 38 mean fore color. 255;0;0 = Red | r;g;b
    • \\033[4m : underline
  4. grep : The grep command is used to search text.

  5. sed -e 's/be_replace_string/new_string/' replace string to new string.

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()
legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.

Select from multiple tables without a join?

select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;

How to stop docker under Linux

if you have no systemctl and started the docker daemon by:

sudo service docker start

you can stop it by:

sudo service docker stop

How to connect to a MySQL Data Source in Visual Studio

Installing the following packages:

adds MySQL Database to the data sources list (Visual Studio 2017)

refresh both the External data source and pivot tables together within a time schedule

I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.

Sub Refresh()

    Dim conn As Variant

    For Each conn In ActiveWorkbook.Connections
        conn.ODBCConnection.BackgroundQuery = False
    Next conn

    ActiveWorkbook.RefreshAll
End Sub

Python and pip, list all versions of a package that's available?

This works for me on OSX:

pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\  '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n'

It returns the list one per line:

1.1.0rc1
1.1.0rc2
1.1.0
1.2.0rc1
1.2.0rc2
1.2.0rc3
1.2.0rc4
1.2.0
1.3.0rc1
1.3.0rc2
1.3.0rc3
1.3.0
1.3.1
1.3.2
1.3.3
1.4.0rc1
1.4.0rc2
1.4.0rc3
1.4.0
1.4.1
1.4.2
1.5.0rc1
1.5.0rc2
1.5.0rc3
1.5.0
1.5.1
1.5.2
1.6.0rc1
1.6.0
1.6.1
1.6.2
1.7.0rc1
1.7.0rc2
1.7.0
1.7.1
1.8.0rc1
1.8.0rc2
1.8.0
1.8.1
1.9.0rc1
1.9.0rc2
1.9.0rc3
1.9.0rc4
1.9.0
1.10.0rc1
1.10.0rc2
1.10.0

Or to get the latest version available:

pip install docker-compose== 2>&1 \
| grep -oE '(\(.*\))' \
| awk -F:\  '{print$NF}' \
| sed -E 's/( |\))//g' \
| tr ',' '\n' \
| gsort -r -V \
| head -1
1.10.0rc2

Keep in mind gsort has to be installed (on OSX) to parse the versions. You can install it with brew install coreutils

Plot a legend outside of the plotting area in base graphics?

I can offer only an example of the layout solution already pointed out.

layout(matrix(c(1,2), nrow = 1), widths = c(0.7, 0.3))
par(mar = c(5, 4, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
par(mar = c(5, 0, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, ylim=c(-2,2), type = "n", axes = FALSE, ann = FALSE)
legend(1, 1, c("group A", "group B"), pch = c(1,2), lty = c(1,2))

an ugly picture :S

What are some examples of commonly used practices for naming git branches?

Here are some branch naming conventions that I use and the reasons for them

Branch naming conventions

  1. Use grouping tokens (words) at the beginning of your branch names.
  2. Define and use short lead tokens to differentiate branches in a way that is meaningful to your workflow.
  3. Use slashes to separate parts of your branch names.
  4. Do not use bare numbers as leading parts.
  5. Avoid long descriptive names for long-lived branches.

Group tokens

Use "grouping" tokens in front of your branch names.

group1/foo
group2/foo
group1/bar
group2/bar
group3/bar
group1/baz

The groups can be named whatever you like to match your workflow. I like to use short nouns for mine. Read on for more clarity.

Short well-defined tokens

Choose short tokens so they do not add too much noise to every one of your branch names. I use these:

wip       Works in progress; stuff I know won't be finished soon
feat      Feature I'm adding or expanding
bug       Bug fix or experiment
junk      Throwaway branch created to experiment

Each of these tokens can be used to tell you to which part of your workflow each branch belongs.

It sounds like you have multiple branches for different cycles of a change. I do not know what your cycles are, but let's assume they are 'new', 'testing' and 'verified'. You can name your branches with abbreviated versions of these tags, always spelled the same way, to both group them and to remind you which stage you're in.

new/frabnotz
new/foo
new/bar
test/foo
test/frabnotz
ver/foo

You can quickly tell which branches have reached each different stage, and you can group them together easily using Git's pattern matching options.

$ git branch --list "test/*"
test/foo
test/frabnotz

$ git branch --list "*/foo"
new/foo
test/foo
ver/foo

$ gitk --branches="*/foo"

Use slashes to separate parts

You may use most any delimiter you like in branch names, but I find slashes to be the most flexible. You might prefer to use dashes or dots. But slashes let you do some branch renaming when pushing or fetching to/from a remote.

$ git push origin 'refs/heads/feature/*:refs/heads/phord/feat/*'
$ git push origin 'refs/heads/bug/*:refs/heads/review/bugfix/*'

For me, slashes also work better for tab expansion (command completion) in my shell. The way I have it configured I can search for branches with different sub-parts by typing the first characters of the part and pressing the TAB key. Zsh then gives me a list of branches which match the part of the token I have typed. This works for preceding tokens as well as embedded ones.

$ git checkout new<TAB>
Menu:  new/frabnotz   new/foo   new/bar


$ git checkout foo<TAB>
Menu:  new/foo   test/foo   ver/foo

(Zshell is very configurable about command completion and I could also configure it to handle dashes, underscores or dots the same way. But I choose not to.)

It also lets you search for branches in many git commands, like this:

git branch --list "feature/*"
git log --graph --oneline --decorate --branches="feature/*" 
gitk --branches="feature/*" 

Caveat: As Slipp points out in the comments, slashes can cause problems. Because branches are implemented as paths, you cannot have a branch named "foo" and another branch named "foo/bar". This can be confusing for new users.

Do not use bare numbers

Do not use use bare numbers (or hex numbers) as part of your branch naming scheme. Inside tab-expansion of a reference name, git may decide that a number is part of a sha-1 instead of a branch name. For example, my issue tracker names bugs with decimal numbers. I name my related branches CRnnnnn rather than just nnnnn to avoid confusion.

$ git checkout CR15032<TAB>
Menu:   fix/CR15032    test/CR15032

If I tried to expand just 15032, git would be unsure whether I wanted to search SHA-1's or branch names, and my choices would be somewhat limited.

Avoid long descriptive names

Long branch names can be very helpful when you are looking at a list of branches. But it can get in the way when looking at decorated one-line logs as the branch names can eat up most of the single line and abbreviate the visible part of the log.

On the other hand long branch names can be more helpful in "merge commits" if you do not habitually rewrite them by hand. The default merge commit message is Merge branch 'branch-name'. You may find it more helpful to have merge messages show up as Merge branch 'fix/CR15032/crash-when-unformatted-disk-inserted' instead of just Merge branch 'fix/CR15032'.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Combining all conditions

select  a.* from tbl_Company a

where  a.Company_ID NOT IN (1,2)  

AND (   
        (0 = 
            CASE WHEN (@Fromdate = '' or @Todate='')
                THEN 0 
                ELSE 1  
            END
        )      -- if 0=0 true , if 0=1 fails (filter only when the fromdate and todate is present)
                OR
        (a.Created_Date between @Fromdate and @Todate )                 
    )

Rename Pandas DataFrame Index

If you want to use the same mapping for renaming both columns and index you can do:

mapping = {0:'Date', 1:'SM'}
df.index.names = list(map(lambda name: mapping.get(name, name), df.index.names))
df.rename(columns=mapping, inplace=True)

What is this date format? 2011-08-12T20:17:46.384Z

If you guys are looking for a solution for Android, you can use the following code to get the epoch seconds from the timestamp string.

public static long timestampToEpochSeconds(String srcTimestamp) {
    long epoch = 0;

    try {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Instant instant = Instant.parse(srcTimestamp);
            epoch = instant.getEpochSecond();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'", Locale.getDefault());
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date date = sdf.parse(srcTimestamp);
            if (date != null) {
                epoch = date.getTime() / 1000;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return epoch;
}

Sample input: 2019-10-15T05:51:31.537979Z

Sample output: 1571128673

Creating and Update Laravel Eloquent

If you need the same functionality using the DB, in Laravel >= 5.5 you can use:

DB::table('table_name')->updateOrInsert($attributes, $values);

or the shorthand version when $attributes and $values are the same:

DB::table('table_name')->updateOrInsert($values);

Selecting multiple classes with jQuery

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

Hide header in stack navigator React navigation

const CallStack = createStackNavigator({
  Calls: Calls,
  CallsScreen:CallsScreen,
}, {headerMode: 'none'});

CallStack.navigationOptions = {
  tabBarLabel: 'Calls',
  tabBarIcon: ({ focused }) => (
    <TabBarIcon
      focused={focused}
      name={Platform.OS === 'ios' ? 'ios-options' : 'md-options'}
    />
  ),

   header: null,

        headerVisible: false,

};

Generics in C#, using type of a variable as parameter

I'm not sure whether I understand your question correctly, but you can write your code in this way:

bool DoesEntityExist<T>(T instance, ....)

You can call the method in following fashion:

DoesEntityExist(myTypeInstance, ...)

This way you don't need to explicitly write the type, the framework will overtake the type automatically from the instance.

Create a new TextView programmatically then display it below another TextView

Try this code:

final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];

for (int i=0; i<str.length; i++)
{
    tv[i] = new TextView(this); 
    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
         ((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
    params.leftMargin = 50;
    params.topMargin  = i*50;
    tv[i].setText(str[i]);
    tv[i].setTextSize((float) 20);
    tv[i].setPadding(20, 50, 20, 50);
    tv[i].setLayoutParams(params);
    rl.addView(tv[i]);  
}

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

You can use this with replacement of CGRectZero

CGRect.zero

Printing tuple with string formatting in Python

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:

t = 1,2,3
print 'This is a tuple {0}'.format(t)

What is the use of BindingResult interface in spring MVC?

Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.

Then, you can check this object looking for validation errors:

validator.validate(modelObject, bindingResult);  
if (bindingResult.hasErrors()) {  
    // do something  
}

A child container failed during start java.util.concurrent.ExecutionException

This is what worked for me:

1) add commons-logging.jar to the WEB-INF/lib folder

2) Add this jar as a maven dependency, e.g. add this to the pom.xml:

 <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
 </dependency>

3) Maven install

4) Run the server.

Hope it helps.

How to implement the Softmax function in Python

Here you can find out why they used - max.

From there:

"When you’re writing code for computing the Softmax function in practice, the intermediate terms may be very large due to the exponentials. Dividing large numbers can be numerically unstable, so it is important to use a normalization trick."

How to get SQL from Hibernate Criteria API (*not* for logging)

This answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:

public static String toSql(Criteria criteria)
{
    String sql = "";
    Object[] parameters = null;
    try
    {
        CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
        SessionImpl sessionImpl = (SessionImpl) criteriaImpl.getSession();
        SessionFactoryImplementor factory = sessionImpl.getSessionFactory();
        String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
        OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister(implementors[0]);
        LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers();
        CriteriaLoader loader = new CriteriaLoader(persister, factory,
            criteriaImpl, implementors[0].toString(), loadQueryInfluencers);
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String) f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("translator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    if (sql != null)
    {
        int fromPosition = sql.indexOf(" from ");
        sql = "\nSELECT * " + sql.substring(fromPosition);

        if (parameters != null && parameters.length > 0)
        {
            for (Object val : parameters)
            {
                String value = "%";
                if (val instanceof Boolean)
                {
                    value = ((Boolean) val) ? "1" : "0";
                }
                else if (val instanceof String)
                {
                    value = "'" + val + "'";
                }
                else if (val instanceof Number)
                {
                    value = val.toString();
                }
                else if (val instanceof Class)
                {
                    value = "'" + ((Class) val).getCanonicalName() + "'";
                }
                else if (val instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss.SSS");
                    value = "'" + sdf.format((Date) val) + "'";
                }
                else if (val instanceof Enum)
                {
                    value = "" + ((Enum) val).ordinal();
                }
                else
                {
                    value = val.toString();
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
        " and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
        "!=").replaceAll("<", " < ").replaceAll(">", " > ");
}

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

For Swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

For Swift 4

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 @objc func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

Run .jar from batch-file

java -jar "C:\\myjarfile.jar"

You might need to add "\\" to the command. Try this!

Can't find android device using "adb devices" command

The same problem I had on Windows 7. It happened that I was using USB tethering feature alongwith trying to use adb. There are some workarounds for this Usb tether and debug at the same time

make an ID in a mysql table auto_increment (after the fact)

For example, here's a table that has a primary key but is not AUTO_INCREMENT:

mysql> CREATE TABLE foo (
  id INT NOT NULL,
  PRIMARY KEY (id)
);
mysql> INSERT INTO foo VALUES (1), (2), (5);

You can MODIFY the column to redefine it with the AUTO_INCREMENT option:

mysql> ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;

Verify this has taken effect:

mysql> SHOW CREATE TABLE foo;

Outputs:

CREATE TABLE foo (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1

Note that you have modified the column definition in place, without requiring creating a second column and dropping the original column. The PRIMARY KEY constraint is unaffected, and you don't need to mention in in the ALTER TABLE statement.

Next you can test that an insert generates a new value:

mysql> INSERT INTO foo () VALUES (); -- yes this is legal syntax
mysql> SELECT * FROM foo;

Outputs:

+----+
| id |
+----+
|  1 | 
|  2 | 
|  5 | 
|  6 | 
+----+
4 rows in set (0.00 sec)

I tested this on MySQL 5.0.51 on Mac OS X.

I also tested with ENGINE=InnoDB and a dependent table. Modifying the id column definition does not interrupt referential integrity.


To respond to the error 150 you mentioned in your comment, it's probably a conflict with the foreign key constraints. My apologies, after I tested it I thought it would work. Here are a couple of links that may help to diagnose the problem:

Highest Salary in each department

select a.*
 from EmpDetails a
 inner join 
 (
 select DeptID,max(Salary) as Salary
 from EmpDetails group by DeptID  
 )b 
on a.DeptID = b.DeptID and a.Salary = b.Salary

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

where does MySQL store database files?

In any case you can know it:

mysql> select @@datadir;
+----------------------------------------------------------------+
| @@datadir                                                      |
+----------------------------------------------------------------+
| D:\Documents and Settings\b394382\My Documents\MySQL_5_1\data\ |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

Thanks Barry Galbraith from the MySql Forum http://forums.mysql.com/read.php?10,379153,379167#msg-379167

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

What is the yield keyword used for in C#?

At first sight, yield return is a .NET sugar to return an IEnumerable.

Without yield, all the items of the collection are created at once:

class SomeData
{
    public SomeData() { }

    static public IEnumerable<SomeData> CreateSomeDatas()
    {
        return new List<SomeData> {
            new SomeData(), 
            new SomeData(), 
            new SomeData()
        };
    }
}

Same code using yield, it returns item by item:

class SomeData
{
    public SomeData() { }

    static public IEnumerable<SomeData> CreateSomeDatas()
    {
        yield return new SomeData();
        yield return new SomeData();
        yield return new SomeData();
    }
}

The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created.

The yield operator allows the creation of items as it is demanded. That's a good reason to use it.

What happens when a duplicate key is put into a HashMap?

I always used:

HashMap<String, ArrayList<String>> hashy = new HashMap<String, ArrayList<String>>();

if I wanted to apply multiple things to one identifying key.

public void MultiHash(){
    HashMap<String, ArrayList<String>> hashy = new HashMap<String, ArrayList<String>>();
    String key = "Your key";

    ArrayList<String> yourarraylist = hashy.get(key);

    for(String valuessaved2key : yourarraylist){
        System.out.println(valuessaved2key);
    }

}

you could always do something like this and create yourself a maze!

public void LOOK_AT_ALL_THESE_HASHMAPS(){
    HashMap<String, HashMap<String, HashMap<String, HashMap<String, String>>>> theultimatehashmap = new HashMap <String, HashMap<String, HashMap<String, HashMap<String, String>>>>();
    String ballsdeep_into_the_hashmap = theultimatehashmap.get("firststring").get("secondstring").get("thirdstring").get("forthstring");
}

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

This might be due to the maximum number of characters allowed for a specific column, like in sql one field might have following Data Type nvarchar(5) but the number of characters entered from the user is more than the specified, hence the error arises.

ToList().ForEach in Linq

employees.ToList().ForEach(
     emp=>
     {
          collection.AddRange(emp.Departments);
          emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
     });

Class has no objects member

I was able to update the user settings.json

On my mac it was stored in:

~/Library/Application Support/Code/User/settings.json

Within it, I set the following:

{
    "python.linting.pycodestyleEnabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pylintPath": "pylint",
    "python.linting.pylintArgs": ["--load-plugins", "pylint_django"]
}

That solved the issue for me.

Javascript Array of Functions

I think this is what the original poster meant to accomplish:

var array_of_functions = [
    function() { first_function('a string') },
    function() { second_function('a string') },
    function() { third_function('a string') },
    function() { fourth_function('a string') }
]

for (i = 0; i < array_of_functions.length; i++) {
    array_of_functions[i]();
}

Hopefully this will help others (like me 20 minutes ago :-) looking for any hint about how to call JS functions in an array.

Input Type image submit form value?

Some browsers (IIRC it is just some versions of Internet Explorer) only send the co-ordinates of the image map (in name.x and name.y) and ignore the value. This is a bug.

The workarounds are to either:

  • Have only one submit button and use a hidden input to sent the value
  • Use regular submit buttons instead of image maps
  • Use unique names instead of values and check for the presence of name.x / name.y

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

i have tested a sample and i would like to share this sample and i am sure it's quite help full. I have done all thing in body, first creating an structure there on click of button you will call a function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens. I have given alerts here on different level so u can test where r u now in the coding .

    <body>
    <h1>javascript to count the number of children of given child</h1>

    <div id="count">
    <span>a</span>
    <span>s</span>
    <span>d</span>
    <span>ff</span>
    <div>fsds</div>
    <p>fffff</p>
    </div>
   <button type="button" onclick="selectallelement('count')">click</button>
   <p>total element no.</p>
    <p id="sho">here</p>
  <script>

  function selectallelement(divid)
  {
 alert(divid);
 var ele = document.getElementById(divid).children;
 var match = new Array();
  var i = fillArray(ele,match);
  alert(i);
   document.getElementById('sho').innerHTML = i;
  }
 function fillArray(e1,a1)
  {
 alert("we are here");
   for(var i =0;i<e1.length;i++)
{
  if(e1[i].id.indexOf('count') == 0)
    a1.push(e1[i]);
}
return i;
   }
   </script>

 </body>

  USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS 

React fetch data in server before render

In React, props are used for component parameters not for handling data. There is a separate construct for that called state. Whenever you update state the component basically re-renders itself according to the new values.

var BookList = React.createClass({
  // Fetches the book list from the server
  getBookList: function() {
    superagent.get('http://localhost:3100/api/books')
      .accept('json')
      .end(function(err, res) {
        if (err) throw err;

        this.setBookListState(res);
      });
  },
  // Custom function we'll use to update the component state
  setBookListState: function(books) {
    this.setState({
      books: books.data
    });
  },
  // React exposes this function to allow you to set the default state
  // of your component
  getInitialState: function() {
    return {
      books: []
    };
  },
  // React exposes this function, which you can think of as the
  // constructor of your component. Call for your data here.
  componentDidMount: function() {
    this.getBookList();
  },
  render: function() {
    var books = this.state.books.map(function(book) {
      return (
        <li key={book.key}>{book.name}</li>
      );
    });

    return (
      <div>
        <ul>
          {books}
        </ul>
      </div>
    );
  }
});

Ternary operators in JavaScript without an "else"

No, it needs three operands. That's why they're called ternary operators.

However, for what you have as your example, you can do this:

if(condition) x = true;

Although it's safer to have braces if you need to add more than one statement in the future:

if(condition) { x = true; }

Edit: Now that you mention the actual code in which your question applies to:

if(!defaults.slideshowWidth)
    { defaults.slideshowWidth = obj.find('img').width()+'px'; }

XPath with multiple conditions

question is not clear, but what i understand you need to select a catagory that has name attribute and should have child author with value specified , correct me if i am worng

here is a xpath

//category[@name='Required value'][./author[contains(.,'Required value')]]
e.g
//category[@name='Sport'][./author[contains(.,'James Small')]]

How to convert the time from AM/PM to 24 hour format in PHP?

$s = '07:05:45PM';
$tarr = explode(':', $s);
if(strpos( $s, 'AM') === false && $tarr[0] !== '12'){
    $tarr[0] = $tarr[0] + 12;
}elseif(strpos( $s, 'PM') === false && $tarr[0] == '12'){
    $tarr[0] = '00';
}
echo preg_replace("/[^0-9 :]/", '', implode(':', $tarr));

Escaping Double Quotes in Batch Script

The escape character in batch scripts is ^. But for double-quoted strings, double up the quotes:

"string with an embedded "" character"

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

What is a None value?

None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.


For example:
if d is a dictionary, d.get(k) will return d[k] if it exists, but None if d has no key k.

Read this info from a great blog: http://python-history.blogspot.in/

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

much simpler:

$("selector for element").get(0).scrollIntoView();

if more than one item returns in the selector, the get(0) will get only the first item.

Page vs Window in WPF?

A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.

INSERT SELECT statement in Oracle 11G

Your query should be:

insert into table1 (col1, col2) 
select t1.col1, t2.col2 
from oldtable1 t1, oldtable2 t2

I.e. without the VALUES part.

OnclientClick and OnClick is not working at the same time?

function UpdateClick(btn) {

    for (i = 0; i < Page_Validators.length; i++) {

        ValidatorValidate(Page_Validators[i]);

        if (Page_Validators[i].isvalid == false)

            return false;
    }

    btn.disabled = 'false';

    btn.value = 'Please Wait...';

    return true;
}

Favicon not showing up in Google Chrome

Upload your favicon.ico to the root directory of your website and that should work with Chrome. Some browsers disregard the meta tag and just use /favicon.ico

Go figure?.....

Update rows in one table with data from another table based on one column in each being equal

If you want to update matching rows in t1 with data from t2 then:

update t1
set (c1, c2, c3) = 
(select c1, c2, c3 from t2
 where t2.user_id = t1.user_id)
where exists
(select * from t2
 where t2.user_id = t1.user_id)

The "where exists" part it to prevent updating the t1 columns to null where no match exists.

How to remove all the occurrences of a char in c++ string

This is how I do it:

std::string removeAll(std::string str, char c) {
    size_t offset = 0;
    size_t size = str.size();

    size_t i = 0;
    while (i < size - offset) {
        if (str[i + offset] == c) {
            offset++;
        }

        if (offset != 0) {
            str[i] = str[i + offset];
        }

        i++;
    }

    str.resize(size - offset);
    return str;
}

Basically whenever I find a given char, I advance the offset and relocate the char to the correct index. I don't know if this is correct or efficient, I'm starting (yet again) at C++ and i'd appreciate any input on that.

How to get just the responsive grid from Bootstrap 3?

It's been a while since this question was asked, but maybe now you can forego Bootstrap altogether and use CSS Grid! (it's simpler, neater, more flexible and faster). See this cool article: Stop using Bootstrap — create a practical CSS Grid template for your component based UI

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regular expression should look like:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

Here is an explanation:

/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/

How do you find the sum of all the numbers in an array in Java?

public class AddDemo {

    public static void main(String[] args) {

        ArrayList <Integer>A = new ArrayList<Integer>();

        Scanner S = new Scanner(System.in);

        System.out.println("Enter the Numbers: ");

        for(int i=0; i<5; i++){

            A.add(S.nextInt());
        }

        System.out.println("You have entered: "+A);

        int Sum = 0;

        for(int i=0; i<A.size(); i++){

            Sum = Sum + A.get(i);

        }

        System.out.println("The Sum of Entered List is: "+Sum);

    }

}

How to write a caption under an image?

CSS

#images{
    text-align:center;
    margin:50px auto; 
}
#images a{
    margin:0px 20px;
    display:inline-block;
    text-decoration:none;
    color:black;
 }

HTML

<div id="images">
    <a href="http://xyz.com/hello">
        <img src="hello.png" width="100px" height="100px">
        <div class="caption">Caption 1</div>
    </a>
    <a href="http://xyz.com/hi">
        <img src="hi.png" width="100px" height="100px"> 
        <div class="caption">Caption 2</div>
    </a>
</div>?

?A fiddle is here.

The way to check a HDFS directory's size?

% of used space on Hadoop cluster
sudo -u hdfs hadoop fs –df

Capacity under specific folder:
sudo -u hdfs hadoop fs -du -h /user

Why is nginx responding to any domain name?

You should have a default server for catch-all, you can return 404 or better to not respond at all (will save some bandwidth) by returning 444 which is nginx specific HTTP response that simply close the connection and return nothing

server {
    listen       80  default_server;
    server_name  _; # some invalid name that won't match anything
    return       444;
}

Need to find a max of three numbers in java

You should know more about java.lang.Math.max:

  1. java.lang.Math.max(arg1,arg2) only accepts 2 arguments but you are writing 3 arguments in your code.
  2. The 2 arguments should be double,int,long and float but your are writing String arguments in Math.max function. You need to parse them in the required type.

You code will produce compile time error because of above mismatches.

Try following updated code, that will solve your purpose:

import java.lang.Math;
import java.util.Scanner;
public class max {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please input 3 integers: ");
        int x = Integer.parseInt(keyboard.nextLine());
        int y = Integer.parseInt(keyboard.nextLine());
        int z = Integer.parseInt(keyboard.nextLine());
        int max = Math.max(x,y);
        if(max>y){ //suppose x is max then compare x with z to find max number
            max = Math.max(x,z);    
        }
        else{ //if y is max then compare y with z to find max number
            max = Math.max(y,z);    
        }
        System.out.println("The max of three is: " + max);
    }
} 

Jquery submit form

You don't really need to do it all in jQuery to do that smoothly. Do it like this:

$(".nextbutton").click(function() { 
   document.forms["form1"].submit();
});

Using Laravel Homestead: 'no input file specified'

vagrant provision related codes didn't work for me, after lost some time, I've restart the whole system. Now it works... -,-"

Runnable with a parameter?

You could put it in a function.

String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);

private Runnable createRunnable(final String paramStr){

    Runnable aRunnable = new Runnable(){
        public void run(){
            someFunc(paramStr);
        }
    };

    return aRunnable;

}

(When I used this, my parameter was an integer ID, which I used to make a hashmap of ID --> myRunnables. That way, I can use the hashmap to post/remove different myRunnable objects in a handler.)

Calculate time difference in minutes in SQL Server

Use DateDiff with MINUTE difference:

SELECT DATEDIFF(MINUTE, '11:10:10' , '11:20:00') AS MinuteDiff

Query that may help you:

SELECT StartTime, EndTime, DATEDIFF(MINUTE, StartTime , EndTime) AS MinuteDiff 
FROM TableName

Get all files and directories in specific path fast

In .NET 4.0 there's the Directory.EnumerateFiles method which returns an IEnumerable<string> and is not loading all the files in memory. It's only once you start iterating over the returned collection that files will be returned and exceptions could be handled.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

The driver connector is not in your build path. Configure the build path and point it to the 'mysql-connector-java-5.1.25-bin.jar' (check the version which you are using). Alternatively you can use maven :D

How to find the foreach index?

PHP arrays have internal pointers, so try this:

foreach($array as $key => $value){
   $index = current($array);
}

Works okay for me (only very preliminarily tested though).

WebView link click open default browser

You only need to add the following line

yourWebViewName.setWebViewClient(new WebViewClient());

Check this for official documentation.

How does MySQL process ORDER BY and LIMIT in a query?

LIMIT is usually applied as the last operation, so the result will first be sorted and then limited to 20. In fact, sorting will stop as soon as first 20 sorted results are found.

Is div inside list allowed?

If I recall correctly, a div inside a li used to be invalid.

@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.

HTML <select> selected option background-color CSS style

<select name=protect_email size=1 style="background: #009966; color: #FFF;" onChange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">    
<option value=0 style="background: #009966; color: #FFF;" selected>Protect my email</option>;  
<option value=1 style="background: #FF0000; color: #FFF;">Show email on advert</option>;
</select>; 

http://pro.org.uk/classified/Directory?act=book&category=120

Tested it in FF,Opera,Konqueror worked fine...

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Run XAMPP Control Panel as Administrator if using Windows 7 or more. Windows may block access to ports if not accessed by adminstrator user.

Xcode : Adding a project as a build dependency

Xcode 10

  1. drag-n-drop a project into another project - is called cross-project references[About]
  2. add the added project as a build dependency - is called Explicit dependency[About]
//Xcode 10
Build Phases -> Target Dependencies -> + Add items 

//Xcode 11
Build Phases -> Dependencies -> + Add items 

In Choose items to add: dialog you will see only targets from your project and the sub-project

enter image description here

Android: Background Image Size (in Pixel) which Support All Devices

Check this. This image will show for all icon size for different screen sizes

Size

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

Before trying to delete/rename any file, you must ensure that all the readers or writers (for ex: BufferedReader/InputStreamReader/BufferedWriter) are properly closed.

When you try to read/write your data from/to a file, the file is held by the process and not released until the program execution completes. If you want to perform the delete/rename operations before the program ends, then you must use the close() method that comes with the java.io.* classes.

How to search all loaded scripts in Chrome Developer Tools?

In addition to Ctrl+Shift+F (Cmd+Option+F on Mac) as suggested in this answer, you can right click on the top tree node in the sources tab and select "Search in All Files":

enter image description here

Iterating on a file doesn't work the second time

As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the file and there is nothing left to read. You can use file.tell() to see where in the file the pointer is and file.seek to set the pointer. For example:

>>> file = open('myfile.txt')
>>> file.tell()
0
>>> file.readline()
'one\n'
>>> file.tell()
4L
>>> file.readline()
'2\n'
>>> file.tell()
6L
>>> file.seek(4)
>>> file.readline()
'2\n'

Also, you should know that file.readlines() reads the whole file and stores it as a list. That's useful to know because you can replace:

for line in file.readlines():
    #do stuff
file.seek(0)
for line in file.readlines():
    #do more stuff

with:

lines = file.readlines()
for each_line in lines:
    #do stuff
for each_line in lines:
    #do more stuff

You can also iterate over a file, one line at a time, without holding the whole file in memory (this can be very useful for very large files) by doing:

for line in file:
    #do stuff

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Git: How to pull a single file from a server repository in Git?

This windows batch works regardless of whether or not it's on GitHub. I'm using it because it shows some stark caveats. You'll notice that the operation is slow and traversing hundreds of megabytes of data, so don't use this method if your requirements are based on available bandwidth/R-W memory.

sparse_checkout.bat

pushd "%~dp0"
if not exist .\ms-server-essentials-docs mkdir .\ms-server-essentials-docs
pushd .\ms-server-essentials-docs
git init
git remote add origin -f https://github.com/MicrosoftDocs/windowsserverdocs.git
git config core.sparseCheckout true
(echo EssentialsDocs)>>.git\info\sparse-checkout
git pull origin master

=>

C:\Users\user name\Desktop>sparse_checkout.bat

C:\Users\user name\Desktop>pushd "C:\Users\user name\Desktop\"

C:\Users\user name\Desktop>if not exist .\ms-server-essentials-docs mkdir .\ms-server-essentials-docs

C:\Users\user name\Desktop>pushd .\ms-server-essentials-docs

C:\Users\user name\Desktop\ms-server-essentials-docs>git init Initialized empty Git repository in C:/Users/user name/Desktop/ms-server-essentials-docs/.git/

C:\Users\user name\Desktop\ms-server-essentials-docs>git remote add origin -f https://github.com/MicrosoftDocs/windowsserverdocs.git Updating origin remote: Enumerating objects: 97, done. remote: Counting objects: 100% (97/97), done. remote: Compressing objects: 100% (44/44), done. remote: Total 145517 (delta 63), reused 76 (delta 53), pack-reused 145420 Receiving objects: 100% (145517/145517), 751.33 MiB | 32.06 MiB/s, done. Resolving deltas: 100% (102110/102110), done. From https://github.com/MicrosoftDocs/windowsserverdocs * [new branch]
1106-conflict -> origin/1106-conflict * [new branch]
FromPrivateRepo -> origin/FromPrivateRepo * [new branch]
PR183 -> origin/PR183 * [new branch]
conflictfix -> origin/conflictfix * [new branch]
eross-msft-patch-1 -> origin/eross-msft-patch-1 * [new branch]
master -> origin/master * [new branch] patch-1
-> origin/patch-1 * [new branch] repo_sync_working_branch -> origin/repo_sync_working_branch * [new branch]
shortpatti-patch-1 -> origin/shortpatti-patch-1 * [new branch]
shortpatti-patch-2 -> origin/shortpatti-patch-2 * [new branch]
shortpatti-patch-3 -> origin/shortpatti-patch-3 * [new branch]
shortpatti-patch-4 -> origin/shortpatti-patch-4 * [new branch]
shortpatti-patch-5 -> origin/shortpatti-patch-5 * [new branch]
shortpatti-patch-6 -> origin/shortpatti-patch-6 * [new branch]
shortpatti-patch-7 -> origin/shortpatti-patch-7 * [new branch]
shortpatti-patch-8 -> origin/shortpatti-patch-8

C:\Users\user name\Desktop\ms-server-essentials-docs>git config core.sparseCheckout true

C:\Users\user name\Desktop\ms-server-essentials-docs>(echo EssentialsDocs ) 1>>.git\info\sparse-checkout

C:\Users\user name\Desktop\ms-server-essentials-docs>git pull origin master
From https://github.com/MicrosoftDocs/windowsserverdocs
* branch master -> FETCH_HEAD

Making authenticated POST requests with Spring RestTemplate for Android

Slightly different approach:

MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("HeaderName", "value");
headers.add("Content-Type", "application/json");

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPass, headers);

restTemplate.postForObject(url, request, ClassWhateverYourControllerReturns.class);

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

What is the difference between using constructor vs getInitialState in React / React Native?

These days we don't have to call the constructor inside the component - we can directly call state={something:""}, otherwise previously first we have do declare constructor with super() to inherit every thing from React.Component class then inside constructor we initialize our state.

If using React.createClass then define initialize state with the getInitialState method.

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

(\s|\(|\.|,|^)bqr(\s|,|\)|$)

How to show full object in Chrome console?

Use console.dir() to output a browse-able object you can click through instead of the .toString() version, like this:

console.dir(functor);

Prints a JavaScript representation of the specified object. If the object being logged is an HTML element, then the properties of its DOM representation are printed [1]


[1] https://developers.google.com/web/tools/chrome-devtools/debug/console/console-reference#dir

Absolute positioning ignoring padding of parent

One thing you could try is using the following css:

.child-element {
    padding-left: inherit;
    padding-right: inherit;
    position: absolute;
    left: 0;
    right: 0;
}

It lets the child element inherit the padding from the parent, then the child can be positioned to match the parents widht and padding.

Also, I am using box-sizing: border-box; for the elements involved.

I have not tested this in all browsers, but it seems to be working in Chrome, Firefox and IE10.

How to convert int to NSString?

NSString *string = [NSString stringWithFormat:@"%d", theinteger];

How to check queue length in Python

len(queue) should give you the result, 3 in this case.

Specifically, len(object) function will call object.__len__ method [reference link]. And the object in this case is deque, which implements __len__ method (you can see it by dir(deque)).


queue= deque([])   #is this length 0 queue?

Yes it will be 0 for empty deque.

C#: Assign same value to multiple variables in single statement

Something a little shorter in syntax but taking what the others have already stated.

int num1, num2 = num1 = 1;

How to remove/ignore :hover css style on touch devices

This is also a possible workaround, but you will have to go through your css and add a .no-touch class before your hover styles.

Javascript:

if (!("ontouchstart" in document.documentElement)) {
document.documentElement.className += " no-touch";
}

CSS Example:

<style>
p span {
    display: none;
}

.no-touch p:hover span {
    display: inline;
}
</style>
<p><a href="/">Tap me</a><span>You tapped!</span></p>

Source

P.s. But we should remember, there are coming more and more touch-devices to the market, which are also supporting mouse input at the same time.

Get selected value of a dropdown's item using jQuery

this will do the trick

$('#dropDownId').val();

Can I escape a double quote in a verbatim string literal?

Use double quotation marks.

string foo = @"this ""word"" is escaped";

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

That's not exactly what I had in mind. What do you do if you have a generic type to only be known at runtime?

public MyDTO toObject() {
  try {
    var methodInfo = MethodBase.GetCurrentMethod();
    if (methodInfo.DeclaringType != null) {
      var fullName = methodInfo.DeclaringType.FullName + "." + this.dtoName;
      Type type = Type.GetType(fullName);
      if (type != null) {
        var obj = JsonConvert.DeserializeObject(payload);
      //var obj = JsonConvert.DeserializeObject<type.MemberType.GetType()>(payload);  // <--- type ?????
          ...
      }
    }

    // Example for java..   Convert this to C#
    return JSONUtil.fromJSON(payload, Class.forName(dtoName, false, getClass().getClassLoader()));
  } catch (Exception ex) {
    throw new ReflectInsightException(MethodBase.GetCurrentMethod().Name, ex);
  }
}

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Mine was quite straightforward if you are on a Mac try:

brew install postgres

This will tell you if you have it already install and what version or install the latest version for you if not then run

brew upgrade postgresql

This will make sure you have the latest version installed then finally

brew services start postgresql

This will start the service again. I hope this helps someone.

Find the files existing in one directory but not in the other

This answer optimizes one of the suggestions from @Adail-Junior by adding the -D option, which is helpful when neither of the directories being compared are git repositories:

git diff -D --no-index dir1/ dir2/

If you use -D then you won't see comparisons to /dev/null: text Binary files a/whatever and /dev/null differ

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

Essentially you want to add code to the Calculate event of the relevant Worksheet.

In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.

Alternatively, copy the code below into the editor of the sheet you want to use:

Private Sub Worksheet_Calculate()

If Sheets("MySheet").Range("A1").Value > 0.5 Then
    MsgBox "Over 50%!", vbOKOnly
End If

End Sub

This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

Background thread with QThread in PyQt

Very nice example from Matt, I fixed the typo and also pyqt4.8 is common now so I removed the dummy class as well and added an example for the dataReady signal

# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt


# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    dataReady = QtCore.pyqtSignal(list, dict)

    @QtCore.pyqtSlot()
    def processA(self):
        print "Worker.processA()"
        self.finished.emit()

    @QtCore.pyqtSlot(str, list, list)
    def processB(self, foo, bar=None, baz=None):
        print "Worker.processB()"
        for thing in bar:
            # lots of processing...
            self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
        self.finished.emit()


def onDataReady(aList, aDict):
    print 'onDataReady'
    print repr(aList)
    print repr(aDict)


app = QtGui.QApplication(sys.argv)

thread = QtCore.QThread()  # no parent!
obj = Worker()  # no parent!
obj.dataReady.connect(onDataReady)

obj.moveToThread(thread)

# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)

# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread.  As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.finished.connect(app.exit)

thread.start()

# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
                                QtCore.Q_ARG(str, "Hello World!"),
                                QtCore.Q_ARG(list, ["args", 0, 1]),
                                QtCore.Q_ARG(list, []))

# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls.  Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking

app.exec_()

Using Colormaps to set color of line in matplotlib

I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.

import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.jet(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')
plt.show()

This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.

cm.jet between 0.0 and 1.0 with 1000 graduations

Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.

enter image description here

So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:

colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]

In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:

>>> from matplotlib import cm
>>> dir(cm)

When correctly use Task.Run and when just async-await

Note the guidelines for performing work on a UI thread, collected on my blog:

  • Don't block the UI thread for more than 50ms at a time.
  • You can schedule ~100 continuations on the UI thread per second; 1000 is too much.

There are two techniques you should use:

1) Use ConfigureAwait(false) when you can.

E.g., await MyAsync().ConfigureAwait(false); instead of await MyAsync();.

ConfigureAwait(false) tells the await that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async method (after the ConfigureAwait), you cannot do anything that assumes you're in the current context (e.g., update UI elements).

For more information, see my MSDN article Best Practices in Asynchronous Programming.

2) Use Task.Run to call CPU-bound methods.

You should use Task.Run, but not within any code you want to be reusable (i.e., library code). So you use Task.Run to call the method, not as part of the implementation of the method.

So purely CPU-bound work would look like this:

// Documentation: This method is CPU-bound.
void DoWork();

Which you would call using Task.Run:

await Task.Run(() => DoWork());

Methods that are a mixture of CPU-bound and I/O-bound should have an Async signature with documentation pointing out their CPU-bound nature:

// Documentation: This method is CPU-bound.
Task DoWorkAsync();

Which you would also call using Task.Run (since it is partially CPU-bound):

await Task.Run(() => DoWorkAsync());

Maven Could not resolve dependencies, artifacts could not be resolved

Looks like you are missing some Maven repos. Ask for your friend's .m2/settings.xml, and you'll probably want to update the POM to include the repositories there.

--edit: after some quick googling, try adding this to your POM:

<repository>
    <id>com.springsource.repository.bundles.release</id>
    <name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
    <url>http://repository.springsource.com/maven/bundles/release</url>
</repository>
<repository>
    <id>com.springsource.repository.bundles.external</id>
    <name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
    <url>http://repository.springsource.com/maven/bundles/external</url>
</repository>

Pair/tuple data type in Go

You could do something like this if you wanted

package main

import "fmt"

type Pair struct {
    a, b interface{}
}

func main() {
    p1 := Pair{"finished", 42}
    p2 := Pair{6.1, "hello"}
    fmt.Println("p1=", p1, "p2=", p2)
    fmt.Println("p1.b", p1.b)
    // But to use the values you'll need a type assertion
    s := p1.a.(string) + " now"
    fmt.Println("p1.a", s)
}

However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.