Programs & Examples On #Msbuild

Microsoft Build Engine, also known as MSBuild, is a build platform for managed code and was part of .NET Framework.

NuGet auto package restore does not work with MSBuild

It took me some time to figure out the whole picture and I'd like to share here.

Visual Studio has two approaches to use package restore: Automatic Package Restore and MSBuild-Integrated package restore. The 'MSBuild-Integrated Package Restore' restores packages DURING the building process that might cause issues in some scenarios. The 'Automatic Package Restore' is the recommended approach by the NuGet team.

There are several steps to to make 'Automatic Package Restore' work:

  1. In Visual Studio, Tools -> Extensions and Updates, Upgrade NuGet if there is a newer version (Version 2.7 or later)

  2. If you use TFS, in your solution's .nuget folder, remove the NuGet.exe and NuGet.targes files. Then edit NuGet.Config to not check in NuGet packages:

    <configuration>  
      <solution>  
        <add key="disableSourceControlIntegration" value="true" />  
      </solution>  
    </configuration> 
    

    If you checked in the solution's packages folder to TFS before, delete the folder and check in the deletion of package folder deletion.

    If you don't use TFS, delete the .nuget folder.

  3. In each project file (.csproj or .vbproj) in your solution, remove the line that references NuGet.targets file. The reference looks like this:

    <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
    

    Remove this line in every project file in your solution.

  4. In Visual Studio menu, either through

    Tools -> Options -> Package Manager -> General or Tools -> NuGet Package Manager -> Package Manager Settings

    please enable the following two options 1) 'Allow NuGet to download missing packages' 2) 'Automatically check for missing packages during build in Visual Studio'

  5. Test your package restore configuration by the following steps

    • Save your solution and close Visual Studio
    • Delete your solution's packages folder
    • Start Visual Studio, open your solution and rebuild it.

How do I fix MSB3073 error in my post-build event?

I had the same problem for my Test project. I found out why my post build event wasn't working and that's because I was copying files before running the $(ProjectName).exe command and some of these files were required for Test project itself. Hence, by just moving $(ProjectName).exe as the first command fix the issue.

Compile Views in ASP.NET MVC

You can use aspnet_compiler for this:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler -v /Virtual/Application/Path/Or/Path/In/IIS/Metabase -p C:\Path\To\Your\WebProject -f -errorstack C:\Where\To\Put\Compiled\Site

where "/Virtual/Application/Path/Or/Path/In/IIS/Metabase" is something like this: "/MyApp" or "/lm/w3svc2/1/root/"

Also there is a AspNetCompiler Task on MSDN, showing how to integrate aspnet_compiler with MSBuild:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="PrecompileWeb">
        <AspNetCompiler
            VirtualPath="/MyWebSite"
            PhysicalPath="c:\inetpub\wwwroot\MyWebSite\"
            TargetPath="c:\precompiledweb\MyWebSite\"
            Force="true"
            Debug="true"
        />
    </Target>
</Project>

NuGet behind a proxy

Maybe you could try this to your devenv.exe.config

<system.net>
    <defaultProxy useDefaultCredentials="true" enabled="true">
        <proxy proxyaddress="http://proxyaddress" />
    </defaultProxy>
    <settings>
        <servicePointManager expect100Continue="false" />
        <ipv6 enabled="true"/>
    </settings>
</system.net>

I found it from the NuGet Issue tracker

There are also other valuable comments about NuGet + network issues.

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.

Running MSBuild fails to read SDKToolsPath

I, too, encountered this problem while trying to build a plugin using Visual Studio 2017 on my horribly messed-up workplace computer. If you search the internet for "unable to find resgen.exe," you can find all this advice that's like 'just use regedit to edit your Windows Registry and make a new key here and copy-and-paste the contents of this folder into this other folder, blah blah blah.'

I spent weeks just messing up my Windows Registry with regedit, probably added a dozen sub-keys and copy-pasted ResGen.exe into many different directories, sometimes putting it in a 'bin' folder, sometimes just keeping it in the main folder, etc.

In the end, I realized, "Hey, if Visual Studio gave a more detailed error message, none of this would be a problem." So, in order to get more details on the error, I ran MSBuild.exe directly on my *.csproj file from the command line:

 "C:/Windows/Microsoft.NET/Framework/v4.0.3.0319/MSBuild.exe C:/Users/Todd/Plugin.csproj -fl -flp:logfile="C:/Users/Todd/Desktop/error_log.log";verbosity=diagnostic"

Of course, you'll have to change the path details to fit your situation, but be sure to put 1) the complete path to MSBuild.exe 2) the complete path to your *.csproj file 3) the -fl -flp:logfile= part, which will tell MSBuild to create a log file of each step it took in the process, 4) the location you would like the *.log file to be saved and 5) ;verbosity=diagnostic, which basically just tells MSBuild to include TONS of details in the *.log file.

After you do this, the build will fail as always, but you will be left with a *.log file showing exactly where MSBuild looked for your ResGen.exe file. In my case, near the bottom of the *.log file, I found:

Compiling plug-in resources (Task ID:41)
Looking in key SOFTWARE\WOW6432Node\Microsoft\Microsoft SDKs\NETFXSDK\4.6.2\WinSDK-NetFx40Tools-x86 (Task ID:41)
Looking in key SOFTWARE\WOW6432Node\Microsoft\Microsoft SDKs\NETFXSDK\4.6.1\WinSDK-NetFx40Tools-x86 (Task ID:41)
Looking in key SOFTWARE\WOW6432Node\Microsoft\Microsoft SDKs\NETFXSDK\4.6\WinSDK-NetFx40Tools-x86 (Task ID:41)
Looking in key SOFTWARE\WOW6432Node\Microsoft\Microsoft SDKs\Windows\v8.1a\WinSDK-NetFx40Tools-x86 (Task ID:41)
Looking in key SOFTWARE\WOW6432Node\Microsoft\Microsoft SDKs\Windows\v8.0a\WinSDK-NetFx40Tools-x86 (Task ID:41)
MSBUILD: error : Failed to locate ResGen.exe and unable to compile plug-in resource file "C:/Users/Todd/PluginResources.resx"

So basically, MSBuild looked in five separate directories for ResGen.exe, then gave up. This is the kind of detail you just can't get from the Visual Studio error message, and it solves the problem: simply use regedit to create a key for any one of those five locations, and put the value "InstallationFolder" in the key, which should point to the folder in which your ResGen.exe resides (in my case it was "C:\Program Files\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools").

If you're a humanities major like myself with no background in computers, you may be tempted to just edit the heck out of your Windows Registry and copy-paste ResGen.exe all over the place when faced with an error like this (which is of course, bad practice). It's better to follow the procedure outlined above: 1) Run MSBuild.exe directly on your *.csproj file to find out the exact location MSBuild is looking for ResGen.exe then 2) edit your Windows Registry precisely so that MSBuild can find ResGen.exe.

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

I only have the need to push files during a build, so I just added a Post-build Event Command Line entry like this:

Copy /Y "$(SolutionDir)Third Party\SomeLibrary\*" "$(TargetDir)"

You can set this by right-clicking your Project in the Solution Explorer, then Properties > Build Events

Path to MSBuild

There are many correct answers. However, here a One-Liner in PowerShell I use to determine the MSBuild path for the most recent version:

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\' | 
    Get-ItemProperty -Name MSBuildToolsPath | 
    Sort-Object PSChildName | 
    Select-Object -ExpandProperty MSBuildToolsPath -first 1

How do I specify the platform for MSBuild?

In Visual Studio 2019, version 16.8.4, you can just add

<Prefer32Bit>false</Prefer32Bit>

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.

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

MSBuild in an independent build tool that is frequently bundled with other tools. It may have been installed on your computer with .NET (older versions), Visual Studio (newer versions), or even Team Foundation Build.

MSBuild needs configuration files, compilers, etc (a ToolSet) that matches the version of Visual Studio or TFS that will use it, as well as the version of .NET against which source code will be compiled.

Depending on how MSBuild was installed, the configuration files may be in one or more of these paths.

  • C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\
  • C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120\
  • C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\

As described in other answers, a registry item and/or environmental variable point must to the ToolSet path.

  • The VCTargetsPath key under HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0
  • The VCTargetsPath environmental variable.

Occasionally, an operation like installing a tool will leave the registry and/or environmental variable set incorrectly. The other answers are all variations on fixing them.

The only thing I have to add is the environmental variable didn't work for me when I left off the trailing \

How do you get the current project directory from C# code when creating a custom MSBuild task?

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.FullName

Will give you the project directory.

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

In My case my web project was not loaded properly ( it was showing project unavailable ) then I had to reload my web project after opening my visual studio in admin mode then everything worked fine.

This project references NuGet package(s) that are missing on this computer

In my case it happened after I moved my solution folder from one location to another, re-organized it a bit and in the process its relative folder structure changed.

So I had to edit all entries similar to the following one in my .csproj file from

  <Import Project="..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />

to

  <Import Project="packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />

(Note the change from ..\packages\ to packages\. It might be a different relative structure in your case, but you get the idea.)

MSBUILD : error MSB1008: Only one project can be specified

In vs2012 just try to create a Build definition "Test Build" using the default TFS template "DefaultTemplate....xaml" (usually a copy of it)

It will fail with the usual self-explaining-error: "MSBUILD : error MSB1008: Only one project can be specified.Switch: Activities"

Off course somewhere in the default TFS template some " are missing so msbuild will receive as parameter a non escaped directory containing spaces so will result in multiple projects(?!)

So NEVER use spaces in you TFS Build Definition names, pretty sad and simple at the same time

How to fully clean bin and obj folders within Visual Studio?

I store my finished VS projects by saving only source code.

I delete BIN, DEBUG, RELEASE, OBJ, ARM and .vs folders from all projects.

This reduces the size of the project considerably. The project

must be rebuilt when pulled out of storage.

Using msbuild to execute a File System Publish Profile

It looks to me like your publish profile is not being used, and doing some default packaging. The Microsoft Web Publish targets do all what you are doing above, it selects the correct targets based on the config.

I got mine to work no problem from TeamCity MSBuild step, but I did specify an explicit path to the profile, you just have to call it by name with no .pubxml (e.g. FileSystemDebug). It will be found so long as in the standard folder, which yours is.

Example:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe ./ProjectRoot/MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=FileSystemDebug

Note this was done using the Visual Studio 2012 versions of the Microsoft Web Publish targets, normally located at "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web". Check out the deploy folder for the specific deployment types targets that are used

How do I run msbuild from the command line using Windows SDK 7.1?

Your bat file could be like:

CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319

msbuild C:\Users\mmaratt\Desktop\BladeTortoise\build\ALL_BUILD.vcxproj

PAUSE

EXIT

Link to all Visual Studio $ variables

While there does not appear to be one complete list, the following may also be helpful:

How to use Environment properties:
  http://msdn.microsoft.com/en-us/library/ms171459.aspx

MSBuild reserved properties:
  http://msdn.microsoft.com/en-us/library/ms164309.aspx

Well-known item properties (not sure how these are used):
  http://msdn.microsoft.com/en-us/library/ms164313.aspx

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

Getting msbuild.exe without installing Visual Studio

It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760

To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

I was having this issue building a SQL Server project on a CI/CD pipeline. In fact, I was having it locally as well, and I did not manage to solve it.

What worked for me was using an MSBuild SDK, capable of producing a SQL Server Data-Tier Application package (.dacpac) from a set of SQL scripts, which implies creating a new project. But I wanted to keep the SQL Server project, so that I could link it to the live database through SQL Server Object Explorer on Visual Studio. I took the following steps to have this up and running:

  1. Kept my SQL Server project with the .sql database scripts.
  2. Created a .NET Standard 2.0 class library project, making sure that the target framework was .NET Standard 2.0, as per the guidelines in the above link.
  3. Set the contents of the .csproj as follows:

    <?xml version="1.0" encoding="utf-8"?>
    <Project Sdk="MSBuild.Sdk.SqlProj/1.0.0">
      <PropertyGroup>
        <SqlServerVersion>Sql140</SqlServerVersion>
        <TargetFramework>netstandard2.0</TargetFramework>
      </PropertyGroup>
    </Project>
    
  4. I have chosen Sql140 as the SQL Server version because I am using SQL Server 2019. Check this answer to find out the mapping to the version you are using.

  5. Ignore the SQL Server project on build, so that it stops breaking locally (it does build on Visual Studio, but it fails on VS Code).

  6. Now we just have to make sure the .sql files are inside the SDK project when it is built. I achieved that with a simple powershell routine on the CI/CD pipeline that would copy the files from the SQL Server project to the SDK project:

