Programs & Examples On #Micr

Magnetic Ink Character Recognition, or MICR, is a character recognition technology used primarily by the banking industry to facilitate the processing of cheques.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Why powershell does not run Angular commands?

Remove ng.ps1 from the directory C:\Users\%username%\AppData\Roaming\npm\ then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\

dotnet ef not found in .NET Core 3

See the announcement for ASP.NET Core 3 Preview 4, which explains that this tool is no longer built-in and requires an explicit install:

The dotnet ef tool is no longer part of the .NET Core SDK

This change allows us to ship dotnet ef as a regular .NET CLI tool that can be installed as either a global or local tool. For example, to be able to manage migrations or scaffold a DbContext, install dotnet ef as a global tool typing the following command:

dotnet tool install --global dotnet-ef

To install a specific version of the tool, use the following command:

dotnet tool install --global dotnet-ef --version 3.1.4

The reason for the change is explained in the docs:

Why

This change allows us to distribute and update dotnet ef as a regular .NET CLI tool on NuGet, consistent with the fact that the EF Core 3.0 is also always distributed as a NuGet package.

In addition, you might need to add the following NuGet packages to your project:

"Permission Denied" trying to run Python on Windows 10

save you time : use wsl and vscode remote extension to properly work with python even with win10 and dont't forget virtualenv! useful https://linuxize.com/post/how-to-install-visual-studio-code-on-ubuntu-18-04/

Error: Java: invalid target release: 11 - IntelliJ IDEA

Got this same error after updating my Idea and I resolved it as follows:

File >> Project Structure... >> Project

“Project language level:” was set to “11 - Local variable syntax for lambda parameters” so I changed it to “SDK default (8 - Lambdas, type annotations etc.)” then applied the change and the error was resolved.

How to setup virtual environment for Python in VS Code?

I was having the same issue until I worked out that I was trying to make my project directory and the virtual environment one and the same - which isn't correct.

I have a \Code\Python directory where I store all my Python projects. My Python 3 installation is on my Path.

If I want to create a new Python project (Project1) with its own virtual environment, then I do this:

python -m venv Code\Python\Project1\venv

Then, simply opening the folder (Project1) in Visual Studio Code ensures that the correct virtual environment is used.

HTTP Error 500.30 - ANCM In-Process Start Failure

For me, everything was just fine but the issue was due to publishing by different VS versions, weird !!! (latest VS 2019 (16.4.2)). When I publish the application with VS 2017 it works fine.

The actual issue is in its dependency json file (e.g. MyWebApp.deps.json) in the publish folder. Hope it helps someone.

enter image description here

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

You should just install python 3.6. I tried it and it worked. Just install that version of python and just do the normal download process (pip install pyaudio).

git clone: Authentication failed for <URL>

As the other answers suggest, editing/removing credentials in the Manage Windows Credentials work and does the job. However, you need to do this each time when the password changes or credentials do not work for some work. Using ssh key has been extremely useful for me where I don't have to bother about these again once I'm done creating a ssh-key and adding them on the server repository (github/bitbucket/gitlab).

Generating a new ssh-key

  1. Open Git Bash.

  2. Paste the text below, substituting in your repo's email address. $ ssh-keygen -t rsa -b 4096 -C "[email protected]"

  3. When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

  4. Then you'll be asked to type a secure passphrase. You can type a passphrase, hit enter and type the passphrase again.

Or, Hit enter twice for empty passphrase.

  1. Copy this on the clipboard:

    clip < ~/.ssh/id_rsa.pub

And then add this key into your repo's profile. For e.g, on github->setting->SSH keys -> paste the key that you coppied ad hit add

Ref: https://help.github.com/en/enterprise/2.15/user/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#generating-a-new-ssh-key

You're done once and for all!

Dart/Flutter : Converting timestamp

If you are using firestore (and not just storing the timestamp as a string) a date field in a document will return a Timestamp. The Timestamp object contains a toDate() method.

Using timeago you can create a relative time quite simply:

_ago(Timestamp t) {
  return timeago.format(t.toDate(), 'en_short');
}

build() {
  return  Text(_ago(document['mytimestamp'])));
}

Make sure to set _firestore.settings(timestampsInSnapshotsEnabled: true); to return a Timestamp instead of a Date object.

How to make audio autoplay on chrome

The video tag can play audio as well. Given the audio tag doesn't seem to be behaving as it should be, you can just use the video tag for audio:

<video autoplay muted id="audio1" src="your.mp3" type="audio/mp3">
    Your browser does not support the <code>video</code> element.
</video>
<script>
    unmuteButton.addEventListener('click', function() 
        { 
            if ( unmuteButton.innerHTML == "unmute" )
            {
                unmuteButton.innerHTML = "mute";
                audio1.muted = false; 
            } else {
                unmuteButton.innerHTML = "unmute";
                audio1.muted = true; 
            }
        });
</script>

You must add a reference to assembly 'netstandard, Version=2.0.0.0

This is where netstandard.dll exists: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7.2\Facades\netstandard.dll Add ref to your Project through this.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

Faced the same error. In my case , what i did wrong was that i injected the service(named DataService in my case) inside the constructor within the Component but I simply forgot to import it within the component.

 constructor(private dataService:DataService ) {
    console.log("constructor called");
  }

I missed the below import code.

import { DataService } from '../../services/data.service';

Flutter does not find android sdk

In my SDK folder there were a empty folder (/build-tools/29.0.0)

I deleted it, and it worked fine

Entity Framework Core: A second operation started on this context before a previous operation completed

In some cases, this error occurs when calling an async method without the await keyword, which can simply be solved by adding await before the method call. however, the answer might not be related to the mentioned question but it can help solving a similar error.

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Your initial statement in the marked solution isn't entirely true. While your new solution may accomplish your original goal, it is still possible to circumvent the original error while preserving your AuthorizationHandler logic--provided you have basic authentication scheme handlers in place, even if they are functionally skeletons.

Speaking broadly, Authentication Handlers and schemes are meant to establish + validate identity, which makes them required for Authorization Handlers/policies to function--as they run on the supposition that an identity has already been established.

ASP.NET Dev Haok summarizes this best best here: "Authentication today isn't aware of authorization at all, it only cares about producing a ClaimsPrincipal per scheme. Authorization has to be aware of authentication somewhat, so AuthenticationSchemes in the policy is a mechanism for you to associate the policy with schemes used to build the effective claims principal for authorization (or it just uses the default httpContext.User for the request, which does rely on DefaultAuthenticateScheme)." https://github.com/aspnet/Security/issues/1469

In my case, the solution I'm working on provided its own implicit concept of identity, so we had no need for authentication schemes/handlers--just header tokens for authorization. So until our identity concepts changes, our header token authorization handlers that enforce the policies can be tied to 1-to-1 scheme skeletons.

Tags on endpoints:

[Authorize(AuthenticationSchemes = "AuthenticatedUserSchemeName", Policy = "AuthorizedUserPolicyName")]

Startup.cs:

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = "AuthenticatedUserSchemeName";
        }).AddScheme<ValidTokenAuthenticationSchemeOptions, ValidTokenAuthenticationHandler>("AuthenticatedUserSchemeName", _ => { });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("AuthorizedUserPolicyName", policy =>
            {
                //policy.RequireClaim(ClaimTypes.Sid,"authToken");
                policy.AddAuthenticationSchemes("AuthenticatedUserSchemeName");
                policy.AddRequirements(new ValidTokenAuthorizationRequirement());
            });
            services.AddSingleton<IAuthorizationHandler, ValidTokenAuthorizationHandler>();

Both the empty authentication handler and authorization handler are called (similar in setup to OP's respective posts) but the authorization handler still enforces our authorization policies.

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

PYODBC--Data source name not found and no default driver specified

for error : pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

No space between the driver and event

connection = Driver={SQL Server Native Client 11.0}; "Server=servername;" "Database=dbname;" "Trusted_Connection=yes;"

VSCode cannot find module '@angular/core' or any other modules

Delete Node Modules folder from project folder.Run below command

npm cache clean --force npm install

It should work.

CSS Grid Layout not working in IE11 even with prefixes

The answer has been given by Faisal Khurshid and Michael_B already.
This is just an attempt to make a possible solution more obvious.

For IE11 and below you need to enable grid's older specification in the parent div e.g. body or like here "grid" like so:

.grid-parent{display:-ms-grid;}

then define the amount and width of the columns and rows like e.g. so:

.grid-parent{
  -ms-grid-columns: 1fr 3fr;
  -ms-grid-rows: 4fr;
}

finally you need to explicitly tell the browser where your element (item) should be placed in e.g. like so:

.grid-item-1{
  -ms-grid-column: 1;
  -ms-grid-row: 1;
}

.grid-item-2{
  -ms-grid-column: 2;
  -ms-grid-row: 1;
}

Unable to create migrations after upgrading to ASP.NET Core 2.0

There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine

https://garywoodfine.com/how-to-seed-your-ef-core-database/

#include errors detected in vscode

If someone have this problem, maybe you just have to install build-essential.

apt install build-essential

Update .NET web service to use TLS 1.2

For me below worked:

Step 1: Downloaded and installed the web Installer exe from https://www.microsoft.com/en-us/download/details.aspx?id=48137 on the application server. Rebooted the application server after installation was completed.

Step 2: Added below changes in the web.config

<system.web>
    <compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->
    <!--Added this httpRuntime -->
    <httpRuntime targetFramework="4.6" />
</system.web>

Step 3: After completing step 1 and 2, it gave an error, "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)" and to resolve this error, I added below key in appsettings in my web.config file

<appSettings>
      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Pip error: Microsoft Visual C++ 14.0 is required

If you already have Visual Studio Build Tools installed but you're still getting that error, then you may need to "Modify" your installation to include the Visual C++ build tools.

To do that:

  1. Open up the Visual Studio Installer (you can search for it in the Start Menu if needed).

  2. Find Visual Studio Build Tools and click "Modify":

enter image description here

  1. Add a checkmark to Visual C++ build tools and then click "Modify" in the bottom right to install them:

enter image description here

After the C++ tools finish installing, run the pip command again and it should work.

Cannot find control with name: formControlName in angular reactive form

I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl to my mat-form-field.

    <form [formGroup]="questionsForm">
        <ng-container *ngFor="let question of questions">
            <mat-form-field [formControlName]="question.id" ngDefaultControl>
                <mat-label>{{question.questionContent}}</mat-label>
                <textarea matInput rows="3" required></textarea>
            </mat-form-field>
        </ng-container>
        <button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
    </form>

In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such

  sendFeedbackAsAgent():void {
    if (this.questionsForm.valid) {
      console.log(this.questionsForm.value)
    }
  }

How to enable CORS in ASP.net Core WebAPI

I'm using .Net CORE 3.1 and I spent ages banging my head against a wall with this one when I realised that my code has started actually working but my debugging environment was broken, so here's 2 hints if you're trying to troubleshoot the problem:

  1. If you're trying to log response headers using ASP.NET middleware, the "Access-Control-Allow-Origin" header will never show up even if it's there. I don't know how but it seems to be added outside the pipeline (in the end I had to use wireshark to see it).

  2. .NET CORE won't send the "Access-Control-Allow-Origin" in the response unless you have an "Origin" header in your request. Postman won't set this automatically so you'll need to add it yourself.

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

How to get IP address of running docker container

For my case, below worked on Mac:

I could not access container IPs directly on Mac. I need to use localhost with port forwarding, e.g. if the port is 8000, then http://localhost:8000

See https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds

The original answer was from: https://github.com/docker/for-mac/issues/2670#issuecomment-371249949

Error: the entity type requires a primary key

None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.

How to put a component inside another component in Angular2?

If you remove directives attribute it should work.

@Component({
    selector: 'parent',
    template: `
            <h1>Parent Component</h1>
            <child></child>
        `
    })
    export class ParentComponent{}


@Component({
    selector: 'child',    
    template: `
            <h4>Child Component</h4>
        `
    })
    export class ChildComponent{}

Directives are like components but they are used in attributes. They also have a declarator @Directive. You can read more about directives Structural Directives and Attribute Directives.

There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.

A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.


Also if you are open the glossary you can find that components are also directives.

Directives fall into one of the following categories:

  • Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.

  • Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.

  • Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.


The difference that components have a template. See Angular Architecture overview.

A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.


The @Component metadata doesn't have directives attribute. See Component decorator.

Error message "Linter pylint is not installed"

If you are using MacPorts, you may need to activate package pylint and autopep8 after you've installed them, i.e.:

sudo port select pylint pylint36
sudo port select autopep8 autopep8-36

'Connect-MsolService' is not recognized as the name of a cmdlet

All links to the Azure Active Directory Connection page now seem to be invalid.

I had an older version of Azure AD installed too, this is what worked for me. Install this.

Run these in an elevated PS session:

uninstall-module AzureAD  # this may or may not be needed
install-module AzureAD
install-module AzureADPreview
install-module MSOnline

I was then able to log in and run what I needed.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I had this issue, it seems that I hadn't added the required NuGet packages, although I thought I had done so, make sure to check them, one by one.

Unit Tests not discovered in Visual Studio 2017

This just worked for me (don't know if it is the result of changing workspaces that corrupted something):

Deleting VS test cache files in %TEMP%\VisualStudioTestExplorerExtensions and restart VS2017.

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

Visual Studio 2017 errors on standard headers

If the problem is not solved by above answer, check whether the Windows SDK version is 10.0.15063.0.

Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0

After this rebuild the solution.  

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Visual Studio 2017 - Git failed with a fatal error

Compounded the problem by deleting the local repo so I could clone a fresh copy. I was faced with new error "git cannot be found Git failed with a fatal error.fatal: repository 'xyz' not found"

I tried everything suggestions i google about with no resolution. The following simple step worked for me and I am adding it to the growing list of possible resolutions:

git config --get http.proxy result is http://google.com:80

this is not right so i got rid of it.

git config --global --unset http.proxy

How to download Visual Studio 2017 Community Edition for offline installation?

The command above worked for me

C:\Users\marcelo\Downloads\vs_community.exe --lang en-en --layout C:\VisualStudio2017 --all

The default XML namespace of the project must be the MSBuild XML namespace

I ran into this issue while opening the Service Fabric GettingStartedApplication in Visual Studio 2015. The original solution was built on .NET Core in VS 2017 and I got the same error when opening in 2015.

Here are the steps I followed to resolve the issue.

  • Right click on (load Failed) project and edit in visual studio.
  • Saw the following line in the Project tag: <Project Sdk="Microsoft.NET.Sdk.Web" >

  • Followed the instruction shown in the error message to add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to this tag

It should now look like:

<Project Sdk="Microsoft.NET.Sdk.Web" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  • Reloading the project gave me the next error (yours may be different based on what is included in your project)

"Update" element <None> is unrecognized

  • Saw that None element had an update attribute as below:

    <None Update="wwwroot\**\*;Views\**\*;Areas\**\Views">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
    
  • Commented that out as below.

    <!--<None Update="wwwroot\**\*;Views\**\*;Areas\**\Views">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>-->
    
  • Onto the next error: Version in Package Reference is unrecognized Version in element <PackageReference> is unrecognized

  • Saw that Version is there in csproj xml as below (Additional PackageReference lines removed for brevity)

  • Stripped the Version attribute

    <PackageReference Include="Microsoft.AspNetCore.Diagnostics" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" />
    
  • I now get the following: VS Auto Upgrade

Bingo! The visual Studio One-way upgrade kicked in! Let VS do the magic!

  • The Project loaded but with reference lib errors. enter image description here

  • Fixed the reference lib errors individually, by removing and replacing in NuGet to get the project working!

Hope this helps another code traveler :-D

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

Specifying Font and Size in HTML table

The font tag has been deprecated for some time now.

That being said, the reason why both of your tables display with the same font size is that the 'size' attribute only accepts values ranging from 1 - 7. The smallest size is 1. The largest size is 7. The default size is 3. Any values larger than 7 will just display the same as if you had used 7, because 7 is the maximum value allowed.

And as @Alex H said, you should be using CSS for this.

How to enable C++17 compiling in Visual Studio?

Visual Studio 2020 version

In tasks.json file, (after you build and debug with the g++-9)

Add -std=c++2a for 2020 features (c++1z for 2017 features). Add -fconcepts to use concept keyword

"args": [
   "-std=c++2a",
   "-fconcepts",
   "-g",
   "${file}",
   "-o",
   "${fileDirname}/${fileBasenameNoExtension}"
],

now compile and you can use the 2020 features.

Entity Framework Core add unique constraint code-first

We can add Unique key index by using fluent api. Below code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<User>().Property(p => p.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));

    }

ps1 cannot be loaded because running scripts is disabled on this system

The following three steps are used to fix Running Scripts is disabled on this System error

Step1 : To fix this kind of problem, we have to start power shell in administrator mode.

Step2 : Type the following command set-ExecutionPolicy RemoteSigned Step3: Press Y for your Confirmation.

Visit the following for more information https://youtu.be/J_596H-sWsk

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

This issue is because you didn't register the data access component with the interface written for it. Try using as follows