Copy-Item -Path "Path.To.The.Database.Project\dbo\Tables\*" -Destination (New-item -Name "dbo\Tables" -Type Directory -Path "Path.To.The.DatabaseSDK.Project\")

PS: The files have to be physically in the SDK project, either in the root or on some folder, so links to the .sdk files in the SQL Server project won't work. In theory, it should be possible to copy these files with a pre-build condition, but for some obscure reason, this was not working for me. I tried also to have the .sql files on the SDK project and link them to the SQL Server project, but that would easily break the link with the SQL Server Object Explorer, so I decided to drop this as well.

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

Run msbuild Foo.sln /t:Rebuild /v:diag (from C:\Program Files (x86)\MSBuild\12.0\bin) to build your solution from command line and get a bit more details, then find the .csproj. that logs the warning and check its references and references of other projects that use the same common assembly that differs in version.

Edit: You can also set the build verbosity directly in VS2013. Go to Tools > Options menu then go to Projects and Solutions and set MSBuild verbosity to Diagnostic.

Edit: Few clarifications as I just got one myself. In my case warning was due to me adding a reference using Resharper prompt as opposed to the Add Reference dialog, which did it versionless even though both v4 and v12 are available to choose from.

<Reference Include="Microsoft.Build, Version=12.0.0.0, ..." />
<Reference Include="Microsoft.Build.Framework" />

vs

<Reference Include="Microsoft.Build, Version=12.0.0.0, ..." />
<Reference Include="Microsoft.Build.Framework, Version=12.0.0.0, ..." />

In the MSBuild log with /v:diag verbosity it looked like the following. giving details which two references conflicted:-

  There was a conflict between 
  "Microsoft.Build.Framework, Version=4.0.0.0, ..." and 
  "Microsoft.Build.Framework, Version=12.0.0.0, ...". (TaskId:16)

      "Microsoft.Build.Framework, Version=4.0.0.0, ..." was chosen because it was primary and 
      "Microsoft.Build.Framework, Version=12.0.0.0, ..." was not. (TaskId:16)

      References which depend on "Microsoft.Build.Framework, Version=4.0.0.0, ..." 
      [C:\...\v4.5.1\Microsoft.Build.Framework.dll]. (TaskId:16)

          C:\...\v4.5.1\Microsoft.Build.Framework.dll (TaskId:16)
            Project file item includes which caused reference "C:\...\v4.5.1\Microsoft.Build.Framework.dll". (TaskId:16)
              Microsoft.Build.Framework (TaskId:16)

      References which depend on "Microsoft.Build.Framework, Version=12.0.0.0, ..." 
      [C:\...\v12.0\Microsoft.Build.Framework.dll]. (TaskId:16)

          C:\...\v12.0\Microsoft.Build.dll (TaskId:16)
            Project file item includes which caused reference "C:\...\v12.0\Microsoft.Build.dll". (TaskId:16)
              Microsoft.Build, Version=12.0.0.0, ... (TaskId:16)

          C:\...\v12.0\Microsoft.Build.Engine.dll (TaskId:16)
            Project file item includes which caused reference "C:\...\v12.0\Microsoft.Build.Engine.dll". (TaskId:16)
              Microsoft.Build, Version=12.0.0.0, ... (TaskId:16)

C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(1697,5): warning MSB3277: 
Found conflicts between different versions of the same dependent assembly that could not be resolved.  
These reference conflicts are listed in the build log when log verbosity is set to detailed. 
[C:\Users\Ilya.Kozhevnikov\Dropbox\BuildTree\BuildTree\BuildTree.csproj]

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

I had a similar issue today, and this is most certainly not the answer to your question. But I'd like to inform everyone, and possibly provide a spark of insight.

I have a ASP.NET application. The build process is set to clean and then build.

I have two Jenkins CI scripts. One for production and one for staging. I deployed my application to staging and everything worked fine. Deployed to production and was missing a DLL file that was referenced. This DLL file was just in the root of the project. Not in any NuGet repository. The DLL was set to do not copy.

The CI script and the application was the same between the two deployments. Still after the clean and deploy in the staging environment the DLL file was replaced in the deploy location of the ASP.NET application (bin/). This was not the case for the production environment.

It turns out in a testing branch I had added a step to the build process to copy over this DLL file to the bin directory. Now the part that took a little while to figure out. The CI process was not cleaning itself. The DLL was left in the working directory and was being accidentally packaged with the ASP.NET .zip file. The production branch never had the DLL file copied in the same way and was never accidentally deploying this.

TLDR; Check and make sure you know what your build server is doing.

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

Sometimes AutoGenerateBindingRedirects isn't enough (even with GenerateBindingRedirectsOutputType). Searching for all the There was a conflict entries and fixing them manually one by one can be tedious, so I wrote a small piece of code that parses the log output and generates them for you (dumps to stdout):

// Paste all "there was a conflict" lines from the msbuild diagnostics log to the file below
const string conflictFile = @"C:\AssemblyConflicts.txt";

var sb = new StringBuilder();
var conflictLines = await File.ReadAllLinesAsync(conflictFile);
foreach (var line in conflictLines.Where(l => !String.IsNullOrWhiteSpace(l)))
{
    Console.WriteLine("Processing line: {0}", line);

    var lineComponents = line.Split('"');
    if (lineComponents.Length < 2) 
        throw new FormatException("Unexpected conflict line component count");

    var assemblySegment = lineComponents[1];
    Console.WriteLine("Processing assembly segment: {0}", assemblySegment);
    var assemblyComponents = assemblySegment
                              .Split(",")
                              .Select(kv => kv.Trim())
                              .Select(kv => kv.Split("=")
                              .Last())
                              .ToArray();

    if (assemblyComponents.Length != 4) 
        throw new FormatException("Unexpected conflict segment component count");

    var assembly = assemblyComponents[0];
    var version = assemblyComponents[1];
    var culture = assemblyComponents[2];
    var publicKeyToken = assemblyComponents[3];

    Console.WriteLine("Generating assebmly redirect for Assembly={0}, Version={1}, Culture={2}, PublicKeyToken={3}", assembly, version, culture, publicKeyToken);
    sb.AppendLine($"<dependentAssembly><assemblyIdentity name=\"{assembly}\" publicKeyToken=\"{publicKeyToken}\" culture=\"{culture}\" /><bindingRedirect oldVersion=\"0.0.0.0-{version}\" newVersion=\"{version}\" /></dependentAssembly>");
}

Console.WriteLine("Generated assembly redirects:");
Console.WriteLine(sb);

Tip: use MSBuild Binary and Structured Log Viewer and only generate binding redirects for the conflicts in the project that emits the warning (that is, only past those there was a conflict lines to the input text file for the code above [AssemblyConflicts.txt]).

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

The projects you are trying to open are in the new .NET Core csproj format. This means you need to use Visual Studio 2017 which supports this new format.

For a little bit of history, initially .NET Core used project.json instead of *.csproj. However, after some considerable internal deliberation at Microsoft, they decided to go back to csproj but with a much cleaner and updated format. However, this new format is only supported in VS2017.

If you want to open the projects but don't want to wait until March 7th for the official VS2017 release, you could use Visual Studio Code instead.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

I am assuming one might also do this with a text template where you create the assembly attributes in question on the fly from the environment like AssemblyVersion.tt does below.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#
var build = Environment.GetEnvironmentVariable("BUILD_NUMBER");
build = build == null ? "0" : int.Parse(build).ToString();
var revision = Environment.GetEnvironmentVariable("SVN_REVISION");
revision = revision == null ? "0" : int.Parse(revision).ToString();    
#>
using System.Reflection;
[assembly: AssemblyVersion("1.0.<#=build#>.<#=revision#>")]
[assembly: AssemblyFileVersion("1.0.<#=build#>.<#=revision#>")]

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

If you use make generators like cmake, JUCE, etc. try to set a correct VS version target (2013, 2015, 2017) and regenerate the solution again.

How to Publish Web with msbuild?

You can Publish the Solution with desired path by below code, Here PublishInDFolder is the name that has the path where we need to publish(we need to create this in below pic)

You can create publish file like this

Add below 2 lines of code in batch file(.bat)

@echo OFF 
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsMSBuildCmd.bat"
MSBuild.exe  D:\\Solution\\DataLink.sln /p:DeployOnBuild=true /p:PublishProfile=PublishInDFolder
pause

Creating temporary files in bash

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of 'Xs' appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing 'Xs' are replaced with a combination of the current process number and random letters.

For more details: man mktemp

Check if array is empty or null

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

  1. $(this) is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).length if you need to, but that is not necessary here because the .each() loop wouldn't run if there were no items so $(this) inside your .each() loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with [] rather than new Array().
  4. if (value) when value is expected to be a string will both protect from value == null, value == undefined and value == "" so you don't have to do if (value && (value != "")). You can just do: if (value) to check for all three empty conditions.
  5. if (album_text.length === 0) will tell you if the array is empty as long as it is a valid, initialized array (which it is here).

What are you trying to do with this selector $("input[name='album_text[]']")?

Where to find htdocs in XAMPP Mac

Simple as ...

From the UI

  • Click Go->Go to Folder then /Applications/XAMPP/htdocs

From Terminal

cd /Applications/XAMPP/htdocs

How do I set headers using python's urllib?

adding HTTP headers using urllib2:

from the docs:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

XmlSerializer giving FileNotFoundException at constructor

In Visual Studio project properties ("Build" page, if I recall it right) there is an option saying "generate serialization assembly". Try turning it on for a project that generates [Containing Assembly of MyType].

Push local Git repo to new remote including all branches and tags

Below command will push all the branches(including the ones which you have never checked-out but present in your git repo, you can see them by git branch -a)

git push origin '*:*'

NOTE: This command comes handy when you are migrating version control service(i.e migrating from Gitlab to GitHub)

Access Controller method from another controller in Laravel 5

Calling a Controller from another Controller is not recommended, however if for any reason you have to do it, you can do this:

Laravel 5 compatible method

return \App::call('bla\bla\ControllerName@functionName');

Note: this will not update the URL of the page.

It's better to call the Route instead and let it call the controller.

return \Redirect::route('route-name-here');

Clean out Eclipse workspace metadata

One of the things that you might want to try out is starting eclipse with the -clean option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.

However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.

See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.

Free XML Formatting tool

Notepad++ dit it well only if you're in ANSI. If you do it in something like "ANSI AS UTF8", tidy dirty the doc :/.

Applications are expected to have a root view controller at the end of application launch

for ARC change:

change to

@synthesize window;

instead of

@synthesize window=_window;

Tooltips with Twitter Bootstrap

Simply mark all the data-toggles...

jQuery(function () {
    jQuery('[data-toggle=tooltip]').tooltip();
});

http://jsfiddle.net/Amged/xUQ6D/19/

Replace or delete certain characters from filenames of all files in a folder

This batch file can help, but it has some limitations. The filename characters = and % cannot be replaced (going from memory here) and an ^ in the filenames might be a problem too.

In this portion %newname: =_% on every line in the lower block it replaces the character after : with the character after = so as it stands the bunch of characters are going to be replaced with an underscore.

Remove the echo to activate the ren command as it will merely print the commands to the console window until you do.

It will only process the current folder, unless you add /s to the DIR command portion and then it will process all folders under the current one too.

To delete a certain character, remove the character from after the = sign. In %newname:z=% an entry like this would remove all z characters (case insensitive).

@echo off
for /f "delims=" %%a in ('dir /a:-d /o:n /b') do call :next "%%a"
pause
GOTO:EOF
:next
set "newname=%~nx1"

set "newname=%newname: =_%"
set "newname=%newname:)=_%"
set "newname=%newname:(=_%"
set "newname=%newname:&=_%"
set "newname=%newname:^=_%"
set "newname=%newname:$=_%"
set "newname=%newname:#=_%"
set "newname=%newname:@=_%"
set "newname=%newname:!=_%"
set "newname=%newname:-=_%"
set "newname=%newname:+=_%"
set "newname=%newname:}=_%"
set "newname=%newname:{=_%"
set "newname=%newname:]=_%"
set "newname=%newname:[=_%"
set "newname=%newname:;=_%"
set "newname=%newname:'=_%"
set "newname=%newname:`=_%"
set "newname=%newname:,=_%"

echo ren %1 "%newname%

Execute Stored Procedure from a Function

Here is another possible workaround:

if exists (select * from master..sysservers where srvname = 'loopback')
    exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = @@servername
go

create function testit()
    returns int
as
begin
    declare @res int;
    select @res=count(*) from openquery(loopback, 'exec sp_who');
    return @res
end
go

select dbo.testit()

It's not so scary as xp_cmdshell but also has too many implications for practical use.

How to set connection timeout with OkHttp

This worked for me:

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .retryOnConnectionFailure(false) <-- not necessary but useful!
    .build();

Source: https://github.com/square/okhttp/issues/3553

write newline into a file

To write text (rather than raw bytes) to a file you should consider using FileWriter. You should also wrap it in a BufferedWriter which will then give you the newLine method.

To write each word on a new line, use String.split to break your text into an array of words.

So here's a simple test of your requirement:

public static void main(String[] args) throws Exception {
    String nodeValue = "i am mostafa";

    // you want to output to file
    // BufferedWriter writer = new BufferedWriter(new FileWriter(file3, true));
    // but let's print to console while debugging
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    String[] words = nodeValue.split(" ");
    for (String word: words) {
        writer.write(word);
        writer.newLine();
    }
    writer.close();
}

The output is:

i
am
mostafa

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Create HTML table using Javascript

This beautiful code here creates a table with each td having array values. Not my code, but it helped me!

var rows = 6, cols = 7;