services.AddTransient<IMyDataProvider, MyDataAccess>();`

docker cannot start on windows

I am using window 10 and i performed below steps to resolve this issue.

  1. check Virtualization is enabled from taskmanager-->performance
  2. Restarted the docker service
  3. Install the latest docker build and restarted the machine.
  4. Make sure the docker service is running.

Above steps helped me to resolve the issue.

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

If you have OS(64bit) and SSMS(64bit) and already install the AccessDatabaseEngine(64bit) and you still received an error, try this following solutions:

1: direct opening the sql server import and export wizard.

if you able to connect using direct sql server import and export wizard, then importing from SSMS is the issue, it's like activating 32bit if you import data from SSMS.

Instead of installing AccessDatabaseEngine(64bit) , try to use the AccessDatabaseEngine(32bit) , upon installation, windows will stop you for continuing the installation if you already have another app installed , if so , then use the following steps. This is from the MICROSOFT. The Quiet Installation.

If Office 365 is already installed, side by side detection will prevent the installation from proceeding. Instead perform a /quiet install of these components from command line. To do so, download the desired AccessDatabaseEngine.exe or AccessDatabaeEngine_x64.exe to your PC, open an administrative command prompt, and provide the installation path and switch Ex: C:\Files\AccessDatabaseEngine.exe /quiet

or check in the Addition Information content from the link below,

https://www.microsoft.com/en-us/download/details.aspx?id=54920

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Even without looking at assembly, the most obvious reason is that /= 2 is probably optimized as >>=1 and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.

Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2 as >>=1 would be the best 1st place to look.


On an unrelated note, if n is odd, the expression n*3+1 will always be even. So there is no need to check. You can change that branch to

{
   n = (n*3+1) >> 1;
   count += 2;
}

So the whole statement would then be

if (n & 1)
{
    n = (n*3 + 1) >> 1;
    count += 2;
}
else
{
    n >>= 1;
    ++count;
}

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

SQL Server® 2016, 2017 and 2019 Express full download

Scott Hanselman put together a great summary page with all of the various SQL downloads here https://www.hanselman.com/blog/DownloadSQLServerExpress.aspx.

For offline installers, see this answer https://stackoverflow.com/a/42952186/407188

Visual Studio Code: How to show line endings

There's an extension that shows line endings. You can configure the color used, the characters that represent CRLF and LF and a boolean that turns it on and off.

Name: Line endings 
Id: jhartell.vscode-line-endings 
Description: Display line ending characters in vscode 
Version: 0.1.0 
Publisher: Johnny Härtell 

VS Marketplace Link

Error: Unexpected value 'undefined' imported by the module

Make sure you should not import a module/component like this:

import { YOUR_COMPONENT } from './';

But it should be

import { YOUR_COMPONENT } from './YOUR_COMPONENT.ts';

Where Sticky Notes are saved in Windows 10 1607

It appears Microsoft now stores them in a SQLite database file called plum.sqlite located here:

C:\Users\%username%\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite

How to change the port number for Asp.Net core app?

Maybe it's because I am not using Core yet. My project didn't have a LaunchSettings.json file but that did prompt me to look in the project properties. I found it under the Web tab and simply changed the project url: enter image description here

ASP.NET Core Identity - get current user

If you are using Bearing Token Auth, the above samples do not return an Application User.

Instead, use this:

ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);

This works in apsnetcore 2.0. Have not tried in earlier versions.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

Adding binding redirect configuration for Newtonsoft.Json in your configuration file (web.config) will resolve the issue.

<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">   
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

Since Newtonsoft.Json version in your case is 9 update the version appropriatly in the configuration.

If this configuration does not work make sure the namespace (xmlns) in your configuration tag is correct or remove the name space completely.

Assembly binding redirect does not work

Homebrew refusing to link OpenSSL

I have a similar case. I need to install openssl via brew and then use pip to install mitmproxy. I get the same complaint from brew link --force. Following is the solution I reached: (without force link by brew)

LDFLAGS=-L/usr/local/opt/openssl/lib 
CPPFLAGS=-I/usr/local/opt/openssl/include
PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig 
pip install mitmproxy

This does not address the question straightforwardly. I leave the one-liner in case anyone uses pip and requires the openssl lib.

Note: the /usr/local/opt/openssl/lib paths are obtained by brew info openssl

How to determine if .NET Core is installed

(1) If you are on the Window system.

Open the command prompt.

 dotnet --version

(2) Run the below command If you are on Linux system.

dotnet --version

dotnet --info

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

How do I get an OAuth 2.0 authentication token in C#

The Rest Client answer is perfect! (I upvoted it)

But, just in case you want to go "raw"

..........

I got this to work with HttpClient.

/*
.nuget\packages\newtonsoft.json\12.0.1
.nuget\packages\system.net.http\4.3.4
*/

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;


    private static async Task<Token> GetElibilityToken(HttpClient client)
    {
        string baseAddress = @"https://blah.blah.blah.com/oauth2/token";

        string grant_type = "client_credentials";
        string client_id = "myId";
        string client_secret = "shhhhhhhhhhhhhhItsSecret";

        var form = new Dictionary<string, string>
                {
                    {"grant_type", grant_type},
                    {"client_id", client_id},
                    {"client_secret", client_secret},
                };

        HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
        return tok;
    }


internal class Token
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }
}       

Here is another working example (based off the answer above)......with a few more tweaks. Sometimes the token-service is finicky:

    private static async Task<Token> GetATokenToTestMyRestApiUsingHttpClient(HttpClient client)
    {
        /* this code has lots of commented out stuff with different permutations of tweaking the request  */

        /* this is a version of asking for token using HttpClient.  aka, an alternate to using default libraries instead of RestClient */

        OAuthValues oav = GetOAuthValues(); /* object has has simple string properties for TokenUrl, GrantType, ClientId and ClientSecret */

        var form = new Dictionary<string, string>
                {
                    { "grant_type", oav.GrantType },
                    { "client_id", oav.ClientId },
                    { "client_secret", oav.ClientSecret }
                };

        /* now tweak the http client */
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Add("cache-control", "no-cache");

        /* try 1 */
        ////client.DefaultRequestHeaders.Add("content-type", "application/x-www-form-urlencoded");

        /* try 2 */
        ////client.DefaultRequestHeaders            .Accept            .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header

        /* try 3 */
        ////does not compile */client.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        ////application/x-www-form-urlencoded

        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, oav.TokenUrl);
        /////req.RequestUri = new Uri(baseAddress);

        req.Content = new FormUrlEncodedContent(form);

        ////string jsonPayload = "{\"grant_type\":\"" + oav.GrantType + "\",\"client_id\":\"" + oav.ClientId + "\",\"client_secret\":\"" + oav.ClientSecret + "\"}";
        ////req.Content = new StringContent(jsonPayload,                                                Encoding.UTF8,                                                "application/json");//CONTENT-TYPE header

        req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        /* now make the request */
        ////HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
        HttpResponseMessage tokenResponse = await client.SendAsync(req);
        Console.WriteLine(string.Format("HttpResponseMessage.ReasonPhrase='{0}'", tokenResponse.ReasonPhrase));

        if (!tokenResponse.IsSuccessStatusCode)
        {
            throw new HttpRequestException("Call to get Token with HttpClient failed.");
        }

        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);

        return tok;
    }

APPEND

Bonus Material!

If you ever get a

"The remote certificate is invalid according to the validation procedure."

exception......you can wire in a handler to see what is going on (and massage if necessary)

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Net;

namespace MyNamespace
{
    public class MyTokenRetrieverWithExtraStuff
    {
        public static async Task<Token> GetElibilityToken()
        {
            using (HttpClientHandler httpClientHandler = new HttpClientHandler())
            {
                httpClientHandler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
                using (HttpClient client = new HttpClient(httpClientHandler))
                {
                    return await GetElibilityToken(client);
                }
            }
        }

        private static async Task<Token> GetElibilityToken(HttpClient client)
        {
            // throws certificate error if your cert is wired to localhost // 
            //string baseAddress = @"https://127.0.0.1/someapp/oauth2/token";

            //string baseAddress = @"https://localhost/someapp/oauth2/token";

        string baseAddress = @"https://blah.blah.blah.com/oauth2/token";

        string grant_type = "client_credentials";
        string client_id = "myId";
        string client_secret = "shhhhhhhhhhhhhhItsSecret";

        var form = new Dictionary<string, string>
                {
                    {"grant_type", grant_type},
                    {"client_id", client_id},
                    {"client_secret", client_secret},
                };

            HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
            var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
            Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
            return tok;
        }

        private static bool CertificateValidationCallBack(
        object sender,
        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
        System.Security.Cryptography.X509Certificates.X509Chain chain,
        System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                if (chain != null && chain.ChainStatus != null)
                {
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) &&
                           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                            continue;
                        }
                        else
                        {
                            if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return false;
                            }
                        }
                    }
                }

                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }


            /* overcome localhost and 127.0.0.1 issue */
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
            {
                if (certificate.Subject.Contains("localhost"))
                {
                    HttpRequestMessage castSender = sender as HttpRequestMessage;
                    if (null != castSender)
                    {
                        if (castSender.RequestUri.Host.Contains("127.0.0.1"))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;

        }


        public class Token
        {
            [JsonProperty("access_token")]
            public string AccessToken { get; set; }

            [JsonProperty("token_type")]
            public string TokenType { get; set; }

            [JsonProperty("expires_in")]
            public int ExpiresIn { get; set; }

            [JsonProperty("refresh_token")]
            public string RefreshToken { get; set; }
        }

    }
}

........................

I recently found (Jan/2020) an article about all this. I'll add a link here....sometimes having 2 different people show/explain it helps someone trying to learn it.

http://luisquintanilla.me/2017/12/25/client-credentials-authentication-csharp/

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

Predefined type 'System.ValueTuple´2´ is not defined or imported

For Visual Studio Code use the built in Terminal and run:

dotnet add package "System.ValueTuple"

Don't forget to run dotnet restore afterwards.

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

This is the solution i found.

https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/miscellaneous/configuring-dbcontext.md

Configure DBContext via AddDbContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

Add new constructor to your DBContext class

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Inject context to your controllers

public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}

The term "Add-Migration" is not recognized

These are the steps I followed and it solved the problem

1)Upgraded my Power shell from version 2 to 3

2)Closed the PM Console

3)Restarted Visual Studio

4)Ran the below command in PM Console dotnet restore

5)Add-Migration InitialMigration

It worked !!!

What's the difference between .NET Core, .NET Framework, and Xamarin?

.NET Core is the current version of .NET that you should be using right now (more features , fixed bugs , etc.)

Xamarin is a platform that provides solutions for cross platform mobile problems coded in C# , so that you don't need to use Swift separately for IOS and the same goes for Android.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

Edit Web Config for each crystaldecisions file version make it equal the same version off the dll file (from rght click on it and select from properties from solution explorer ) Eg. crystaldecisions.reportappserver.commlayer.dll --> 13.0.2000.0 after upgrade crystal report to CRforVS_13_0_21 edit it to ---> 13.0.35.00.0

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

Microsoft now recommends using an IHttpClientFactory with the following benefits:

  • Provides a central location for naming and configuring logical HttpClient instances. For example, a client named github could be registered and configured to access GitHub. A default client can be registered for general access.
  • Codifies the concept of outgoing middleware via delegating handlers in HttpClient. Provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient.
  • Manages the pooling and lifetime of underlying HttpClientMessageHandler instances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managing HttpClient lifetimes.
  • Adds a configurable logging experience (via ILogger) for all requests sent through clients created by the factory.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1

Setup:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        // Remaining code deleted for brevity.

POST example:

public class BasicUsageModel : PageModel
{
    private readonly IHttpClientFactory _clientFactory;

    public BasicUsageModel(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    
    public async Task CreateItemAsync(TodoItem todoItem)
    {
        var todoItemJson = new StringContent(
            JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
            Encoding.UTF8,
            "application/json");
            
        var httpClient = _clientFactory.CreateClient();
        
        using var httpResponse =
            await httpClient.PostAsync("/api/TodoItems", todoItemJson);
    
        httpResponse.EnsureSuccessStatusCode();
    }

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#make-post-put-and-delete-requests

tsc throws `TS2307: Cannot find module` for a local file

The vscode codebase does not use relative paths, but everything works fine for them

Really depends on your module loader. If you are using systemjs with baseurl then it would work. VSCode uses its own custom module loader (based on an old version of requirejs).

Recommendation

Use relative paths as that is what commonjs supports. If you move files around you will get a typescript compile time error (a good thing) so you will be better off than a great majority of pure js projects out there (on npm).

How to check encoding of a CSV file

Use chardet https://github.com/chardet/chardet (documentation is short and easy to read).

Install python, then pip install chardet, at last use the command line command.

I tested under GB2312 and it's pretty accurate. (Make sure you have at least a few characters, sample with only 1 character may fail easily).

file is not reliable as you can see.

enter image description here

Disable beep of Linux Bash on Windows 10

Since the only noise terminals tend to make is the bell and if you want it off everywhere, the very simplest way to do it for bash on Windows:

  1. Mash backspace a bunch at the prompt
  2. Right click sound icon and choose Open Volume Mixer
  3. Lower volume on Console Window Host to zero

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

New .NET 5 Solution:

In .NET 5, a new class has been introduced called JsonContent, which derives from HttpContent. See in Microsoft docs

This class has a static method called Create(), which takes an object as a parameter.

Usage:

var myObject = new
{
    foo = "Hello",
    bar = "World",
};

JsonContent content = JsonContent.Create(myObject);

HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);

Could not autowire field:RestTemplate in Spring boot application

If a TestRestTemplate is a valid option in your unit test, this documentation might be relevant

http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-rest-templates-test-utility

Short answer: if using

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

then @Autowired will work. If using

@SpringBootTest(webEnvironment=WebEnvironment.MOCK)

then create a TestRestTemplate like this

private TestRestTemplate template = new TestRestTemplate();

How to use SqlClient in ASP.NET Core?

Try this one Open your projectname.csproj file its work for me.

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

You need to add this Reference "ItemGroup" tag inside.

How to edit default dark theme for Visual Studio Code?

The file you are looking for is at,

Microsoft VS Code\resources\app\extensions\theme-defaults\themes

on Windows and search for filename dark_vs.json to locate it on any other system.


Update:

With new versions of VSCode you don't need to hunt for the settings file to customize the theme. Now you can customize your color theme with the workbench.colorCustomizations and editor.tokenColorCustomizations user settings. Documentation on the matter can be found here.

Angular 2 router no base href set

https://angular.io/docs/ts/latest/guide/router.html

Add the base element just after the <head> tag. If the app folder is the application root, as it is for our application, set the href value exactly as shown here.

The <base href="/"> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.

<head>
  <base href="/">
  ...
</head>

Alternatively add

>= Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  declarations: [AppComponent],
  imports: [routing /* or RouterModule */], 
  providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]); 

in your bootstrap.

In older versions the imports had to be like

< Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  {provide: APP_BASE_HREF, useValue : '/' });
]); 

< RC.0

import {provide} from 'angular2/core';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  provide(APP_BASE_HREF, {useValue : '/' });
]); 

< beta.17

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

import {APP_BASE_HREF} from 'angular2/platform/common';

See also Location and HashLocationStrategy stopped working in beta.16

Build error, This project references NuGet

In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.

I just edited the Project Name in csproj file of the Project & it Worked...!

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

Here is the solution I found:

Go to SQL Server Management, Disable Memory Shared, TCP/IP and Pipes named.

Restart the server and try again.

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.

In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.

Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.

1.The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226). Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.

For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

  1. Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime? The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state: 1) If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061 2) If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy. a. This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds). 3) If the Windows Update service is in a non-ready state, you can see errors reflecting that. a. We recently investigated a failure with an error code indicating the WUSA service was shutting down.

  2. To identify if the prerequisite KB2919355 is installed there are 2 options: Registry key: 64bit hive HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14 CurrentState = 112 32bit hive HKLM\SOFTWARE[WOW6432Node]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14 CurrentState = 112

Or check the file version of: C:\Windows\SysWOW64\wuaueng.dll C:\Windows\System32\wuaueng.dll 7.9.9600.17031 or later

Multiple Errors Installing Visual Studio 2015 Community Edition

For some reason the installation broke while in process. After this, nothing helped and repair/unistall only produced package errors. What finally helped was this thing: https://github.com/Microsoft/VisualStudioUninstaller

after I ran it a couple times (it didn't remove everything on the first pass...es) I was finally able to start a fresh installation and it worked.

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

On Mac OS X El Capitan I had to run these two commands to fix this error:

xcode-select --install
pip install lxml

Which ended up installing lxml-3.5.0

When you run the xcode-select command you may have to sign a EULA (so have an X-Term handy for the UI if you're doing this on a headless machine).

Connecting to Microsoft SQL server using Python

Minor addition to what has been said before. You likely want to return a dataframe. This would be done as

import pypyodbc 
import pandas as pd

cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=server_name;"
                        "Database=db_name;"
                        "uid=User;pwd=password")
df = pd.read_sql_query('select * from table', cnxn)

Where can I read the Console output in Visual Studio 2015

What may be happening is that your console is closing before you get a chance to see the output. I would add Console.ReadLine(); after your Console.WriteLine("Hello World"); so your code would look something like this:

static void Main(string[] args)
    {
        Console.WriteLine("Hello World");
        Console.ReadLine();

    }

This way, the console will display "Hello World" and a blinking cursor underneath. The Console.ReadLine(); is the key here, the program waits for the users input before closing the console window.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

What is the reason for the error message "System cannot find the path specified"?

There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

For more details see the Microsoft documentation about File System Redirector.

So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"

Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

How it works?

There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

I have the same problem that my app worked in Vs2013 but getting the error after updating to Vs2015.

  1. In Vs2015, right click project's References folder, to open NuGet Package Manager
  2. Under Browse tab, search for "DotNetCompilerPlatform" and install "Microsoft.CodeDom.Providers.DotNetCompilerPlatform" lib

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

  1. Delete all temp files
    • search %TEMP%
    • delete all
  2. Perform a clean boot. see How to perform a clean boot in Windows
  3. Install vc_redist.x64 see Download Visual C++ Redistributable for Visual Studio 2015
  4. Restart without clean boot

The type or namespace name 'System' could not be found

Open Project References, I had lots of yellow warning triangles on the various packages. Click Add Reference, just doing that seems to get VS to refresh it references, and the yellow triangles disappeared and the errors from the code also.

You might have to do this in a few projects if your solution reference to other projects

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I had the same issue today recently installing VS2015 Community Edition Update 1.

I fixed the problem by just adding the "SQL Server Data Tools" from the VS2015 setup installer... When I ran the installer the first time I selected the "Custom" installation type instead of the "Default". I wanted to see what install options were available but not select anything different than what was already ticked. My assumption was that whatever was already ticked was essentially the default install. But its not.

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

For Ubuntu, please install the below things:

sudo apt-get update && sudo apt-get install build-essential

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

The target principal name is incorrect. Cannot generate SSPI context

I had this problem on my sql server. I setspn -D mssqlsvc\Hostname.domainname Hostname then stoped and started my SQL server service.

I am thinking that just stopping and starting my sql service would have done it.

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not know about woff and woff2 file mime types.

Solution 1:

Add these lines in your web.config project:

 <system.webServer>
  ...
  </modules>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>

Solution 2:

On IIS project page:

Step 1: Go to your project IIS home page and double click on MIME Types button:

Step 1

Step 2: Click on Add button from Actions menu: Step 2

Step 3: In the middle of the screen appears a window and in this window you need to add the two lines from solution 1: Step 3

NuGet Packages are missing

The error message is completely correct. I tried all the tricks and none worked. The project (simple MVC Web App test) moved from Windows 8.1 VS 2015 Community to my new test box on Windows 10. All the latest updates to VS 2015 applied. I could not even install any newer version of the compilers package.

Loop:
<LOOP>This seems to be a Ground Hog Day phenomena.</LOOP>
GoTo Loop

I finally just copied Microsoft.Net.Compilers.1.0.0 from the old project into the new one and it worked. I could then start to update other packages to newer version. Looks like a nuget project upgrade process bug to me.

NOTE: The original project was created in VS 2015 and does not have any legacy nuget methodologies.

Visual Studio Community 2015 expiration date

There is and there isn't an expiration date. If you register Visual Studio 2015 Community Edition by successfully signing into Visual Studio then the product is fully unlocked with no set expiry date. If you don't sign in (or haven't entered a purchased licence key), you only have 30 day evaluation license.

You can check whether your copy of Visual Studio has is registered or not by selecting Help -> About Microsoft Studio and clicking on the "License Status" link in the upper right of the About dialog. If your product isn't registered you'll see something like this:

Visual Studio 2015 License Status Window

Change the location of the ~ directory in a Windows install of Git Bash

Instead of modifying the global profile you could create the .bash_profile in your default $HOME directory (e.g. C:\Users\WhateverUser\.bash_profile) with the following contents:

export HOME="C:\my\projects\dir"
cd "$HOME" # if you'd like it to be the starting dir of the git shell

How to Identify Microsoft Edge browser via CSS?

For Internet Explorer 

@media all and (-ms-high-contrast: none) {
        .banner-wrapper{
            background: rgba(0, 0, 0, 0.16)
         }
}

For Edge
@supports (-ms-ime-align:auto) {
    .banner-wrapper{
            background: rgba(0, 0, 0, 0.16);
         }
}

Visual Studio 2015 doesn't have cl.exe

Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++

How to enable CORS in ASP.NET Core

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAnyOrigin",
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
    });

    services.Configure<MvcOptions>(options => {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
    });            
}

How do I enable Java in Microsoft Edge web browser?

Edge has dropped all support for plugins. This means that Java, ActiveX, Silverlight, and other plugins are no longer supported. For this reason Microsoft has included Internet Explorer 11, which does support these plugins, with non-mobile versions of Windows 10. If you are running Windows 10 and need plugin support Edge is not an option, but IE 11 is.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

Run JavaScript in Visual Studio Code

Another way would be to open terminal ctrl+` execute node. Now you have a node REPL active. You can now send your file or selected text to terminal. In order to do that open VSCode command pallete (F1 or ctrl+shift+p) and execute >run selected text in active terminal or >run active file in active terminal.

If you need a clean REPL before executing your code you will have to restart the node REPL. This is done when in the Terminal with the node REPL ctrl+c ctrl+c to exit it and typing node to start new.

You could probably key bind the command pallete commands to whatever key you wish.

PS: node should be installed and in your path

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

First of all its not the Notepad++ problem for sure. Its your "String Matching problem"

The common string throughout all IE version is MSIE Check out the various userAgent strings at http://www.useragentstring.com/pages/Internet%20Explorer/

if(navigator.userAgent.indexOf("MSIE") != -1){
   alert('I am Internet Explorer!!');
}

CMake does not find Visual C++ compiler

I looked in CMakeError.log file and found an error about cannot run 'rc.exe'

I searched and found this answer to copy RC.Exe and RcDll.Dll from the Microsoft SDKs bin to the VC bin, and then CMake worked.


Edit: The top answer to another question suggests that it's a PATH issue, so it could be enough to ensure the Microsoft SDK bin is in your PATH.

Missing Microsoft RDLC Report Designer in Visual Studio

I've had the same problem as you and I installed Microsoft rdlc designer to solve my problem.

And if you already installed this but still can't found rdlc designer try open visual studio > tools > Extension and Updates > then enable Miscrosoft Rdlc designer extensions.

installing apache: no VCRUNTIME140.dll

Be sure you have C++ Redistributable for Visual Studio 2015 RC. Try to download the last version:

https://www.microsoft.com/en-us/download/details.aspx?id=52685

Obs: Credit to parsecer

How do you create a custom AuthorizeAttribute in ASP.NET Core?

For authorization in our app. We had to call a service based on the parameters passed in authorization attribute.

For example, if we want to check if logged in doctor can view patient appointments we will pass "View_Appointment" to custom authorize attribute and check that right in DB service and based on results we will athorize. Here is the code for this scenario:

    public class PatientAuthorizeAttribute : TypeFilterAttribute
    {
    public PatientAuthorizeAttribute(params PatientAccessRights[] right) : base(typeof(AuthFilter)) //PatientAccessRights is an enum
    {
        Arguments = new object[] { right };
    }

    private class AuthFilter : IActionFilter
    {
        PatientAccessRights[] right;

        IAuthService authService;

        public AuthFilter(IAuthService authService, PatientAccessRights[] right)
        {
            this.right = right;
            this.authService = authService;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var allparameters = context.ActionArguments.Values;
            if (allparameters.Count() == 1)
            {
                var param = allparameters.First();
                if (typeof(IPatientRequest).IsAssignableFrom(param.GetType()))
                {
                    IPatientRequest patientRequestInfo = (IPatientRequest)param;
                    PatientAccessRequest userAccessRequest = new PatientAccessRequest();
                    userAccessRequest.Rights = right;
                    userAccessRequest.MemberID = patientRequestInfo.PatientID;
                    var result = authService.CheckUserPatientAccess(userAccessRequest).Result; //this calls DB service to check from DB
                    if (result.Status == ReturnType.Failure)
                    {
                        //TODO: return apirepsonse
                        context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
                    }
                }
                else
                {
                    throw new AppSystemException("PatientAuthorizeAttribute not supported");
                }
            }
            else
            {
                throw new AppSystemException("PatientAuthorizeAttribute not supported");
            }
        }
    }
}

And on API action we use it like this:

    [PatientAuthorize(PatientAccessRights.PATIENT_VIEW_APPOINTMENTS)] //this is enum, we can pass multiple
    [HttpPost]
    public SomeReturnType ViewAppointments()
    {

    }

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).

Class weights

The weights from the class_weight parameter are used to train the classifier. They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.

Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.

The metrics

Once you have a classifier, you want to know how well it is performing. Here you can use the metrics you mentioned: accuracy, recall_score, f1_score...

Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.