for(var i = 0; i < rows; i++) {
  $('table').append('<tr></tr>');
  for(var j = 0; j < cols; j++) {
    $('table').find('tr').eq(i).append('<td></td>');
    $('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
  }
}

Running AngularJS initialization code when view is loaded

Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:

function MyCtrl($scope) {
    $scope.isSaving = false;

    (function() {  // init
        if (true) { // $routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
    })()

    $scope.isClean = function () {
       return $scope.hasChanges() && !$scope.isSaving;
    }

    $scope.hasChanges = function() { return false }
}

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

Replace console output in Python

A more elegant solution could be:

def progressBar(current, total, barLength = 20):
    percent = float(current) * 100 / total
    arrow   = '-' * int(percent/100 * barLength - 1) + '>'
    spaces  = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')

call this function with value and endvalue, result should be

Progress: [------------->      ] 69 %

Note: Python 2.x version here.

Deleting all files from a folder using PHP?

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

Byte and char conversion in Java

new String(byteArray, Charset.defaultCharset())

This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.

PHP - check if variable is undefined

You can use -

$isTouch = isset($variable);

It will return true if the $variable is defined. if the variable is not defined it will return false.

Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

If you want to check for false, 0 etc You can then use empty() -

$isTouch = empty($variable);

empty() works for -

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

HTML5 Form Input Pattern Currency Format

Use this pattern "^\d*(\.\d{2}$)?"

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

Also you can use LINQ. For example for clear Textbox text do something like:

this.Controls.OfType<TextBox>().ToList().ForEach(t => t.Text = string.Empty);

Clearing UIWebview cache

For swift 2.0:

let cacheSizeMemory = 4*1024*1024; // 4MB
let cacheSizeDisk = 32*1024*1024; // 32MB
let sharedCache = NSURLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "nsurlcache")
NSURLCache.setSharedURLCache(sharedCache)

nodejs - first argument must be a string or Buffer - when using response.write with http.request

The first argument must be one of type string or Buffer. Received type object

 at write_

I was getting like the above error while I passing body data to the request module.

I have passed another parameter that is JSON: true and its working.

var option={
url:"https://myfirstwebsite/v1/appdata",
json:true,
body:{name:'xyz',age:30},
headers://my credential
}
rp(option)
.then((res)=>{
res.send({response:res});})
.catch((error)=>{
res.send({response:error});})

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

In my case, getter and setter dependencies were coming through lombok plugin (Using java with Spring). And in the new installation of intellij idea, I had not installed the lombok plugin. Installing the lombok plugin fixed it for me.

Updating records codeigniter

In codeigniter doc if you update specific field just do this

$data = array(
    'yourfieldname' => value,
    'name' => $name,
    'date' => $date
);

$this->db->where('yourfieldname', yourfieldvalue);
$this->db->update('yourtablename', $data);

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

Can I use conditional statements with EJS templates (in JMVC)?

Conditionals work if they're structured correctly, I ran into this issue and figured it out.

For conditionals, the tag before else has to be paired with the end tag of the previous if otherwise the statements will evaluate separately and produce an error.

ERROR!

<% if(true){ %>
   <h1>foo</h1>
<% } %>
<% else{ %>
   <h1>bar</h1>
 <% } %>

Correct

<% if(true){ %>
   <h1>foo</h1>
 <% } else{ %>  
   <h1>bar</h1>
<% } %>

hope this helped.

use std::fill to populate vector with increasing numbers

I created a simple templated function, Sequence(), for generating sequences of numbers. The functionality follows the seq() function in R (link). The nice thing about this function is that it works for generating a variety of number sequences and types.

#include <iostream>
#include <vector>

template <typename T>
std::vector<T> Sequence(T min, T max, T by) {
  size_t n_elements = ((max - min) / by) + 1;
  std::vector<T> vec(n_elements);
  min -= by;
  for (size_t i = 0; i < vec.size(); ++i) {
    min += by;
    vec[i] = min;
  }
  return vec;
}

Example usage:

int main()
{
    auto vec = Sequence(0., 10., 0.5);
    for(auto &v : vec) {
        std::cout << v << std::endl;
    }
}

The only caveat is that all of the numbers should be of the same inferred type. In other words, for doubles or floats, include decimals for all of the inputs, as shown.

Updated: June 14, 2018

Reading file from Workspace in Jenkins with Groovy script

Based on your comments, you would be better off with Text-finder plugin.

It allows to search file(s), as well as console, for a regular expression and then set the build either unstable or failed if found.

As for the Groovy, you can use the following to access ${WORKSPACE} environment variable:
def workspace = manager.build.getEnvVars()["WORKSPACE"]

is the + operator less performant than StringBuffer.append()

As far I know, every concatenation implies a memory reallocation. So the problem is not the operator used to do it, the solution is to reduce the number of concatenations. For example do the concatenations outside of the iteration structures when you can.

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How do I revert a Git repository to a previous commit?

Revert is the command to rollback the commits.

git revert <commit1> <commit2> 

Sample:

git revert 2h3h23233

It is capable of taking range from the HEAD like below. Here 1 says "revert last commit."

git revert HEAD~1..HEAD

and then do git push

How to reset all checkboxes using jQuery or pure JS?

The above answer did not work for me -

The following worked

$('input[type=checkbox]').each(function() 
{ 
        this.checked = false; 
}); 

This makes sure all the checkboxes are unchecked.

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

pdftk compression option

Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook setting for gs. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.

pdftk compress:

no change in size
bookmarks TOC are gone

gs screen:

takes a ridiculously long time and 100% CPU
errors:
    sfopen: gs_parse_file_name failed.                                 ? 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone

gs printer:

takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone

gs ebook:

errors:
    sfopen: gs_parse_file_name failed.
      ./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic 
    | ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone

qpdf --linearize:

very fast, a few seconds
no size change
bookmarks TOC are gone

pdf2ps:

took very long time
output_pdf2ps.ps 74.8MB-->331.6MB

ps2pdf:

pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone

socket.shutdown vs socket.close

Here's one explanation:

Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.

Downcasting in Java

Downcasting is allowed when there is a possibility that it succeeds at run time:

Object o = getSomeObject(),
String s = (String) o; // this is allowed because o could reference a String

In some cases this will not succeed:

Object o = new Object();
String s = (String) o; // this will fail at runtime, because o doesn't reference a String

When a cast (such as this last one) fails at runtime a ClassCastException will be thrown.

In other cases it will work:

Object o = "a String";
String s = (String) o; // this will work, since o references a String

Note that some casts will be disallowed at compile time, because they will never succeed at all:

Integer i = getSomeInteger();
String s = (String) i; // the compiler will not allow this, since i can never reference a String.

Access images inside public folder in laravel

Just use public_path() it will find public folder and address it itself.

<img src=public_path().'/images/imagename.jpg' >

How to have an auto incrementing version number (Visual Studio)?

If you add an AssemblyInfo class to your project and amend the AssemblyVersion attribute to end with an asterisk, for example:

[assembly: AssemblyVersion("2.10.*")]

Visual studio will increment the final number for you according to these rules (thanks galets, I had that completely wrong!)

To reference this version in code, so you can display it to the user, you use reflection. For example,

Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
DateTime buildDate = new DateTime(2000, 1, 1)
                        .AddDays(version.Build).AddSeconds(version.Revision * 2);
string displayableVersion = $"{version} ({buildDate})";

Three important gotchas that you should know

From @ashes999:

It's also worth noting that if both AssemblyVersion and AssemblyFileVersion are specified, you won't see this on your .exe.

From @BrainSlugs83:

Setting only the 4th number to be * can be bad, as the version won't always increment. The 3rd number is the number of days since the year 2000, and the 4th number is the number of seconds since midnight (divided by 2) [IT IS NOT RANDOM]. So if you built the solution late in a day one day, and early in a day the next day, the later build would have an earlier version number. I recommend always using X.Y.* instead of X.Y.Z.* because your version number will ALWAYS increase this way.

Newer versions of Visual Studio give this error:

(this thread begun in 2009)

The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation.

See this SO answer which explains how to remove determinism (https://stackoverflow.com/a/58101474/1555612)

Prevent wrapping of span or div

As mentioned you can use:

overflow: scroll;

If you only want the scroll bar to appear when necessary, you can use the "auto" option:

overflow: auto;

I don't think you should be using the "float" property with "overflow", but I'd have to try out your example first.

Drop a temporary table if it exists

From SQL Server 2016 you can just use

 DROP TABLE IF EXISTS ##CLIENTS_KEYWORD

On previous versions you can use

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
   client_id INT
)

You could also consider truncating the table instead rather than dropping and recreating.

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
  TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
  CREATE TABLE ##CLIENTS_KEYWORD
  (
     client_id INT
  ) 

Detect browser or tab closing

I needed to automatically log the user out when the browser or tab closes, but not when the user navigates to other links. I also did not want a confirmation prompt shown when that happens. After struggling with this for a while, especially with IE and Edge, here's what I ended doing (checked working with IE 11, Edge, Chrome, and Firefox) after basing off the approach by this answer.

First, start a countdown timer on the server in the beforeunload event handler in JS. The ajax calls need to be synchronous for IE and Edge to work properly. You also need to use return; to prevent the confirmation dialog from showing like this:

    window.addEventListener("beforeunload", function (e) {        
      $.ajax({
          type: "POST",
          url: startTimerUrl,
          async: false           
      });
      return;
    });

Starting the timer sets the cancelLogout flag to false. If the user refreshes the page or navigates to another internal link, the cancelLogout flag on the server is set to true. Once the timer event elapses, it checks the cancelLogout flag to see if the logout event has been cancelled. If the timer has been cancelled, then it would stop the timer. If the browser or tab was closed, then the cancelLogout flag would remain false and the event handler would log the user out.

Implementation note: I'm using ASP.NET MVC 5 and I'm cancelling logout in an overridden Controller.OnActionExecuted() method.

Validate phone number using angular js

Use ng-pattern, in this example you can validate a simple patern with 10 numbers, when the patern is not matched ,the message is show and the button is disabled.

 <form  name="phoneNumber">

        <label for="numCell" class="text-strong">Phone number</label>

        <input id="numCell" type="text" name="inputCelular"  ng-model="phoneNumber" 
            class="form-control" required  ng-pattern="/^[0-9]{10,10}$/"></input>
        <div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
            <p> write a phone number</p>
        </div>

    <button id="button"  class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>

Also you can use another complex patern like

^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$

, for more complex phone numbers

javac is not recognized as an internal or external command, operable program or batch file

TL;DR

For experienced readers:

  1. Find the Java path; it looks like this: C:\Program Files\Java\jdkxxxx\bin\
  2. Start-menu search for "environment variable" to open the options dialog.
  3. Examine PATH. Remove old Java paths.
  4. Add the new Java path to PATH.
  5. Edit JAVA_HOME.
  6. Close and re-open console/IDE.

Welcome!

You have encountered one of the most notorious technical issues facing Java beginners: the 'xyz' is not recognized as an internal or external command... error message.

In a nutshell, you have not installed Java correctly. Finalizing the installation of Java on Windows requires some manual steps. You must always perform these steps after installing Java, including after upgrading the JDK.

Environment variables and PATH

(If you already understand this, feel free to skip the next three sections.)

When you run javac HelloWorld.java, cmd must determine where javac.exe is located. This is accomplished with PATH, an environment variable.

An environment variable is a special key-value pair (e.g. windir=C:\WINDOWS). Most came with the operating system, and some are required for proper system functioning. A list of them is passed to every program (including cmd) when it starts. On Windows, there are two types: user environment variables and system environment variables.

You can see your environment variables like this:

C:\>set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\craig\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
...

The most important variable is PATH. It is a list of paths, separated by ;. When a command is entered into cmd, each directory in the list will be scanned for a matching executable.

On my computer, PATH is:

C:\>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPower
Shell\v1.0\;C:\ProgramData\Microsoft\Windows\Start Menu\Programs;C:\Users\craig\AppData\
Roaming\Microsoft\Windows\Start Menu\Programs;C:\msys64\usr\bin;C:\msys64\mingw64\bin;C:\
msys64\mingw32\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\Yarn\bin\;C:\Users\
craig\AppData\Local\Yarn\bin;C:\Program Files\Java\jdk-10.0.2\bin;C:\ProgramFiles\Git\cmd;
C:\Program Files\Oracle\VirtualBox;C:\Program Files\7-Zip\;C:\Program Files\PuTTY\;C:\
Program Files\launch4j;C:\Program Files (x86)\NSIS\Bin;C:\Program Files (x86)\Common Files
\Adobe\AGL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program
Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\iCLS Client\;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
(x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\iCLS
Client\;C:\Users\craig\AppData\Local\Microsoft\WindowsApps

When you run javac HelloWorld.java, cmd, upon realizing that javac is not an internal command, searches the system PATH followed by the user PATH. It mechanically enters every directory in the list, and checks if javac.com, javac.exe, javac.bat, etc. is present. When it finds javac, it runs it. When it does not, it prints 'javac' is not recognized as an internal or external command, operable program or batch file.

You must add the Java executables directory to PATH.

JDK vs. JRE

(If you already understand this, feel free to skip this section.)

When downloading Java, you are offered a choice between:

  • The Java Runtime Environment (JRE), which includes the necessary tools to run Java programs, but not to compile new ones – it contains java but not javac.
  • The Java Development Kit (JDK), which contains both java and javac, along with a host of other development tools. The JDK is a superset of the JRE.

You must make sure you have installed the JDK. If you have only installed the JRE, you cannot execute javac because you do not have an installation of the Java compiler on your hard drive. Check your Windows programs list, and make sure the Java package's name includes the words "Development Kit" in it.

Don't use set

(If you weren't planning to anyway, feel free to skip this section.)

Several other answers recommend executing some variation of:

C:\>:: DON'T DO THIS
C:\>set PATH=C:\Program Files\Java\jdk1.7.0_09\bin

Do not do that. There are several major problems with that command:

  1. This command erases everything else from PATH and replaces it with the Java path. After executing this command, you might find various other commands not working.
  2. Your Java path is probably not C:\Program Files\Java\jdk1.7.0_09\bin – you almost definitely have a newer version of the JDK, which would have a different path.
  3. The new PATH only applies to the current cmd session. You will have to reenter the set command every time you open Command Prompt.

Points #1 and #2 can be solved with this slightly better version:

C:\>:: DON'T DO THIS EITHER
C:\>set PATH=C:\Program Files\Java\<enter the correct Java folder here>\bin;%PATH%

But it is just a bad idea in general.

Find the Java path

The right way begins with finding where you have installed Java. This depends on how you have installed Java.

Exe installer

You have installed Java by running a setup program. Oracle's installer places versions of Java under C:\Program Files\Java\ (or C:\Program Files (x86)\Java\). With File Explorer or Command Prompt, navigate to that directory.

Each subfolder represents a version of Java. If there is only one, you have found it. Otherwise, choose the one that looks like the newer version. Make sure the folder name begins with jdk (as opposed to jre). Enter the directory.

Then enter the bin directory of that.

You are now in the correct directory. Copy the path. If in File Explorer, click the address bar. If in Command Prompt, copy the prompt.

The resulting Java path should be in the form of (without quotes):

C:\Program Files\Java\jdkxxxx\bin\

Zip file

You have downloaded a .zip containing the JDK. Extract it to some random place where it won't get in your way; C:\Java\ is an acceptable choice.

Then locate the bin folder somewhere within it.

You are now in the correct directory. Copy its path. This is the Java path.

Remember to never move the folder, as that would invalidate the path.

Open the settings dialog

That is the dialog to edit PATH. There are numerous ways to get to that dialog, depending on your Windows version, UI settings, and how messed up your system configuration is.

Try some of these:

  • Start Menu/taskbar search box » search for "environment variable"
  • Win + R » control sysdm.cpl,,3
  • Win + R » SystemPropertiesAdvanced.exe » Environment Variables
  • File Explorer » type into address bar Control Panel\System and Security\System » Advanced System Settings (far left, in sidebar) » Environment Variables
  • Desktop » right-click This PC » Properties » Advanced System Settings » Environment Variables
  • Start Menu » right-click Computer » Properties » Advanced System Settings » Environment Variables
  • Control Panel (icon mode) » System » Advanced System Settings » Environment Variables
  • Control Panel (category mode) » System and Security » System » Advanced System Settings » Environment Variables
  • Desktop » right-click My Computer » Advanced » Environment Variables
  • Control Panel » System » Advanced » Environment Variables

Any of these should take you to the right settings dialog.

If you are on Windows 10, Microsoft has blessed you with a fancy new UI to edit PATH. Otherwise, you will see PATH in its full semicolon-encrusted glory, squeezed into a single-line textbox. Do your best to make the necessary edits without breaking your system.

Clean PATH

Look at PATH. You almost definitely have two PATH variables (because of user vs. system environment variables). You need to look at both of them.

Check for other Java paths and remove them. Their existence can cause all sorts of conflicts. (For instance, if you have JRE 8 and JDK 11 in PATH, in that order, then javac will invoke the Java 11 compiler, which will create version 55 .class files, but java will invoke the Java 8 JVM, which only supports up to version 52, and you will experience unsupported version errors and not be able to compile and run any programs.) Sidestep these problems by making sure you only have one Java path in PATH. And while you're at it, you may as well uninstall old Java versions, too. And remember that you don't need to have both a JDK and a JRE.

If you have C:\ProgramData\Oracle\Java\javapath, remove that as well. Oracle intended to solve the problem of Java paths breaking after upgrades by creating a symbolic link that would always point to the latest Java installation. Unfortunately, it often ends up pointing to the wrong location or simply not working. It is better to remove this entry and manually manage the Java path.

Now is also a good opportunity to perform general housekeeping on PATH. If you have paths relating to software no longer installed on your PC, you can remove them. You can also shuffle the order of paths around (if you care about things like that).

Add to PATH

Now take the Java path you found three steps ago, and place it in the system PATH.

It shouldn't matter where in the list your new path goes; placing it at the end is a fine choice.

If you are using the pre-Windows 10 UI, make sure you have placed the semicolons correctly. There should be exactly one separating every path in the list.

There really isn't much else to say here. Simply add the path to PATH and click OK.

Set JAVA_HOME

While you're at it, you may as well set JAVA_HOME as well. This is another environment variable that should also contain the Java path. Many Java and non-Java programs, including the popular Java build systems Maven and Gradle, will throw errors if it is not correctly set.

If JAVA_HOME does not exist, create it as a new system environment variable. Set it to the path of the Java directory without the bin/ directory, i.e. C:\Program Files\Java\jdkxxxx\.

Remember to edit JAVA_HOME after upgrading Java, too.

Close and re-open Command Prompt

Though you have modified PATH, all running programs, including cmd, only see the old PATH. This is because the list of all environment variables is only copied into a program when it begins executing; thereafter, it only consults the cached copy.

There is no good way to refresh cmd's environment variables, so simply close Command Prompt and open it again. If you are using an IDE, close and re-open it too.

See also

How can I make Bootstrap columns all the same height?

Just checking through bootstrap documentation and I found the simple solution for the problem of column same height.

Add the extra clearfix for only the required viewport

<div class="clearfix visible-xs-block"></div>

For example:

<div class="col-md-3 col-xs-6">This is a long text</div>
<div class="col-md-3 col-xs-6">This is short</div>
<div class="clearfix visible-xs-block">This is a long text</div>
<div class="col-md-3 col-xs-6">Short</div>
<div class="col-md-3 col-xs-6">Long Text</div>
<div class="clearfix visible-xs-block"></div>
<div class="col-md-3 col-xs-6">Longer text which will push down</div>
<div class="col-md-3 col-xs-6">Short</div>

Please refer to http://getbootstrap.com/css/#grid-responsive-resets

How do I stretch a background image to cover the entire HTML element?

To expand on @PhiLho answer, you can center a very large image (or any size image) on a page with:

{ 
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center; 
}

Or you could use a smaller image with a background color that matches the background of the image (if it is a solid color). This may or may not suit your purposes.

{ 
background-color: green;
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center; 
}

Simplest way to detect a pinch

Unfortunately, detecting pinch gestures across browsers is a not as simple as one would hope, but HammerJS makes it a lot easier!

Check out the Pinch Zoom and Pan with HammerJS demo. This example has been tested on Android, iOS and Windows Phone.

You can find the source code at Pinch Zoom and Pan with HammerJS.

For your convenience, here is the source code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport"_x000D_
        content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">_x000D_
  <title>Pinch Zoom</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div>_x000D_
_x000D_
    <div style="height:150px;background-color:#eeeeee">_x000D_
      Ignore this area. Space is needed to test on the iPhone simulator as pinch simulation on the_x000D_
      iPhone simulator requires the target to be near the middle of the screen and we only respect_x000D_
      touch events in the image area. This space is not needed in production._x000D_
    </div>_x000D_
_x000D_
    <style>_x000D_
_x000D_
      .pinch-zoom-container {_x000D_
        overflow: hidden;_x000D_
        height: 300px;_x000D_
      }_x000D_
_x000D_
      .pinch-zoom-image {_x000D_
        width: 100%;_x000D_
      }_x000D_
_x000D_
    </style>_x000D_
_x000D_
    <script src="https://hammerjs.github.io/dist/hammer.js"></script>_x000D_
_x000D_
    <script>_x000D_
_x000D_
      var MIN_SCALE = 1; // 1=scaling when first loaded_x000D_
      var MAX_SCALE = 64;_x000D_
_x000D_
      // HammerJS fires "pinch" and "pan" events that are cumulative in nature and not_x000D_
      // deltas. Therefore, we need to store the "last" values of scale, x and y so that we can_x000D_
      // adjust the UI accordingly. It isn't until the "pinchend" and "panend" events are received_x000D_
      // that we can set the "last" values._x000D_
_x000D_
      // Our "raw" coordinates are not scaled. This allows us to only have to modify our stored_x000D_
      // coordinates when the UI is updated. It also simplifies our calculations as these_x000D_
      // coordinates are without respect to the current scale._x000D_
_x000D_
      var imgWidth = null;_x000D_
      var imgHeight = null;_x000D_
      var viewportWidth = null;_x000D_
      var viewportHeight = null;_x000D_
      var scale = null;_x000D_
      var lastScale = null;_x000D_
      var container = null;_x000D_
      var img = null;_x000D_
      var x = 0;_x000D_
      var lastX = 0;_x000D_
      var y = 0;_x000D_
      var lastY = 0;_x000D_
      var pinchCenter = null;_x000D_
_x000D_
      // We need to disable the following event handlers so that the browser doesn't try to_x000D_
      // automatically handle our image drag gestures._x000D_
      var disableImgEventHandlers = function () {_x000D_
        var events = ['onclick', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',_x000D_
                      'onmouseup', 'ondblclick', 'onfocus', 'onblur'];_x000D_
_x000D_
        events.forEach(function (event) {_x000D_
          img[event] = function () {_x000D_
            return false;_x000D_
          };_x000D_
        });_x000D_
      };_x000D_
_x000D_
      // Traverse the DOM to calculate the absolute position of an element_x000D_
      var absolutePosition = function (el) {_x000D_
        var x = 0,_x000D_
          y = 0;_x000D_
_x000D_
        while (el !== null) {_x000D_
          x += el.offsetLeft;_x000D_
          y += el.offsetTop;_x000D_
          el = el.offsetParent;_x000D_
        }_x000D_
_x000D_
        return { x: x, y: y };_x000D_
      };_x000D_
_x000D_
      var restrictScale = function (scale) {_x000D_
        if (scale < MIN_SCALE) {_x000D_
          scale = MIN_SCALE;_x000D_
        } else if (scale > MAX_SCALE) {_x000D_
          scale = MAX_SCALE;_x000D_
        }_x000D_
        return scale;_x000D_
      };_x000D_
_x000D_
      var restrictRawPos = function (pos, viewportDim, imgDim) {_x000D_
        if (pos < viewportDim/scale - imgDim) { // too far left/up?_x000D_
          pos = viewportDim/scale - imgDim;_x000D_
        } else if (pos > 0) { // too far right/down?_x000D_
          pos = 0;_x000D_
        }_x000D_
        return pos;_x000D_
      };_x000D_
_x000D_
      var updateLastPos = function (deltaX, deltaY) {_x000D_
        lastX = x;_x000D_
        lastY = y;_x000D_
      };_x000D_
_x000D_
      var translate = function (deltaX, deltaY) {_x000D_
        // We restrict to the min of the viewport width/height or current width/height as the_x000D_
        // current width/height may be smaller than the viewport width/height_x000D_
_x000D_
        var newX = restrictRawPos(lastX + deltaX/scale,_x000D_
                                  Math.min(viewportWidth, curWidth), imgWidth);_x000D_
        x = newX;_x000D_
        img.style.marginLeft = Math.ceil(newX*scale) + 'px';_x000D_
_x000D_
        var newY = restrictRawPos(lastY + deltaY/scale,_x000D_
                                  Math.min(viewportHeight, curHeight), imgHeight);_x000D_
        y = newY;_x000D_
        img.style.marginTop = Math.ceil(newY*scale) + 'px';_x000D_
      };_x000D_
_x000D_
      var zoom = function (scaleBy) {_x000D_
        scale = restrictScale(lastScale*scaleBy);_x000D_
_x000D_
        curWidth = imgWidth*scale;_x000D_
        curHeight = imgHeight*scale;_x000D_
_x000D_
        img.style.width = Math.ceil(curWidth) + 'px';_x000D_
        img.style.height = Math.ceil(curHeight) + 'px';_x000D_
_x000D_
        // Adjust margins to make sure that we aren't out of bounds_x000D_
        translate(0, 0);_x000D_
      };_x000D_
_x000D_
      var rawCenter = function (e) {_x000D_
        var pos = absolutePosition(container);_x000D_
_x000D_
        // We need to account for the scroll position_x000D_
        var scrollLeft = window.pageXOffset ? window.pageXOffset : document.body.scrollLeft;_x000D_
        var scrollTop = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;_x000D_
_x000D_
        var zoomX = -x + (e.center.x - pos.x + scrollLeft)/scale;_x000D_
        var zoomY = -y + (e.center.y - pos.y + scrollTop)/scale;_x000D_
_x000D_
        return { x: zoomX, y: zoomY };_x000D_
      };_x000D_
_x000D_
      var updateLastScale = function () {_x000D_
        lastScale = scale;_x000D_
      };_x000D_
_x000D_
      var zoomAround = function (scaleBy, rawZoomX, rawZoomY, doNotUpdateLast) {_x000D_
        // Zoom_x000D_
        zoom(scaleBy);_x000D_
_x000D_
        // New raw center of viewport_x000D_
        var rawCenterX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
        var rawCenterY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
        // Delta_x000D_
        var deltaX = (rawCenterX - rawZoomX)*scale;_x000D_
        var deltaY = (rawCenterY - rawZoomY)*scale;_x000D_
_x000D_
        // Translate back to zoom center_x000D_
        translate(deltaX, deltaY);_x000D_
_x000D_
        if (!doNotUpdateLast) {_x000D_
          updateLastScale();_x000D_
          updateLastPos();_x000D_
        }_x000D_
      };_x000D_
_x000D_
      var zoomCenter = function (scaleBy) {_x000D_
        // Center of viewport_x000D_
        var zoomX = -x + Math.min(viewportWidth, curWidth)/2/scale;_x000D_
        var zoomY = -y + Math.min(viewportHeight, curHeight)/2/scale;_x000D_
_x000D_
        zoomAround(scaleBy, zoomX, zoomY);_x000D_
      };_x000D_
_x000D_
      var zoomIn = function () {_x000D_
        zoomCenter(2);_x000D_
      };_x000D_
_x000D_
      var zoomOut = function () {_x000D_
        zoomCenter(1/2);_x000D_
      };_x000D_
_x000D_
      var onLoad = function () {_x000D_
_x000D_
        img = document.getElementById('pinch-zoom-image-id');_x000D_
        container = img.parentElement;_x000D_
_x000D_
        disableImgEventHandlers();_x000D_
_x000D_
        imgWidth = img.width;_x000D_
        imgHeight = img.height;_x000D_
        viewportWidth = img.offsetWidth;_x000D_
        scale = viewportWidth/imgWidth;_x000D_
        lastScale = scale;_x000D_
        viewportHeight = img.parentElement.offsetHeight;_x000D_
        curWidth = imgWidth*scale;_x000D_
        curHeight = imgHeight*scale;_x000D_
_x000D_
        var hammer = new Hammer(container, {_x000D_
          domEvents: true_x000D_
        });_x000D_
_x000D_
        hammer.get('pinch').set({_x000D_
          enable: true_x000D_
        });_x000D_
_x000D_
        hammer.on('pan', function (e) {_x000D_
          translate(e.deltaX, e.deltaY);_x000D_
        });_x000D_
_x000D_
        hammer.on('panend', function (e) {_x000D_
          updateLastPos();_x000D_
        });_x000D_
_x000D_
        hammer.on('pinch', function (e) {_x000D_
_x000D_
          // We only calculate the pinch center on the first pinch event as we want the center to_x000D_
          // stay consistent during the entire pinch_x000D_
          if (pinchCenter === null) {_x000D_
            pinchCenter = rawCenter(e);_x000D_
            var offsetX = pinchCenter.x*scale - (-x*scale + Math.min(viewportWidth, curWidth)/2);_x000D_
            var offsetY = pinchCenter.y*scale - (-y*scale + Math.min(viewportHeight, curHeight)/2);_x000D_
            pinchCenterOffset = { x: offsetX, y: offsetY };_x000D_
          }_x000D_
_x000D_
          // When the user pinch zooms, she/he expects the pinch center to remain in the same_x000D_
          // relative location of the screen. To achieve this, the raw zoom center is calculated by_x000D_
          // first storing the pinch center and the scaled offset to the current center of the_x000D_
          // image. The new scale is then used to calculate the zoom center. This has the effect of_x000D_
          // actually translating the zoom center on each pinch zoom event._x000D_
          var newScale = restrictScale(scale*e.scale);_x000D_
          var zoomX = pinchCenter.x*newScale - pinchCenterOffset.x;_x000D_
          var zoomY = pinchCenter.y*newScale - pinchCenterOffset.y;_x000D_
          var zoomCenter = { x: zoomX/newScale, y: zoomY/newScale };_x000D_
_x000D_
          zoomAround(e.scale, zoomCenter.x, zoomCenter.y, true);_x000D_
        });_x000D_
_x000D_
        hammer.on('pinchend', function (e) {_x000D_
          updateLastScale();_x000D_
          updateLastPos();_x000D_
          pinchCenter = null;_x000D_
        });_x000D_
_x000D_
        hammer.on('doubletap', function (e) {_x000D_
          var c = rawCenter(e);_x000D_
          zoomAround(2, c.x, c.y);_x000D_
        });_x000D_
_x000D_
      };_x000D_
_x000D_
    </script>_x000D_
_x000D_
    <button onclick="zoomIn()">Zoom In</button>_x000D_
    <button onclick="zoomOut()">Zoom Out</button>_x000D_
_x000D_
    <div class="pinch-zoom-container">_x000D_
      <img id="pinch-zoom-image-id" class="pinch-zoom-image" onload="onLoad()"_x000D_
           src="https://hammerjs.github.io/assets/img/pano-1.jpg">_x000D_
    </div>_x000D_
_x000D_
_x000D_
  </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

how to add key value pair in the JSON object already declared

possible duplicate , best way to achieve same as stated below:

function getKey(key) {
  return `${key}`;
}

var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};

https://stackoverflow.com/a/47405116/3510511

How to change position of Toast in Android?

From the documentation,

Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.

Download a file by jQuery.Ajax

You can with HTML5

NB: The file data returned MUST be base64 encoded because you cannot JSON encode binary data

In my AJAX response I have a data structure that looks like this:

{
    result: 'OK',
    download: {
        mimetype: string(mimetype in the form 'major/minor'),
        filename: string(the name of the file to download),
        data: base64(the binary data as base64 to download)
    }
}

That means that I can do the following to save a file via AJAX

var a = document.createElement('a');
if (window.URL && window.Blob && ('download' in a) && window.atob) {
    // Do it the HTML5 compliant way
    var blob = base64ToBlob(result.download.data, result.download.mimetype);
    var url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = result.download.filename;
    a.click();
    window.URL.revokeObjectURL(url);
}

The function base64ToBlob was taken from here and must be used in compliance with this function

function base64ToBlob(base64, mimetype, slicesize) {
    if (!window.atob || !window.Uint8Array) {
        // The current browser doesn't have the atob function. Cannot continue
        return null;
    }
    mimetype = mimetype || '';
    slicesize = slicesize || 512;
    var bytechars = atob(base64);
    var bytearrays = [];
    for (var offset = 0; offset < bytechars.length; offset += slicesize) {
        var slice = bytechars.slice(offset, offset + slicesize);
        var bytenums = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            bytenums[i] = slice.charCodeAt(i);
        }
        var bytearray = new Uint8Array(bytenums);
        bytearrays[bytearrays.length] = bytearray;
    }
    return new Blob(bytearrays, {type: mimetype});
};

This is good if your server is dumping filedata to be saved. However, I've not quite worked out how one would implement a HTML4 fallback

How to calculate md5 hash of a file using javascript

it is pretty easy to calculate the MD5 hash using the MD5 function of CryptoJS and the HTML5 FileReader API. The following code snippet shows how you can read the binary data and calculate the MD5 hash from an image that has been dragged into your Browser:

var holder = document.getElementById('holder');

holder.ondragover = function() {
  return false;
};

holder.ondragend = function() {
  return false;
};

holder.ondrop = function(event) {
  event.preventDefault();

  var file = event.dataTransfer.files[0];
  var reader = new FileReader();

  reader.onload = function(event) {
    var binary = event.target.result;
    var md5 = CryptoJS.MD5(binary).toString();
    console.log(md5);
  };

  reader.readAsBinaryString(file);
};

I recommend to add some CSS to see the Drag & Drop area:

#holder {
  border: 10px dashed #ccc;
  width: 300px;
  height: 300px;
}