I will not detail all these metrics but note that, with the exception of accuracy, they are naturally applied at the class level: as you can see in this print of a classification report they are defined for each class. They rely on concepts such as true positives or false negative that require defining which class is the positive one.

             precision    recall  f1-score   support

          0       0.65      1.00      0.79        17
          1       0.57      0.75      0.65        16
          2       0.33      0.06      0.10        17
avg / total       0.52      0.60      0.51        50

The warning

F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The 
default `weighted` averaging is deprecated, and from version 0.18, 
use of precision, recall or F-score with multiclass or multilabel data  
or pos_label=None will result in an exception. Please set an explicit 
value for `average`, one of (None, 'micro', 'macro', 'weighted', 
'samples'). In cross validation use, for instance, 
scoring="f1_weighted" instead of scoring="f1".

You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:

  1. Take the average of the f1-score for each class: that's the avg / total result above. It's also called macro averaging.
  2. Compute the f1-score using the global count of true positives / false negatives, etc. (you sum the number of true positives / false negatives for each class). Aka micro averaging.
  3. Compute a weighted average of the f1-score. Using 'weighted' in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.

These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average argument for the score method.

Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.

The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.

Computing scores

Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.

Here's a way to do it using StratifiedShuffleSplit, which gives you a random splits of your data (after shuffling) that preserve the label distribution.

from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
    X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
    svc.fit(X_train, y_train)
    y_pred = svc.predict(X_test)
    print(f1_score(y_test, y_pred, average="macro"))
    print(precision_score(y_test, y_pred, average="macro"))
    print(recall_score(y_test, y_pred, average="macro"))    

Hope this helps.

Lazy Loading vs Eager Loading

Lazy loading - is good when handling with pagination like on page load list of users appear which contains 10 users and as the user scrolls down the page an api call brings next 10 users.Its good when you don't want to load enitire data at once as it would take more time and would give bad user experience.

Eager loading - is good as other people suggested when there are not much relations and fetch entire data at once in single call to database

Ansible date variable

The command ansible localhost -m setup basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output.

When you run the echo command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-playbook to run a playbook that looks something like this:

- hosts: localhost
  tasks:
      - debug: var=ansible_date_time

      - debug: msg="the current date is {{ ansible_date_time.date }}"

Because this runs as a playbook facts for localhost are gathered before the tasks are run. The output of the above playbook will be something like this:

PLAY [localhost] **************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [debug var=ansible_date_time] *******************************************
ok: [localhost] => {
    "ansible_date_time": {
        "date": "2015-07-09",
        "day": "09",
        "epoch": "1436461166",
        "hour": "16",
        "iso8601": "2015-07-09T16:59:26Z",
        "iso8601_micro": "2015-07-09T16:59:26.896629Z",
        "minute": "59",
        "month": "07",
        "second": "26",
        "time": "16:59:26",
        "tz": "UTC",
        "tz_offset": "+0000",
        "weekday": "Thursday",
        "year": "2015"
    }
}

TASK: [debug msg="the current date is {{ ansible_date_time.date }}"] **********
ok: [localhost] => {
    "msg": "the current date is 2015-07-09"
}

PLAY RECAP ********************************************************************
localhost      : ok=3    changed=0    unreachable=0    failed=0

Flask ImportError: No Module Named Flask

If you are using Pycharm then this is the virtual environment issue.

So, at the time of creating your Python project you will have to select "Existing interpreter" option -> click "system Interpreter" -> select the correct option for example "*\AppData\Local\Programs\Python\Python3.6\python.exe".

You can use 'New Virtual Env' as well, but I have just given the quick fix that should work for Pycharm users.

Microsoft.ReportViewer.Common Version=12.0.0.0

Issue

Parser Error Message: Could not load file or assembly 'Microsoft.ReportViewer.WebForms / Winforms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Cause

Microsoft ReportViewer runtime and SQL CLR Types for SQL Server 2014 is required to run and is missing from the server hosting Internet Information Services (IIS) or your application.

Resolution

Install the following packages on the IIS server and then restart the system:

Download Microsoft ReportViewer runtime

Download Microsoft SQL CLR types for SQL Server 2014

Once restarted connect to Web service / Your app again and verify that the error has been resolved.

Or you cant follow this link to read more.

How to open URL in Microsoft Edge from the command line?

It will do more or less the same thing in good old dos script fashion

set add=%1
if %add%$ ==$ set add="about:blank" && goto launch

rem http://
set test=%add:~0, 7%
if %test% == http:// goto launch

rem ftp:// 
set test=%add:~0, 6%
if %test% == ftp:// goto launch

rem https://
set test=%add:~0, 8%
if %test% == https:// goto launch

rem add http
set add=http://%add%

:launch
start microsoft-edge:%add%

Cordova - Error code 1 for command | Command failed for

I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.

  • Downgrade NodeJs to 0.10.36
  • Upgrade Android SDK 22

How to get the current logged in user Id in ASP.NET Core

Until ASP.NET Core 1.0 RC1 :

It's User.GetUserId() from System.Security.Claims namespace.

Since ASP.NET Core 1.0 RC2 :

You now have to use UserManager. You can create a method to get the current user :

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

And get user information with the object :

var user = await GetCurrentUserAsync();

var userId = user?.Id;
string mail = user?.Email;

Note : You can do it without using a method writing single lines like this string mail = (await _userManager.GetUserAsync(HttpContext.User))?.Email, but it doesn't respect the single responsibility principle. It's better to isolate the way you get the user because if someday you decide to change your user management system, like use another solution than Identity, it will get painful since you have to review your entire code.

Authentication failed because remote party has closed the transport stream

If you want to use an older version of .net, create your own flag and cast it.

    //
    // Summary:
    //     Specifies the security protocols that are supported by the Schannel security
    //     package.
    [Flags]
    private enum MySecurityProtocolType
    {
        //
        // Summary:
        //     Specifies the Secure Socket Layer (SSL) 3.0 security protocol.
        Ssl3 = 48,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.0 security protocol.
        Tls = 192,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.1 security protocol.
        Tls11 = 768,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.2 security protocol.
        Tls12 = 3072
    }
    public Session()
    {
        System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(MySecurityProtocolType.Tls12 | MySecurityProtocolType.Tls11 | MySecurityProtocolType.Tls);
    }

Simple InputBox function

The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString

This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

If the info does not need to be secure at all you can convert it to plain text:

$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))

Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0

How do I create a local database inside of Microsoft SQL Server 2014?

As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx

Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio (full version) is a "full-featured" and "convenient" development environment.

Visual Studio (free "Express" versions - only until 2017) are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.

Visual Studio (free Community edition - since 2015) is a simplified version of the full version and replaces the separated express editions used before 2015.

Visual Studio Code (VSCode) is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.

For example, if you want to create an ASP.NET application using Visual Studio Code you need to perform several steps on your own to setup the project. There is a separate tutorial for each OS.

checking for typeof error in JS

I asked the original question - @Trott's answer is surely the best.

However with JS being a dynamic language and with there being so many JS runtime environments, the instanceof operator can fail especially in front-end development when crossing boundaries such as iframes. See: https://github.com/mrdoob/three.js/issues/5886

If you are ok with duck typing, this should be good:

let isError = function(e){
 return e && e.stack && e.message;
}

I personally prefer statically typed languages, but if you are using a dynamic language, it's best to embrace a dynamic language for what it is, rather than force it to behave like a statically typed language.

if you wanted to get a little more precise, you could do this:

   let isError = function(e){
     return e && e.stack && e.message && typeof e.stack === 'string' 
            && typeof e.message === 'string';
    }

Does Visual Studio Code have box select/multi-line edit?

Press Ctrl+Alt+Down or Ctrl+Alt+Up to insert cursors below or above.

Find and replace with a newline in Visual Studio Code

In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.

Image of multiline search in local search

If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.

Image of multiline search in global search

If you want to search for multilines by the character literal, remember to check the rightmost regex icon.

Image of regex mode in search replace


In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.

How do I set up Visual Studio Code to compile C++ code?

A makefile task example for new 2.0.0 tasks.json version.

In the snippet below some comments I hope they will be useful.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "<TASK_NAME>",
            "type": "shell",
            "command": "make",
            // use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
            "options": {
                "cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
            },
            // start the build without prompting for task selection, use "group": "build" otherwise
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared"
            },
            // arg passing example: in this case is executed make QUIET=0
            "args": ["QUIET=0"],
            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["absolute"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

How do I duplicate a line or selection within Visual Studio Code?

In VScode, they call this Copy Line Up and Copy Line Down

From the menu, go to:

File > Preferences > Keyboard Shortcuts

Check already assigned keyboard shortcut for this, or adjust yours.

Sometimes the default assigned shortcut may not work, mostly because of OS.

In my Ubuntu, I adjusted this to: Ctrl+Shift+D

enter image description here

How to compile c# in Microsoft's new Visual Studio Code?

SHIFT+CTRL+B should work

However sometimes an issue can happen in a locked down non-adminstrator evironment:

If you open an existing C# application from the folder you should have a .sln (solution file) etc..

Commonly you can get these message in VS Code

Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!

Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'

Finished
Failed to spawn 'dotnet --info'  //this is a possible issue

To which then you will be asked to install .NET CLI tools

If impossible to get SDK installed with no admin privilege - then use other solution.

How do I hide certain files from the sidebar in Visual Studio Code?

The __pycache__ folder and *.pyc files are totally unnecessary to the developer. To hide these files from the explorer view, we need to edit the settings.json for VSCode. Add the folder and the files as shown below:

"files.exclude": {
  ...
  ...
  "**/*.pyc": {"when": "$(basename).py"}, 
  "**/__pycache__": true,
  ...
  ...
}

How to install VS2015 Community Edition offline

Go to https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx

Navigate to "Visual studio downloads", select "Visual studio 2015"

enter image description here

Next, choose format "ISO"

enter image description here

How can I rebuild indexes and update stats in MySQL innoDB?

For basic cleanup and re-analyzing you can run "OPTIMIZE TABLE ...", it will compact out the overhead in the indexes and run ANALYZE TABLE too, but it's not going to re-sort them and make them as small & efficient as they could be.

https://dev.mysql.com/doc/refman/8.0/en/optimize-table.html

However, if you want the indexes completely rebuilt for best performance, you can:

  1. drop / re-add indexes (obviously)
  2. dump / reload the table
  3. ALTER TABLE and "change" using the same storage engine
  4. REPAIR TABLE (only works for MyISAM, ARCHIVE, and CSV)

https://dev.mysql.com/doc/refman/8.0/en/rebuilding-tables.html

If you do an ALTER TABLE on a field (that is part of an index) and change its type, then it will also fully rebuild the related index(es).

How to view an HTML file in the browser with Visual Studio Code

One click solution simply install open-in-browser Extensions from the Visual Studio marketplace.

How do I create a shortcut via command-line in Windows?

To create a shortcut for warp-cli.exe, I based rojo's Powershell command and added WorkingDirectory, Arguments, IconLocation and minimized WindowStyle attribute to it.

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\CWarp_DoH.lnk');$s.TargetPath='E:\Program\CloudflareWARP\warp-cli.exe';$s.Arguments='connect';$s.IconLocation='E:\Program\CloudflareWARP\Cloudflare WARP.exe';$s.WorkingDirectory='E:\Program\CloudflareWARP';$s.WindowStyle=7;$s.Save()"

Other PS attributes for CreateShortcut: https://stackoverflow.com/a/57547816/4127357

Uncaught TypeError: Cannot read property 'appendChild' of null

Instead of using your script tag defining the source of your .js file in <head>, place it at the bottom of your HTML code.

How do I open multiple instances of Visual Studio Code?

To open a new instance with your project loaded from terminal, just type code <directory-path>

How to call VS Code Editor from terminal / command line

This will work. This is your directory name "Directory_Name"

 sudo code --user-data-dir="Directory_Name"

Microsoft Visual C++ Compiler for Python 3.4

Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:

Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.

See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw

This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

If you have already installed Visual Studio Build Tools (as in other comments), and upgraded setuptools but it still doesn't work:

Make sure to run pip under x86 or x64 Native Tools Command Prompt.

It can be found under VS folder in Windows start menu. The default command line prompt may NOT provide Pip the path to the VS build tool, as is in my case.

Visual Studio 2015 or 2017 does not discover unit tests

I had the same issue. The unit test template of Visual Studio 2015 (Update 3) generates a class with TestContext property defined as follow:

    private TestContext testContextInstance;

    /// <summary>
    ///Gets or sets the test context which provides
    ///information about and functionality for the current test run.
    ///</summary>
    public TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }

After changing it to a public field (ungly) the test runner could discover the test.

public TestContext TestContext;

Very strange behaviour, but it was the cause of the issue in my case.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

I was getting this error too and the reason ended up being wrong call url. I am leaving this answer here, if someone else happens to mix the urls and getting this error. Took me hours to realize I had wrong URL.

Error I got (HTTP code 400):

{
    "error": "unsupported_grant_type",
    "error_description": "grant type not supported"
}

I was calling:

https://MY_INSTANCE.lightning.force.com

While the correct URL would have been:

https://MY_INSTANCE.cs110.my.salesforce.com

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

You just need to change some files. This works for me.

Global.ascx

public class WebApiApplication : System.Web.HttpApplication {
    protected void Application_Start()
    {
        WebApiConfig.Register(GlobalConfiguration.Configuration);
    } }

WebApiConfig.cs

All the requests has to call this code.

public static class WebApiConfig {
    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        AddRoutes(config);
    }

    private static void AddRoutes(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/"
        );
    }

    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute(
            origins: "*", 
            headers: "*", 
            methods: "*");
        config.EnableCors(cors);
    } }

Some Controller

Nothing to change.

Web.config

You need to add handlers in your web.config

<configuration> 
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>   
  </system.webServer> 
</configuration>

JavaScript Array to Set

By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.

var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}


var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}

So, do not convert to set if you have repeated values in your array.

How do I check if a PowerShell module is installed?

You can use the Get-InstalledModule

If (-not(Get-InstalledModule SomeModule -ErrorAction silentlycontinue)) {
  Write-Host "Module does not exist"
}
Else {
  Write-Host "Module exists"
}

How to get 'System.Web.Http, Version=5.2.3.0?

Uninstalling and re-installing the NuGet package worked for me.

  1. Remove any old reference from the project.

Execute this in the Package Manager Console:

  1. UnInstall-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
  2. Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Return content with IHttpActionResult for non-OK response

Simple:

return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Your message"));

Remember to reference System.Net.Http and System.Net.

How to extend available properties of User.Identity

I was looking for the same solution and Pawel gave me 99% of the answer. The only thing that was missing that I needed for the Extension to display was adding the following Razor Code into the cshtml(view) page:

@using programname.Models.Extensions

I was looking for the FirstName, to display in the top right of my NavBar after the user logged in.

I thought I would post this incase it helps someone else, So here is my code:

I created a new folder called Extensions(Under my Models Folder) and created the new class as Pawel specified above: IdentityExtensions.cs

using System.Security.Claims;
using System.Security.Principal;

namespace ProgramName.Models.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetUserFirstname(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("FirstName");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

IdentityModels.cs :

public class ApplicationUser : IdentityUser
{

    //Extended Properties
    public string FirstName { get; internal set; }
    public string Surname { get; internal set; }
    public bool isAuthorized { get; set; }
    public bool isActive { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("FirstName", this.FirstName));

        return userIdentity;
    }
}

Then in my _LoginPartial.cshtml(Under Views/Shared Folders) I added @using.ProgramName.Models.Extensions

I then added the change to the folling line of code that was going to use the Users First name after Logging in :

@Html.ActionLink("Hello " + User.Identity.GetUserFirstname() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Perhaps this helps someone else down the line.

Default SecurityProtocol in .NET 4.5

Some of the those leaving comments have noted that setting System.Net.ServicePointManager.SecurityProtocol to specific values means that your app won't be able to take advantage of future TLS versions that may become the default values in future updates to .NET. Instead of specifying a fixed list of protocols, you can instead turn on or off protocols you know and care about, leaving any others as they are.

To turn on TLS 1.1 and 1.2 without affecting other protocols:

System.Net.ServicePointManager.SecurityProtocol |= 
    SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Notice the use of |= to turn on these flags without turning others off.

To turn off SSL3 without affecting other protocols:

System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS for Visual Studio Community 2015.

Then run the following (substituting the variable on the right-hand side if yours has a different name):

set VS100COMNTOOLS=%VS140COMNTOOLS%

This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.

For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.

Windows Scipy Install: No Lapack/Blas Resources Found

do this, it solved for me pip install -U scikit-learn

Force uninstall of Visual Studio

If you don't have media, doing a dir /s vs_ultimate.exe from the root prompt will find it. Mine was in C:\ProgramData\Package Cache\{[guid]}. Once I navigated there and ran vs_ultimate.exe with the /uninstall and /force flags, the uninstaller ran

I opened the program "Command Prompt" with as administrator and search run "dir /s vs_ultimate.exe" in ProgramData folder and find path to vs_ultimate.exe file.

Then I changed my working directory to that path and ran vs_ultimate.exe /uninstall /force.

Finally its done.

How to call a php script/function on a html button click

Modify the_script.php like this.

<script>
the_function() {
    alert("You win");
}
</script>

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

After doing a lot of things, I upgraded pip, setuptools and virtualenv.

  1. python -m pip install -U pip
  2. pip install -U setuptools
  3. pip install -U virtualenv

I did steps 1, 2 in my virtual environment as well as globally. Next, I installed the package through pip and it worked.

Microsoft Excel ActiveX Controls Disabled?

Advice in KB and above didn't work for me. I discovered that if one Excel 2007 user (with or without the security update; not sure of exact circumstances that cause this) saves the file, the original error returns.

I discovered that the fastest way to repair the file again is to delete all the VBA code. Save. Then replace the VBA code (copy/paste). Save. Before attempting this, I delete the .EXD files first, because otherwise I get an error on open.

In my case, I cannot upgrade/update all users of my Excel file in various locations. Since the problem comes back after some users save the Excel file, I am going to have to replace the ActiveX control with something else.

No process is on the other end of the pipe (SQL Server 2012)

For me the password expired for my login user, and i got the same exception. Then i login with Windows Authentication mode and change the password for the associated user, and it solved my problem.

How can I verify if an AD account is locked?

I found also this list of property flags: How to use the UserAccountControl flags

SCRIPT  0x0001  1
ACCOUNTDISABLE  0x0002  2
HOMEDIR_REQUIRED    0x0008  8
LOCKOUT 0x0010  16
PASSWD_NOTREQD  0x0020  32
PASSWD_CANT_CHANGE 0x0040   64
ENCRYPTED_TEXT_PWD_ALLOWED  0x0080  128
TEMP_DUPLICATE_ACCOUNT  0x0100  256
NORMAL_ACCOUNT  0x0200  512
INTERDOMAIN_TRUST_ACCOUNT   0x0800  2048
WORKSTATION_TRUST_ACCOUNT   0x1000  4096
SERVER_TRUST_ACCOUNT    0x2000  8192
DONT_EXPIRE_PASSWORD    0x10000 65536
MNS_LOGON_ACCOUNT   0x20000 131072
SMARTCARD_REQUIRED  0x40000 262144
TRUSTED_FOR_DELEGATION  0x80000 524288
NOT_DELEGATED   0x100000    1048576
USE_DES_KEY_ONLY    0x200000    2097152
DONT_REQ_PREAUTH    0x400000    4194304
PASSWORD_EXPIRED    0x800000    8388608
TRUSTED_TO_AUTH_FOR_DELEGATION  0x1000000   16777216
PARTIAL_SECRETS_ACCOUNT 0x04000000      67108864

You must make a binary-AND of property userAccountControl with 0x002. In order to get all locked (i.e. disabled) accounts you can filter on this:

(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))

For operator 1.2.840.113556.1.4.803 see LDAP Matching Rules

Set proxy through windows command line including login parameters

IE can set username and password proxies, so maybe setting it there and import does work

reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /t REG_SZ /d name:port
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyUser /t REG_SZ /d username
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyPass /t REG_SZ /d password
netsh winhttp import proxy source=ie

What is ".NET Core"?

I was trying to create a new project in Visual Studio 2017 today (recently upgraded from Visual Studio 2015) and noticed new set of choices for the type of project. Either they're new or it's been a while since I started a new project!! :)

Visual Studio Screenshot

I came across this documentation link and found it very useful, so I am sharing. The details of the bullets are also provided in the article. I am just posting bullets here:

You should use .NET Core for your server application when:

You have cross-platform needs.
You are targeting microservices.
You are using Docker containers.
You need high performance and scalable systems.
You need side by side of .NET versions by application.

You should use .NET Framework for your server application when:

Your application currently uses .NET Framework (recommendation is to extend instead of migrating)
You need to use third-party .NET libraries or NuGet packages not available for .NET Core.
You need to use .NET technologies that are not available for .NET Core.
You need to use a platform that doesn’t support .NET Core.

This link provides a glossary of .NET terms.

EDIT 10/7/2020 Check out .NET 5.0 - "... just one .NET going forward, and you will be able to use it to target Windows, Linux, macOS, iOS, Android, tvOS, watchOS and WebAssembly and more" It's supposed to be released November 2020.

mysql-python install error: Cannot open include file 'config-win.h'

for 64-bit windows

Installing NumPy and SciPy on 64-bit Windows (with Pip)

If you are on windows , you wouldn't need wheel anyway! You can directly install package by downloading the 32-bit package as win32 from this link [http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy] and then move that downloaded package to cmd's current directory and open cmd and write following codepip install numpy-1.13.1+mkl-cp36-cp36m-win32.whl then do it same for scipy