#holder.hover {
  border: 10px dashed #333;
}

More about the Drag & Drop functionality can be found here: File API & FileReader

I tested the sample in Google Chrome Version 32.

How to get CRON to call in the correct PATHs

Most likely, cron is running in a very sparse environment. Check the environment variables cron is using by appending a dummy job which dumps env to a file like this:

* * * * * env > env_dump.txt

Compare that with the output of env in a normal shell session.

You can prepend your own environment variables to the local crontab by defining them at the top of your crontab.

Here's a quick fix to prepend $PATH to the current crontab:

# echo PATH=$PATH > tmp.cron
# echo >> tmp.cron
# crontab -l >> tmp.cron
# crontab tmp.cron

The resulting crontab will look similar to chrissygormley's answer, with PATH defined before the crontab rules.

I cannot start SQL Server browser

Make sure that you run the SQL Server Configuration Manager snap-in as Administrator if UAC is enabled. Then right click the service and then click properties, change the start mode to enabled, then start it.

How large should my recv buffer be when calling recv in the socket library

There is no absolute answer to your question, because technology is always bound to be implementation-specific. I am assuming you are communicating in UDP because incoming buffer size does not bring problem to TCP communication.

According to RFC 768, the packet size (header-inclusive) for UDP can range from 8 to 65 515 bytes. So the fail-proof size for incoming buffer is 65 507 bytes (~64KB)