For 64-bit you need to install mingw-w64 as it is gcc and compiles numpy and scipy as precompiled status.

Currently it works fine with 32-bit.So I had opted for win32 package both for numpy+mkl and scipy in that link.

Hope This works! Give a try

System.web.mvc missing

Just in case someone is a position where he get's the same error. In my case downgrading Microsoft.AspNet.Mvc and then upgrading it again helped. I had this problem after installing Glimpse and removing it. System.Web.Mvc was references wrong somehow, cleaning the solution or rebuilding it didin't worked in my case. Just give it try if none of the above answers works for you.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

If you're curious which protocols .NET supports, you can try HttpClient out on https://www.howsmyssl.com/

// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");

File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);

// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");

The result is damning:

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

As Eddie explains above, you can enable better protocols manually:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; 

I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

I use VS 2017. By default SQL Server Instance name is (LocalDB)\MSSQLLocalDB. However, downgrading the compatibility level of the database to 110 as in @user3390927's answer, I could attach the database file in VS, choosing Server Name as "localhost\SQLExpress".

Error C1083: Cannot open include file: 'stdafx.h'

Just running through a Visual Studio Code tutorial and came across a similiar issue.

Replace #include "stdafx.h" with #include "pch.h" which is the updated name for the precompiled headers.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

http://www.aspsnippets.com/Articles/The-OLE-DB-provider-Microsoft.Ace.OLEDB.12.0-for-linked-server-null.aspx

This solves the issue. For some reason SQL Server does not like the default MSSQLSERVER account. Switching it to a local user account resolves the issue.

The given key was not present in the dictionary. Which key?

In the general case, the answer is No.

However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.

In Visual Studio, this option is located here:

Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic

There, you can check the Thrown box.


For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

Uses for the '&quot;' entity in HTML

As other answers pointed out, it is most likely generated by some tool.

But if I were the original author of the file, my answer would be: Consistency.

If I am not allowed to put double quotes in my attributes, why put them in the element's content ? Why do these specs always have these exceptional cases .. If I had to write the HTML spec, I would say All double quotes need to be encoded. Done.

Today it is like In attribute values we need to encode double quotes, except when the attribute value itself is defined by single quotes. In the content of elements, double quotes can be, but are not required to be, encoded. (And I am surely forgetting some cases here).

Double quotes are a keyword of the spec, encode them. Lesser/greater than are a keyword of the spec, encode them. etc..

Azure SQL Database "DTU percentage" metric

From this document, this DTU percent is determined by this query:

SELECT end_time,   
  (SELECT Max(v)    
   FROM (VALUES (avg_cpu_percent), (avg_data_io_percent), 
(avg_log_write_percent)) AS    
   value(v)) AS [avg_DTU_percent]   
FROM sys.dm_db_resource_stats;  

looks like the max of avg_cpu_percent, avg_data_io_percent and avg_log_write_percent

Reference:

https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-resource-stats-azure-sql-database

How do I use Join-Path to combine more than two strings into a file path?

The following approach is more concise than piping Join-Path statements:

$p = "a"; "b", "c", "d" | ForEach-Object -Process { $p = Join-Path $p $_ }

$p then holds the concatenated path 'a\b\c\d'.

(I just noticed that this is the exact same approach as Mike Fair's, sorry.)

NuGet: 'X' already has a dependency defined for 'Y'

This was resolved by installing the latest NuGet Package Manager:

https://visualstudiogallery.msdn.microsoft.com/4ec1526c-4a8c-4a84-b702-b21a8f5293ca

Don't forget to restart Visual Studio.

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

Spring Boot + JPA : Column name annotation ignored

For hibernate5 I solved this issue by puting next lines in my application.properties file:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

After installing SQL Server 2014 Express can't find local db

Also, if you just installed localDB, you won't see the instance in the configuration manager. You would need to initiate it first, and then connect to it using server name (localdb)\mssqllocaldb. Source

Using a PagedList with a ViewModel ASP.Net MVC

I modified the code as follow:

ViewModel

using System.Collections.Generic;
using ContosoUniversity.Models;

namespace ContosoUniversity.ViewModels
{
    public class InstructorIndexData
    {
     public PagedList.IPagedList<Instructor> Instructors { get; set; }
     public PagedList.IPagedList<Course> Courses { get; set; }
     public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
    }
}

Controller

public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
 int instructPageNumber = (InstructorPage?? 1);
 int CoursePageNumber = (CoursePage?? 1);
 int EnrollmentPageNumber = (EnrollmentPage?? 1);
 var viewModel = new InstructorIndexData();
 viewModel.Instructors = db.Instructors
    .Include(i => i.OfficeAssignment)
    .Include(i => i.Courses.Select(c => c.Department))
    .OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);

 if (id != null)
 {
    ViewBag.InstructorID = id.Value;
    viewModel.Courses = viewModel.Instructors.Where(
        i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
 }

 if (courseID != null)
 {
    ViewBag.CourseID = courseID.Value;
    viewModel.Enrollments = viewModel.Courses.Where(
        x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
 }

 return View(viewModel);
}

View

<div>
   Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount

   @Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))

</div>

I hope this would help you!!

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.

Why does the static change the performance?

The line in question: uint64_t size = atol(argv[1])<<20;

Short Answer

I would look at the assembly generated for accessing size and see if there are extra steps of pointer indirection involved for the non-static version.

Long Answer

Since there is only one copy of the variable whether it was declared static or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.

Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.

When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.

Running CMD command in PowerShell

One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.

PS C:\> "notepad.exe" | cmd

Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.


Edits

CMD's Startup Message is Shown

As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.

Why am I getting a "401 Unauthorized" error in Maven?

One of the reasons for this error is when repositoryId is not specified or specified incorrectly. As mentioned already it should be the same as in section in settings.xml. Couple of hints... Run mvn with -e -X options and check the debug output. It will tell you which repositoryId it is using:

[DEBUG]   (f) offline = false
[DEBUG]   (f) packaging = exe
[DEBUG]   (f) pomFile = c:\temp\build-test\pom.xml
[DEBUG]   (f) project = MavenProject: org.apache.maven:standalone-pom:1 @ 
[DEBUG]   (f) repositoryId = remote-repository
[DEBUG]   (f) repositoryLayout = default
[DEBUG]   (f) retryFailedDeploymentCount = 1
[DEBUG]   (f) uniqueVersion = true
[DEBUG]   (f) updateReleaseInfo = false
[DEBUG]   (f) url = https://nexus.url.blah.com/...
[DEBUG]   (f) version = 13.1
[DEBUG] -- end configuration --

In this case it uses the default value "remote-repository", which means that something went wrong.

Apparently I have specified -DrepositoryID (note ID in capital) instead of -DrepositoryId.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Found conflicts between different versions of the same dependent assembly that could not be resolved

Please note that I solved this problem by putting the AutoGenerateBindingRedirects right after the TargetFramework in the csproj file:

<TargetFramework>net462</TargetFramework>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>

Why is it that "No HTTP resource was found that matches the request URI" here?

Please check the class you inherited. Whether it is simply Controller or APIController.

By mistake we might create a controller from MVC 5 controller. It should be from Web API Controller.

notifyDataSetChanged not working on RecyclerView

Just to complement the other answers as I don't think anyone mentioned this here: notifyDataSetChanged() should be executed on the main thread (other notify<Something> methods of RecyclerView.Adapter as well, of course)

From what I gather, since you have the parsing procedures and the call to notifyDataSetChanged() in the same block, either you're calling it from a worker thread, or you're doing JSON parsing on main thread (which is also a no-no as I'm sure you know). So the proper way would be:

protected void parseResponse(JSONArray response, String url) {
    // insert dummy data for demo
    // <yadda yadda yadda>
    mBusinessAdapter = new BusinessAdapter(mBusinesses);
    // or just use recyclerView.post() or [Fragment]getView().post()
    // instead, but make sure views haven't been destroyed while you were
    // parsing
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            mBusinessAdapter.notifyDataSetChanged();
        }
    });

}

PS Weird thing is, I don't think you get any indications about the main thread thing from either IDE or run-time logs. This is just from my personal observations: if I do call notifyDataSetChanged() from a worker thread, I don't get the obligatory Only the original thread that created a view hierarchy can touch its views message or anything like that - it just fails silently (and in my case one off-main-thread call can even prevent succeeding main-thread calls from functioning properly, probably because of some kind of race condition)

Moreover, neither the RecyclerView.Adapter api reference nor the relevant official dev guide explicitly mention the main thread requirement at the moment (the moment is 2017) and none of the Android Studio lint inspection rules seem to concern this issue either.

But, here is an explanation of this by the author himself

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

Can't start Tomcat as Windows Service

  1. Check the apache tomcat catalina log: ../logs/catalina.log
  2. If in the log you find the "port was used" exception, then Check windows used ports and processes with following command: Run cmd netstat -ao it will list all listening ports and corresponding process Id, you can find the port which was used by Tomcat from the configuration file: ../conf/server.xml

    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
    

and kill the process which use the tomcat port

How to update a claim in ASP.NET Identity?

Compiled some answers from here into re-usable ClaimsManager class with my additions.

Claims got persisted, user cookie updated, sign in refreshed.

Please note that ApplicationUser can be substituted with IdentityUser if you didn't customize former. Also in my case it needs to have slightly different logic in Development environment, so you might want to remove IWebHostEnvironment dependency.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using YourMvcCoreProject.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Hosting;

namespace YourMvcCoreProject.Identity
{
    public class ClaimsManager
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IWebHostEnvironment _env;
        private readonly ClaimsPrincipalAccessor _currentPrincipalAccessor;

        public ClaimsManager(
            ClaimsPrincipalAccessor currentPrincipalAccessor,
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            IWebHostEnvironment env)
        {
            _currentPrincipalAccessor = currentPrincipalAccessor;
            _userManager = userManager;
            _signInManager = signInManager;
            _env = env;
        }

        /// <param name="refreshSignin">Sometimes (e.g. when adding multiple claims at once) it is desirable to refresh cookie only once, for the last one </param>
        public async Task AddUpdateClaim(string claimType, string claimValue, bool refreshSignin = true)
        {
            await AddClaim(
                _currentPrincipalAccessor.ClaimsPrincipal,
                claimType,
                claimValue, 
                async user =>
                {
                    await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, user, claimType);
                },
                refreshSignin);
        }

        public async Task AddClaim(string claimType, string claimValue, bool refreshSignin = true)
        {
            await AddClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, claimValue, refreshSignin);
        }

        /// <summary>
        /// At certain stages of user auth there is no user yet in context but there is one to work with in client code (e.g. calling from ClaimsTransformer)
        /// that's why we have principal as param
        /// </summary>
        public async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, bool refreshSignin = true)
        {
            await AddClaim(
                principal,
                claimType,
                claimValue, 
                async user =>
                {
                    // allow reassignment in dev
                    if (_env.IsDevelopment()) 
                        await RemoveClaim(principal, user, claimType);

                    if (GetClaim(principal, claimType) != null)
                        throw new ClaimCantBeReassignedException(claimType);                
                },
                refreshSignin);
        }

        public async Task RemoveClaims(IEnumerable<string> claimTypes, bool refreshSignin = true)
        {
            await RemoveClaims(_currentPrincipalAccessor.ClaimsPrincipal, claimTypes, refreshSignin);
        }

        public async Task RemoveClaims(ClaimsPrincipal principal, IEnumerable<string> claimTypes, bool refreshSignin = true)
        {
            AssertAuthenticated(principal);
            foreach (var claimType in claimTypes)
            {
                await RemoveClaim(principal, claimType);
            }
            // reflect the change in the Identity cookie
            if (refreshSignin)
                await _signInManager.RefreshSignInAsync(await _userManager.GetUserAsync(principal));
        }

        public async Task RemoveClaim(string claimType, bool refreshSignin = true)
        {
            await RemoveClaim(_currentPrincipalAccessor.ClaimsPrincipal, claimType, refreshSignin);
        }

        public async Task RemoveClaim(ClaimsPrincipal principal, string claimType, bool refreshSignin = true)
        {
            AssertAuthenticated(principal);
            var user = await _userManager.GetUserAsync(principal);
            await RemoveClaim(principal, user, claimType);
            // reflect the change in the Identity cookie
            if (refreshSignin)
                await _signInManager.RefreshSignInAsync(user);
        }

        private async Task AddClaim(ClaimsPrincipal principal, string claimType, string claimValue, Func<ApplicationUser, Task> processExistingClaims, bool refreshSignin)
        {
            AssertAuthenticated(principal);
            var user = await _userManager.GetUserAsync(principal);
            await processExistingClaims(user);
            var claim = new Claim(claimType, claimValue);
            ClaimsIdentity(principal).AddClaim(claim);
            await _userManager.AddClaimAsync(user, claim);
            // reflect the change in the Identity cookie
            if (refreshSignin)
                await _signInManager.RefreshSignInAsync(user);
        }

        /// <summary>
        /// Due to bugs or as result of debug it can be more than one identity of the same type.
        /// The method removes all the claims of a given type.
        /// </summary>
        private async Task RemoveClaim(ClaimsPrincipal principal, ApplicationUser user, string claimType)
        {
            AssertAuthenticated(principal);
            var identity = ClaimsIdentity(principal);
            var claims = identity.FindAll(claimType).ToArray();
            if (claims.Length > 0)
            {
                await _userManager.RemoveClaimsAsync(user, claims);
                foreach (var c in claims)
                {
                    identity.RemoveClaim(c);
                }
            }
        }

        private static Claim GetClaim(ClaimsPrincipal principal, string claimType)
        {
            return ClaimsIdentity(principal).FindFirst(claimType);    
        }    

        /// <summary>
        /// This kind of bugs has to be found during testing phase
        /// </summary>
        private static void AssertAuthenticated(ClaimsPrincipal principal)
        {
            if (!principal.Identity.IsAuthenticated)
                throw new InvalidOperationException("User should be authenticated in order to update claims");
        }

        private static ClaimsIdentity ClaimsIdentity(ClaimsPrincipal principal)
        {
            return (ClaimsIdentity) principal.Identity;
        }
    }


    public class ClaimCantBeReassignedException : Exception
    {
        public ClaimCantBeReassignedException(string claimType) : base($"{claimType} can not be reassigned")
        {
        }
    }

public class ClaimsPrincipalAccessor
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public ClaimsPrincipalAccessor(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public ClaimsPrincipal ClaimsPrincipal => _httpContextAccessor.HttpContext.User;
}

// to register dependency put this into your Startup.cs and inject ClaimsManager into Controller constructor (or other class) the in same way as you do for other dependencies    
public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<ClaimsPrincipalAccessor>();
        services.AddTransient<ClaimsManager>();
    }
}

}

PowerShell The term is not recognized as cmdlet function script file or operable program

For the benefit of searchers, there is another way you can produce this error message - by missing the $ off the script block name when calling it.

e.g. I had a script block like so:

$qa = {
    param($question, $answer)
    Write-Host "Question = $question, Answer = $answer"
}

I tried calling it using:

&qa -question "Do you like powershell?" -answer "Yes!"

But that errored. The correct way was:

&$qa -question "Do you like powershell?" -answer "Yes!"

Microsoft.ACE.OLEDB.12.0 is not registered

I followed the instructions to use the /passive switch here, after downloading the 64 bit Access database engine. I'm running Office 32-bit, SSAS Tabular Model in SQL Server 2012. When I downloaded and ran the 64-bit Access database engine it came up with a message saying that I couldn't install this without first uninstalling Office 2010, but the /passive switch seems to have solved this (I can now import Excel workbooks and Access tables in a tabular model).

Register .NET Framework 4.5 in IIS 7.5

Hosting asp.net 4.5/4.5.1 Web application on Local IIS 1)Be Sure IIS Installation before Visual Installation Installataion then aspnet_regiis will already registerd with IIS

If Not Install IIS and then Register aspnet_regiis with IIS by cmd Editor

For VS2012 and 32 bit OS Run Below code on command editor :

1)Install IIS First & then

2)

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319   

  C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i

For VS2012 and 64 bit OS Below code on command editor:

1)Install IIS First & then

2)

cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319    
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis -i

BY Following Above Steps Current Version of VS2012 registered with IIS Hosting (VS2012 Web APP)

Create VS2012 Web Application(WebForm/MVC) then Build Application Right Click On WebApplication(WebForm/MVC) go to 'Properties' Click On 'Web' Tab on then 'Use Local IIS Web Server' Then Uncheck 'Use IIS Express' (If Visul Studio 2013 Select 'Local IIS' from Dropdown) Provide Project Url like "http://localhost/MvcDemoApp" Then Click On 'Create Virtual Directory' Button Then Open IIS by Prssing 'Window + R' Run Command and type 'inetmgr' and 'Enter' (or 'OK' Button) Then Expand 'Sites->Default Web Site' you Hosted Successfully. If Still Gets any Server Error like 'The resource cannot be found.' Then Include following code in web.config

 <configuration>
     <system.webServer>
         <modules runAllManagedModulesForAllRequests="true"></modules>

And Run Application

If still problem occurs Check application pool by : In iis Right click on application->Manage Application->Advanced setting->General. you see the application pool. then close advance setting window. click on 'Application Pools' you will see the all application pools in middle window. Right click on application pool in which application hosted(DefaultAppPool). click 'Basic Setting' -> Change .Net FrameWork Version to->.Net FrameWork v4.0.30349

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

I've just had the same issue but using sourcetree on windows Same steps for normal GIT on Windows as well. Following the following steps I was able to solve this issue.

  1. Obtain the server certificate tree This can be done using chrome. Navigate to be server address. Click on the padlock icon and view the certificates. Export all of the certificate chain as base64 encoded files (PEM) format.
  2. Add the certificates to the trust chain of your GIT trust config file Run "git config --list". find the "http.sslcainfo" configuration this shows where the certificate trust file is located. Copy all the certificates into the trust chain file including the "- -BEGIN- -" and the "- -END- -".
  3. Make sure you add the entire certificate Chain to the certificates file

This should solve your issue with the self-signed certificates and using GIT.

I tried using the "http.sslcapath" configuration but this did not work. Also if i did not include the whole chain in the certificates file then this would also fail. If anyone has pointers on these please let me know as the above has to be repeated for a new install.

If this is the system GIT then you can use the options in TOOLS -> options GIt tab to use the system GIT and this then solves the issue in sourcetree as well.

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

Setting DataContext in XAML in WPF

There are several issues here.

  1. You can't assign DataContext as DataContext="{Binding Employee}" because it's a complex object which can't be assigned as string. So you have to use <Window.DataContext></Window.DataContext> syntax.
  2. You assign the class that represents the data context object to the view, not an individual property so {Binding Employee} is invalid here, you just have to specify an object.
  3. Now when you assign data context using valid syntax like below
   <Window.DataContext>
      <local:Employee/>
   </Window.DataContext>

know that you are creating a new instance of the Employee class and assigning it as the data context object. You may well have nothing in default constructor so nothing will show up. But then how do you manage it in code behind file? You have typecast the DataContext.

    private void my_button_Click(object sender, RoutedEventArgs e)
    {
        Employee e = (Employee) DataContext;
    }
  1. A second way is to assign the data context in the code behind file itself. The advantage then is your code behind file already knows it and can work with it.

    public partial class MainWindow : Window
    {
       Employee employee = new Employee();
    
       public MainWindow()
       {
           InitializeComponent();
    
           DataContext = employee;
       }
    }
    

Project Links do not work on Wamp Server

This works on Wamp 3+.

  • Go to wamp folder (wamp/ or wamp64/)
  • Open wampmanager.conf
  • Find urlAddLocalhost param and set it on: urlAddLocalhost = "on"

There should not be the need to tweak the index.php in www folder.

Disable button after click in JQuery

Consider also .attr()

$("#roommate_but").attr("disabled", true); worked for me.

Why does pycharm propose to change method to static

Agreed with @jolvi, @ArundasR, and others, the warning happens on a member function that doesn't use self.

If you're sure PyCharm is wrong, that the function should not be a @staticmethod, and if you value zero warnings, you can make this one go away two different ways:

Workaround #1

def bar(self):
    self.is_not_used()
    doing_something_without_self()

def is_not_used(self):
    pass

Workaround #2 [Thanks @DavidPärsson]

# noinspection PyMethodMayBeStatic
def bar(self):
    doing_something_without_self()

The application I had for this (the reason I could not use @staticmethod) was in making a table of handler functions for responding to a protocol subtype field. All handlers had to be the same form of course (static or nonstatic). But some didn't happen to do anything with the instance. If I made those static I'd get "TypeError: 'staticmethod' object is not callable".

In support of the OP's consternation, suggesting you add staticmethod whenever you can, goes against the principle that it's easier to make code less restrictive later, than to make it more -- making a method static makes it less restrictive now, in that you can call class.f() instead of instance.f().

Guesses as to why this warning exists:

  • It advertises staticmethod. It makes developers aware of something they may well have intended.
  • As @JohnWorrall's points out, it gets your attention when self was inadvertently left out of the function.
  • It's a cue to rethink the object model; maybe the function does not belong in this class at all.

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Google access token expiration time

From Google OAuth2.0 for Client documentation,

  • expires_in -- The number of seconds left before the token becomes invalid.

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

How to pass variable from jade template file to a script file?

It's a little late but...

script.
  loginName="#{login}";

This is working fine in my script. In Express, I am doing this:

exports.index = function(req, res){
  res.render( 'index',  { layout:false, login: req.session.login } );
};

I guess the latest jade is different?

Merc.

edit: added "." after script to prevent Jade warning.

How to search through all Git and Mercurial commits in the repository for a certain string?

In Mercurial you use hg log --keyword to search for keywords in the commit messages and hg log --user to search for a particular user. See hg help log for other ways to limit the log.

How to run a JAR file

Java

class Hello{
   public static void main(String [] args){
    System.out.println("Hello Shahid");
   }
}

manifest.mf

Manifest-version: 1.0
Main-Class: Hello

On command Line:

$ jar cfm HelloMss.jar  manifest.mf Hello.class 
$ java -jar HelloMss.jar

Output:

Hello Shahid

How do you set the document title in React?

If you're a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in "index.html" and put yours. Don't forget to save so it will reflect.

"The system cannot find the file specified"

If you encounter this error in GoDaddy after deploying a .Net MVC web application..And your web.config is absolutely correct... Right click your data project select settings and make sure that the correct connection strings to the GoDaddy server is in use

Create a .txt file if doesn't exist, and if it does append a new line

 else if (File.Exists(path)) 
{ 
  using (StreamWriter w = File.AppendText(path))
        {
            w.WriteLine("The next line!"); 
            w.Close();
        }
 } 

Date to milliseconds and back to date in Swift

Unless you absolutely have to convert the date to an integer, consider using a Double instead to represent the time interval. After all, this is the type that timeIntervalSince1970 returns. All of the answers that convert to integers loose sub-millisecond precision, but this solution is much more accurate (although you will still lose some precision due to floating-point imprecision).

public extension Date {
    
    /// The interval, in milliseconds, between the date value and
    /// 00:00:00 UTC on 1 January 1970.
    /// Equivalent to `self.timeIntervalSince1970 * 1000`.
    var millisecondsSince1970: Double {
        return self.timeIntervalSince1970 * 1000
    }

    /**
     Creates a date value initialized relative to 00:00:00 UTC
     on 1 January 1970 by a given number of **milliseconds**.
     
     equivalent to
     ```
     self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
     ```
     - Parameter millisecondsSince1970: A time interval in milliseconds.
     */
    init(millisecondsSince1970: Double) {
        self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }

}

How can I download HTML source in C#

basically:

using System.Net;
using System.Net.Http;  // in LINQPad, also add a reference to System.Net.Http.dll

WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";

string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
    source = reader.ReadToEnd();
}

Console.WriteLine(source);

Basic example of using .ajax() with JSONP?

There is even easier way how to work with JSONP using jQuery

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.

The ternary (conditional) operator in C

The same as

if(0)
do();


if(0)
{
do();
}

How to read multiple text files into a single RDD?

you can use

JavaRDD<String , String> records = sc.wholeTextFiles("path of your directory")

here you will get the path of your file and content of that file. so you can perform any action of a whole file at a time that saves the overhead

Euclidean distance of two vectors

If you want to use less code, you can also use the norm in the stats package (the 'F' stands for Forbenius, which is the Euclidean norm):

norm(matrix(x1-x2), 'F')

While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:

set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)

Then testing for time yields the following:

> system.time(a<-sqrt(sum((x1-x2)^2)))
user  system elapsed 
1.02    0.12    1.18 
> system.time(b<-norm(matrix(x1-x2), 'F'))
user  system elapsed 
0.97    0.33    1.31 

Find out where MySQL is installed on Mac OS X

If you downloaded mySQL using a DMG (easiest way to download found here http://dev.mysql.com/downloads/mysql/) in Terminal try: cd /usr/local/

When you type ls you should see mysql-YOUR-VERSION. You will also see mysql which is the installation directory.

Source: http://geeksww.com/tutorials/database_management_systems/mysql/installation/how_to_download_and_install_mysql_on_mac_os_x.php

How do I get my page title to have an icon?

Apparently you can use this trick.

<title> My title</title>

That icon-alike is actually a text.

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:

When I log in the user I save the access token:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$accessToken = $facebook->getAccessToken();
//save the access token for later

Now when I make requests to facebook I just do something like this:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)

C++ Loop through Map

Try the following

for ( const auto &p : table )
{
   std::cout << p.first << '\t' << p.second << std::endl;
} 

The same can be written using an ordinary for loop

for ( auto it = table.begin(); it != table.end(); ++it  )
{
   std::cout << it->first << '\t' << it->second << std::endl;
} 

Take into account that value_type for std::map is defined the following way

typedef pair<const Key, T> value_type

Thus in my example p is a const reference to the value_type where Key is std::string and T is int

Also it would be better if the function would be declared as

void output( const map<string, int> &table );

day of the week to day number (Monday = 1, Tuesday = 2)

What about using idate()? idate()

$integer = idate('w', $timestamp);

MongoDB logging all queries

if you want the queries to be logged to mongodb log file, you have to set both the log level and the profiling, like for example:

db.setLogLevel(1)
db.setProfilingLevel(2)

(see https://docs.mongodb.com/manual/reference/method/db.setLogLevel)

Setting only the profiling would not have the queries logged to file, so you can only get it from

db.system.profile.find().pretty()

How to change sender name (not email address) when using the linux mail command for autosending mail?

mail -s "$(echo -e "This is the subject\nFrom: Paula <[email protected]>\n
Reply-to: [email protected]\nContent-Type: text/html\n")" 
[email protected] < htmlFileMessage.txt

the above is my solution..just replace the "Paula" with any name you want e.g Johny Bravo..any extra headers can be added just after the from and before the reply to...just make sure you know your headers syntax before adding them....this worked perfectly for me.

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

Adding additional data to select options using jQuery

To store another value in select options:

$("#select").append('<option value="4">another</option>')

Swift presentViewController

I had a similar issue but in my case, the solution was to dispatch the action as an async task in the main queue

DispatchQueue.main.async {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)
}

Failed to instantiate module error in Angular js

For me the solution was fixing a syntax error:

removing a unwanted semi colon in the angular.module function

Changing project port number in Visual Studio 2013

Steps to resolve this:

  1. Open the solution file.
  2. Find the Port tag against your project name.
  3. Assign any different port as current.
  4. Right click on your project and select Property Pages.
  5. Click on Start Options tab and checked Start URL: option.
  6. Assign the start URL in front of Start URL option like:
    localhost:8080/login.aspx

nginx showing blank PHP pages

Also had this issue and finally found the solution here. In short, you need to add the following line to your nginx fastcgi config file (/etc/nginx/fastcgi_params in Ubuntu 12.04)

fastcgi_param PATH_TRANSLATED $document_root$fastcgi_script_name;

How to display 3 buttons on the same line in css

This will serve the purpose. There is no need for any divs or paragraph. If you want the spaces between them to be specified, use margin-left or margin-right in the css classes.

<div style="width:500px;">
    <button type="submit" class="msgBtn" onClick="return false;" >Save</button>
    <button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
    <button class="msgBtnBack">Back</button>
</div> 

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
print "Please choose what you'd like to do:"

print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"



#Capture the menu choice.
choice = raw_input()    

if choice == "0":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(addition(numberA, numberB)) + "\n"
elif choice == "1":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
    print "Bye!"
    keepProgramRunning = False
else:
    print "Please choose a valid option."
    print "\n"

New Line Issue when copying data from SQL Server 2012 to Excel

I found a workaround for the problem; instead of copy-pasting by hand, use Excel to connect to your database and import the complete table. Then remove the data you are not interested in.

Here are the steps (for Excel 2010)

  1. Go to menu Data > Get external data: From other sources > From SQL Server
  2. Type the sql server name (and credentials if you don't have Windows authentication on your server) and connect.
  3. Select the database and table that contains the data with the newlines and click 'Finish'.
  4. Select the destination worksheet and click 'Ok'.

Excel will now import the complete table with the newlines intact.

What is the official "preferred" way to install pip and virtualenv systemwide?

http://www.pip-installer.org/en/latest/installing.html is really the canonical answer to this question.

Specifically, the systemwide instructions are:

$ curl -O http://python-distribute.org/distribute_setup.py
$ python distribute_setup.py
$ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ python get-pip.py

The section quoted in the question is the virtualenv instructions rather than the systemwide ones. The easy_install instructions have been around for longer, but it isn't necessary to do it that way any more.

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:

STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB

You can also set sql mode by this:

SET GLOBAL sql_mode=TRADITIONAL;

Deleting multiple elements from a list

You can use enumerate and remove the values whose index matches the indices you want to remove:

indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]

How do I edit SSIS package files?

I prefer to use :

(from SSDT visual studio just opened) file> open > file > locate dtsx file > open

then you can edit work and save

Replace all elements of Python NumPy Array that are greater than some value

You can also use &, | (and/or) for more flexibility:

values between 5 and 10: A[(A>5)&(A<10)]

values greater than 10 or smaller than 5: A[(A<5)|(A>10)]

Word-wrap in an HTML table

As mentioned, putting the text within div almost works. You just have to specify the width of the div, which is fortunate for layouts which are static.

This works on FF 3.6, IE 8, Chrome.

<td>
  <div style="width: 442px; word-wrap: break-word">
    <!-- Long Content Here-->
  </div>
</td>

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

How to correctly use the ASP.NET FileUpload control

Old Question, but still, if it might help someone, here is complete sample

<form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" /><br/>
        <asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="UploadFile" /><br/>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>
</form>

In your Code-behind, C# code to grab file and save it in Directory

protected void UploadFile(object sender, EventArgs e)
    {
        //folder path to save uploaded file
        string folderPath = Server.MapPath("~/Upload/");

        //Check whether Directory (Folder) exists, although we have created, if it si not created this code will check
        if (!Directory.Exists(folderPath))
        {
            //If folder does not exists. Create it.
            Directory.CreateDirectory(folderPath);
        }

       //save file in the specified folder and path
        FileUpload1.SaveAs(folderPath + Path.GetFileName(FileUpload1.FileName));

        //once file is uploaded show message to user in label control
        Label1.Text = Path.GetFileName(FileUpload1.FileName) + " has been uploaded.";
    }

Source: File Upload in ASP.NET (Web-Forms Upload control example)

Setting action for back button in navigation controller

Overriding navigationBar(_ navigationBar:shouldPop): This is not a good idea, even if it works. for me it generated random crashes on navigating back. I advise you to just override the back button by removing the default backButton from navigationItem and creating a custom back button like below:

override func viewDidLoad(){
   super.viewDidLoad()
   
   navigationItem.leftBarButton = .init(title: "Go Back", ... , action: #selector(myCutsomBackAction) 

   ...
 
}

========================================

Building on previous responses with UIAlert in Swift5 in a Asynchronous way


protocol NavigationControllerBackButtonDelegate {
    func shouldPopOnBackButtonPress(_ completion: @escaping (Bool) -> ())
}

extension UINavigationController: UINavigationBarDelegate {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
      
        if viewControllers.count < navigationBar.items!.count {
            return true
        }
        
        // Check if we have a view controller that wants to respond to being popped
        
        if let viewController = topViewController as? NavigationControllerBackButtonDelegate {
            
            viewController.shouldPopOnBackButtonPress { shouldPop in
                if (shouldPop) {
                    /// on confirm => pop
                    DispatchQueue.main.async {
                        self.popViewController(animated: true)
                    }
                } else {
                    /// on cancel => do nothing
                }
            }
            /// return false => so navigator will cancel the popBack
            /// until user confirm or cancel
            return false
        }else{
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        }
        return true
    }
}


On your controller


extension MyController: NavigationControllerBackButtonDelegate {
    
    func shouldPopOnBackButtonPress(_ completion: @escaping (Bool) -> ()) {
    
        let msg = "message"
        
        /// show UIAlert
        alertAttention(msg: msg, actions: [
            
            .init(title: "Continuer", style: .destructive, handler: { _ in
                completion(true)
            }),
            .init(title: "Annuler", style: .cancel, handler: { _ in
                completion(false)
            })
            ])
   
    }

}

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

Display a loading bar before the entire page is loaded

Whenever you try to load any data in this window this gif will load.

HTML

Make a Div

<div class="loader"></div>

CSS .

.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);

jQuery

$(window).load(function() {
        $(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

enter image description here

Disabled form inputs do not appear in the request

Simple workaround - just use hidden field as placeholder for select, checkbox and radio.

From this code to -

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <!-- this does not appear in request -->
    <input type="textbox" name="Percentage" value="100" disabled="disabled" /> 
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>

</form>

that code -

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <input type="textbox" value="100" readonly /> 

    <input type="hidden" name="gender" value="female" />
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>
</form>

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

T-SQL CASE Clause: How to specify WHEN NULL

The problem is that null is not considered equal to itself, hence the clause never matches.

You need to check for null explicitly:

SELECT CASE WHEN last_name is NULL THEN first_name ELSE first_name + ' ' + last_name

C/C++ NaN constant (literal)?

yes, by the concept of pointer you can do it like this for an int variable:

int *a;
int b=0;
a=NULL; // or a=&b; for giving the value of b to a
if(a==NULL) 
  printf("NULL");
else
  printf(*a);

it is very simple and straitforward. it worked for me in Arduino IDE.

How to know that a string starts/ends with a specific string in jQuery?

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

How to navigate through a vector using iterators? (C++)

You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively.

using namespace std;  

vector<string> myvector;  // a vector of stings.


// push some strings in the vector.
myvector.push_back("a");
myvector.push_back("b");
myvector.push_back("c");
myvector.push_back("d");


vector<string>::iterator it;  // declare an iterator to a vector of strings
int n = 3;  // nth element to be found.
int i = 0;  // counter.

// now start at from the beginning
// and keep iterating over the element till you find
// nth element...or reach the end of vector.
for(it = myvector.begin(); it != myvector.end(); it++,i++ )    {
    // found nth element..print and break.
    if(i == n) {
        cout<< *it << endl;  // prints d.
        break;
    }
}

// other easier ways of doing the same.
// using operator[]
cout<<myvector[n]<<endl;  // prints d.

// using the at method
cout << myvector.at(n) << endl;  // prints d.

Java List.contains(Object with field value equal to x)

Map

You could create a Hashmap<String, Object> using one of the values as a key, and then seeing if yourHashMap.keySet().contains(yourValue) returns true.

Create an enum with string values

i was looking for a way to implement descriptions in typescript enums (v2.5) and this pattern worked for me:

export enum PriceTypes {
    Undefined = 0,
    UndefinedDescription = 'Undefined' as any,
    UserEntered = 1,
    UserEnteredDescription = 'User Entered' as any,
    GeneratedFromTrade = 2,
    GeneratedFromTradeDescription = 'Generated From Trade' as any,
    GeneratedFromFreeze = 3,
    GeneratedFromFreezeDescription = 'Generated Rom Freeze' as any
}

...

    GetDescription(e: any, id: number): string {
        return e[e[id].toString() + "Description"];
    }
    getPriceTypeDescription(price: IPricePoint): string {
        return this.GetDescription(PriceTypes, price.priceType);
    }

Why use multiple columns as primary keys (composite primary key)

Yes, they both form the primary key. Especially in tables where you don't have a surrogate key, it may be necessary to specify multiple attributes as the unique identifier for each record (bad example: a table with both a first name and last name might require the combination of them to be unique).

:touch CSS pseudo-class or something similar?

I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

Python Error: "ValueError: need more than 1 value to unpack"

You can't run this particular piece of code in the interactive interpreter. You'll need to save it into a file first so that you can pass the argument to it like this

$ python hello.py user338690

SqlServer: Login failed for user

If you are using Windows Authentication, make sure to log-in to Windows at least once with that user.

Fit cell width to content

I'm not sure if I understand your question, but I'll take a stab at it:

_x000D_
_x000D_
td {
    border: 1px solid #000;
}

tr td:last-child {
    width: 1%;
    white-space: nowrap;
}
_x000D_
<table style="width: 100%;">
    <tr>
        <td class="block">this should stretch</td>
        <td class="block">this should stretch</td>
        <td class="block">this should be the content width</td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

How to Allow Remote Access to PostgreSQL database

This is a complementary answer for the specific case of you using AWS cloud computing (either EC2 or RDS machines).

Besides doing everything proposed above, when using AWS cloud computing you will need to set you inbound rules in a way that let you access to the ports. Please check this post, which is valid for EC2 and RDS.

function declaration isn't a prototype

Try:

extern int testlib(void);

TSQL select into Temp table from dynamic sql

Take a look at OPENROWSET, and do something like:

SELECT * INTO #TEMPTABLE FROM OPENROWSET('SQLNCLI'
     , 'Server=(local)\SQL2008;Trusted_Connection=yes;',
     'SELECT * FROM ' + @tableName)

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

"fatal: Not a git repository (or any of the parent directories)" from git status

Simply, after you clone the repo you need to cd (change your current directory) to the new cloned folder

git clone https://[email protected]/Repo_Name.git

cd Repo_Name

How to read pickle file?

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

Matplotlib 2 Subplots, 1 Colorbar

Shared colormap and colorbar

This is for the more complex case where the values are not just between 0 and 1; the cmap needs to be shared instead of just using the last one.

import numpy as np
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt
import matplotlib.cm as cm
fig, axes = plt.subplots(nrows=2, ncols=2)
cmap=cm.get_cmap('viridis')
normalizer=Normalize(0,4)
im=cm.ScalarMappable(norm=normalizer)
for i,ax in enumerate(axes.flat):
    ax.imshow(i+np.random.random((10,10)),cmap=cmap,norm=normalizer)
    ax.set_title(str(i))
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()

Convert python long/int to fixed size byte array

One-liner:

bytearray.fromhex('{:0192x}'.format(big_int))

The 192 is 768 / 4, because OP wanted 768-bit numbers and there are 4 bits in a hex digit. If you need a bigger bytearray use a format string with a higher number. Example:

>>> big_int = 911085911092802609795174074963333909087482261102921406113936886764014693975052768158290106460018649707059449553895568111944093294751504971131180816868149233377773327312327573120920667381269572962606994373889233844814776702037586419
>>> bytearray.fromhex('{:0192x}'.format(big_int))
bytearray(b'\x96;h^\xdbJ\x8f3obL\x9c\xc2\xb0-\x9e\xa4Sj-\xf6i\xc1\x9e\x97\x94\x85M\x1d\x93\x10\\\x81\xc2\x89\xcd\xe0a\xc0D\x81v\xdf\xed\xa9\xc1\x83p\xdbU\xf1\xd0\xfeR)\xce\x07\xdepM\x88\xcc\x7fv\\\x1c\x8di\x87N\x00\x8d\xa8\xbd[<\xdf\xaf\x13z:H\xed\xc2)\xa4\x1e\x0f\xa7\x92\xa7\xc6\x16\x86\xf1\xf3')
>>> lepi_int = 0x963b685edb4a8f336f624c9cc2b02d9ea4536a2df669c19e9794854d1d93105c81c289cde061c0448176dfeda9c18370db55f1d0fe5229ce07de704d88cc7f765c1c8d69874e008da8bd5b3cdfaf137a3a48edc229a41e0fa792a7c61686f1f
>>> bytearray.fromhex('{:0192x}'.format(lepi_int))
bytearray(b'\tc\xb6\x85\xed\xb4\xa8\xf36\xf6$\xc9\xcc+\x02\xd9\xeaE6\xa2\xdff\x9c\x19\xe9yHT\xd1\xd91\x05\xc8\x1c(\x9c\xde\x06\x1c\x04H\x17m\xfe\xda\x9c\x187\r\xb5_\x1d\x0f\xe5"\x9c\xe0}\xe7\x04\xd8\x8c\xc7\xf7e\xc1\xc8\xd6\x98t\xe0\x08\xda\x8b\xd5\xb3\xcd\xfa\xf17\xa3\xa4\x8e\xdc"\x9aA\xe0\xfay*|aho\x1f')

[My answer had used hex() before. I corrected it with format() in order to handle ints with odd-sized byte expressions. This fixes previous complaints about ValueError.]

Java: getMinutes and getHours

From the Javadoc for Date.getHours

As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)

So use

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);

and the equivalent for getMinutes.

Export SQL query data to Excel

For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3 and entity framework core 2.0.3

First create your model class.

public class User
{  
    public string Name { get; set; }  
    public int Address { get; set; }  
    public int ZIP { get; set; }  
    public string Gender { get; set; }  
} 

Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)

Install-Package EPPlus -Version 4.0.5

The create ExcelExportHelper class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.

public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
        }

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {

            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }


                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);

                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn column in dataTable.Columns)
                {
                    int maxLength;
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                    try
                    {
                        maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
                    }
                    catch (Exception) //nishanc
                    {
                        maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
                    }

                    //workSheet.Column(columnIndex).AutoFit();
                    if (maxLength < 150)
                    {
                        //workSheet.Column(columnIndex).AutoFit();
                    }


                    columnIndex++;
                }

                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                // removed ignored columns  
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                {
                    if (i == 0 && showSrNo)
                    {
                        continue;
                    }
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                    {
                        workSheet.DeleteColumn(i + 1);
                    }
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                   // workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 10;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult. Whatever query you execute, important thing is you must have the results in a List.

[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
    DateTime startDate = getReport.StartDate;
    DateTime endDate = getReport.EndDate;

    // call the stored procedure and store dataset in a List.
    List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
    //set custome column names
    string[] columns = { "Name", "Address", "ZIP", "Gender"};
    byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
    // set file name.
    return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx"); 
}

More details can be found here

Unable to begin a distributed transaction

I was able to resolve this issue (as others mentioned in comments) by disabling "Enable Promotion of Distributed Transactions for RPC" (i.e. setting it to False):

enter image description here

As requested by @WonderWorker, you can do this via SQL script:

EXEC master.dbo.sp_serveroption
     @server = N'[mylinkedserver]',
     @optname = N'remote proc transaction promotion',
     @optvalue = N'false'

How can I include a YAML file inside another?

Unfortunately YAML doesn't provide this in its standard.

But if you are using Ruby, there is a gem providing the functionality you are asking for by extending the ruby YAML library: https://github.com/entwanderer/yaml_extend

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

Pandas: Creating DataFrame from Series

No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame() with the parens).