However, not all large packets can be properly routed by network devices, refer to existing discussion for more information:

What is the optimal size of a UDP packet for maximum throughput?
What is the largest Safe UDP Packet Size on the Internet

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

Which Python memory profiler is recommended?

Consider the objgraph library (see this blog post for an example use case).

Javascript close alert box

no control over the dialog box, if you had control over the dialog box you could write obtrusive javascript code. (Its is not a good idea to use alert for anything except debugging)

Close popup window

For such a seemingly simple thing this can be a royal pain in the butt! I found a solution that works beautifully (class="video-close" is obviously particular to this button and optional)

 <a href="javascript:window.open('','_self').close();" class="video-close">Close this window</a>

How to make a smooth image rotation in Android?

In Kotlin:

 ivBall.setOnClickListener(View.OnClickListener {

            //Animate using XML
            // val rotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.rotate_indefinitely)

            //OR using Code
            val rotateAnimation = RotateAnimation(
                    0f, 359f,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f

            )
            rotateAnimation.duration = 300
            rotateAnimation.repeatCount = 2

            //Either way you can add Listener like this
            rotateAnimation.setAnimationListener(object : Animation.AnimationListener {

                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {

                    val rand = Random()
                    val ballHit = rand.nextInt(50) + 1
                    Toast.makeText(context, "ballHit : " + ballHit, Toast.LENGTH_SHORT).show()
                }
            })

            ivBall.startAnimation(rotateAnimation)
        })

How do I get the directory from a file's full path?

If you are working with a FileInfo object, then there is an easy way to extract a string representation of the directory's full path via the DirectoryName property.

Description of the FileInfo.DirectoryName Property via MSDN:

Gets a string representing the directory's full path.

Sample usage:

string filename = @"C:\MyDirectory\MyFile.bat";
FileInfo fileInfo = new FileInfo(filename);
string directoryFullPath = fileInfo.DirectoryName; // contains "C:\MyDirectory"

Link to the MSDN documentation.

Want to make Font Awesome icons clickable

Please use Like below.
<a style="cursor: pointer" **(click)="yourFunctionComponent()"** >
<i class="fa fa-dribbble fa-4x"></i>
 </a>

The above can be used so that the fa icon will be shown and also on the click function you could write your logic.

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

Convert bytes to bits in python

What about something like this?

>>> bin(int('ff', base=16))
'0b11111111'

This will convert the hexadecimal string you have to an integer and that integer to a string in which each byte is set to 0/1 depending on the bit-value of the integer.

As pointed out by a comment, if you need to get rid of the 0b prefix, you can do it this way:

>>> bin(int('ff', base=16)).lstrip('0b')
'11111111'

or this way:

>>> bin(int('ff', base=16))[2:]
'11111111'

How to set python variables to true or false?

First to answer your question, you set a variable to true or false by assigning True or False to it:

myFirstVar = True
myOtherVar = False

If you have a condition that is basically like this though:

if <condition>:
    var = True
else:
    var = False

then it is much easier to simply assign the result of the condition directly:

var = <condition>

In your case:

match_var = a == b

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

If none of the solution worked and you are working with JAXB, then you need to annotate your class with @XmlRootElement to avoid 415 unsupported media type

Get value from hashmap based on key to JSTL

could you please try below code

<c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
  </c:forEach>

Getting mouse position in c#

To answer your specific example:

// your example
Location.X = Cursor.Position.X;
Location.Y = Cursor.Position.Y;

// sample code
Console.WriteLine("x: " + Cursor.Position.X + " y: " + Cursor.Position.Y);

Don't forget to add using System.Windows.Forms;, and adding the reference to it (right click on references > add reference > .NET tab > Systems.Windows.Forms > ok)

How to "set a breakpoint in malloc_error_break to debug"

In your screenshot, you didn't specify any module: try setting "libsystem_c.dylib"

enter image description here

I did that, and it works : breakpoint stops here (although the stacktrace often rise from some obscure system lib...)

Print all day-dates between two dates

Using a list comprehension:

from datetime import date, timedelta

d1 = date(2008,8,15)
d2 = date(2008,9,15)

# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]

for d in dd:
    print d

# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)

How to search in a List of Java object

I modifie this list and add a List to the samples try this

Pseudocode

Sample {
   List<String> values;
   List<String> getList() {
   return values}
}



for(Sample s : list) {
   if(s.getString.getList.contains("three") {
      return s;
   }
}

How to initialize a List<T> to a given size (as opposed to capacity)?

If I understand correctly, you want the List<T> version of new T[size], without the overhead of adding values to it.

If you are not afraid the implementation of List<T> will change dramatically in the future (and in this case I believe the probability is close to 0), you can use reflection:

    public static List<T> NewOfSize<T>(int size) {
        var list = new List<T>(size);
        var sizeField = list.GetType().GetField("_size",BindingFlags.Instance|BindingFlags.NonPublic);
        sizeField.SetValue(list, size);
        return list;
    }

Note that this takes into account the default functionality of the underlying array to prefill with the default value of the item type. All int arrays will have values of 0 and all reference type arrays will have values of null. Also note that for a list of reference types, only the space for the pointer to each item is created.

If you, for some reason, decide on not using reflection, I would have liked to offer an option of AddRange with a generator method, but underneath List<T> just calls Insert a zillion times, which doesn't serve.

I would also like to point out that the Array class has a static method called ResizeArray, if you want to go the other way around and start from Array.

To end, I really hate when I ask a question and everybody points out that it's the wrong question. Maybe it is, and thanks for the info, but I would still like an answer, because you have no idea why I am asking it. That being said, if you want to create a framework that has an optimal use of resources, List<T> is a pretty inefficient class for anything than holding and adding stuff to the end of a collection.

Java: How to read a text file

You can use Files#readAllLines() to get all lines of a text file into a List<String>.

for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    // ...
}

Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files


You can use String#split() to split a String in parts based on a regular expression.

for (String part : line.split("\\s+")) {
    // ...
}

Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String


You can use Integer#valueOf() to convert a String into an Integer.

Integer i = Integer.valueOf(part);

Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings


You can use List#add() to add an element to a List.

numbers.add(i);

Tutorial: Interfaces > The List Interface


So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String part : line.split("\\s+")) {
        Integer i = Integer.valueOf(part);
        numbers.add(i);
    }
}

If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines().

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\\s+")).flatMap(Arrays::stream)
    .map(Integer::valueOf)
    .collect(Collectors.toList());

Tutorial: Processing data with Java 8 streams

Excel formula to get cell color

Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.

While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.

Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.

Error 405 (Method Not Allowed) Laravel 5

This might help someone so I'll put my inputs here as well.

I've encountered the same (or similar) problem. Apparently, the problem was the POST request was blocked by Modsec by the following rules: 350147, 340147, 340148, 350148

After blocking the request, I was redirected to the same endpoint but as a GET request of course and thus the 405.

I whitelisted those rules and voila, the 405 error was gone.

Hope this helps someone.

How can I get the domain name of my site within a Django template?

If you want the actual HTTP Host header, see Daniel Roseman's comment on @Phsiao's answer. The other alternative is if you're using the contrib.sites framework, you can set a canonical domain name for a Site in the database (mapping the request domain to a settings file with the proper SITE_ID is something you have to do yourself via your webserver setup). In that case you're looking for:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
current_site.domain

you'd have to put the current_site object into a template context yourself if you want to use it. If you're using it all over the place, you could package that up in a template context processor.

Pass a list to a function to act as multiple arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

Adding files to a GitHub repository

The general idea is to add, commit and push your files to the GitHub repo.

First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.

git --work-tree=yourSrcFolder add .

(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)

That way, you keep separate your initial source folder, from your Git working tree.


Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.

d

how to File.listFiles in alphabetical order?

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));

How to sort an object array by date property?

i was able to achieve sorting using below lines:

array.sort(function(a, b)
{
   if (a.DueDate > b.DueDate) return 1;
   if (a.DueDate < b.DueDate) return -1;
})

Sending command line arguments to npm script

I know there is an approved answer already, but I kinda like this JSON approach.

npm start '{"PROJECT_NAME_STR":"my amazing stuff", "CRAZY_ARR":[0,7,"hungry"], "MAGICAL_NUMBER_INT": 42, "THING_BOO":true}';

Usually I have like 1 var I need, such as a project name, so I find this quick n' simple.

Also I often have something like this in my package.json

"scripts": {
    "start": "NODE_ENV=development node local.js"
}

And being greedy I want "all of it", NODE_ENV and the CMD line arg stuff.

You simply access these things like so in your file (in my case local.js)

console.log(process.env.NODE_ENV, starter_obj.CRAZY_ARR, starter_obj.PROJECT_NAME_STR, starter_obj.MAGICAL_NUMBER_INT, starter_obj.THING_BOO);

You just need to have this bit above it (I'm running v10.16.0 btw)

var starter_obj = JSON.parse(JSON.parse(process.env.npm_config_argv).remain[0]);

Anyhoo, question already answered. Thought I'd share, as I use this method a lot.

Difference between app.use and app.get in express.js

Difference between app.use & app.get:

app.use ? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.

app.get ? It is only for handling GET HTTP requests.

Now, there is a confusion between app.use & app.all. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests. But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.

  1. app.use() ? It takes only one callback.
    app.all() ? It can take multiple callbacks.

  2. app.use() will only see whether url starts with specified path.
    But, app.all() will match the complete path.

For example,

app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject

app.all( "/book" , handler);
// will match /book
// won't match /book/author   
// won't match /book/subject    

app.all( "/book/*" , handler);
// won't match /book        
// will match /book/author
// will match /book/subject
  1. next() call inside the app.use() will call either the next middleware or any route handler, but next() call inside app.all() will invoke the next route handler (app.all(), app.get/post/put... etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.

Is it possible to compile a program written in Python?

Python, as a dynamic language, cannot be "compiled" into machine code statically, like C or COBOL can. You'll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation.

You can "translate" source code in bytecode, which is just an intermediate process that the interpreter does to speed up the load of the code, It converts text files, with comments, blank spaces, words like 'if', 'def', 'in', etc in binary code, but the operations behind are exactly the same, in Python, not in machine code or any other language. This is what it's stored in .pyc files and it's also portable between architectures.

Probably what you need it's not "compile" the code (which it's not possible) but to "embed" an interpreter (in the right architecture) with the code to allow running the code without an external installation of the interpreter. To do that, you can use all those tools like py2exe or cx_Freeze.

Maybe I'm being a little pedantic on this :-P

How can I play sound in Java?

I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.

https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java

Here is the code for reference.

package com.athanazio.jaga.desktop.sound;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {

    AudioInputStream in;

    AudioFormat decodedFormat;

    AudioInputStream din;

    AudioFormat baseFormat;

    SourceDataLine line;

    private boolean loop;

    private BufferedInputStream stream;

    // private ByteArrayInputStream stream;

    /**
     * recreate the stream
     * 
     */
    public void reset() {
        try {
            stream.reset();
            in = AudioSystem.getAudioInputStream(stream);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            line = getLine(decodedFormat);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            line.close();
            din.close();
            in.close();
        } catch (IOException e) {
        }
    }

    Sound(String filename, boolean loop) {
        this(filename);
        this.loop = loop;
    }

    Sound(String filename) {
        this.loop = false;
        try {
            InputStream raw = Object.class.getResourceAsStream(filename);
            stream = new BufferedInputStream(raw);

            // ByteArrayOutputStream out = new ByteArrayOutputStream();
            // byte[] buffer = new byte[1024];
            // int read = raw.read(buffer);
            // while( read > 0 ) {
            // out.write(buffer, 0, read);
            // read = raw.read(buffer);
            // }
            // stream = new ByteArrayInputStream(out.toByteArray());

            in = AudioSystem.getAudioInputStream(stream);
            din = null;

            if (in != null) {
                baseFormat = in.getFormat();

                decodedFormat = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED, baseFormat
                                .getSampleRate(), 16, baseFormat.getChannels(),
                        baseFormat.getChannels() * 2, baseFormat
                                .getSampleRate(), false);

                din = AudioSystem.getAudioInputStream(decodedFormat, in);
                line = getLine(decodedFormat);
            }
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    private SourceDataLine getLine(AudioFormat audioFormat)
            throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }

    public void play() {

        try {
            boolean firstTime = true;
            while (firstTime || loop) {

                firstTime = false;
                byte[] data = new byte[4096];

                if (line != null) {

                    line.start();
                    int nBytesRead = 0;

                    while (nBytesRead != -1) {
                        nBytesRead = din.read(data, 0, data.length);
                        if (nBytesRead != -1)
                            line.write(data, 0, nBytesRead);
                    }

                    line.drain();
                    line.stop();
                    line.close();

                    reset();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Instead of exceptions, just use:

if (Build.VERSION.SDK_INT >= 11)

and use

@SuppressLint("NewApi")

to suppress the warnings.

How to remove elements from a generic list while iterating over it?

There is an option that hasn't been mentioned here.

If you don't mind adding a bit of code somewhere in your project, you can add and extension to List to return an instance of a class that does iterate through the list in reverse.

You would use it like this :

foreach (var elem in list.AsReverse())
{
    //Do stuff with elem
    //list.Remove(elem); //Delete it if you want
}

And here is what the extension looks like:

public static class ReverseListExtension
{
    public static ReverseList<T> AsReverse<T>(this List<T> list) => new ReverseList<T>(list);

    public class ReverseList<T> : IEnumerable
    {
        List<T> list;
        public ReverseList(List<T> list){ this.list = list; }

        public IEnumerator GetEnumerator()
        {
            for (int i = list.Count - 1; i >= 0; i--)
                yield return list[i];
            yield break;
        }
    }
}

This is basically list.Reverse() without the allocation.

Like some have mentioned you still get the drawback of deleting elements one by one, and if your list is massively long some of the options here are better. But I think there is a world where someone would want the simplicity of list.Reverse(), without the memory overhead.

Open a PDF using VBA in Excel

If it's a matter of just opening PDF to send some keys to it then why not try this

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub

I am assuming that you have some pdf reader installed.

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

Best way to copy from one array to another

There are lots of solutions:

b = Arrays.copyOf(a, a.length);

Which allocates a new array, copies over the elements of a, and returns the new array.

Or

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Which copies the source array content into a destination array that you allocate yourself.

Or

b = a.clone();

which works very much like Arrays.copyOf(). See this thread.

Or the one you posted, if you reverse the direction of the assignment in the loop:

b[i] = a[i]; // NOT a[i] = b[i];

Tooltip on image

You can use the following format to generate a tooltip for an image.

<div class="tooltip"><img src="joe.jpg" />
  <span class="tooltiptext">Tooltip text</span>
</div>

UnicodeEncodeError: 'latin-1' codec can't encode character

Character U+201C Left Double Quotation Mark is not present in the Latin-1 (ISO-8859-1) encoding.

It is present in code page 1252 (Western European). This is a Windows-specific encoding that is based on ISO-8859-1 but which puts extra characters into the range 0x80-0x9F. Code page 1252 is often confused with ISO-8859-1, and it's an annoying but now-standard web browser behaviour that if you serve your pages as ISO-8859-1, the browser will treat them as cp1252 instead. However, they really are two distinct encodings:

>>> u'He said \u201CHello\u201D'.encode('iso-8859-1')
UnicodeEncodeError
>>> u'He said \u201CHello\u201D'.encode('cp1252')
'He said \x93Hello\x94'

If you are using your database only as a byte store, you can use cp1252 to encode and other characters present in the Windows Western code page. But still other Unicode characters which are not present in cp1252 will cause errors.

You can use encode(..., 'ignore') to suppress the errors by getting rid of the characters, but really in this century you should be using UTF-8 in both your database and your pages. This encoding allows any character to be used. You should also ideally tell MySQL you are using UTF-8 strings (by setting the database connection and the collation on string columns), so it can get case-insensitive comparison and sorting right.

In Linux, how to tell how much memory processes are using?

In case you don't have a current or long running process to track, you can use /usr/bin/time.

This is not the same as Bash time (as you will see).

Eg

# /usr/bin/time -f "%M" echo

2028

This is "Maximum resident set size of the process during its lifetime, in Kilobytes" (quoted from the man page). That is, the same as RES in top et al.

There are a lot more you can get from /usr/bin/time.

# /usr/bin/time -v echo

Command being timed: "echo"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 0%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 1988
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 77
Voluntary context switches: 1
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0

How to make a gui in python

easygui is a wrapper around Tkinter to make things easier

How to make CREATE OR REPLACE VIEW work in SQL Server?

Borrowing from @Khan's answer, I would do:

IF OBJECT_ID('dbo.test_abc_def', 'V') IS NOT NULL
    DROP VIEW dbo.test_abc_def
GO

CREATE VIEW dbo.test_abc_def AS
SELECT 
    VCV.xxxx
    ,VCV.yyyy AS yyyy
    ,VCV.zzzz AS zzzz
FROM TABLE_A

MSDN Reference

Get current time as formatted string in Go?

Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)

t := time.Now()
fmt.Println(t.Format("20060102150405"))

Online demo (with date fixed in the past in the playground, never mind)

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

// This pair of functions convert HSL to RGB and vice-versa.
// It's pretty optimized for execution speed

typedef unsigned char       BYTE
typedef struct _RGB
{
    BYTE R;
    BYTE G;
    BYTE B;
} RGB, *pRGB;
typedef struct _HSL
{
    float   H;  // color Hue (0.0 to 360.0 degrees)
    float   S;  // color Saturation (0.0 to 1.0)
    float   L;  // Luminance (0.0 to 1.0)
    float   V;  // Value (0.0 to 1.0)
} HSL, *pHSL;

float   *fMin       (float *a, float *b)
{
    return *a <= *b?  a : b;
}

float   *fMax       (float *a, float *b)
{
    return *a >= *b? a : b;
}

void    RGBtoHSL    (pRGB rgb, pHSL hsl)
{
// See https://en.wikipedia.org/wiki/HSL_and_HSV
// rgb->R, rgb->G, rgb->B: [0 to 255]
    float r =       (float) rgb->R / 255;
    float g =       (float) rgb->G / 255;
    float b =       (float) rgb->B / 255;
    float *min =    fMin(fMin(&r, &g), &b);
    float *max =    fMax(fMax(&r, &g), &b);
    float delta =   *max - *min;

// L, V [0.0 to 1.0]
    hsl->L = (*max + *min)/2;
    hsl->V = *max;
// Special case for H and S
    if (delta == 0)
    {
        hsl->H = 0.0f;
        hsl->S = 0.0f;
    }
    else
    {
// Special case for S
        if((*max == 0) || (*min == 1))
            hsl->S = 0;
        else
// S [0.0 to 1.0]
            hsl->S = (2 * *max - 2*hsl->L)/(1 - fabsf(2*hsl->L - 1));
// H [0.0 to 360.0]
        if      (max == &r)     hsl->H = fmod((g - b)/delta, 6);    // max is R
        else if (max == &g)     hsl->H = (b - r)/delta + 2;         // max is G
        else                    hsl->H = (r - g)/delta + 4;         // max is B
        hsl->H *= 60;
    }
}

void    HSLtoRGB    (pHSL hsl, pRGB rgb)
{
// See https://en.wikipedia.org/wiki/HSL_and_HSV
    float a, k, fm1, fp1, f1, f2, *f3;
// L, V, S: [0.0 to 1.0]
// rgb->R, rgb->G, rgb->B: [0 to 255]
    fm1 = -1;
    fp1 = 1;
    f1 = 1-hsl->L;
    a = hsl->S * *fMin(&hsl->L, &f1);
    k = fmod(0 + hsl->H/30, 12);
    f1 = k - 3;
    f2 = 9 - k;
    f3 = fMin(fMin(&f1, &f2), &fp1) ;
    rgb->R = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));

    k = fmod(8 + hsl->H/30, 12);
    f1 = k - 3;
    f2 = 9 - k;
    f3 = fMin(fMin(&f1, &f2), &fp1) ;
    rgb->G = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));

    k = fmod(4 + hsl->H/30, 12);
    f1 = k - 3;
    f2 = 9 - k;
    f3 = fMin(fMin(&f1, &f2), &fp1) ;
    rgb->B = (BYTE) (255 * (hsl->L - a * *fMax(f3, &fm1)));
}

Find length of 2D array Python

You can also use np.size(a,1), 1 here is the axis and this will give you the number of columns

SQL Server Linked Server Example Query

SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME..TABLENAME')

This may help you.

How to use 'hover' in CSS

Not an answer, but explanation of why your css is not matching HTML.

In css space is used as a separator to tell browser to look in children, so your css

a .hover :hover{
   text-decoration:underline;
}

means "look for a element, then look for any descendants of it that have hover class and look of any descendants of those descendants that have hover state" and would match this markup

<a>
   <span class="hover">
      <span>
         I will become underlined when you hover on me
      <span/>
   </span>
</a> 

If you want to match <a class="hover">I will become underlined when you hover on me</a> you should use a.hover:hover, which means "look for any a element with class hover and with hover state"

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

What is the 'new' keyword in JavaScript?

Javascript is not object oriented programming(OOP) language therefore the LOOK UP process in javascript work using 'DELEGATION PROCESS' also known as prototype delegation or prototypical inheritance.

If you try to get the value of a property from an object that it doesn't have, the JavaScript engine looks to the object's prototype (and its prototype, 1 step above at a time) it's prototype chain untll the chain ends upto null which is Object.prototype == null (Standard Object Prototype). At this point if property or method is not defined than undefined is returned.

Thus with the new keyword some of the task that were manually done e.g

  1. Manual Object Creation e.g newObj.
  2. Hidden bond Creation using proto (aka: dunder proto) in JS spec [[prototype]] (i.e. proto)
  3. referencing and assign properties to newObj
  4. return of newObj object.

All is done manually.

function CreateObj(value1, value2) {
  const newObj = {};
  newObj.property1 = value1;
  newObj.property2 = value2;
  return newObj;
}
var obj = CreateObj(10,20);

obj.__proto__ === Object.prototype;              // true
Object.getPrototypeOf(obj) === Object.prototype // true

Javascript Keyword new helps to automate this process:

  1. new object literal is created identified by this:{}
  2. referencing and assign properties to this
  3. Hidden bond Creation [[prototype]] (i.e. proto) to Function.prototype shared space.
  4. implicit return of this object {}
function CreateObj(value1, value2) {
  this.property1 = value1;
  this.property2 = value2;
}

var obj = new CreateObj(10,20);
obj.__proto__ === CreateObj.prototype             // true
Object.getPrototypeOf(obj) == CreateObj.prototype // true

Calling Constructor Function without the new Keyword:

=> this: Window

function CreateObj(value1, value2) {
  var isWindowObj = this === window;
  console.log("Is Pointing to Window Object", isWindowObj);
  this.property1 = value1;
  this.property2 = value2;
}
var obj = new CreateObj(10,20); // Is Pointing to Window Object false
var obj = CreateObj(10,20); // Is Pointing to Window Object true
window.property1; // 10
window.property2; // 20

Can't change z-index with JQuery

Setting the style.zIndex property has no effect on non-positioned elements, that is, the element must be either absolutely positioned, relatively positioned, or fixed.

So I would try:

$(this).parent().css('position', 'relative');
$(this).parent().css('z-index', 3000);

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

You just need to add three file and two css links. You can either cdn's as well. Links for the js files and css files are as such :-

  1. jQuery.dataTables.min.js
  2. dataTables.bootstrap.min.js
  3. dataTables.bootstrap.min.css
  4. bootstrap-datepicker.css
  5. bootstrap-datepicker.js

They are valid if you are using bootstrap in your project.

I hope this will help you. Regards, Vivek Singla

How do I create a dynamic key to be added to a JavaScript object variable

Associative Arrays in JavaScript don't really work the same as they do in other languages. for each statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push method:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

Manually put files to Android emulator SD card

If you are using Eclipse you can move files to and from the SD Card through the Android Perspective (it is called DDMS in Eclipse). Just select the Emulator in the left part of the screen and then choose the File Explorer tab. Above the list with your files should be two symbols, one with an arrow pointing at a phone, clicking this will allow you to choose a file to move to phone memory.

How do I enable MSDTC on SQL Server?

Do you even need MSDTC? The escalation you're experiencing is often caused by creating multiple connections within a single TransactionScope.

If you do need it then you need to enable it as outlined in the error message. On XP:

  • Go to Administrative Tools -> Component Services
  • Expand Component Services -> Computers ->
  • Right-click -> Properties -> MSDTC tab
  • Hit the Security Configuration button

How can I analyze a heap dump in IntelliJ? (memory leak)

You can install the JVisualVM plugin from here: https://plugins.jetbrains.com/plugin/3749?pr=

This will allow you to analyse the dump within the plugin.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

Here is a solution I made using the above ideas that can be used for TextBoxFor and PasswordFor:

public static class HtmlHelperEx
{
    public static MvcHtmlString TextBoxWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return htmlHelper.TextBoxFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));

    }

    public static MvcHtmlString PasswordWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return htmlHelper.PasswordFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));

    }
}