Instead, to create a DataFrame where each series is a column,

  1. make a list of Series, series, and
  2. concatenate them horizontally with df = pd.concat(series, axis=1)

Something like:

series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)

Performing Breadth First Search recursively

I have made a program using c++ which is working in joint and disjoint graph too .

    #include <queue>
#include "iostream"
#include "vector"
#include "queue"

using namespace std;

struct Edge {
    int source,destination;
};

class Graph{
    int V;
    vector<vector<int>> adjList;
public:

    Graph(vector<Edge> edges,int V){
        this->V = V;
        adjList.resize(V);
        for(auto i : edges){
            adjList[i.source].push_back(i.destination);
            //     adjList[i.destination].push_back(i.source);
        }
    }
    void BFSRecursivelyJoinandDisjointtGraphUtil(vector<bool> &discovered, queue<int> &q);
    void BFSRecursivelyJointandDisjointGraph(int s);
    void printGraph();


};

void Graph :: printGraph()
{
    for (int i = 0; i < this->adjList.size(); i++)
    {
        cout << i << " -- ";
        for (int v : this->adjList[i])
            cout <<"->"<< v << " ";
        cout << endl;
    }
}


void Graph ::BFSRecursivelyJoinandDisjointtGraphUtil(vector<bool> &discovered, queue<int> &q) {
    if (q.empty())
        return;
    int v = q.front();
    q.pop();
    cout << v <<" ";
    for (int u : this->adjList[v])
    {
        if (!discovered[u])
        {
            discovered[u] = true;
            q.push(u);
        }
    }
    BFSRecursivelyJoinandDisjointtGraphUtil(discovered, q);

}

void Graph ::BFSRecursivelyJointandDisjointGraph(int s) {
    vector<bool> discovered(V, false);
    queue<int> q;

    for (int i = s; i < V; i++) {
        if (discovered[i] == false)
        {
            discovered[i] = true;
            q.push(i);
            BFSRecursivelyJoinandDisjointtGraphUtil(discovered, q);
        }
    }
}

int main()
{

    vector<Edge> edges =
            {
                    {0, 1}, {0, 2}, {1, 2}, {2, 0}, {2,3},{3,3}
            };

    int V = 4;
    Graph graph(edges, V);
 //   graph.printGraph();
    graph.BFSRecursivelyJointandDisjointGraph(2);
    cout << "\n";




    edges = {
            {0,4},{1,2},{1,3},{1,4},{2,3},{3,4}
    };

    Graph graph2(edges,5);

    graph2.BFSRecursivelyJointandDisjointGraph(0);
    return 0;
}

How to swap two variables in JavaScript

In ES6 now there is destructuring assignment and you can do:

let a = 1;
let b = 2;
[b, a] = [a, b]  // a = 2, b = 1

Bootstrap collapse animation not smooth

Jerking happens when the parent div ".collapse" has padding.

Padding goes on the child div, not the parent. jQuery is animating the height, not the padding.

Example:

  <div class="form-group">
       <a for="collapseOne" data-toggle="collapse" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">+ addInfo</a>
       <div class="collapse" id="collapseOne" style="padding: 0;">
          <textarea class="form-control" rows="4" style="padding: 20px;"></textarea>
       </div>
  </div>

  <div class="form-group">
    <a for="collapseTwo" data-toggle="collapse" href="#collapseTwo" aria-expanded="true" aria-controls="collapseOne">+ subtitle</a>
    <input type="text" class="form-control collapse" id="collapseTwo">
  </div>

Fiddle Showing Both

Hope this helps.

Test if a command outputs an empty string

As mentioned by tripleee in the question comments , use moreutils ifne (if input not empty).

In this case we want ifne -n which negates the test:

ls -A /tmp/empty | ifne -n command-to-run-if-empty-input

The advantage of this over many of the another answers when the output of the initial command is non-empty. ifne will start writing it to STDOUT straight away, rather than buffering the entire output then writing it later, which is important if the initial output is slowly generated or extremely long and would overflow the maximum length of a shell variable.

There are a few utils in moreutils that arguably should be in coreutils -- they're worth checking out if you spend a lot of time living in a shell.

In particular interest to the OP may be dirempty/exists tool which at the time of writing is still under consideration, and has been for some time (it could probably use a bump).

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Instead, you could git CtrlZ and retry the commit but this time add " -m " with a message in quotes after it, then it will commit without prompting you with that page.

Regular expression to match balanced parentheses

I didn't use regex since it is difficult to deal with nested code. So this snippet should be able to allow you to grab sections of code with balanced brackets:

def extract_code(data):
    """ returns an array of code snippets from a string (data)"""
    start_pos = None
    end_pos = None
    count_open = 0
    count_close = 0
    code_snippets = []
    for i,v in enumerate(data):
        if v =='{':
            count_open+=1
            if not start_pos:
                start_pos= i
        if v=='}':
            count_close +=1
            if count_open == count_close and not end_pos:
                end_pos = i+1
        if start_pos and end_pos:
            code_snippets.append((start_pos,end_pos))
            start_pos = None
            end_pos = None

    return code_snippets

I used this to extract code snippets from a text file.

How to install JQ on Mac by command-line?

For CentOS, RHEL, Amazon Linux: sudo yum install jq

REST API error return good practices

Don't forget the 5xx errors as well for application errors.

In this case what about 409 (Conflict)? This assumes that the user can fix the problem by deleting stored resources.

Otherwise 507 (not entirely standard) may also work. I wouldn't use 200 unless you use 200 for errors in general.

Checking if a variable is defined?

defined? is great, but if you are in a Rails environment you can also use try, especially in cases where you want to check a dynamic variable name:

foo = 1
my_foo = "foo"
my_bar = "bar"
try(:foo)        # => 1
try(:bar)        # => nil
try(my_foo)      # => 1
try(my_bar)      # => nil

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

Example:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

Send form data with jquery ajax json

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

How to sort an array in Bash

array=(z 'b c'); { set "${array[@]}"; printf '%s\n' "$@"; } \
    | sort \
    | mapfile -t array; declare -p array
declare -a array=([0]="b c" [1]="z")
  • Open an inline function {...} to get a fresh set of positional arguments (e.g. $1, $2, etc).
  • Copy the array to the positional arguments. (e.g. set "${array[@]}" will copy the nth array argument to the nth positional argument. Note the quotes preserve whitespace that may be contained in an array element).
  • Print each positional argument (e.g. printf '%s\n' "$@" will print each positional argument on its own line. Again, note the quotes preserve whitespace that may be contained in each positional argument).
  • Then sort does its thing.
  • Read the stream into an array with mapfile (e.g. mapfile -t array reads each line into the variable array and the -t ignores the \n in each line).
  • Dump the array to show its been sorted.

As a function:

set +m
shopt -s lastpipe

sort_array() { 
    declare -n ref=$1
    set "${ref[@]}"
    printf '%s\n' "$@"
    | sort \
    | mapfile -t $ref
}

then

array=(z y x); sort_array array; declare -p array
declare -a array=([0]="x" [1]="y" [2]="z")

I look forward to being ripped apart by all the UNIX gurus! :)

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

filtering a list using LINQ

Based on http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b,

EqualAll is the approach that best meets your needs.

public void Linq96() 
{ 
    var wordsA = new string[] { "cherry", "apple", "blueberry" }; 
    var wordsB = new string[] { "cherry", "apple", "blueberry" }; 

    bool match = wordsA.SequenceEqual(wordsB); 

    Console.WriteLine("The sequences match: {0}", match); 
} 

SQL Server : fetching records between two dates?

Your question didnt ask how to use BETWEEN correctly, rather asked for help with the unexpectedly truncated results...

As mentioned/hinting at in the other answers, the problem is that you have time segments in addition to the dates.

In my experience, using date diff is worth the extra wear/tear on the keyboard. It allows you to express exactly what you want, and you are covered.

select * 
from xxx 
where datediff(d, '2012-10-26', dates) >=0
and  datediff(d, dates,'2012-10-27') >=0

using datediff, if the first date is before the second date, you get a positive number. There are several ways to write the above, for instance always having the field first, then the constant. Just flipping the operator. Its a matter of personal preference.

you can be explicit about whether you want to be inclusive or exclusive of the endpoints by dropping one or both equal signs.

BETWEEN will work in your case, because the endpoints are both assumed to be midnight (ie DATEs). If your endpoints were also DATETIME, using BETWEEN may require even more casting. In my mind DATEDIFF was put in our lives to insulate us from those issues.

SQL - Query to get server's IP address

I know this is an old post, but perhaps this solution can be usefull when you want to retrieve the IP address and TCP port from a Shared Memory connection (e.g. from a script run in SSMS locally on the server). The key is to open a secondary connection to your SQL Server using OPENROWSET, in which you specify 'tcp:' in your connection string. The rest of the code is merely building dynamic SQL to get around OPENROWSET’s limitation of not being able to take variables as its parameters.

DECLARE @ip_address       varchar(15)
DECLARE @tcp_port         int 
DECLARE @connectionstring nvarchar(max) 
DECLARE @parm_definition  nvarchar(max)
DECLARE @command          nvarchar(max)

SET @connectionstring = N'Server=tcp:' + @@SERVERNAME + ';Trusted_Connection=yes;'
SET @parm_definition  = N'@ip_address_OUT varchar(15) OUTPUT
                        , @tcp_port_OUT   int         OUTPUT';

SET @command          = N'SELECT  @ip_address_OUT = a.local_net_address,
                                  @tcp_port_OUT   = a.local_tcp_port
                          FROM OPENROWSET(''SQLNCLI''
                                 , ''' + @connectionstring + '''
                                 , ''SELECT local_net_address
                                          , local_tcp_port
                                     FROM sys.dm_exec_connections
                                     WHERE session_id = @@spid
                                   '') as a'

EXEC SP_executeSQL @command
                 , @parm_definition
                 , @ip_address_OUT = @ip_address OUTPUT
                 , @tcp_port_OUT   = @tcp_port OUTPUT;


SELECT @ip_address, @tcp_port

Insert text with single quotes in PostgreSQL

In postgresql if you want to insert values with ' in it then for this you have to give extra '

 insert into test values (1,'user''s log');
 insert into test values (2,'''my users''');
 insert into test values (3,'customer''s');

Create a Cumulative Sum Column in MySQL

select Id, Count, @total := @total + Count as cumulative_sum
from YourTable, (Select @total := 0) as total ;

Java - Create a new String instance with specified length and filled with specific character. Best solution?

using Dollar is simple:

String filled = $("=").repeat(10).toString(); // produces "=========="

Windows service start failure: Cannot start service from the command line or debugger

To install Open CMD and type in {YourServiceName} -i once its installed type in NET START {YourserviceName} to start your service

to uninstall

To uninstall Open CMD and type in NET STOP {YourserviceName} once stopped type in {YourServiceName} -u and it should be uninstalled

Is __init__.py not required for packages in Python 3.3+

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

Packages are only recognized if they include an __init__.py file

UPD: If you want to use implicit namespace packages without __init__.py you just have to use find_namespace_packages() instead

Docs

What is attr_accessor in Ruby?

Simple Explanation Without Any Code

Most of the above answers use code. This explanation attempts to answer it without using any, via an analogy/story:

Outside parties cannot access internal CIA secrets

  • Let's imagine a really secret place: the CIA. Nobody knows what's happening in the CIA apart from the people inside the CIA. In other words, external people cannot access any information in the CIA. But because it's no good having an organisation that is completely secret, certain information is made available to the outside world - only things that the CIA wants everyone to know about of course: e.g. the Director of the CIA, how environmentally friendly this department is compared to all other government departments etc. Other information: e.g. who are its covert operatives in Iraq or Afghanistan - these types of things will probably remain a secret for the next 150 years.

  • If you're outside the CIA you can only access the information that it has made available to the public. Or to use CIA parlance you can only access information that is "cleared".

  • The information that the CIA wants to make available to the general public outside the CIA are called: attributes.

The meaning of read and write attributes:

  • In the case of the CIA, most attributes are "read only". This means if you are a party external to the CIA, you can ask: "who is the director of the CIA?" and you will get a straight answer. But what you cannot do with "read only" attributes is to make changes changes in the CIA. e.g. you cannot make a phone call and suddenly decide that you want Kim Kardashian to be the Director, or that you want Paris Hilton to be the Commander in Chief.

  • If the attributes gave you "write" access, then you could make changes if you want to, even if you were outside. Otherwise, the only thing you can do is read.

    In other words accessors allow you to make inquiries, or to make changes, to organisations that otherwise do not let external people in, depending on whether the accessors are read or write accessors.

Objects inside a class can easily access each other

  • On the other hand, if you were already inside the CIA, then you could easily call up your CIA operative in Kabul because this information is easily accessible given you are already inside. But if you're outside the CIA, you simply will not be given access: you will not be able to know who they are (read access), and you will not be able to change their mission (write access).

Exact same thing with classes and your ability to access variables, properties and methods within them. HTH! Any questions, please ask and I hope i can clarify.

foreach for JSON array , syntax

You can do something like

for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

How can I make PHP display the error instead of giving me 500 Internal Server Error

If all else fails try moving (i.e. in bash) all files and directories "away" and adding them back one by one.

I just found out that way that my .htaccess file was referencing a non-existant .htpasswd file. (#silly)

How to install node.js as windows service?

The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.

Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable machine-wide.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

Understanding the map function

Python3 - map(func, iterable)

One thing that wasn't mentioned completely (although @BlooB kinda mentioned it) is that map returns a map object NOT a list. This is a big difference when it comes to time performance on initialization and iteration. Consider these two tests.

import time
def test1(iterable):
    a = time.clock()
    map(str, iterable)
    a = time.clock() - a

    b = time.clock()
    [ str(x) for x in iterable ]
    b = time.clock() - b

    print(a,b)


def test2(iterable):
    a = time.clock()
    [ x for x in map(str, iterable)]
    a = time.clock() - a

    b = time.clock()
    [ str(x) for x in iterable ]
    b = time.clock() - b

    print(a,b)


test1(range(2000000))  # Prints ~1.7e-5s   ~8s
test2(range(2000000))  # Prints ~9s        ~8s

As you can see initializing the map function takes almost no time at all. However iterating through the map object takes longer than simply iterating through the iterable. This means that the function passed to map() is not applied to each element until the element is reached in the iteration. If you want a list use list comprehension. If you plan to iterate through in a for loop and will break at some point, then use map.

generating variable names on fly in python

Another example, which is really a variation of another answer, in that it uses a dictionary too:

>>> vr={} 
... for num in range(1,4): 
...     vr[str(num)] = 5 + num
...     
>>> print vr["3"]
8
>>> 

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

Well, In my applications I just need to Add a reference to "DocumentFormat.OpenXml" under .Net tab and both references (DocumentFormat.OpenXml and WindowsBase) are always added automatically. But They are not included within the Bin folder. So when the Application is published to an external server I always place DocumentFormat.OpenXml.dll under the Bin folder manually. Or set the reference "Copy Local" property to true.

Refresh certain row of UITableView based on Int in Swift

How about:

self.tableView.reloadRowsAtIndexPaths([NSIndexPath(rowNumber)], withRowAnimation: UITableViewRowAnimation.Top)

How do I get the web page contents from a WebView?

I managed to get this working using the code from @jluckyiv's answer but I had to add in @JavascriptInterface annotation to the processHTML method in the MyJavaScriptInterface.

class MyJavaScriptInterface
{
    @SuppressWarnings("unused")
    @JavascriptInterface
    public void processHTML(String html)
    {
        // process the html as needed by the app
    }
}

pandas how to check dtype for all columns in a dataframe?

Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:

df.info()

matplotlib: how to change data points color based on some variable

This is what matplotlib.pyplot.scatter is for.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t,x,c=y)
plt.show()

enter image description here

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Suppose this task is possible. Just prior to output, there will be an in-memory representation of the million sorted numbers. How many different such representations are there? Since there may be repeated numbers we can't use nCr (choose), but there is an operation called multichoose that works on multisets.

  • There are 2.2e2436455 ways to choose a million numbers in range 0..99,999,999.
  • That requires 8,093,730 bits to represent every possible combination, or 1,011,717 bytes.

So theoretically it may be possible, if you can come up with a sane (enough) representation of the sorted list of numbers. For example, an insane representation might require a 10MB lookup table or thousands of lines of code.

However, if "1M RAM" means one million bytes, then clearly there is not enough space. The fact that 5% more memory makes it theoretically possible suggests to me that the representation will have to be VERY efficient and probably not sane.

How to git reset --hard a subdirectory?

If the size of the subdirectory is not particularly huge, AND you wish to stay away from the CLI, here's a quick solution to manually reset the sub-directory:

  1. Switch to master branch and copy the sub-directory to be reset.
  2. Now switch back to your feature branch and replace the sub-directory with the copy you just created in step 1.
  3. Commit the changes.

Cheers. You just manually reset a sub-directory in your feature branch to be same as that of master branch !!

How to check if all inputs are not empty with jQuery

I just wanted to point out my answer since I know for loop is faster then $.each loop here it is:

just add class="required" to inputs you want to be required and then in jquery do:

$('#signup_form').submit(function(){
    var fields = $('input.required');
    for(var i=0;i<fields.length;i++){
        if($(fields[i]).val() != ''){
            //whatever
        }
    }
});

How can I add shadow to the widget in flutter?

PhysicalModel will help you to give it elevation shadow.

 Container(
        alignment: Alignment.center,
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 60,
            ),
            Container(
              child: PhysicalModel(
                borderRadius: BorderRadius.circular(20),
                color: Colors.blue,
                elevation: 18,
                shadowColor: Colors.red,
                child: Container(
                  height: 100,
                  width: 100,
                ),
              ),
            ),
            SizedBox(
              height: 60,
            ),
            Container(
              child: PhysicalShape(
                color: Colors.blue,
                shadowColor: Colors.red,
                elevation: 18,
                clipper: ShapeBorderClipper(shape: CircleBorder()),
                child: Container(
                  height: 150,
                  width: 150,
                ),
              ),
            )
          ],
        ),
      )

enter image description here

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

what you have is fine - however to save some typing, you can simply use for your data


data: $('#formId').serialize()

see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.

In C#, how to check whether a string contains an integer?

You can check if string contains numbers only:

Regex.IsMatch(myStringVariable, @"^-?\d+$")

But number can be bigger than Int32.MaxValue or less than Int32.MinValue - you should keep that in mind.

Another option - create extension method and move ugly code there:

public static bool IsInteger(this string s)
{
   if (String.IsNullOrEmpty(s))
       return false;

   int i;
   return Int32.TryParse(s, out i);
}

That will make your code more clean:

if (myStringVariable.IsInteger())
    // ...

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Browsers can block access to window.top due to same origin policy. IE bugs also take place. Here's the working code:

function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

top and self are both window objects (along with parent), so you're seeing if your window is the top window.

How to strip all whitespace from string

The standard techniques to filter a list apply, although they are not as efficient as the split/join or translate methods.

We need a set of whitespaces:

>>> import string
>>> ws = set(string.whitespace)

The filter builtin:

>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'

A list comprehension (yes, use the brackets: see benchmark below):

>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'

A fold:

>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'

Benchmark:

>>> from timeit import timeit
>>> timeit('"".join("strip my spaces".split())')
0.17734256500003198
>>> timeit('"strip my spaces".translate(ws_dict)', 'import string; ws_dict = {ord(ws):None for ws in string.whitespace}')
0.457635745999994
>>> timeit('re.sub(r"\s+", "", "strip my spaces")', 'import re')
1.017787621000025

>>> SETUP = 'import string, operator, functools, itertools; ws = set(string.whitespace)'
>>> timeit('"".join([c for c in "strip my spaces" if c not in ws])', SETUP)
0.6484303600000203
>>> timeit('"".join(c for c in "strip my spaces" if c not in ws)', SETUP)
0.950212219999969
>>> timeit('"".join(filter(lambda c: c not in ws, "strip my spaces"))', SETUP)
1.3164566040000523
>>> timeit('"".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))', SETUP)
1.6947649049999995

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

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

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

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

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

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

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

How to open an existing project in Eclipse?

In case you closed multiple projects and trying to re-open all of them then in Project Explorer, select all projects. Go to Project -> Open Project.

Convert Iterable to Stream using Java 8 JDK

I've created this class:

public class Streams {
    /**
     * Converts Iterable to stream
     */
    public static <T> Stream<T>  streamOf(final Iterable<T> iterable) {
        return toStream(iterable, false);
    }

    /**
     * Converts Iterable to parallel stream
     */
    public static <T> Stream<T> parallelStreamOf(final Iterable<T> iterable) {
        return toStream(iterable, true);
    }

    private static <T> Stream<T> toStream(final Iterable<T> iterable, final boolean isParallel) {
        return StreamSupport.stream(iterable.spliterator(), isParallel);
    }
}

I think it's perfectly readable because you don't have to think about spliterators and booleans (isParallel).

How to show one layout on top of the other programmatically in my case?

Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...

Here is an example where a TextView is displayed on top of an ImageView:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <ImageView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 

    android:scaleType="center"
    android:src="@drawable/golden_gate" />

  <TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="12dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Golden Gate" />

</FrameLayout>

Here is the result