public static class HtmlAttributesHelper
{
    public static IDictionary<string, object> AddAttribute(this object htmlAttributes, string name, object value)
    {
        var dictionary = htmlAttributes == null ? new Dictionary<string, object>() : htmlAttributes.ToDictionary();
        if (!String.IsNullOrWhiteSpace(name) && value != null && !String.IsNullOrWhiteSpace(value.ToString()))
            dictionary.Add(name, value);
        return dictionary;
    }

    public static IDictionary<string, object> ToDictionary(this object obj)
    {
        return TypeDescriptor.GetProperties(obj)
            .Cast<PropertyDescriptor>()
            .ToDictionary(property => property.Name, property => property.GetValue(obj));
    }
}

How do I pass multiple parameters into a function in PowerShell?

Function Test {
    Param([string]$arg1, [string]$arg2)

    Write-Host $arg1
    Write-Host $arg2
}

This is a proper params declaration.

See about_Functions_Advanced_Parameters.

And it indeed works.

jQuery: How to get the HTTP status code from within the $.ajax.error method?

An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.

function checkHttpStatus(url) {     
    $.ajax({
        type: "GET",
        data: {},
        url: url,
        error: function(response) {
            alert(url + " returns a " + response.status);
        }, success() {
            alert(url + " Good link");
        }
    });
}

ASP.Net which user account running Web Service on IIS 7?

Server 2008

Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.

In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity

Here's the info from Microsoft on setting up Application Pool Identites:

http://learn.iis.net/page.aspx/624/application-pool-identities/

Why is char[] preferred over String for passwords?

To quote an official document, the Java Cryptography Architecture guide says this about char[] vs. String passwords (about password-based encryption, but this is more generally about passwords of course):

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

Guideline 2-2 of the Secure Coding Guidelines for the Java Programming Language, Version 4.0 also says something similar (although it is originally in the context of logging):

Guideline 2-2: Do not log highly sensitive information

Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use. Clearing data structures has reduced effectiveness on typical Java runtime systems as objects are moved in memory transparently to the programmer.

This guideline also has implications for implementation and use of lower-level libraries that do not have semantic knowledge of the data they are dealing with. As an example, a low-level string parsing library may log the text it works on. An application may parse an SSN with the library. This creates a situation where the SSNs are available to administrators with access to the log files.

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

Globally catch exceptions in a WPF application?

In addition what others mentioned here, note that combining the Application.DispatcherUnhandledException (and its similars) with

<configuration>
  <runtime>  
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

in the app.config will prevent your secondary threads exception from shutting down the application.

How to find the array index with a value?

how about indexOf ?

alert(imageList.indexOf(200));

Convert ASCII number to ASCII Character in C

You can assign int to char directly.

int a = 65;
char c = a;
printf("%c", c);

In fact this will also work.

printf("%c", a);  // assuming a is in valid range

How to convert string to boolean in typescript Angular 4

Boolean("true") will do the work too

How to get all options of a select using jQuery?

I don't know jQuery, but I do know that if you get the select element, it contains an 'options' object.

var myOpts = document.getElementById('yourselect').options;
alert(myOpts[0].value) //=> Value of the first option

Is there an Eclipse plugin to run system shell in the Console?

I wrote this to get a native shell...it uses the same GTK widget the gnome-terminal uses so the behavior should be nearly identical.

http://github.com/maihde/Eclipse-Terminal

How can I hide the Android keyboard using JavaScript?

HTML

<input type="text" id="txtFocus" style="display:none;">

SCRIPT

$('#txtFocus').show().focus().hide();
$.msg({ content : 'Alert using jquery msg' });

Sending and receiving data over a network using TcpClient

First of all, TCP does not guarantee that everything that you send will be received with the same read at the other end. It only guarantees that all bytes that you send will arrive and in the correct order.

Therefore, you will need to keep building up a buffer when reading from the stream. You will also have to know how large each message is.

The simplest ever is to use a non-typeable ASCII character to mark the end of the packet and look for it in the received data.

Remove Datepicker Function dynamically

You can try the enable/disable methods instead of using the option method:

$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");

This disables the entire textbox. So may be you can use datepicker.destroy() instead:

$(document).ready(function() {
    $("#ddlSearchType").change(function() {
        if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
            $("#txtSearch").datepicker();
        }
        else {
            $("#txtSearch").datepicker("destroy");
        }
    }).change();
});

Demo here.

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

Google Colab: how to read data from my google drive?

Consider just downloading the file with permanent link and gdown preinstalled like here

Cannot lower case button text in android studio

there are 3 ways to do it.

1.Add the following line on style.xml to change entire application

<item name="android:textAllCaps">false</item>

2.Use

android:textAllCaps="false"

in your layout-v21

mButton.setTransformationMethod(null);
  1. add this line under the element(button or edit text) in xml

android:textAllCaps="false"

regards

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

How to find numbers from a string?

I was looking for the answer of the same question but for a while I found my own solution and I wanted to share it for other people who will need those codes in the future. Here is another solution without function.

Dim control As Boolean
Dim controlval As String
Dim resultval As String
Dim i as Integer

controlval = "A1B2C3D4"

For i = 1 To Len(controlval)
control = IsNumeric(Mid(controlval, i, 1))
If control = True Then resultval = resultval & Mid(controlval, i, 1)
Next i

resultval = 1234

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.

How to install cron

Cron is so named "deamon" (same as service under Win).

Most likely cron is already installed on your system (if it is a Linux/Unix system).

Look here: http://www.comptechdoc.org/os/linux/startupman/linux_sucron.html

or there http://en.wikipedia.org/wiki/Cron

for more details.

Recursion or Iteration?

I would think in (non tail) recursion there would be a performance hit for allocating a new stack etc every time the function is called (dependent on language of course).

Convert form data to JavaScript object with jQuery

const formData = new FormData(form);

let formDataJSON = {};

for (const [key, value] of formData.entries()) {

    formDataJSON[key] = value;
}

Use FontAwesome or Glyphicons with css :before

Re: using icon in :before – recent Font Awesome builds include the .fa-icon() mixin for SASS and LESS. This will automatically include the font-family as well as some rendering tweaks (e.g. -webkit-font-smoothing). Thus you can do, e.g.:

// Add "?" icon to header.
h1:before {
    .fa-icon();
    content: "\f059";
}

How do I create test and train samples from one dataframe with pandas?

You can use ~ (tilde operator) to exclude the rows sampled using df.sample(), letting pandas alone handle sampling and filtering of indexes, to obtain two sets.

train_df = df.sample(frac=0.8, random_state=100)
test_df = df[~df.index.isin(train_df.index)]

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

.rar, .zip files MIME Type

As extension might contain more or less that three characters the following will test for an extension regardless of the length of it.

Try this:

$allowedExtensions = array( 'mkv', 'mp3', 'flac' );

$temp = explode(".", $_FILES[$file]["name"]);
$extension = strtolower(end($temp));

if( in_array( $extension, $allowedExtensions ) ) { ///

to check for all characters after the last '.'

Dynamically add script tag with src that may include document.write

Here is a minified snippet, same code as Google Analytics and Facebook Pixel uses:

!function(e,s,t){(t=e.createElement(s)).async=!0,t.src="https://example.com/foo.js",(e=e.getElementsByTagName(s)[0]).parentNode.insertBefore(t,e)}(document,"script");

Replace https://example.com/foo.js with your script path.

How to open every file in a folder

import pyautogui
import keyboard
import time
import os
import pyperclip

os.chdir("target directory")

# get the current directory
cwd=os.getcwd()

files=[]

for i in os.walk(cwd):
    for j in i[2]:
        files.append(os.path.abspath(j))

os.startfile("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe")
time.sleep(1)


for i in files:
    print(i)
    pyperclip.copy(i)
    keyboard.press('ctrl')
    keyboard.press_and_release('o')
    keyboard.release('ctrl')
    time.sleep(1)

    keyboard.press('ctrl')
    keyboard.press_and_release('v')
    keyboard.release('ctrl')
    time.sleep(1)
    keyboard.press_and_release('enter')
    keyboard.press('ctrl')
    keyboard.press_and_release('p')
    keyboard.release('ctrl')
    keyboard.press_and_release('enter')
    time.sleep(3)
    keyboard.press('ctrl')
    keyboard.press_and_release('w')
    keyboard.release('ctrl')
    pyperclip.copy('')

Matrix Multiplication in pure Python?

This is incorrect initialization. You interchanged row with col!

C = [[0 for row in range(len(A))] for col in range(len(B[0]))]

Correct initialization would be

C = [[0 for col in range(len(B[0]))] for row in range(len(A))]

Also I would suggest using better naming conventions. Will help you a lot in debugging. For example:

def matrixmult (A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    if cols_A != rows_B:
      print "Cannot multiply the two matrices. Incorrect dimensions."
      return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]
    return C

You can do a lot more, but you get the idea...

JavaScript CSS how to add and remove multiple CSS classes to an element

2 great ways to ADD:

But the first way is more cleaner, since for the second you have to add a space at the beginning. This is to avoid the class name from joining with the previous class.

element.classList.add("d-flex", "align-items-center");
element.className += " d-flex align-items-center";

Then to REMOVE use the cleaner way, by use of classList

element.classList.remove("d-grid", "bg-danger");

How can I remove the outline around hyperlinks images?

include this code in your style sheet

img {border : 0;}

a img {outline : none;}

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Just use MS Web platform Installer 4.5 to install all stuff for MS SQL Server 2008 R2.

And don't forget to reload machine.

:)

Is there an addHeaderView equivalent for RecyclerView?

There isn't an easy way like listview.addHeaderView() but you can achieve this by adding a type to your adapter for header.

Here is an example

public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    String[] data;

    public HeaderAdapter(String[] data) {
        this.data = data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new VHItem(null);
        } else if (viewType == TYPE_HEADER) {
            //inflate your layout and pass it to view holder
            return new VHHeader(null);
        }

        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VHItem) {
            String dataItem = getItem(position);
            //cast holder to VHItem and set data
        } else if (holder instanceof VHHeader) {
            //cast holder to VHHeader and set data for header.
        }
    }

    @Override
    public int getItemCount() {
        return data.length + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

    private String getItem(int position) {
        return data[position - 1];
    }

    class VHItem extends RecyclerView.ViewHolder {
        TextView title;

        public VHItem(View itemView) {
            super(itemView);
        }
    }

    class VHHeader extends RecyclerView.ViewHolder {
        Button button;

        public VHHeader(View itemView) {
            super(itemView);
        }
    }
}

link to gist -> here

Run javascript script (.js file) in mongodb including another file inside js

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2

jQuery UI Slider (setting programmatically)

Mal's answer was the only one that worked for me (maybe jqueryUI has changed), here is a variant for dealing with a range:

$( "#slider-range" ).slider('values',0,lowerValue);
$( "#slider-range" ).slider('values',1,upperValue);
$( "#slider-range" ).slider("refresh");

What's the difference between a Future and a Promise?

I will give an example of what is Promise and how its value could be set at any time, in opposite to Future, which value is only readable.

Suppose you have a mom and you ask her for money.

// Now , you trick your mom into creating you a promise of eventual
// donation, she gives you that promise object, but she is not really
// in rush to fulfill it yet:
Supplier<Integer> momsPurse = ()-> {

        try {
            Thread.sleep(1000);//mom is busy
        } catch (InterruptedException e) {
            ;
        }

        return 100;

    };


ExecutorService ex = Executors.newFixedThreadPool(10);

CompletableFuture<Integer> promise =  
CompletableFuture.supplyAsync(momsPurse, ex);

// You are happy, you run to thank you your mom:
promise.thenAccept(u->System.out.println("Thank you mom for $" + u ));

// But your father interferes and generally aborts mom's plans and 
// completes the promise (sets its value!) with far lesser contribution,
// as fathers do, very resolutely, while mom is slowly opening her purse 
// (remember the Thread.sleep(...)) :
promise.complete(10); 

Output of that is:

Thank you mom for $10

Mom's promise was created , but waited for some "completion" event.

CompletableFuture<Integer> promise...

You created such event, accepting her promise and announcing your plans to thank your mom:

promise.thenAccept...

At this moment mom started open her purse...but very slow...

and father interfered much faster and completed the promise instead of your mom:

promise.complete(10);

Have you noticed an executor that I wrote explicitly?

Interestingly, if you use a default implicit executor instead (commonPool) and father is not at home, but only mom with her "slow purse", then her promise will only complete, if the program lives longer than mom needs to get money from the purse.

The default executor acts kind of like a "daemon" and does not wait for all promises to be fulfilled. I have not found a good description of this fact...

How to force a WPF binding to refresh?

You can use binding expressions:

private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
    ((ComboBox)sender).GetBindingExpression(ComboBox.ItemsSourceProperty)
                      .UpdateTarget();
}

But as Blindmeis noted you can also fire change notifications, further if your collection implements INotifyCollectionChanged (for example implemented in the ObservableCollection<T>) it will synchronize so you do not need to do any of this.

View's getWidth() and getHeight() returns 0

Gone views returns 0 as height if app in background. This my code (1oo% works)

fun View.postWithTreeObserver(postJob: (View, Int, Int) -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            measure(widthSpec, heightSpec)
            postJob(this@postWithTreeObserver, measuredWidth, measuredHeight)
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                @Suppress("DEPRECATION")
                viewTreeObserver.removeGlobalOnLayoutListener(this)
            } else {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
    })
}

Pass a String from one Activity to another Activity in Android

Most likely as others have said you want to attach it to your Intent with putExtra. But I want to throw out there that depending on what your use case is, it may be better to have one activity that switches between two fragments. The data is stored in the activity and never has to be passed.

adb remount permission denied, but able to access super user in shell -- android

Some newer builds require the following additional adb commands to be run first

adb root
adb disable-verity
adb reboot

Then

adb root
adb remount

else & elif statements not working in Python

 if guess == number:
     print ("Good")
 elif guess == 2:
     print ("Bad")
 else:
     print ("Also bad")

Make sure you have your identation right. The syntax is ok.

manage.py runserver

You need to tell manage.py the local ip address and the port to bind to. Something like python manage.py runserver 192.168.23.12:8000. Then use that same ip and port from the other machine. You can read more about it here in the documentation.

Compare two objects in Java with possible null values

For those on android, who can't use API 19's Objects.equals(str1, str2), there is this:

android.text.TextUtils.equals(str1, str2);

It is null safe. It rarely has to use the more expensive string.equals() method because identical strings on android almost always compare true with the "==" operand thanks to Android's String Pooling, and length checks are a fast way to filter out most mismatches.

Source Code:

/**
 * Returns true if a and b are equal, including if they are both null.
 * <p><i>Note: In platform versions 1.1 and earlier, this method only worked  well if
 * both the arguments were instances of String.</i></p>
 * @param a first CharSequence to check
 * @param b second CharSequence to check
 * @return true if a and b are equal
 */
public static boolean equals(CharSequence a, CharSequence b) {
    if (a == b) return true;
    int length;
    if (a != null && b != null && (length = a.length()) == b.length()) {
        if (a instanceof String && b instanceof String) {
            return a.equals(b);
        } else {
            for (int i = 0; i < length; i++) {
                if (a.charAt(i) != b.charAt(i)) return false;
            }
            return true;
        }
    }
    return false;
}

Implementing a Custom Error page on an ASP.Net website

<system.webServer>     
<httpErrors errorMode="DetailedLocalOnly">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
    </httpErrors>
</system.webServer>

How to parse data in JSON format?

For URL or file, use json.load(). For string with .json content, use json.loads().

#! /usr/bin/python

import json
# from pprint import pprint

json_file = 'my_cube.json'
cube = '1'

with open(json_file) as json_data:
    data = json.load(json_data)

# pprint(data)

print "Dimension: ", data['cubes'][cube]['dim']
print "Measures:  ", data['cubes'][cube]['meas']

How do I put two increment statements in a C++ 'for' loop?

for (int i = 0; i != 5; ++i, ++j) 
    do_something(i, j);

How to get option text value using AngularJS?

The best way is to use the ng-options directive on the select element.

Controller

function Ctrl($scope) {
  // sort options
  $scope.products = [{
    value: 'prod_1',
    label: 'Product 1'
  }, {
    value: 'prod_2',
    label: 'Product 2'
  }];   
}

HTML

<select ng-model="selected_product" 
        ng-options="product as product.label for product in products">           
</select>

This will bind the selected product object to the ng-model property - selected_product. After that you can use this:

<p>Ordered by: {{selected_product.label}}</p>

jsFiddle: http://jsfiddle.net/bmleite/2qfSB/

Button background as transparent

I achieved this with in XML with

android:background="@android:color/transparent"

Difference between Spring MVC and Spring Boot

  • Spring MVC is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with @Controller, where you implement methods you can access using different HTTP requests. It has an equivalent @RestController to implement REST-based APIs.
  • Spring boot is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under its umbrella, as spring-core, spring-data, spring-web (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on).

So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based production-ready project initializer. You might find useful visiting the Spring MVC tag wiki as well as the Spring Boot tag wiki in SO.

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

Make sure, that all of your class methods (updateVelocity, updatePosition, ...) take at least one positional argument, which is canonically named self and refers to the current instance of the class.

When you call particle.updateVelocity(), the called method implicitly gets an argument: the instance, here particle as first parameter.

Programmatically get own phone number in iOS

Update: capability appears to have been removed by Apple on or around iOS 4


Just to expand on an earlier answer, something like this does it for me:

NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];

Note: This retrieves the "Phone number" that was entered during the iPhone's iTunes activation and can be null or an incorrect value. It's NOT read from the SIM card.

At least that does in 2.1. There are a couple of other interesting keys in NSUserDefaults that may also not last. (This is in my app which uses a UIWebView)

WebKitJavaScriptCanOpenWindowsAutomatically
NSInterfaceStyle
TVOutStatus
WebKitDeveloperExtrasEnabledPreferenceKey

and so on.

Not sure what, if anything, the others do.

Serializing class instance to JSON

Python3.x

The best aproach I could reach with my knowledge was this.
Note that this code treat set() too.
This approach is generic just needing the extension of class (in the second example).
Note that I'm just doing it to files, but it's easy to modify the behavior to your taste.

However this is a CoDec.

With a little more work you can construct your class in other ways. I assume a default constructor to instance it, then I update the class dict.

import json
import collections


class JsonClassSerializable(json.JSONEncoder):

    REGISTERED_CLASS = {}

    def register(ctype):
        JsonClassSerializable.REGISTERED_CLASS[ctype.__name__] = ctype

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in self.REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = self.REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


JsonClassSerializable.register(C)


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


JsonClassSerializable.register(B)


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()

JsonClassSerializable.register(A)

A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
print(b.b)
print(b.c.a)

Edit

With some more of research I found a way to generalize without the need of the SUPERCLASS register method call, using a metaclass

import json
import collections

REGISTERED_CLASS = {}

class MetaSerializable(type):

    def __call__(cls, *args, **kwargs):
        if cls.__name__ not in REGISTERED_CLASS:
            REGISTERED_CLASS[cls.__name__] = cls
        return super(MetaSerializable, cls).__call__(*args, **kwargs)


class JsonClassSerializable(json.JSONEncoder, metaclass=MetaSerializable):

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        if isinstance(obj, JsonClassSerializable):
            jclass = {}
            jclass["name"] = type(obj).__name__
            jclass["dict"] = obj.__dict__
            return dict(_class_object=jclass)
        else:
            return json.JSONEncoder.default(self, obj)

    def json_to_class(self, dct):
        if '_set_object' in dct:
            return set(dct['_set_object'])
        elif '_class_object' in dct:
            cclass = dct['_class_object']
            cclass_name = cclass["name"]
            if cclass_name not in REGISTERED_CLASS:
                raise RuntimeError(
                    "Class {} not registered in JSON Parser"
                    .format(cclass["name"])
                )
            instance = REGISTERED_CLASS[cclass_name]()
            instance.__dict__ = cclass["dict"]
            return instance
        return dct

    def encode_(self, file):
        with open(file, 'w') as outfile:
            json.dump(
                self.__dict__, outfile,
                cls=JsonClassSerializable,
                indent=4,
                sort_keys=True
            )

    def decode_(self, file):
        try:
            with open(file, 'r') as infile:
                self.__dict__ = json.load(
                    infile,
                    object_hook=self.json_to_class
                )
        except FileNotFoundError:
            print("Persistence load failed "
                  "'{}' do not exists".format(file)
                  )


class C(JsonClassSerializable):

    def __init__(self):
        self.mill = "s"


class B(JsonClassSerializable):

    def __init__(self):
        self.a = 1230
        self.c = C()


class A(JsonClassSerializable):

    def __init__(self):
        self.a = 1
        self.b = {1, 2}
        self.c = B()


A().encode_("test")
b = A()
b.decode_("test")
print(b.a)
# 1
print(b.b)
# {1, 2}
print(b.c.a)
# 1230
print(b.c.c.mill)
# s

What is a callback function?

A callback is an idea of passing a function as a parameter to another function and have this one invoked once the process has completed.

If you get the concept of callback through awesome answers above, I recommend you should learn the background of its idea.

"What made them(Computer-Scientists) develop callback?" You might learn a problem, which is blocking.(especially blocking UI) And callback is not the only solution to it. There are a lot of other solutions(ex: Thread, Futures, Promises...).

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

As suggested by others,

android.enableAapt2=false

is the most common solution.

But in my case, the error was due different versions in compileSdkVersion and buildToolsVersion.

Make sure that the major version is maintained the same.

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

The ActionBar will use the android:logo attribute of your manifest, if one is provided. That lets you use separate drawable resources for the icon (Launcher) and the logo (ActionBar, among other things).

Django optional url parameters

Django = 2.2

urlpatterns = [
    re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

How to find Oracle Service Name

Connect to the database with the "system" user, and execute the following command:

show parameter service_name 

How can I divide two integers stored in variables in Python?

if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b

Try float(a)/b

Checking if object is empty, works with ng-show but not from controller?

you can check length of items

ng-show="items.length"

How to debug a bash script?

You can also write "set -x" within the script.

Checking if a SQL Server login already exists

This works on SQL Server 2000.

use master
select count(*) From sysxlogins WHERE NAME = 'myUsername'

on SQL 2005, change the 2nd line to

select count(*) From syslogins WHERE NAME = 'myUsername'

I'm not sure about SQL 2008, but I'm guessing that it will be the same as SQL 2005 and if not, this should give you an idea of where t start looking.

How to count lines in a document?

cat file.log | wc -l | grep -oE '\d+'
  • grep -oE '\d+': In order to return the digit numbers ONLY.

How to restart counting from 1 after erasing table in MS Access?

In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.

Set opacity of background image without affecting child elements

If you have to set the opacity only to the bullet, why don't you set the alpha channel directly into the image? By the way I don't think there is a way to set the opacity to a background image via css without changing the opacity of the whole element (and its children too).

How to get certain commit from GitHub project

The easiest way that I found to recover a lost commit (that only exists on github and not locally) is to create a new branch that includes this commit.

  1. Have the commit open (url like: github.com/org/repo/commit/long-commit-sha)
  2. Click "Browse Files" on the top right
  3. Click the dropdown "Tree: short-sha..." on the top left
  4. Type in a new branch name
  5. git pull the new branch down to local

php exec command (or similar) to not wait for result

You can run the command in the background by adding a & at the end of it as:

exec('run_baby_run &');

But doing this alone will hang your script because:

If a program is started with exec function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So you can redirect the stdout of the command to a file, if you want to see it later or to /dev/null if you want to discard it as:

exec('run_baby_run > /dev/null &');

Temporary tables in stored procedures

For short: No


Explanation:

According to the official docs: https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver15

If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb is made up of the table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, table_name specified for a local temporary name cannot exceed 116 characters.

Using Python's os.path, how do I go up one directory?

With using os.path we can go one directory up like that

one_directory_up_path = os.path.dirname('.')

also after finding the directory you want you can join with other file/directory path

other_image_path = os.path.join(one_directory_up_path, 'other.jpg')

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Using npm behind corporate proxy .pac

I solved this problem this way:

1) I run this command:

npm config set strict-ssl false

2) Then set npm to run with http, instead of https:

npm config set registry "http://registry.npmjs.org/"

3) Then install your package

npm install <package name>

Same font except its weight seems different on different browsers

I don't think using "points" for font-size on a screen is a good idea. Try using px or em on font-size.

From W3C:

Do not specify the font-size in pt, or other absolute length units. They render inconsistently across platforms and can't be resized by the User Agent (e.g browser).

Can I change the fill color of an svg path with CSS?

Put in all your svg:

fill="var(--svgcolor)"

In Css:

:root {
  --svgcolor: tomato;
}

To use pseudo-classes:

span.github:hover {
  --svgcolor:aquamarine;
}

Explanation

root = html page.
--svgcolor = a variable.
span.github = selecting a span element with a class github, a svg icon inside and assigning pseudo-class hover.

Java ArrayList clear() function

it's not true the clear() function clear the Arraylist and start from index 0

What is a vertical tab?

I believe it's still being used, not sure exactly. There might be even a key combination of it.

As English is written Left to Right, Arabic Right to Left, there are languages in world that are also written top to bottom. In that case a vertical tab might be useful same as the horizontal tab is used for English text.

I tried searching, but couldn't find anything useful yet.

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

There is an easy way with Sharpeserializer (open source) :

http://www.sharpserializer.com/

It can directly serialize/de-serialize dictionary.

There is no need to mark your object with any attribute, nor do you have to give the object type in the Serialize method (See here ).

To install via nuget : Install-package sharpserializer

Then it is very simple :

Hello World (from the official website):

// create fake obj
var obj = createFakeObject();

// create instance of sharpSerializer
// with standard constructor it serializes to xml
var serializer = new SharpSerializer();

// serialize
serializer.Serialize(obj, "test.xml");

// deserialize
var obj2 = serializer.Deserialize("test.xml");

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

What is the difference between “int” and “uint” / “long” and “ulong”?

u means unsigned, so ulong is a large number without sign. You can store a bigger value in ulong than long, but no negative numbers allowed.

A long value is stored in 64-bit,with its first digit to show if it's a positive/negative number. while ulong is also 64-bit, with all 64 bit to store the number. so the maximum of ulong is 2(64)-1, while long is 2(63)-1.

SystemError: Parent module '' not loaded, cannot perform relative import

I usually use this workaround:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.