Is there a way to get version from package.json in nodejs code?

For those who look for a safe client-side solution that also works on server-side, there is genversion. It is a command-line tool that reads the version from the nearest package.json and generates an importable CommonJS module file that exports the version. Disclaimer: I'm a maintainer.

$ genversion lib/version.js

I acknowledge the client-side safety was not OP's primary intention, but as discussed in answers by Mark Wallace and aug, it is highly relevant and also the reason I found this Q&A.

How do I set a textbox's text to bold at run time?

You could use Extension method to switch between Regular Style and Bold Style as below:

static class Helper
    {
        public static void SwtichToBoldRegular(this TextBox c)
        {
            if (c.Font.Style!= FontStyle.Bold)
                c.Font = new Font(c.Font, FontStyle.Bold);
            else
                c.Font = new Font(c.Font, FontStyle.Regular);
        }
    }

And usage:

textBox1.SwtichToBoldRegular();

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Copied from the stacktrace:

BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()

By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib has a constructor with a SessionFactory argument. By adding the @Autowired annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory in your case, and provide it as a constructor argument, e.g.

@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
    // ...
}

`getchar()` gives the same output as the input string

Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.

Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.

To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).

You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.

If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c

What is DOM element?

To find out concept of DOM element it is essential to understand concept of Dynamic HTML and DOM. Everything is started from the time that requirements of all stockholders of web pages are enhanced. They wanted the Web pages that can be more interactive, dynamic and lively. In addition, to reach this goal, developers required the tools and mechanisms that via them the presentation and content of each section of web page can be modified or manipulated. Therefore the concept of Dynamic HTML is created. To understand it, a great definition for Dynamic HTML is accessible in Wikipedia:

Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and animated websites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model (DOM).

So, writing standard DHTML web pages are standardized in three fields, including client-side scripting language (such as JavaScript), a presentation definition language (such as CSS) and uniform programming interface(API) to access and modify the Web page (Document Object Model). This activity is performed by W3C and others. Also to solve the problem of cross browser, W3C tried to reach a general consensus (with different browser vendors) about scripts to access and manipulate HTML and XML documents via Document Object Model (DOM) as a standard application programming interface (API).

But the main question is that how they designed the structure of Document Object Model to meet their needs. Their solution was simple but wonderful. They used a hierarchical structure such as tree which at the root of the tree you can find document object, also each node is equivalent of a HTML elements (DOM element). This abstraction of your web page give you a great facility to access any HTML element, style sheets, and ... . To understand it better you can map each indent of your HTML code to each level of DOM tree. Please pay attention to this example:

Your HTML:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p>...</p>
        <ul>
            <li>...</li>
        </ul>
        <table>
            <tr>...</tr>
        </table>
    </body>
</html> 

DOM Structure:

    document
      |    .    
    <html>    .
    /   \         .
 <head> <body>  styleSheets
        /  \  \
      <p> <ul> <table>
      /     \       \
    text    <li>    <tr>  

So, each node of this hierarchical structure (DOM tree) refers to a DOM element. To learn more use tis reference

SQL JOIN - WHERE clause vs. ON clause

They are not the same thing.

Consider these queries:

SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID
WHERE Orders.ID = 12345

and

SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID 
    AND Orders.ID = 12345

The first will return an order and its lines, if any, for order number 12345. The second will return all orders, but only order 12345 will have any lines associated with it.

With an INNER JOIN, the clauses are effectively equivalent. However, just because they are functionally the same, in that they produce the same results, does not mean the two kinds of clauses have the same semantic meaning.

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Creating CSS Global Variables : Stylesheet theme management

Latest Update: 16/01/2020

CSS Custom Properties (Variables) have arrived!

It's 2020 and time to officially roll out this feature in your new applications.


Preprocessor "NOT" required!

There is a lot of repetition in CSS. A single color may be used in several places.

For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally.

For non-trivial projects, this is not always possible. By declaring a variable on the :root pseudo-element, a CSS author can halt some instances of repetition by using the variable.

How it works

Set your variable at the top of your stylesheet:

CSS

Create a root class:

:root {
}

Create variables (-- [String] : [value])

:root {
  --red: #b00;
  --blue: #00b;
  --fullwidth: 100%;
}

Set your variables anywhere in your CSS document:

h1 {
  color: var(--red);
}
#MyText {
  color: var(--blue);
  width: var(--fullwidth);
}

BROWSER SUPPORT / COMPATIBILITY

See caniuse.com for current compatability.

![supported browsers


Firefox: Version 31+ (Enabled by default)

Supported since 2014 (Leading the way as usual.)

More info from Mozilla


Chrome: Version 49+ (Enabled by default).

Supported since 2016


Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).

Supported since 2016


Opera: Version 39+ (Enabled by default).

Supported since 2016


Android: Version 52+ (Enabled by default).

Supported since 2016


Edge: Version 15+ (Enabled by default).

Supported since 2017

CSS Custom Properties landed in Windows Insider Preview build 14986


IE: When pigs fly.

It's time to finally let this ship sink. No one enjoyed riding her anyway. ?


W3C SPEC

Full specification for upcoming CSS variables

Read more


TRY IT OUT

A fiddle and snippet are attached below for testing:

(It will only work with supported browsers.)

DEMO FIDDLE

_x000D_
_x000D_
:root {
  --red: #b00;
  --blue: #4679bd;
  --grey: #ddd;
  --W200: 200px;
  --Lft: left;
}
.Bx1,
.Bx2,
.Bx3,
.Bx4 {
  float: var(--Lft);
  width: var(--W200);
  height: var(--W200);
  margin: 10px;
  padding: 10px;
  border: 1px solid var(--red);
}
.Bx1 {
  color: var(--red);
  background: var(--grey);
}
.Bx2 {
  color: var(--grey);
  background: black;
}
.Bx3 {
  color: var(--grey);
  background: var(--blue);
}
.Bx4 {
  color: var(--grey);
  background: var(--red);
}
_x000D_
<p>If you see four square boxes then variables are working as expected.</p>

<div class="Bx1">I should be red text on grey background.</div>
<div class="Bx2">I should be grey text on black background.</div>
<div class="Bx3">I should be grey text on blue background.</div>
<div class="Bx4">I should be grey text on red background.</div>
_x000D_
_x000D_
_x000D_

Modifying a subset of rows in a pandas dataframe

Starting from pandas 0.20 ix is deprecated. The right way is to use df.loc

here is a working example

>>> import pandas as pd 
>>> import numpy as np 
>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN
>>> 

Explanation:

As explained in the doc here, .loc is primarily label based, but may also be used with a boolean array.

So, what we are doing above is applying df.loc[row_index, column_index] by:

  • Exploiting the fact that loc can take a boolean array as a mask that tells pandas which subset of rows we want to change in row_index
  • Exploiting the fact loc is also label based to select the column using the label 'B' in the column_index

We can use logical, condition or any operation that returns a series of booleans to construct the array of booleans. In the above example, we want any rows that contain a 0, for that we can use df.A == 0, as you can see in the example below, this returns a series of booleans.

>>> df = pd.DataFrame({"A":[0,1,0], "B":[2,0,5]}, columns=list('AB'))
>>> df 
   A  B
0  0  2
1  1  0
2  0  5
>>> df.A == 0 
0     True
1    False
2     True
Name: A, dtype: bool
>>> 

Then, we use the above array of booleans to select and modify the necessary rows:

>>> df.loc[df.A == 0, 'B'] = np.nan
>>> df
   A   B
0  0 NaN
1  1   0
2  0 NaN

For more information check the advanced indexing documentation here.

AngularJS : The correct way of binding to a service properties

To bind any data,which sends service is not a good idea (architecture),but if you need it anymore I suggest you 2 ways to do that

1) you can get the data not inside you service.You can get data inside your controller/directive and you will not have a problem to bind it anywhere

2) you can use angularjs events.Whenever you want,you can send a signal(from $rootScope) and catch it wherever you want.You can even send a data on that eventName.

Maybe this can help you. If you need more with examples,here is the link

http://www.w3docs.com/snippets/angularjs/bind-value-between-service-and-controller-directive.html

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I recently got this error. I had compiled the binary with -O3. Google told me that this means "illegal opcode", which seemed fishy to me. I then turned off all optimizations and reran. Now the error transformed to a segfault. Hence by setting -g and running valgrind I tracked the source down and fixed it. Reenabling all optimizations showed no further appearances of illegal instruction 4.

Apparently, optimizing wrong code can yield weird results.

Pandas - replacing column values

Can try this too!
Create a dictionary of replacement values.

import pandas as pd
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

enter image description here

replace_dict= {0:'Female',1:'Male'}
print(replace_dict)

enter image description here

Use the map function for replacing values

data['sex']=data['sex'].map(replace_dict)

Output after replacing
enter image description here

True/False vs 0/1 in MySQL

If you are into performance, then it is worth using ENUM type. It will probably be faster on big tables, due to the better index performance.

The way of using it (source: http://dev.mysql.com/doc/refman/5.5/en/enum.html):

CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);

But, I always say that explaining the query like this:

EXPLAIN SELECT * FROM shirts WHERE size='medium';

will tell you lots of information about your query and help on building a better table structure. For this end, it is usefull to let phpmyadmin Propose a table table structure - but this is more a long time optimisation possibility, when the table is already filled with lots of data.

How to generate .json file with PHP?

You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.

Returning a boolean from a Bash function

Following up on @Bruno Bronosky and @mrteatime, I offer the suggestion that you just write your boolean return "backwards". This is what I mean:

foo()
{
    if [ "$1" == "bar" ]; then
        true; return
    else
        false; return
    fi;
}

That eliminates the ugly two line requirement for every return statement.

Parsing JSON Object in Java

There are many JSON libraries available in Java.

The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.

There are typically three things one should look at for choosing any library:

  1. Performance
  2. Ease of use (code is simple to write and legible) - that goes with features.
  3. For mobile apps: dependency/jar size

Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.

For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs. For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...

Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.

For your particular example, the following code decodes your json with jackson:

public class MyObj {

    private List<Interest> interests;

    static final class Interest {
        private String interestKey;
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
    }
}

Let me know if you have any questions.

Including a css file in a blade template?

You should try this :

{{ Html::style('css/styles.css') }}

OR

<link href="{{ asset('css/styles.css') }}" rel="stylesheet">

Hope this help for you !!!

How to solve WAMP and Skype conflict on Windows 7?

Detail blog to fix this issue is : http://goo.gl/JXWqfJ

You can solve this problem by following two ways:
A) Start your WAMP befor you login to skype. So that WAMP will take over the the port and there will be no conflict with the port number. And you are able to use Skype as well as WAMP.
But this is not the permanent solution for your problem. Whenever you want to start WAMP you need to signout Skype first and than only you are able to start WAMP. Which is really i don’t like.

B) Second option is to change the port of Skype itself, so that it will not conflict with WAMP. Following screen/steps will help you to solve this problem:
1) SignIn to Skype.
2) Got to the Tools -> options
3) Select the “Advanced” -> Connection
4) Unchecked “Use port 80 and 443 as alternatives for incoming connections” checkbox and click save.
5) Now Signout and SignIn again to skype. (this change will take affect only you relogin to skype)
Now every time you start WAMP will not conflict with skype.

jQuery UI themes and HTML tables

There are a bunch of resources out there:

Plugins with ThemeRoller support:

jqGrid

DataTables.net

UPDATE: Here is something I put together that will style the table:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            };
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);
                input.addClass(options.css);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                        $(this).children("td").addClass("ui-state-hover");
                    } else {
                        $(this).children("td").removeClass("ui-state-hover");
                    }
                });

                input.find("th").addClass("ui-state-default");
                input.find("td").addClass("ui-widget-content");

                input.find("tr").each(function () {
                    $(this).children("td:not(:first)").addClass("first");
                    $(this).children("th:not(:first)").addClass("first");
                });
            });
        };
    })(jQuery);

    $(document).ready(function () {
        $("#Table1").styleTable();
    });

</script>

<table id="Table1" class="full">
    <tr>
        <th>one</th>
        <th>two</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
</table>

The CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

How do I drop a MongoDB database from the command line?

use following command from mongo shell to drop db

use ; db.dropDatabase();

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

In Swift the isEmpty function it will check if the string is empty.

 if username.isEmpty || password.isEmpty {
      println("Sign in failed. Empty character")
 }

find -exec with multiple commands

1st answer of Denis is the answer to resolve the trouble. But in fact it is no more a find with several commands in only one exec like the title suggest. To answer the one exec with several commands thing we will have to look for something else to resolv. Here is a example:

Keep last 10000 lines of .log files which has been modified in the last 7 days using 1 exec command using severals {} references

1) see what the command will do on which files:

find / -name "*.log" -a -type f -a -mtime -7 -exec sh -c "echo tail -10000 {} \> fictmp; echo cat fictmp \> {} " \;

2) Do it: (note no more "\>" but only ">" this is wanted)

find / -name "*.log" -a -type f -a -mtime -7 -exec sh -c "tail -10000 {} > fictmp; cat fictmp > {} ; rm fictmp" \;

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

Save classifier to disk in scikit-learn

You can also use joblib.dump and joblib.load which is much more efficient at handling numerical arrays than the default python pickler.

Joblib is included in scikit-learn:

>>> import joblib
>>> from sklearn.datasets import load_digits
>>> from sklearn.linear_model import SGDClassifier

>>> digits = load_digits()
>>> clf = SGDClassifier().fit(digits.data, digits.target)
>>> clf.score(digits.data, digits.target)  # evaluate training error
0.9526989426822482

>>> filename = '/tmp/digits_classifier.joblib.pkl'
>>> _ = joblib.dump(clf, filename, compress=9)

>>> clf2 = joblib.load(filename)
>>> clf2
SGDClassifier(alpha=0.0001, class_weight=None, epsilon=0.1, eta0=0.0,
       fit_intercept=True, learning_rate='optimal', loss='hinge', n_iter=5,
       n_jobs=1, penalty='l2', power_t=0.5, rho=0.85, seed=0,
       shuffle=False, verbose=0, warm_start=False)
>>> clf2.score(digits.data, digits.target)
0.9526989426822482

Edit: in Python 3.8+ it's now possible to use pickle for efficient pickling of object with large numerical arrays as attributes if you use pickle protocol 5 (which is not the default).

C++ terminate called without an active exception

year, the thread must be join(). when the main exit

Pass command parameter to method in ViewModel in WPF?

If you are that particular to pass elements to viewmodel You can use

 CommandParameter="{Binding ElementName=ManualParcelScanScreen}"

Custom height Bootstrap's navbar

For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..

<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
    <div class="navbar-collapse collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
        </ul>
    </div>
</nav>

Bootstrap 4 Navbar Height Demo

How do I create an abstract base class in JavaScript?

You might want to check out Dean Edwards' Base Class: http://dean.edwards.name/weblog/2006/03/base/

Alternatively, there is this example / article by Douglas Crockford on classical inheritance in JavaScript: http://www.crockford.com/javascript/inheritance.html

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

On official docs: https://electronjs.org/docs/faq#i-can-not-use-jqueryrequirejsmeteorangularjs-in-electron

<head>
  <script>
  window.nodeRequire = require;
  delete window.require;
  delete window.exports;
  delete window.module;
  </script>
  <script type="text/javascript" src="jquery.js"></script>
</head>

Appending to an existing string

Yet an other way:

s.insert(-1, ' world')

Hibernate openSession() vs getCurrentSession()

As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context - you don't need to close this.

If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.

You should never use one session per web app - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

How to pass multiple values to single parameter in stored procedure

This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.

Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:

CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
    IF NOT <@PortfolioID contains Comma>
    BEGIN
        INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
        SET @PortfolioID = ''
    END ELSE
    BEGIN
         INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
         SET @PortfolioID = <Everything after the next comma>
    END
END

Then, change your condition to

WHERE PortfolioId IN (SELECT ID FROM #TempTable)

EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:

You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:

The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.

The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.

The query must use an IN clause to specify the parameter.

This I found here.

Creating a LINQ select from multiple tables

You can use anonymous types for this, i.e.:

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new { pg, op }).SingleOrDefault();

This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new
                  {
                      PermissionName = pg, 
                      ObjectPermission = op
                  }).SingleOrDefault();

This will enable you to say:-

if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();

For example :-)

How to validate a file upload field using Javascript/jquery

Simple and powerful way(dynamic validation)

place formats in array like "image/*"

_x000D_
_x000D_
var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{

console.log(upload.value)
})
_x000D_
<input type="file" id="upload" >
_x000D_
_x000D_
_x000D_

How to use Google Translate API in my Java application?

You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
1) Create new script with such code on google script:

var mock = {
  parameter:{
    q:'hello',
    source:'en',
    target:'fr'
  }
};


function doGet(e) {
  e = e || mock;

  var sourceText = ''
  if (e.parameter.q){
    sourceText = e.parameter.q;
  }

  var sourceLang = '';
  if (e.parameter.source){
    sourceLang = e.parameter.source;
  }

  var targetLang = 'en';
  if (e.parameter.target){
    targetLang = e.parameter.target;
  }

  var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});

  return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
}

2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.
google script deploy

3) Use this java code for testing your API:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Translator {

    public static void main(String[] args) throws IOException {
        String text = "Hello world!";
        //Translated text: Hallo Welt!
        System.out.println("Translated text: " + translate("en", "de", text));
    }

    private static String translate(String langFrom, String langTo, String text) throws IOException {
        // INSERT YOU URL HERE
        String urlStr = "https://your.google.script.url" +
                "?q=" + URLEncoder.encode(text, "UTF-8") +
                "&target=" + langTo +
                "&source=" + langFrom;
        URL url = new URL(urlStr);
        StringBuilder response = new StringBuilder();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

}

As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

You could roll your own:

function resolve(objectToGetValueFrom, stringOfDotSeparatedParameters) {
    var returnObject = objectToGetValueFrom,
        parameters = stringOfDotSeparatedParameters.split('.'),
        i,
        parameter;

    for (i = 0; i < parameters.length; i++) {
        parameter = parameters[i];

        returnObject = returnObject[parameter];

        if (returnObject === undefined) {
            break;
        }
    }
    return returnObject;
};

And use it like this:

var result = resolve(obj, 'a.b.c.d'); 

* result is undefined if any one of a, b, c or d is undefined.

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.

Using SimpleXML to create an XML object from scratch

Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.

$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
    $w->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));

By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I was getting similar errors and eventually found just that cleaning the build folder resolved my issue.

mvn clean install

How to open a file / browse dialog using javascript?

Use this.

<script>
  function openFileOption()
{
  document.getElementById("file1").click();
}
</script>
     <input type="file" id="file1" style="display:none">
     <a href="#" onclick="openFileOption();return;">open File Dialog</a>

CSS3 Rotate Animation

if you want to flip image you can use it.

.image{
    width: 100%;
    -webkit-animation:spin 3s linear infinite;
    -moz-animation:spin 3s linear infinite;
    animation:spin 3s linear infinite;
}
@-moz-keyframes spin { 50% { -moz-transform: rotateY(90deg); } }
@-webkit-keyframes spin { 50% { -webkit-transform: rotateY(90deg); } }
@keyframes spin { 50% { -webkit-transform: rotateY(90deg); transform:rotateY(90deg); } }

How to initialize an array of custom objects

Maybe you mean like this? I like to make an object and use Format-Table:

> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table

Name                                                                        Age Info
----                                                                        --- ----
Joe                                                                          32  something about him

This will put all objects you have in the array in columns according to their properties.

Tip: Using -auto sizes the table better

> $array | Format-Table -Auto

Name Age Info
---- --- ----
Joe   32 something about him

You can also specify which properties you want in the table. Just separate each property name with a comma:

> $array | Format-Table Name, Age -Auto

Name Age
---- ---
Joe   32

Wildcards in a Windows hosts file

I found a posting about Using the Windows Hosts File that also says "No wildcards are allowed."

In the past, I have just added the additional entries to the hosts file, because (as previously said), it's not that much extra work when you already are editing the apache config file.

Changing the maximum length of a varchar column?

You need

ALTER TABLE YourTable ALTER COLUMN YourColumn <<new_datatype>> [NULL | NOT NULL]

But remember to specify NOT NULL explicitly if desired.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NOT NULL;

If you leave it unspecified as below...

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500);

Then the column will default to allowing nulls even if it was originally defined as NOT NULL. i.e. omitting the specification in an ALTER TABLE ... ALTER COLUMN is always treated as.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NULL;

This behaviour is different from that used for new columns created with ALTER TABLE (or at CREATE TABLE time). There the default nullability depends on the ANSI_NULL_DFLT settings.

How can I check that two objects have the same set of property names?

You can serialize simple data to check for equality:

data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)

This will give you something like

'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'

As a function...

function compare(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);

EDIT

If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section

EDIT 2

If you just want to check keys...

function compareKeys(a, b) {
  var aKeys = Object.keys(a).sort();
  var bKeys = Object.keys(b).sort();
  return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}

should do it.

How to change the Jupyter start-up folder

I just had the same problem and tested the methods mentioned above. After several trials, I realized that they are partially correct and are not the complete solution. I tested the below in Windows 10 and Anaconda 4.4.0 with python 3.6.

There are two ways to do even though they have only very small difference. Follow the way marneylc suggested above: i.e.

1) Open "Anaconda Prompt" and type jupyter notebook --generate-config

2) You find the file in C:\Users\username\.jupyter\jupyter_notebook_config.py

3) Change the line of #c.NotebookApp.notebook_dir = '' to c.NotebookApp.notebook_dir = 'c:\test\your_root\'

4) Then, go to the shortcut of Jupyter Notebook located in C:\Users\User_name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)

5) Do the right click and go to the Properties

6) In the Target field, remove %USERPROFILE% as stenlytw suggested above.

7) Then, In the field of Start in, type the same directory of c:\test\your_root\ in jupyter_notebook_config.py

8) Done!

As the simpler way, after step 3, go to C:\Users\User_name\Anaconda3\Scripts

4-2) You can see the file of jupyter-notebook.exe and click it.

5-2) Then, the Jupyter start the folder you specified in jupyter_notebook_config.py. So make the shortcut of this file.

6-2) Done.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

You need to explicitly include a BoundField of the primary key. If you don't want the user to see the primary key, you have to hide it via css:

    <asp:BoundField DataField="Id_primary_key" ItemStyle-CssClass="hidden" 
HeaderStyle-CssClass="hidden" />

Where 'hidden' is a class in css that has it's display set to 'none'.

jQuery .val change doesn't change input value

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
function changes() {
$('#link').val('new value');
}
</script>
<button onclick="changes()">a</button>
<input type='text' value='http://www.link.com' id='link'>

Sorting an IList in C#

try this  **USE ORDER BY** :

   public class Employee
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

 private static IList<Employee> GetItems()
        {
            List<Employee> lst = new List<Employee>();

            lst.Add(new Employee { Id = "1", Name = "Emp1" });
            lst.Add(new Employee { Id = "2", Name = "Emp2" });
            lst.Add(new Employee { Id = "7", Name = "Emp7" });
            lst.Add(new Employee { Id = "4", Name = "Emp4" });
            lst.Add(new Employee { Id = "5", Name = "Emp5" });
            lst.Add(new Employee { Id = "6", Name = "Emp6" });
            lst.Add(new Employee { Id = "3", Name = "Emp3" });

            return lst;
        }

**var lst = GetItems().AsEnumerable();

            var orderedLst = lst.OrderBy(t => t.Id).ToList();

            orderedLst.ForEach(emp => Console.WriteLine("Id - {0} Name -{1}", emp.Id, emp.Name));**

Using Switch Statement to Handle Button Clicks

One way of achieving this is to make your class implement OnClickListener and then add it to your buttons like this:

Example:

//make your class implement OnClickListener
public class MyClass implements OnClickListener{

        ...

        //Create your buttons and set their onClickListener to "this"
        Button b1 = (Button) findViewById(R.id.buttonplay);   
        b1.setOnClickListener(this);

        Button b2 = (Button) findViewById(R.id.buttonstop);   
        b2.setOnClickListener(this);

        ...

        //implement the onClick method here
        public void onClick(View v) {
           // Perform action on click
          switch(v.getId()) {
            case R.id.buttonplay:
              //Play voicefile
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
              break;
            case R.id.buttonstop:
              //Stop MediaPlayer
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
              break;
          }
       }
}

For more information see Android Developers > Handling UI Events.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Using Visual Studio I could never come up with a simple project to reproduce the error.

My solution was to disable the Visual Studio Hosting process.

For those interested I have attached a handle trace for the offending handle:

0:044> !htrace 242C
--------------------------------------
Handle = 0x000000000000242c - OPEN
Thread ID = 0x0000000000001cd0, Process ID = 0x0000000000001a5c

0x000000007722040a: ntdll!ZwCreateFile+0x000000000000000a
0x0000000074b4bfe3: wow64!whNtCreateFile+0x000000000000010f
0x0000000074b3cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074ac276d: wow64cpu!TurboDispatchJumpAddressEnd+0x0000000000000024
0x0000000074b3d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074b3c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x00000000772184c8: ntdll!LdrpInitializeProcess+0x00000000000017e2
0x0000000077217623: ntdll! ?? ::FNODOBFM::`string'+0x000000000002bea0
0x000000007720308e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000773d0066: ntdll_773b0000!NtCreateFile+0x0000000000000012
0x000000007541b616: KERNELBASE!CreateFileW+0x000000000000035e
0x0000000075b42345: KERNEL32!CreateFileWImplementation+0x0000000000000069
0x000000006a071b47: mscorwks_ntdef!StgIO::Open+0x000000000000028c
--------------------------------------
Handle = 0x000000000000242c - CLOSE
Thread ID = 0x0000000000000cd4, Process ID = 0x0000000000001a5c

0x000000007721ffaa: ntdll!ZwClose+0x000000000000000a
0x0000000074b3f2cd: wow64!whNtClose+0x0000000000000011
0x0000000074b3cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074ac276d: wow64cpu!TurboDispatchJumpAddressEnd+0x0000000000000024
0x0000000074b3d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074b3c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x000000007724d177: ntdll! ?? ::FNODOBFM::`string'+0x000000000002bfe4
0x000000007720308e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000773cf992: ntdll_773b0000!ZwClose+0x0000000000000012
0x0000000075b42642: KERNEL32!BaseRegCloseKeyInternal+0x0000000000000041
0x0000000075b425bc: KERNEL32!RegCloseKey+0x000000000000007d
*** WARNING: Unable to verify checksum for mscorlib.ni.dll
0x0000000068f13ca3: mscorlib_ni+0x0000000000233ca3
0x0000000069bc21db: mscorwks_ntdef!CallDescrWorker+0x0000000000000033
0x0000000069be4a2a: mscorwks_ntdef!CallDescrWorkerWithHandler+0x000000000000008e
--------------------------------------
Handle = 0x000000000000242c - OPEN
Thread ID = 0x00000000000006cc, Process ID = 0x0000000000001a5c

0x0000000077220e0a: ntdll!NtOpenKeyEx+0x000000000000000a
0x0000000074b5d1c9: wow64!Wow64NtOpenKey+0x0000000000000091
0x0000000074b5313b: wow64!whNtOpenKeyEx+0x0000000000000073
0x0000000074b3cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074ac276d: wow64cpu!TurboDispatchJumpAddressEnd+0x0000000000000024
0x0000000074b3d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074b3c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x000000007724d177: ntdll! ?? ::FNODOBFM::`string'+0x000000000002bfe4
0x000000007720308e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000773d0fca: ntdll_773b0000!NtOpenKeyEx+0x0000000000000012
0x0000000075b42721: KERNEL32!LocalBaseRegOpenKey+0x000000000000010c
0x0000000075b428c9: KERNEL32!RegOpenKeyExInternalW+0x0000000000000130
0x0000000075b427b5: KERNEL32!RegOpenKeyExW+0x0000000000000021
--------------------------------------
Handle = 0x000000000000242c - CLOSE
Thread ID = 0x0000000000000cd4, Process ID = 0x0000000000001a5c

0x000000007721ffaa: ntdll!ZwClose+0x000000000000000a
0x0000000074b3f2cd: wow64!whNtClose+0x0000000000000011
0x0000000074b3cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074ac276d: wow64cpu!TurboDispatchJumpAddressEnd+0x0000000000000024
0x0000000074b3d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074b3c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x000000007724d177: ntdll! ?? ::FNODOBFM::`string'+0x000000000002bfe4
0x000000007720308e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000773cf992: ntdll_773b0000!ZwClose+0x0000000000000012
0x0000000075b42642: KERNEL32!BaseRegCloseKeyInternal+0x0000000000000041
0x0000000075b425bc: KERNEL32!RegCloseKey+0x000000000000007d
0x0000000068f13ca3: mscorlib_ni+0x0000000000233ca3
0x0000000069bc21db: mscorwks_ntdef!CallDescrWorker+0x0000000000000033
0x0000000069be4a2a: mscorwks_ntdef!CallDescrWorkerWithHandler+0x000000000000008e
--------------------------------------
Handle = 0x000000000000242c - OPEN
Thread ID = 0x0000000000001cd0, Process ID = 0x0000000000001a5c

0x0000000077220e0a: ntdll!NtOpenKeyEx+0x000000000000000a
0x0000000074b5d1c9: wow64!Wow64NtOpenKey+0x0000000000000091
0x0000000074b5313b: wow64!whNtOpenKeyEx+0x0000000000000073
0x0000000074b3cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074ac276d: wow64cpu!TurboDispatchJumpAddressEnd+0x0000000000000024
0x0000000074b3d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074b3c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x00000000772184c8: ntdll!LdrpInitializeProcess+0x00000000000017e2
0x0000000077217623: ntdll! ?? ::FNODOBFM::`string'+0x000000000002bea0
0x000000007720308e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000773d0fca: ntdll_773b0000!NtOpenKeyEx+0x0000000000000012
0x0000000075b42721: KERNEL32!LocalBaseRegOpenKey+0x000000000000010c
0x0000000075b428c9: KERNEL32!RegOpenKeyExInternalW+0x0000000000000130
--------------------------------------
Handle = 0x000000000000242c - CLOSE
Thread ID = 0x0000000000000cd4, Process ID = 0x0000000000001a5c

0x000000007721ffaa: ntdll!ZwClose+0x000000000000000a
0x0000000074b3f2cd: wow64!whNtClose+0x0000000000000011
0x0000000074b3cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074ac276d: wow64cpu!TurboDispatchJumpAddressEnd+0x0000000000000024
0x0000000074b3d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074b3c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x000000007724d177: ntdll! ?? ::FNODOBFM::`string'+0x000000000002bfe4
0x000000007720308e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000773cf992: ntdll_773b0000!ZwClose+0x0000000000000012
0x0000000075b42642: KERNEL32!BaseRegCloseKeyInternal+0x0000000000000041
0x0000000075b425bc: KERNEL32!RegCloseKey+0x000000000000007d
0x0000000068f13ca3: mscorlib_ni+0x0000000000233ca3
0x0000000069bc21db: mscorwks_ntdef!CallDescrWorker+0x0000000000000033
0x0000000069be4a2a: mscorwks_ntdef!CallDescrWorkerWithHandler+0x000000000000008e
--------------------------------------
Handle = 0x000000000000242c - OPEN
Thread ID = 0x0000000000001cd0, Process ID = 0x0000000000001a5c

0x0000000077220e0a: ntdll!NtOpenKeyEx+0x000000000000000a
0x0000000074b5d1c9: wow64!Wow64NtOpenKey+0x0000000000000091
0x0000000074b5313b: wow64!whNtOpenKeyEx+0x0000000000000073
0x0000000074b3cf87: wow64!Wow64SystemServiceEx+0x00000000000000d7
0x0000000074ac276d: wow64cpu!TurboDispatchJumpAddressEnd+0x0000000000000024
0x0000000074b3d07e: wow64!RunCpuSimulation+0x000000000000000a
0x0000000074b3c549: wow64!Wow64LdrpInitialize+0x0000000000000429
0x00000000772184c8: ntdll!LdrpInitializeProcess+0x00000000000017e2
0x0000000077217623: ntdll! ?? ::FNODOBFM::`string'+0x000000000002bea0
0x000000007720308e: ntdll!LdrInitializeThunk+0x000000000000000e
0x00000000773d0fca: ntdll_773b0000!NtOpenKeyEx+0x0000000000000012
0x0000000075b42721: KERNEL32!LocalBaseRegOpenKey+0x000000000000010c
0x0000000075b428c9: KERNEL32!RegOpenKeyExInternalW+0x0000000000000130

--------------------------------------
Parsed 0x358E stack traces.
Dumped 0x7 stack traces.
0:044> !handle 242c ff
Handle 242c
  Type          File
  Attributes    0
  GrantedAccess 0x120089:
         ReadControl,Synch
         Read/List,ReadEA,ReadAttr
  HandleCount   2
  PointerCount  3
  No Object Specific Information available

PHP Accessing Parent Class Variable

Just echo it since it's inherited

echo $this->bb;

Singular matrix issue with Numpy

The matrix you pasted

[[   1,    8,   50],
 [   8,   64,  400],
 [  50,  400, 2500]]

Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)

http://en.wikipedia.org/wiki/Invertible_matrix

Pip install - Python 2.7 - Windows 7

This is one way of installing pip on a Windows system.

  1. Download the "get-pip" python script from here: https://bootstrap.pypa.io/get-pip.py

  2. Save the file as getpip.py

  3. Run it from cmd: python getpip.py install

Use formula in custom calculated field in Pivot Table

I'll post this comment as answer, as I'm confident enough that what I asked is not possible.

I) Couple of similar questions trying to do the same, without success:

II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:

  • For calculated fields, the individual amounts in the other fields are summed, and then the calculation is performed on the total amount.
  • Calculated field formulas cannot refer to the pivot table totals or subtotals
  • Calculated field formulas cannot refer to worksheet cells by address or by name.
  • Sum is the only function available for a calculated field.
  • Calculated fields are not available in an OLAP-based pivot table.

III) There is tiny limited possibility to use AVERAGE() and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE(), referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.

VBA vlookup reference in different sheet

The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

  1. The value is actually not present (pointed out by chris nielsen).

  2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

    Sub srch()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim srchres As Variant
    
        Set ws1 = Worksheets("Sheet1")
        Set ws2 = Worksheets("Sheet2")
    
        On Error Resume Next
        srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
        On Error GoTo 0
        If (IsEmpty(srchres)) Then
          ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
        Else
          ws2.Range("E2").Value = srchres
        End If
    End Sub
    

I will point out a few additional notable points:

  1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

  2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

  3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

  4. Both solutions by L42 qualify Ranges suitably.

  5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

CSS: How to change colour of active navigation page menu

I think you are getting confused about what the a:active CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected into your CSS and when you select a link, update the selected menu item with new class e.g.

<div class="menuBar">
    <ul>
        <li class="selected"><a href="index.php">HOME</a></li>
        <li><a href="two.php">PORTFOLIO</a></li>
        ....
    </ul>
</div>

// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; } 
// more general CSS
li.selected a { color: #FF0000; }

You will need to update your template page to take in a selectedPage parameter.

error LNK2005, already defined?

Presence of int k; in the header file causes symbol k to be defined within each translation unit this header is included to while linker expects it to be defined only once (aka One Definition Rule Violation).

While suggestion involving extern are not wrong, extern is a C-ism and should not be used.

Pre C++17 solution that would allow variable in header file to be defined in multiple translation units without causing ODR violation would be conversion to template:

template<typename x_Dummy = void> class
t_HeaderVariableHolder
{
    public: static int s_k;
};

template<typename x_Dummy> int t_HeaderVariableHolder<x_Dummy>::s_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return t_HeaderVariableHolder<>::s_k;
}

With C++17 things become much simpler as it allows inline variables:

inline int g_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return g_k;
}

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Kotlin version:

Use these extensions with infix functions that simplify later calls

infix fun View.below(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

infix fun View.leftOf(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}

infix fun View.alightParentRightIs(aligned: Boolean) {
    val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
    if (aligned) {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
    } else {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
    }
    this.layoutParams = layoutParams
}

Then use them as infix functions calls:

view1 below view2
view1 leftOf view2
view1 alightParentRightIs true

Or you can use them as normal functions:

view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)

Combine two integer arrays

Here a simple function that use variable arguments:

final static
public int[] merge(final int[] ...arrays ) {
    int size = 0;
    for ( int[] a: arrays )
        size += a.length;

        int[] res = new int[size];

        int destPos = 0;
        for ( int i = 0; i < arrays.length; i++ ) {
            if ( i > 0 ) destPos += arrays[i-1].length;
            int length = arrays[i].length;
            System.arraycopy(arrays[i], 0, res, destPos, length);
        }

        return res;
}

To use:

int[] array1 = {1,2,3};
int[] array2 = {4,5,6};
int[] array3 = {7,8,9};
int[] array1and2and3 = merge(array1, array2, array3);
for ( int x: array1and2and3 ) 
    System.out.print( String.format("%3d", x) );

How to increase Java heap space for a tomcat app

You need to add the following lines in your catalina.sh file.

export CATALINA_OPTS="-Xms512M -Xmx1024M"

UPDATE : catalina.sh content clearly says -

Do not set the variables in this script. Instead put them into a script setenv.sh in CATALINA_BASE/bin to keep your customizations separate.

So you can add above in setenv.sh instead (create a file if it does not exist).

To check if string contains particular word

.contains() is perfectly valid and a good way to check.

(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence))

Since you didn't post the error, I guess d is either null or you are getting the "Cannot refer to a non-final variable inside an inner class defined in a different method" error.

To make sure it's not null, first check for null in the if statement. If it's the other error, make sure d is declared as final or is a member variable of your class. Ditto for c.

Batch script to install MSI

Here is the batch file which should work for you:

@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder

:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"

if not exist "%Package%" (
   echo.
   echo The entered folder/MSI file does not exist ^(typing mistake^).
   echo.
   setlocal EnableDelayedExpansion
   set /P "Retry=Try again [Y/N]: "
   if /I "!Retry!"=="Y" endlocal & goto select
   endlocal
   goto :EOF
)

echo.
echo Selected installation: %MSI%
echo.
echo.

:verify
echo Is This Correct?
echo.
echo.
echo    0: ABORT INSTALL
echo    1: YES
echo    2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select

:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"

The characters listed on last page output on entering in a command prompt window either help cmd or cmd /? have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^ as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.

And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec with the command line option /i to install the application inside MSI package.

Run msiexec.exe /? to get in a GUI window the available options or look at Msiexec (command-line options).

I have added already /quiet additionally to required option /i for a silent installation.

In batch code above command start is used with option /wait to start Windows application msiexec.exe and hold execution of batch file until installation finished (or aborted).

use current date as default value for a column

To use the current date as the default for a date column, you will need to:

1- open table designer

2- select the column

3- go to column proprerties

4- set the value of Default value or binding propriete To (getdate())

enter image description here

Git commit with no commit message

git generally requires a non-empty message because providing a meaningful commit message is part of good development practice and good repository stewardship. The first line of the commit message is used all over the place within git; for more, read "A Note About Git Commit Messages".

If you open Terminal.app, cd to your project directory, and git commit -am '', you will see that it fails because an empty commit message is not allowed. Newer versions of git have the
--allow-empty-message commandline argument, including the version of git included with the latest version of Xcode. This will let you use this command to make a commit with an empty message:

git commit -a --allow-empty-message -m ''

Prior to the --allow-empty-message flag, you had to use the commit-tree plumbing command. You can see an example of using this command in the "Raw Git" chapter of the Git book.

Error: The type exists in both directories

Assuming you're building a Web Application, which it appears you are given the MVC2 point, you shouldn't use the App_Code folder. It was not designed to be integrated with Web Application projects.

When you Compile in Visual Studio, all the code in your application (including in App_Code) gets compiled into an assembly. When you run your application, asp.net knows about a "special" folder called App_Code and compiles the content of it into an assembly with a unique name. Thus, anytime you run the project you'll run into this problem.

The solution:

Rename your App_Code folder to something like "Code" or "Global" (and update your now broken references) & voila, problem solved.

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

Disable Input fields in reactive form

This worked for me: this.form.get('first').disable({onlySelf: true});

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

A reference to the dll could not be added

You can not add a reference to a native DLL. However You can include them in the solution (right click solution, select "Add existing file"), but they will not be referenced unless you declare something like

[DllImport("...")]
public static extern void MyFunction();

Maybe there's some kind of wrapper DLL, which you are actually referencing and which contains the DLL imports.

Sometimes, You may reference the wrapper DLL but still can not make your program running, where error prompt suggests you to ensure the file exists and all dependencies are available.

This problem is because the assembly you are trying to add is targeted and compiled only for a x86 or x64 processor architecture.

Just try change the Target Platform to x86 or x64 in Build -> Configuration Manager.

Protractor : How to wait for page complete after click a button?

With Protractor, you can use the following approach

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain newPageName
browser.wait(EC.urlContains('newPageName'), 10000);

So your code will look something like,

emailEl.sendKeys('jack');
passwordEl.sendKeys('123pwd');

btnLoginEl.click();

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain efg
ptor.wait(EC.urlContains('efg'), 10000);

expect(ptor.getCurrentUrl()).toEqual(url + 'abc#/efg');

Note: This may not mean that new page has finished loading and DOM is ready. The subsequent 'expect()' statement will ensure Protractor waits for DOM to be available for test.

Reference: Protractor ExpectedConditions

CSS center display inline block?

Great article i found what worked best for me was to add a % to the size

.wrap {
margin-top:5%;
margin-bottom:5%;
height:100%;
display:block;}

How to disable XDebug

(This is for CentOS)

Rename the config file and restart apache.

sudo mv /etc/php.d/xdebug.ini /etc/php.d/xdebug.ini.old
sudo service httpd restart

Do the reverse to re-enable.

Getting the docstring from a function

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code

Can't bind to 'routerLink' since it isn't a known property

In my case I just need to import my newly created component to RouterModule

{path: 'newPath', component: newComponent}

Then in your app.module import the router and configure the routes:

import { RouterModule } from '@angular/router';

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent},
            {path: 'newPath', component: newComponent}
        ])
    ],

Hope this helps to some one !!!

Best practices for circular shift (rotate) operations in C++

Since it's C++, use an inline function:

template <typename INT> 
INT rol(INT val) {
    return (val << 1) | (val >> (sizeof(INT)*CHAR_BIT-1));
}

C++11 variant:

template <typename INT> 
constexpr INT rol(INT val) {
    static_assert(std::is_unsigned<INT>::value,
                  "Rotate Left only makes sense for unsigned types");
    return (val << 1) | (val >> (sizeof(INT)*CHAR_BIT-1));
}

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You must check if result returned by mysql_query is false.

$r = mysql_qyery("...");
if ($r) {
  mysql_fetch_assoc($r);
}

You can use @mysql_fetch_assoc($r) to avoid error displaying.