Programs & Examples On #Build

The process of converting source code files into standalone software artifact(s) that can be run on a computer

Xcode warning: "Multiple build commands for output file"

I found a pretty easy solution for this:

  1. Select the file causing the problem from the project navigator
  2. Uncheck the target membership from the file inspector
  3. Build the project
  4. Recheck the target membership for the file again

The warning is gone! Check this image for reference.

enter image description here

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

How/When does Execute Shell mark a build as failure in Jenkins?

In Jenkins ver. 1.635, it is impossible to show a native environment variable like this:

$BUILD_NUMBER or ${BUILD_NUMBER}

In this case, you have to set it in an other variable.

set BUILDNO = $BUILD_NUMBER
$BUILDNO

Component is part of the declaration of 2 modules

In this scenario, create another shared module in that import all the component which is being used in multiple module.

In shared component. declare those component. And then import shared module in appmodule as well as in other module where you want to access. It will work 100% , I did this and got it working.

@NgModule({
    declarations: [HeaderComponent, NavigatorComponent],
    imports: [
        CommonModule, BrowserModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        FormsModule,
    ] 
})
export class SharedmoduleModule { }
const routes: Routes = [
{
    path: 'Parent-child-relationship',
    children: [
         { path: '', component: HeaderComponent },
         { path: '', component: ParrentChildComponent }
    ]
}];
@NgModule({
    declarations: [ParrentChildComponent, HeaderComponent],
    imports: [ RouterModule.forRoot(routes), CommonModule, SharedmoduleModule ],
    exports: [RouterModule]
})
export class TutorialModule {
}
imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    MatInputModule,
    MatButtonModule,
    MatSelectModule,
    MatIconModule,
    SharedmoduleModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

How do I add a new sourceset to Gradle?

The nebula-facet plugin eliminates the boilerplate:

apply plugin: 'nebula.facet'
facets {
    integrationTest {
        parentSourceSet = 'test'
    }
}

For integration tests specifically, even this is done for you, just apply:

apply plugin: 'nebula.integtest'

The Gradle plugin portal links for each are:

  1. nebula.facet
  2. nebula.integtest

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

Gradle does not find tools.jar

In my case (Windows 10) after Java update I lost my Enviroment Variables, so I fixed added the variables again, based in the following steps https://confluence.atlassian.com/doc/setting-the-java_home-variable-in-windows-8895.html

How do I get Maven to use the correct repositories?

By default, Maven will always look in the official Maven repository, which is http://repo1.maven.org.

When Maven tries to build a project, it will look in your local repository (by default ~/.m2/repository but you can configure it by changing the <localRepository> value in your ~/.m2/settings.xml) to find any dependency, plugin or report defined in your pom.xml. If the adequate artifact is not found in your local repository, it will look in all external repositories configured, starting with the default one, http://repo1.maven.org.

You can configure Maven to avoid this default repository by setting a mirror in your settings.xml file:

<mirrors>
    <mirror>
        <id>repoMirror</id>
        <name>Our mirror for Maven repository</name>
        <url>http://the/server/</url>
        <mirrorOf>*</mirrorOf>
    </mirror>
</mirrors>

This way, instead of contacting http://repo1.maven.org, Maven will contact your entreprise repository (http://the/server in this example).

If you want to add another repository, you can define a new one in your settings.xml file:

<profiles>
    <profile>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <repositories>
            <repository>
                <id>foo.bar</id>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
                <url>http://new/repository/server</url>
            </repository>
        </repositories>

You can see the complete settings.xml model here.

Concerning the clean process, you can ask Maven to run it offline. In this case, Maven will not try to reach any external repositories:

mvn -o clean 

The project cannot be built until the build path errors are resolved.

None of the other answers worked for me. Even after fixing my build path issues, doing a refresh, clean, rebuild, and restart (of both eclipse and the computer), I was still getting the little red exclamation point.

I fixed it by closing the project (right-click, close project) and reopening it (double-click the closed project), which seemed to force eclipse to "notice" that the build path problems had been corrected.

NoClassDefFoundError - Eclipse and Android

I'm not sure if this is related, or if you're even still looking for an answer, but I came across this thread while trying to research the same error (but possibly for different reasons).

I couldn't find any solutions online, but an answer on a similar thread got me thinking and realized I probably just needed to rebuild (or clean) the project.

In Eclipse, go to Project => Clean. Select your project and Eclipse seemed to fix it itself. For me this solved the problem.

Hope this helps.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Changing the version of the support library of the last one enabled (28.0.0) by the previous (27.1.0), the error Android Resource Linking Failed disappeared.

It should be noted that version 27.1.0 is the maximum allowed in our implementations, which works, but you could use an older one if you wish. And this has to be used in all dependencies that start with the string com.android.support:

project/app/build.gradle

implementation "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
implementation "com.android.support:support-v4:$rootProject.supportLibraryVersion"

project/build.gradle

ext {
    supportLibraryVersion= '27.1.0'
}

Then, Sync Project with Gradle Files

GL

Docker and securing passwords

While I totally agree there is no simple solution. There continues to be a single point of failure. Either the dockerfile, etcd, and so on. Apcera has a plan that looks like sidekick - dual authentication. In other words two container cannot talk unless there is a Apcera configuration rule. In their demo the uid/pwd was in the clear and could not be reused until the admin configured the linkage. For this to work, however, it probably meant patching Docker or at least the network plugin (if there is such a thing).

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

Node package ( Grunt ) installed but not available

If you did have installed Grunt package by running npm install -g grunt and it still say's No command 'grunt' found or grunt: command not found, a quick and dirty way to get this working is linking node binaries to your $PATH manually.

On MacOSX/Linux you can add this line to your ~/.bash_profile or ~/.bashrc file.

PATH=$PATH:/usr/local/Cellar/node/HEAD/bin # Add NPM binaries

You probably should replace /usr/local/Cellar/node/HEAD/bin by the path where your node binaries could be found.

If this is quick and dirty to me, it's because everything should work without doing this, but for an unknown reason, a link seem broken. As nobody on IRC could tell me why this happened, I found my own way to make it (grunt) work.

PS: This should help you make grunt works, this answer is not jquery-ui related.

Update 02/2013 : You should take a look at @tom-p's answer which explains better what is going on. Tom gives us the real solution instead of hacking your bashrc file : both should work, but you should try installing grunt-cli first.

Unable to locate tools.jar

it has been solved with me in windows os by setting the JAVA_HOME variable before running as follows:

set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_111

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had this too and you can fix it by setting the tools version in your build definition.

This is very easy to do. Open your build definition and go to the "Process" page. Then under the "3. Advanced" group you have a property called "MSBuild Arguments". Place the parameter there with the following syntax

/p:VisualStudioVersion=12.0 

If you have more parameters, separate them with a space and not a comma.

docker build with --build-arg with multiple arguments

It's a shame that we need multiple ARG too, it results in multiple layers and slows down the build because of that, and for anyone also wondering that, currently there is no way to set multiple ARGs.

How is "mvn clean install" different from "mvn install"?

Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

So In my case, After trying all the above options, I realized it was VPN (company firewall).once connected and ran cmd: clean install spring-boot:run. Issue is resolved. Step 1: check maven is configured correctly or not. Step 2: check settings.xml is mapped correctly or not. Step 3: verify if you are behind any firewall then map your repo urls accordingly. Step 4:run clean install spring-boot:run step 5: issue is resolved.

Maven: add a dependency to a jar by relative path

This is another method in addition to my previous answer at Can I add jars to maven 2 build classpath without installing them?

This will get around the limit when using multi-module builds especially if the downloaded JAR is referenced in child projects outside of the parent. This also reduces the setup work by creating the POM and the SHA1 files as part of the build. It also allows the file to reside anywhere in the project without fixing the names or following the maven repository structure.

This uses the maven-install-plugin. For this to work, you need to set up a multi-module project and have a new project representing the build to install files into the local repository and ensure that one is first.

You multi-module project pom.xml would look like this:

<packaging>pom</packaging>
<modules>
<!-- The repository module must be first in order to ensure
     that the local repository is populated -->
    <module>repository</module>
    <module>... other modules ...</module>
</modules>

The repository/pom.xml file will then contain the definitions to load up the JARs that are part of your project. The following are some snippets of the pom.xml file.

<artifactId>repository</artifactId>
<packaging>pom</packaging>

The pom packaging prevents this from doing any tests or compile or generating any jar file. The meat of the pom.xml is in the build section where the maven-install-plugin is used.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <executions>
                <execution>
                        <id>com.ibm.db2:db2jcc</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>install-file</goal>
                        </goals>
                        <configuration>
                            <groupId>com.ibm.db2</groupId>
                            <artifactId>db2jcc</artifactId>
                            <version>9.0.0</version>
                            <packaging>jar</packaging>
                            <file>${basedir}/src/jars/db2jcc.jar</file>
                            <createChecksum>true</createChecksum>
                            <generatePom>true</generatePom>
                        </configuration>
                </execution>
                <execution>...</execution>
            </executions>
        </plugin>
    </plugins>
</build>

To install more than one file, just add more executions.

Go build: "Cannot find package" (even though GOPATH is set)

Although the accepted answer is still correct about needing to match directories with package names, you really need to migrate to using Go modules instead of using GOPATH. New users who encounter this problem may be confused about the mentions of using GOPATH (as was I), which are now outdated. So, I will try to clear up this issue and provide guidance associated with preventing this issue when using Go modules.

If you're already familiar with Go modules and are experiencing this issue, skip down to my more specific sections below that cover some of the Go conventions that are easy to overlook or forget.

This guide teaches about Go modules: https://golang.org/doc/code.html

Project organization with Go modules

Once you migrate to Go modules, as mentioned in that article, organize the project code as described:

A repository contains one or more modules. A module is a collection of related Go packages that are released together. A Go repository typically contains only one module, located at the root of the repository. A file named go.mod there declares the module path: the import path prefix for all packages within the module. The module contains the packages in the directory containing its go.mod file as well as subdirectories of that directory, up to the next subdirectory containing another go.mod file (if any).

Each module's path not only serves as an import path prefix for its packages, but also indicates where the go command should look to download it. For example, in order to download the module golang.org/x/tools, the go command would consult the repository indicated by https://golang.org/x/tools (described more here).

An import path is a string used to import a package. A package's import path is its module path joined with its subdirectory within the module. For example, the module github.com/google/go-cmp contains a package in the directory cmp/. That package's import path is github.com/google/go-cmp/cmp. Packages in the standard library do not have a module path prefix.

You can initialize your module like this:

$ go mod init github.com/mitchell/foo-app

Your code doesn't need to be located on github.com for it to build. However, it's a best practice to structure your modules as if they will eventually be published.

Understanding what happens when trying to get a package

There's a great article here that talks about what happens when you try to get a package or module: https://medium.com/rungo/anatomy-of-modules-in-go-c8274d215c16 It discusses where the package is stored and will help you understand why you might be getting this error if you're already using Go modules.

Ensure the imported function has been exported

Note that if you're having trouble accessing a function from another file, you need to ensure that you've exported your function. As described in the first link I provided, a function must begin with an upper-case letter to be exported and made available for importing into other packages.

Names of directories

Another critical detail (as was mentioned in the accepted answer) is that names of directories are what define the names of your packages. (Your package names need to match their directory names.) You can see examples of this here: https://medium.com/rungo/everything-you-need-to-know-about-packages-in-go-b8bac62b74cc With that said, the file containing your main method (i.e., the entry point of your application) is sort of exempt from this requirement.

As an example, I had problems with my imports when using a structure like this:

/my-app
+-- go.mod
+-- /src
   +-- main.go
   +-- /utils
      +-- utils.go

I was unable to import the code in utils into my main package.

However, once I put main.go into its own subdirectory, as shown below, my imports worked just fine:

/my-app
+-- go.mod
+-- /src
   +-- /app
   |  +-- main.go
   +-- /utils
      +-- utils.go

In that example, my go.mod file looks like this:

module git.mydomain.com/path/to/repo/my-app

go 1.14

When I saved main.go after adding a reference to utils.MyFunction(), my IDE automatically pulled in the reference to my package like this:

import "git.mydomain.com/path/to/repo/my-app/src/my-app"

(I'm using VS Code with the Golang extension.)

Notice that the import path included the subdirectory to the package.

Dealing with a private repo

If the code is part of a private repo, you need to run a git command to enable access. Otherwise, you can encounter other errors This article mentions how to do that for private Github, BitBucket, and GitLab repos: https://medium.com/cloud-native-the-gathering/go-modules-with-private-git-repositories-dfe795068db4 This issue is also discussed here: What's the proper way to "go get" a private repository?

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I've updated com.google.gms:google-services from 3.1.1 to 3.2.0 and the warning stopped appearing.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

    classpath 'com.google.gms:google-services:3.2.0'
    }
}

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

<maven.compiler.release> (not source & target)

Several of the other Answers show <maven.compiler.source> & <maven.compiler.target>. Both of these are now supplanted by the simpler single element: <maven.compiler.release>.

<maven.compiler.release>15</maven.compiler.release>

So this:

  <!--old-school-->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>15</maven.compiler.source>
    <maven.compiler.target>15</maven.compiler.target>
  </properties>

…becomes:

  <!--modern-->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.release>15</maven.compiler.release>
  </properties>

See Question, “maven.compiler.release” as an replacement for source and target?

How to read an external properties file in Maven

Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.

  <build>    
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>${basedir}/../project-parent/buildNumber.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
   </plugins>

How to compile Go program consisting of multiple files?

It depends on your project structure. But most straightforward is:

go build -o ./myproject ./...

then run ./myproject.

Suppose your project structure looks like this

- hello
|- main.go

then you just go to the project directory and run

go build -o ./myproject

then run ./myproject on shell.

or

# most easiest; builds and run simultaneously
go run main.go

suppose your main file is nested into a sub-directory like a cmd

- hello
|- cmd
 |- main.go

then you will run

go run cmd/main.go

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

How can I run multiple npm scripts in parallel?

From windows cmd you can use start:

"dev": "start npm run start-watch && start npm run wp-server"

Every command launched this way starts in its own window.

How can I change the app display name build with Flutter?

  • Review the default app manifest file, AndroidManifest.xml, located in <app dir>/android/app/src/main

  • Edit the android:label to your desired display name

How to build & install GLFW 3 and use it in a Linux project

The well-described answer is already there, but I went through this SHORTER recipe:

  1. Install Linuxbrew
  2. $ brew install glfw
  3. cd /home/linuxbrew/.linuxbrew/Cellar/glfw/X.X/include
  4. sudo cp -R GLFW /usr/include

Explanation: We manage to build GLFW by CMAKE which is done by Linuxbrew (Linux port of beloved Homebrew). Then copy the header files to where Linux reads from (/usr/include).

How to execute Ant build in command line

Try running all targets individually to check that all are running correct

run ant target name to run a target individually

e.g. ant build-project

Also the default target you specified is

project basedir="." default="build" name="iControlSilk4J"

This will only execute build-subprojects,build-project and init

How schedule build in Jenkins?

In the job configuration one can define various build triggers. With periodically build you can schedule the build by defining the date or day of the week and the time to execute the build.

The format is as follows:

MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)

The letter H, representing the word Hash can be inserted instead of any of the values, it will calculate the parameter based on the hash code of your project name, this is so that if you are building several projects on your build machine at the same time, lets say midnight each day, they do not all start there build execution at the same time, each project starts its execution at a different minute depending on its hash code. You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30

Examples:

start build daily at 08:30 in the morning, Monday - Friday:

  • 30 08 * * 1-5

weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday:

  • 00 0,12 * * 0-4

start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash:

  • H 16 * * 1-5

start build at midnight:

  • @midnight

or start build at midnight, every Saturday:

  • 59 23 * * 6

every first of every month between 2:00 a.m. - 02:30 a.m. :

  • H(0-30) 02 01 * *

more on CRON expressions

How to mark a build unstable in Jenkins when running shell scripts

One easy way to set a build as unstable, is in your "execute shell" block, run exit 13

How to compile multiple java source files in command line

Try the following:

javac file1.java file2.java

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

I found the solution. I misplaced the path to the keystore.jks file. Searched for the file on my computer used that path and everything worked great.

Where is Xcode's build folder?

With a project previously created in Xcode3, I see an intermediate directory under build/ called Foo.build where Foo is my project's name, and then in that are the directories you'd expect (Debug-iphonesimulator, Release-iphoneos, etc, assuming you've done a build of that type) containing the object files and products.

Now, I suspect that if you start a new project in Xcode4, the default location is under DerivedData, but if you open an Xcode3 project in Xcode4, then Xcode4 uses the build/ directory (as described above). So, there are several correct answers. :-) Under the File menu, Project Settings, you can see you can customize how XCode works in this regard as much or as little as you like.

NuGet auto package restore does not work with MSBuild

There is a packages.config file with the project, it contains the package details.

Also there is a .nuget folder which contains the NuGet.exe and NuGet.targets. if any one of the file is missing it will not restore the missing package and cause "are you missing a using directive or an assembly reference?" error

Build unsigned APK file with Android Studio

Just go to Your Application\app\build\outputs\apk

and copy both to phone and install app-debug.apk

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

In my case, the reason was a simple typo.

<parent>
    <groupId>org.sringframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>

A missing character in the groupId org.s(p)ringframework lead to this error.

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.

Module not found: Error: Can't resolve 'core-js/es6'

I found possible answer. You have core-js version 3.0, and this version doesn't have separate folders for ES6 and ES7; that's why the application cannot find correct paths.

To resolve this error, you can downgrade the core-js version to 2.5.7. This version produces correct catalogs structure, with separate ES6 and ES7 folders.

To downgrade the version, simply run:

npm i -S [email protected]

In my case, with Angular, this works ok.

Ant build failed: "Target "build..xml" does not exist"

I'm probably late but this worked for me:


  1. Open your build.xml file located in your project's directory.
  2. Copy and Paste the following code in the main project tag : <target name="build" />

Visual Studio "Could not copy" .... during build

@Gerard's answer was correct.

When clean+build has not resolved this problem for me, I have had success by doing the following:

Closing Visual Studio
Deleting the bin and obj folders, and
Reopening Visual Studio.

But I needed to do some extra work in console:

> Add-Migration Initial
> Update-Database

Then I started to debug and it worked.

error: This is probably not a problem with npm. There is likely additional logging output above

Delete node_module directory and run below in command line

rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
npm install

If still not working, try below

npm install webpack --save

Android Studio gradle takes too long to build

Following the steps will make it 10 times faster and reduce build time 90%

First create a file named gradle.properties in the following directory:

/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)

Add this line to the file:

org.gradle.daemon=true

org.gradle.parallel=true

What does the Visual Studio "Any CPU" target mean?

An AnyCPU assembly will JIT to 64-bit code when loaded into a 64-bit process and 32 bit when loaded into a 32-bit process.

By limiting the CPU you would be saying: There is something being used by the assembly (something likely unmanaged) that requires 32 bits or 64 bits.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

In my case, setting the 'Gradle version' same as the 'Android Plugin version' under File->Project Structure->Project fixed the issue for me.

error MSB6006: "cmd.exe" exited with code 1

For the sake of future readers. My problem was that I was specifying an incompatible openssl library to build my program through CMAKE. Projects were generated but build started failing with this error without any other useful information or error. Verbose cmake/compilation logs didn't help either.

My take away lesson is that cross check the incompatibilities in case your program has dependencies on the any other third party library.

How to change target build on Android project?

  1. You can change your the Build Target for your project at any time:

    Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.

  2. Edit the following elements in the AndroidManifest.xml file (it is in your project root directory)

    In this case, that will be:

    <uses-sdk android:minSdkVersion="3" />
    <uses-sdk android:targetSdkVersion="8" />
    

    Save it

  3. Rebuild your project.

    Click the Project on the menu bar, select Clean...

  4. Now, run the project again.

    Right Click Project name, move on Run as, and select Android Application

By the way, reviewing Managing Projects from Eclipse with ADT will be helpful. Especially the part called Creating an Android Project.

eclipse stuck when building workspace

Some time it's very helpful to execute eclipse from command line with "-clean" parameter to enforce it produce clean up for workspace.

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

CMake output/build directory

Turning my comment into an answer:

In case anyone did what I did, which was start by putting all the build files in the source directory:

cd src
cmake .

cmake will put a bunch of build files and cache files (CMakeCache.txt, CMakeFiles, cmake_install.cmake, etc) in the src dir.

To change to an out of source build, I had to remove all of those files. Then I could do what @Angew recommended in his answer:

mkdir -p src/build
cd src/build
cmake ..

AndroidStudio: Failed to sync Install build tools

problem:

Error:failed to find Build Tools revision 23.0.0 rc2

solution:

File > Project Structure > click on Modules > Properties
Change Build Tool Version to 23.0.1

its work for me

iOS - Build fails with CocoaPods cannot find header files

I've found that including the library as a pod install directly helps dynamic libraries. For example, for Firebase:

pod 'RNFirebase', :path => 'path/to/node_modules/react-native-firebase/ios'

Or for ASLogger:

pod 'ASLogger', :path => 'path/to/node_modules/aslogger/ios' // path to header files

Changing or hardcoding HEADER_SEARCH_PATHS did not help me. If the error ever recurs, it's not necessary to rm -rf node_modules nor delete the pod file etc, I found it useful to clear the cache.

For react-native, I run

    rm -rf $TMPDIR/react-native-packager-cache-*
    rm -rf $TMPDIR/metro-bundler-cache-*
    rm -rf $TMPDIR/metro-* 
    rm -rf $TMPDIR/react-* 
    rm -rf $TMPDIR/haste-*
    rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"
    npm start -- --reset-cache

For Xcode I remove folders in ~/Library/Developer/Xcode/DerivedData

Run a command shell in jenkins

Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"

*Don't write bin at the end

Xcode process launch failed: Security

"If you get this, the app has installed on your device. You have to tap the icon. It will ask you if you really want to run it. Say “yes” and then Build & Run again."

To add to that, this only holds true the moment you get the error, if you click OK, then tap on the app. It will do nothing. Scratched my head on that for 30 odd minutes, searching for alternative ways to address the problem.

What is a Maven artifact?

An artifact is a file, usually a JAR, that gets deployed to a Maven repository.

A Maven build produces one or more artifacts, such as a compiled JAR and a "sources" JAR.

Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version string. The three together uniquely identify the artifact.

A project's dependencies are specified as artifacts.

Why maven? What are the benefits?

Figuring out dependencies for small projects is not hard. But once you start dealing with a dependency tree with hundreds of dependencies, things can easily get out of hand. (I'm speaking from experience here ...)

The other point is that if you use an IDE with incremental compilation and Maven support (like Eclipse + m2eclipse), then you should be able to set up edit/compile/hot deploy and test.

I personally don't do this because I've come to distrust this mode of development due to bad experiences in the past (pre Maven). Perhaps someone can comment on whether this actually works with Eclipse + m2eclipse.

ERROR: Sonar server 'http://localhost:9000' can not be reached

You should configure the sonar-runner to use your existing SonarQube server. To do so, you need to update its conf/sonar-runner.properties file and specify the SonarQube server URL, username, password, and JDBC URL as well. See https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner for details.

If you don't yet have an up and running SonarQube server, then you can launch one locally (with the default configuration) - it will bind to http://localhost:9000 and work with the default sonar-runner configuration. See https://docs.sonarqube.org/latest/setup/get-started-2-minutes/ for details on how to get started with the SonarQube server.

ant warning: "'includeantruntime' was not set"

Chet Hosey wrote a nice explanation here:

Historically, Ant always included its own runtime in the classpath made available to the javac task. So any libraries included with Ant, and any libraries available to ant, are automatically in your build's classpath whether you like it or not.

It was decided that this probably wasn't what most people wanted. So now there's an option for it.

If you choose "true" (for includeantruntime), then at least you know that your build classpath will include the Ant runtime. If you choose "false" then you are accepting the fact that the build behavior will change between older versions and 1.8+.

As annoyed as you are to see this warning, you'd be even less happy if your builds broke entirely. Keeping this default behavior allows unmodified build files to work consistently between versions of Ant.

Trying to include a library, but keep getting 'undefined reference to' messages

If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in

extern "C" void foo();

What are the obj and bin folders (created by Visual Studio) used for?

I would encourage you to see this youtube video which demonstrates the difference between C# bin and obj folders and also explains how we get the benefit of incremental/conditional compilation.

C# compilation is a two-step process, see the below diagram for more details:

  1. Compiling: In compiling phase individual C# code files are compiled into individual compiled units. These individual compiled code files go in the OBJ directory.
  2. Linking: In the linking phase these individual compiled code files are linked to create single unit DLL and EXE. This goes in the BIN directory.

C# bin vs obj folders

If you compare both bin and obj directory you will find greater number of files in the "obj" directory as it has individual compiled code files while "bin" has a single unit.

bin vs obj

What is pluginManagement in Maven's pom.xml?

You still need to add

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
    </plugin>
</plugins>

in your build, because pluginManagement is only a way to share the same plugin configuration across all your project modules.

From Maven documentation:

pluginManagement: is an element that is seen along side plugins. Plugin Management contains plugin elements in much the same way, except that rather than configuring plugin information for this particular project build, it is intended to configure project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.

"make clean" results in "No rule to make target `clean'"

I suppose you have figured it out by now. The answer is hidden in your first mail itself.

The make command by default looks for makefile, Makefile, and GNUMakefile as the input file and you are having Makefile.txt in your folder. Just remove the file extension (.txt) and it should work.

Re-sign IPA (iPhone)

I think the easiest is to use Fastlane:

sudo gem install fastlane -NV
hash -r # for bash
rehash # for zsh
fastlane sigh resign ./path/app.ipa --signing_identity "Apple Distribution: Company Name" -p "my.mobileprovision"

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I was importing an Android application in Android Studio (Gradle version 2.10) from Eclipse. The drawable images are not supported, then manually remove those images and paste some PNG images.

And also update the Android drawable importer from the Android repository. Then clean and rebuild the application, and then it works.

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

For Iranian people: We need use proxy or VPN to building app.

Reason: The boycott by Google's servers causes that you can't build app or upgrade your requirement.

How to update maven repository in Eclipse?

Sometimes the dependencies don't update even with Maven->Update Project->Force Update option checked using m2eclipse plugin.

In case it doesn't work for anyone else, this method worked for me:

  • mvn eclipse:eclipse

    This will update your .classpath file with the new dependencies while preserving your .project settings and other eclipse config files.

If you want to clear your old settings for whatever reason, you can run:

  • mvn eclipse:clean
  • mvn eclipse:eclipse

    mvn eclipse:clean will erase your old settings, then mvn eclipse:eclipse will create new .project, .classpath and other eclipse config files.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

run gradle assembleDebug --scan in Android studio Terminal, in my case I removed an element in XML and forgotten to remove it from code, but the compiler couldn't compile and show Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details to me.

enter image description here

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

Xcode "Build and Archive" from command line

I have given a brief description of steps to follow, and parameters to pass while generating an ipa using terrminal below:

  1. Go to the folder which contains the MyApp.xcodeproject file in terminal

  2. By using the command given below you will get all the Targets of the application

    /usr/bin/xcodebuild -list 
    
  3. After the above command is executed, you will get a list of targets of which you should select a specific target you need to generate .ipa

    /usr/bin/xcodebuild -target $TARGET -sdk iphoneos -configuration Release
    
  4. The above command builds the project and creates a .app file.The path to locate the .app file is ./build/Release-iphoneos/MyApp.app

  5. After Build gets succeeded then execute the following command to generate .ipa of the application using Developer Name and Provisioning Profile using the syntax below:

    /usr/bin/xcrun -sdk iphoneos PackageApplication -v “${TARGET}.app” -o “${OUTDIR}/${TARGET}.ipa” –sign “${IDENTITY}” –embed “${PROVISONING_PROFILE}”
    

Explanation of each Parameter in the above syntax:

${TARGET}.app                == Target path (ex :/Users/XXXXXX/desktop/Application/build/Release-iphoneos/MyApp.app)
${OUTDIR}                    == Select the output directory(Where you want to save .ipa file)
${IDENTITY}                   == iPhone Developer: XXXXXXX (XXXXXXXXXX)(which can be obtained from Keychain access)
${PROVISONING_PROFILE}   == Path to the provisioning profile(/Users/XXXXXX/Library/MobileDevice/Provisioning Profiles/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.mobileprovision”)
  1. ipa will be generated at selected output directory "${OUTDIR}"

Bootstrap 3 select input form inline

I think I've accidentally found a solution. The only thing to do is inserting an empty <span class="input-group-addon"></span> between the <input> and the <select>.

Additionally you can make it "invisible" by reducing its width, horizontal padding and borders:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <span class="input-group-addon" title="* Price" id="priceLabel">Price</span>_x000D_
    <input type="number" id="searchbygenerals_priceFrom" name="searchbygenerals[priceFrom]" required="required" class="form-control" value="0">_x000D_
    <span class="input-group-addon">-</span>_x000D_
    <input type="number" id="searchbygenerals_priceTo" name="searchbygenerals[priceTo]" required="required" class="form-control" value="0">_x000D_
  _x000D_
    <!-- insert this line -->_x000D_
    <span class="input-group-addon" style="width:0px; padding-left:0px; padding-right:0px; border:none;"></span>_x000D_
  _x000D_
    <select id="searchbygenerals_currency" name="searchbygenerals[currency]" class="form-control">_x000D_
        <option value="1">HUF</option>_x000D_
        <option value="2">EUR</option>_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tested on Chrome and FireFox.

React.createElement: type is invalid -- expected a string

In my case I forgot to import and export my (new) elements called by the render in the index.js file.

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

How to change the integrated terminal in visual studio code or VSCode

Probably it is too late but the below thing worked for me:

  1. Open Settings --> this will open settings.json
  2. type terminal.integrated.windows.shell
  3. Click on {} at the top right corner -- this will open an editor where this setting can be over ridden.
  4. Set the value as terminal.integrated.windows.shell: C:\\Users\\<user_name>\\Softwares\\Git\\bin\\bash.exe
  5. Click Ctrl + S

Try to open new terminal. It should open in bash editor in integrated mode.

AngularJS : Why ng-bind is better than {{}} in angular?

ng-bind has its problems too.When you try to use angular filters, limit or something else, you maybe can have problem if you use ng-bind. But in other case, ng-bind is better in UX side.when user opens a page, he/she will see (10ms-100ms) that print symbols ( {{ ... }} ), that's why ng-bind is better.

Is there any way to prevent input type="number" getting negative values?

This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.

Markup:

<form>
  <input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
  <input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>

Javascript

$(document).ready(function() {
  $("input.positive-numeric-only").on("keydown", function(e) {
    var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
    if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
      e.preventDefault();
    }
  });

  $("input.positive-numeric-only").bind("paste", function(e) {
    var numbers = e.originalEvent.clipboardData
      .getData("text")
      .replace(/[^0-9^.^,]/g, "");
    e.preventDefault();
    var the_val = parseFloat(numbers);
    if (the_val > 0) {
      $(this).val(the_val.toFixed(2));
    }
  });

  $("input.positive-numeric-only").focusout(function(e) {
    if (!isNaN(this.value) && this.value.length != 0) {
      this.value = Math.abs(parseFloat(this.value)).toFixed(2);
    } else {
      this.value = 0;
    }
  });
});

Get multiple elements by Id

If you can change the markup, you might want to use class instead.

<!-- html -->
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

// javascript
var elements = document.getElementsByClassName("test");
var names = '';
for(var i=0; i<elements.length; i++) {
    names += elements[i].name;
}
document.write(names);

jsfiddle demo

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

The big thing to get your head around is that the File class tries to represent a view of what Sun like to call "hierarchical pathnames" (basically a path like c:/foo.txt or /usr/muggins). This is why you create files in terms of paths. The operations you are describing are all operations upon this "pathname".

  • getPath() fetches the path that the File was created with (../foo.txt)
  • getAbsolutePath() fetches the path that the File was created with, but includes information about the current directory if the path is relative (/usr/bobstuff/../foo.txt)
  • getCanonicalPath() attempts to fetch a unique representation of the absolute path to the file. This eliminates indirection from ".." and "." references (/usr/foo.txt).

Note I say attempts - in forming a Canonical Path, the VM can throw an IOException. This usually occurs because it is performing some filesystem operations, any one of which could fail.

How to grep (search) committed code in the Git history

For simplicity, I'd suggest using GUI: gitk - The Git repository browser. It's pretty flexible

  1. To search code:

    Enter image description here
  2. To search files:

    Enter image description here
  3. Of course, it also supports regular expressions:

    Enter image description here

And you can navigate through the results using the up/down arrows.

Close Current Tab

As of Chrome 46, a simple onclick=window.close() does the trick. This only closes the tab, and not the entire browser, if multiple tabs are opened.

How to use conditional breakpoint in Eclipse?

From Eclipsepedia on how to set a conditional breakpoint:

First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as list.size()==0. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.

Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.

How to read json file into java with simple JSON library

Hope this example helps too

I have done java coding in a similar way for the below json array example as follows :

following is the json data format : stored as "EMPJSONDATA.json"

[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},

{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},

{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}

{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]

public class Jsonminiproject {

public static void main(String[] args) {

      JSONParser parser = new JSONParser();

    try {
        JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
        for (Object o : a)
        {
            JSONObject employee = (JSONObject) o;

            Long no = (Long) employee.get("EMPNO");
            System.out.println("Employee Number : " + no);

            String st = (String) employee.get("EMP_NAME");
            System.out.println("Employee Name : " + st);

            String dob = (String) employee.get("DOB");
            System.out.println("Employee DOB : " + dob);

            String doj = (String) employee.get("DOJ");
            System.out.println("Employee DOJ : " + doj);

            String role = (String) employee.get("ROLE");
            System.out.println("Employee Role : " + role);

            System.out.println("\n");

        }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

}

Ansible - Use default if a variable is not defined

If anybody is looking for an option which handles nested variables, there are several such options in this github issue.

In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:

- hosts: 'localhost'
  tasks:
    - debug:
        msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"

or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.

How to change Status Bar text color in iOS

What I had to do for swift and navigation controller

extension UINavigationController {
    override open var preferredStatusBarStyle: UIStatusBarStyle {
       return .lightContent
    }   
}

What is the difference between buffer and cache memory in Linux?

Seth Robertson's Link 2 said "For thorough understanding of those terms, refer to Linux kernel book like Linux Kernel Development by Robert M. Love."

I found some contents about 'buffer' in the 2nd edition of the book.

Although the physical device itself is addressable at the sector level, the kernel performs all disk operations in terms of blocks.

When a block is stored in memory (say, after a read or pending a write), it is stored in a 'buffer'. Each 'buffer' is associated with exactly one block. The 'buffer' serves as the object that represents a disk block in memory.

A 'buffer' is the in-memory representation of a single physical disk block.

Block I/O operations manipulate a single disk block at a time. A common block I/O operation is reading and writing inodes. The kernel provides the bread() function to perform a low-level read of a single block from disk. Via 'buffers', disk blocks are mapped to their associated in-memory pages. "

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

There are two things I learned from this:

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

  2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

I hope this helps someone else!

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left

When should I really use noexcept?

This actually does make a (potentially) huge difference to the optimizer in the compiler. Compilers have actually had this feature for years via the empty throw() statement after a function definition, as well as propriety extensions. I can assure you that modern compilers do take advantage of this knowledge to generate better code.

Almost every optimization in the compiler uses something called a "flow graph" of a function to reason about what is legal. A flow graph consists of what are generally called "blocks" of the function (areas of code that have a single entrance and a single exit) and edges between the blocks to indicate where flow can jump to. Noexcept alters the flow graph.

You asked for a specific example. Consider this code:

void foo(int x) {
    try {
        bar();
        x = 5;
        // Other stuff which doesn't modify x, but might throw
    } catch(...) {
        // Don't modify x
    }

    baz(x); // Or other statement using x
}

The flow graph for this function is different if bar is labeled noexcept (there is no way for execution to jump between the end of bar and the catch statement). When labeled as noexcept, the compiler is certain the value of x is 5 during the baz function - the x=5 block is said to "dominate" the baz(x) block without the edge from bar() to the catch statement.

It can then do something called "constant propagation" to generate more efficient code. Here if baz is inlined, the statements using x might also contain constants and then what used to be a runtime evaluation can be turned into a compile-time evaluation, etc.

Anyway, the short answer: noexcept lets the compiler generate a tighter flow graph, and the flow graph is used to reason about all sorts of common compiler optimizations. To a compiler, user annotations of this nature are awesome. The compiler will try to figure this stuff out, but it usually can't (the function in question might be in another object file not visible to the compiler or transitively use some function which is not visible), or when it does, there is some trivial exception which might be thrown that you're not even aware of, so it can't implicitly label it as noexcept (allocating memory might throw bad_alloc, for example).

Writing to an Excel spreadsheet

  • xlrd/xlwt (standard): Python does not have this functionality in it's standard library, but I think of xlrd/xlwt as the "standard" way to read and write excel files. It is fairly easy to make a workbook, add sheets, write data/formulas, and format cells. If you need all of these things, you may have the most success with this library. I think you could choose openpyxl instead and it would be quite similar, but I have not used it.

    To format cells with xlwt, define a XFStyle and include the style when you write to a sheet. Here is an example with many number formats. See example code below.

  • Tablib (powerful, intuitive): Tablib is a more powerful yet intuitive library for working with tabular data. It can write excel workbooks with multiple sheets as well as other formats, such as csv, json, and yaml. If you don't need formatted cells (like background color), you will do yourself a favor to use this library, which will get you farther in the long run.

  • csv (easy): Files on your computer are either text or binary. Text files are just characters, including special ones like newlines and tabs, and can be easily opened anywhere (e.g. notepad, your web browser, or Office products). A csv file is a text file that is formatted in a certain way: each line is a list of values, separated by commas. Python programs can easily read and write text, so a csv file is the easiest and fastest way to export data from your python program into excel (or another python program).

    Excel files are binary and require special libraries that know the file format, which is why you need an additional library for python, or a special program like Microsoft Excel, Gnumeric, or LibreOffice, to read/write them.


import xlwt

style = xlwt.XFStyle()
style.num_format_str = '0.00E+00'

...

for i,n in enumerate(list1):
    sheet1.write(i, 0, n, fmt)

Zero an array in C code

int arr[20] = {0} would be easiest if it only needs to be done once.

How to change Apache Tomcat web server port number

Navigate to /tomcat-root/conf folder. Within you will find the server.xml file.

Open the server.xml in your preferred editor. Search the below similar statement (not exactly same as below will differ)

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

Going to give the port number to 9090

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

Save the file and restart the server. Now the tomcat will listen at port 9090

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

I had a case where I read from a handwritten json file. The json is perfect. However, this error occurred. So I write from a java object to json file, then read from that json file. things are fine. I could not see any difference between the handwritten json and the one from java object. Tried beyondCompare it sees no difference. I finally noticed the two file sizes are slightly different, and I used winHex tool and detected extra stuff. So the solution for my situation is, make copy of the good json file, paste content into it and use.

enter image description here

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

How to query first 10 rows and next time query other 10 rows from table

Ok. So I think you just need to implement Pagination.

$perPage = 10;

$pageNo = $_GET['page'];

Now find total rows in database.

$totalRows = Get By applying sql query;

$pages = ceil($totalRows/$perPage);    

$offset = ($pageNo - 1) * $perPage + 1

$sql = "SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT ".$offset." ,".$perPage

Iframe transparent background

Set the background color of the src to none and allow transparencey.

[WITHIN SCR PAGE STYLE]
<style type="text/css">
    body
    {
        background:none transparent;
    }
</style>

[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>

NOTE: I code my CSS a little different to how everyone else does.

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

Actually i think that you have downloaded just a part of the script. Try to check 'Core' checkbox before download the whole script in jquery site.

Using two CSS classes on one element

You can try this:

HTML

<div class="social">
    <div class="socialIcon"><img src="images/facebook.png" alt="Facebook" /></div>
    <div class="socialText">Find me on Facebook</div>
</div>

CSS CODE

.social {
  width:330px;
  height:75px;
  float:right;
  text-align:left;
  padding:10px 0;
  border-bottom:dotted 1px #6d6d6d;
}
.social .socialIcon{
  padding-top:0;
}
.social .socialText{
  border:0;
}

To add multiple class in the same element you can use the following format:

<div class="class1 class2 class3"></div>

DEMO

Xcode 9 error: "iPhone has denied the launch request"

The problem for me was that I was using a free developer account (simply signed in with my Apple ID). When looking at the device logs I found (bold added)

(RequestDenied); reason: "The request was denied by service delegate (SBMainWorkspace) for reason: Security ("Unable to launch {com.my.bundleID} because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user")"

That made me realize that I needed to go into Settings -> General -> Device Management -> {My Apple ID} -> Trust

After that, everything worked as expected.

In previous versions of iOS I would encounter a dialog on my device that would tell me that this was the problem. Maybe Apple took it out for iOS 11.

How to write to file in Ruby?

Are you looking for the following?

File.open(yourfile, 'w') { |file| file.write("your text") }

git visual diff between branches

If you use Eclipse you can visually compare your current branch on the workspace with another tag/branch:

Eclipse workspace compare

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

I used Laravel 8, This is my solution

Goto: storage/framework/cache/data
set permission directory data is 777

It's worked for me

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

resize2fs: Bad magic number in super-block while trying to open

os: rhel7

After gparted, # xfs_growfs /dev/mapper/rhel-root did the trick on a living system.

$ df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   47G   47G   20M 100% /
devtmpfs               1.9G     0  1.9G   0% /dev
tmpfs                  1.9G     0  1.9G   0% /dev/shm
tmpfs                  1.9G  9.3M  1.9G   1% /run
tmpfs                  1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1             1014M  205M  810M  21% /boot
tmpfs                  379M  8.0K  379M   1% /run/user/42
tmpfs                  379M     0  379M   0% /run/user/1000


# lvresize -l +100%FREE /dev/mapper/rhel-root
  Size of logical volume rhel/root changed from <47.00 GiB (12031 extents) to <77.00 GiB (19711 extents).
  Logical volume rhel/root successfully resized.


# xfs_growfs /dev/mapper/rhel-root
meta-data=/dev/mapper/rhel-root  isize=512    agcount=7, agsize=1900032 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=0 spinodes=0
data     =                       bsize=4096   blocks=12319744, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=3711, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 12319744 to 20184064


# df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   77G   47G   31G  62% /
devtmpfs               1.9G     0  1.9G   0% /dev
tmpfs                  1.9G     0  1.9G   0% /dev/shm
tmpfs                  1.9G  9.3M  1.9G   1% /run
tmpfs                  1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1             1014M  205M  810M  21% /boot
tmpfs                  379M  8.0K  379M   1% /run/user/42
tmpfs                  379M     0  379M   0% /run/user/1000

How to change text and background color?

SetConsoleTextAttribute.

HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);

This would produce red text on a white background.

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case, the error was triggered by duplicating an import of a component in the module.

Read .csv file in C

Thought I'd share this code. It's fairly simple, but effective. It parses comma-separated files with parenthesis. You can easily modify it to suit your needs.

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


int main(int argc, char *argv[])
{
  //argv[1] path to csv file
  //argv[2] number of lines to skip
  //argv[3] length of longest value (in characters)

  FILE *pfinput;
  unsigned int nSkipLines, currentLine, lenLongestValue;
  char *pTempValHolder;
  int c;
  unsigned int vcpm; //value character marker
  int QuotationOnOff; //0 - off, 1 - on

  nSkipLines = atoi(argv[2]);
  lenLongestValue = atoi(argv[3]);

  pTempValHolder = (char*)malloc(lenLongestValue);  

  if( pfinput = fopen(argv[1],"r") ) {

    rewind(pfinput);

    currentLine = 1;
    vcpm = 0;
    QuotationOnOff = 0;

    //currentLine > nSkipLines condition skips ignores first argv[2] lines
    while( (c = fgetc(pfinput)) != EOF)
    {
       switch(c)
       {
          case ',':
            if(!QuotationOnOff && currentLine > nSkipLines) 
            {
              pTempValHolder[vcpm] = '\0';
              printf("%s,",pTempValHolder);
              vcpm = 0;
            }
            break;
          case '\n':
            if(currentLine > nSkipLines)
            {
              pTempValHolder[vcpm] = '\0';
              printf("%s\n",pTempValHolder);
              vcpm = 0;
            }
            currentLine++;
            break;
          case '\"':
            if(currentLine > nSkipLines)
            {
              if(!QuotationOnOff) {
                QuotationOnOff = 1;
                pTempValHolder[vcpm] = c;
                vcpm++;
              } else {
                QuotationOnOff = 0;
                pTempValHolder[vcpm] = c;
                vcpm++;
              }
            }
            break;
          default:
            if(currentLine > nSkipLines)
            {
              pTempValHolder[vcpm] = c;
              vcpm++;
            }
            break;
       }
    }

    fclose(pfinput); 
    free(pTempValHolder);

  }

  return 0;
}

HTTP 404 when accessing .svc file in IIS

Adding the .svc suffix as allowed in request filtering did the trick for me.

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

How to embed small icon in UILabel

Your reference image looks like a button. Try (can also be done in Interface Builder):

enter image description here

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(50, 50, 100, 44)];
[button setImage:[UIImage imageNamed:@"img"] forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
[button setTitle:@"Abc" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor yellowColor]];
[view addSubview:button];

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

Replace get with jsonp:

 $http.jsonp('http://mywebservice').success(function ( data ) {
    alert(data);
    });
}

ARM compilation error, VFP registers used by executable, not object file

This is guesswork, but you may need to supply some or all of the floating point related switches for the link stage as well.

Iterate through Nested JavaScript Objects

modify from Peter Olson's answer: https://stackoverflow.com/a/8085118

  1. can avoid string value !obj || (typeof obj === 'string'
  2. can custom your key

var findObjectByKeyVal= function (obj, key, val) {
  if (!obj || (typeof obj === 'string')) {
    return null
  }
  if (obj[key] === val) {
    return obj
  }

  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      var found = findObjectByKeyVal(obj[i], key, val)
      if (found) {
        return found
      }
    }
  }
  return null
}

MySQL Great Circle Distance (Haversine formula)

I have had to work this out in some detail, so I'll share my result. This uses a zip table with latitude and longitude tables. It doesn't depend on Google Maps; rather you can adapt it to any table containing lat/long.

SELECT zip, primary_city, 
       latitude, longitude, distance_in_mi
  FROM (
SELECT zip, primary_city, latitude, longitude,r,
       (3963.17 * ACOS(COS(RADIANS(latpoint)) 
                 * COS(RADIANS(latitude)) 
                 * COS(RADIANS(longpoint) - RADIANS(longitude)) 
                 + SIN(RADIANS(latpoint)) 
                 * SIN(RADIANS(latitude)))) AS distance_in_mi
 FROM zip
 JOIN (
        SELECT  42.81  AS latpoint,  -70.81 AS longpoint, 50.0 AS r
   ) AS p 
 WHERE latitude  
  BETWEEN latpoint  - (r / 69) 
      AND latpoint  + (r / 69)
   AND longitude 
  BETWEEN longpoint - (r / (69 * COS(RADIANS(latpoint))))
      AND longpoint + (r / (69 * COS(RADIANS(latpoint))))
  ) d
 WHERE distance_in_mi <= r
 ORDER BY distance_in_mi
 LIMIT 30

Look at this line in the middle of that query:

    SELECT  42.81  AS latpoint,  -70.81 AS longpoint, 50.0 AS r

This searches for the 30 nearest entries in the zip table within 50.0 miles of the lat/long point 42.81/-70.81 . When you build this into an app, that's where you put your own point and search radius.

If you want to work in kilometers rather than miles, change 69 to 111.045 and change 3963.17 to 6378.10 in the query.

Here's a detailed writeup. I hope it helps somebody. http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

Where is the visual studio HTML Designer?

Another way of setting the default to the HTML web forms editor is:

  1. At the top menu in Visual Studio go to File > New > File
  2. Select HTML Page
  3. In the lower right corner of the New File dialog on the Open button there is a down arrow
  4. Click it and you should see an option Open With
  5. Select HTML (Web Forms) Editor
  6. Click Set as Default
  7. Press OK

Screenshot showing how to get to the "Open With" dialog box when creating a new file.

Postgres: How to convert a json string to text?

An easy way of doing this:

SELECT  ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;

Just convert the json string into a json list

File loading by getClass().getResource()

getClass().getResource() uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.

When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:

  • .java files are compiled into .class files that go the the bin directory (by default)
  • other files are copied to the bin directory (respecting the package/folder hirearchy)

When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource() or getResourceAsStream().

If it doesn't work from the command line, it's thus because the file is not in the classpath.

Note that you should NOT do

FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));

to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use

getClass().getResourceAsStream("Test.properties")

And finally, as the documentation indicates,

Foo.class.getResourceAsStream("Test.properties")

will load a Test.properties file located in the same package as the class Foo.

Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")

will load a Test.properties file located in the package com.foo.bar.

How to pick an image from gallery (SD Card) for my app?

public class BrowsePictureActivity extends Activity {
private static final int SELECT_PICTURE = 1;

private String selectedImagePath;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById(R.id.Button01))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {

                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,
                            "Select Picture"), SELECT_PICTURE);
                }
            });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
        }
    }
}

public String getPath(Uri uri) {

        if( uri == null ) {
            return null;
        }

        // this will only work for images selected from gallery
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }

        return uri.getPath();
}

}

How to get response status code from jQuery.ajax?

Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete() method of jquery ajax. I quote the notice on jquery website here:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

To know the status code of a ajax response, one can use the following code:

$.ajax( url [, settings ] )
.always(function (jqXHR) {
    console.log(jqXHR.status);
});

Works similarily for .done() and .fail()

HTML Input="file" Accept Attribute File Type (CSV)

In addition to the top-answer, CSV files, for example, are reported as text/plain under macOS but as application/vnd.ms-excel under Windows. So I use this:

<input type="file" accept="text/plain, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

How to start anonymous thread class

The entire new expression is an object reference, so methods can be invoked on it:

public class A {
    public static void main(String[] arg)
    {
        new Thread()
        {
            public void run() {
                System.out.println("blah");
            }
        }.start();
    }
}

What are .a and .so files?

.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.

.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).

How to do Base64 encoding in node.js?

crypto now supports base64 (reference):

cipher.final('base64') 

So you could simply do:

var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');

How can I check if an argument is defined when starting/calling a batch file?

The check for whether a commandline argument has been set can be [%1]==[], but, as Dave Costa points out, "%1"=="" will also work.

I also fixed a syntax error in the usage echo to escape the greater-than and less-than signs. In addition, the exit needs a /B argument otherwise CMD.exe will quit.

@echo off

if [%1]==[] goto usage
@echo This should not execute
@echo Done.
goto :eof
:usage
@echo Usage: %0 ^<EnvironmentName^>
exit /B 1

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Have a look at the content by type web part - http://codeplex.com/eoffice - probably the most flexible viewing web part.

How to extract multiple JSON objects from one file?

Added streaming support based on the answer of @dunes:

import re
from json import JSONDecoder, JSONDecodeError

NOT_WHITESPACE = re.compile(r"[^\s]")


def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
    buf = ""
    ex = None
    while True:
        block = file_obj.read(buf_size)
        if not block:
            break
        buf += block
        pos = 0
        while True:
            match = NOT_WHITESPACE.search(buf, pos)
            if not match:
                break
            pos = match.start()
            try:
                obj, pos = decoder.raw_decode(buf, pos)
            except JSONDecodeError as e:
                ex = e
                break
            else:
                ex = None
                yield obj
        buf = buf[pos:]
    if ex is not None:
        raise ex

Understanding __get__ and __set__ and Python descriptors

Why do I need the descriptor class?

It gives you extra control over how attributes work. If you're used to getters and setters in Java, for example, then it's Python's way of doing that. One advantage is that it looks to users just like an attribute (there's no change in syntax). So you can start with an ordinary attribute and then, when you need to do something fancy, switch to a descriptor.

An attribute is just a mutable value. A descriptor lets you execute arbitrary code when reading or setting (or deleting) a value. So you could imagine using it to map an attribute to a field in a database, for example – a kind of ORM.

Another use might be refusing to accept a new value by throwing an exception in __set__ – effectively making the "attribute" read only.

What is instance and owner here? (in __get__). What is the purpose of these parameters?

This is pretty subtle (and the reason I am writing a new answer here - I found this question while wondering the same thing and didn't find the existing answer that great).

A descriptor is defined on a class, but is typically called from an instance. When it's called from an instance both instance and owner are set (and you can work out owner from instance so it seems kinda pointless). But when called from a class, only owner is set – which is why it's there.

This is only needed for __get__ because it's the only one that can be called on a class. If you set the class value you set the descriptor itself. Similarly for deletion. Which is why the owner isn't needed there.

How would I call/use this example?

Well, here's a cool trick using similar classes:

class Celsius:

    def __get__(self, instance, owner):
        return 5 * (instance.fahrenheit - 32) / 9

    def __set__(self, instance, value):
        instance.fahrenheit = 32 + 9 * value / 5


class Temperature:

    celsius = Celsius()

    def __init__(self, initial_f):
        self.fahrenheit = initial_f


t = Temperature(212)
print(t.celsius)
t.celsius = 0
print(t.fahrenheit)

(I'm using Python 3; for python 2 you need to make sure those divisions are / 5.0 and / 9.0). That gives:

100.0
32.0

Now there are other, arguably better ways to achieve the same effect in python (e.g. if celsius were a property, which is the same basic mechanism but places all the source inside the Temperature class), but that shows what can be done...

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

How to git-cherry-pick only changes to certain files?

Perhaps the advantage of this method over Jefromi's answer is that you don't have to remember which behaviour of git reset is the right one :)

 # Create a branch to throw away, on which we'll do the cherry-pick:
 git checkout -b to-discard

 # Do the cherry-pick:
 git cherry-pick stuff

 # Switch back to the branch you were previously on:
 git checkout -

 # Update the working tree and the index with the versions of A and B
 # from the to-discard branch:
 git checkout to-discard -- A B

 # Commit those changes:
 git commit -m "Cherry-picked changes to A and B from [stuff]"

 # Delete the temporary branch:
 git branch -D to-discard

file_get_contents() Breaks Up UTF-8 Characters

I had a similar problem, what solved it was html_entity_decode.

My code is:

$content = file_get_contents("http://example.com/fr");
$x = new SimpleXMLElement($content);
foreach($x->channel->item as $entry) {
    $subEntry = html_entity_decode($entry->description);
}

In here I am retrieving an xml file (in French), that's why I'm using this $x object variable. And only then I decode it into this variable $subEntry.

I tried mb_convert_encoding but this didn't work for me.

Count how many files in directory PHP

Maybe usefull to someone. On a Windows system, you can let Windows do the job by calling the dir-command. I use an absolute path, like E:/mydir/mysubdir.

<?php 
$mydir='E:/mydir/mysubdir';
$dir=str_replace('/','\\',$mydir);
$total = exec('dir '.$dir.' /b/a-d | find /v /c "::"');

Regex (grep) for multi-line search needed

Your fundamental problem is that grep works one line at a time - so it cannot find a SELECT statement spread across lines.

Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.

I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.

In outline, for a single file:

$/ = "\n\n";    # Paragraphs

while (<>)
{
     if ($_ =~ m/SELECT.*customerName.*FROM/mi)
     {
         printf file name
         go to next file
     }
}

That needs to be wrapped into a sub that is then invoked by the methods of File::Find.

How to remove commits from a pull request

This is what helped me:

  1. Create a new branch with the existing one. Let's call the existing one branch_old and new as branch_new.

  2. Reset branch_new to a stable state, when you did not have any problem commit at all. For example, to put it at your local master's level do the following:

    git reset —hard master git push —force origin

  3. cherry-pick the commits from branch_old into branch_new

  4. git push

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

Where is my m2 folder on Mac OS X Mavericks

On the top of the screen you can find the Finder. Click Go -> Go to Folder -> search ~/.m2

If it is not found, as m2 is a hidden file you need to enable visibility by typing the following command in terminal:

defaults write com.apple.finder AppleShowAllFiles YES

Numpy first occurrence of value greater than existing value

In [34]: a=np.arange(-10,10)

In [35]: a
Out[35]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])

In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)

In [37]: np.where(a>5)[0][0]
Out[37]: 16

Remove the legend on a matplotlib figure

If you are not using fig and ax plot objects you can do it like so:

import matplotlib.pyplot as plt

# do plot specifics
plt.legend('')
plt.show()

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

Finding child element of parent pure javascript

You have a parent element, you want to get all child of specific attribute 1. get the parent 2. get the parent nodename by using parent.nodeName.toLowerCase() convert the nodename to lower case e.g DIV will be div 3. for further specific purpose, get an attribute of the parent e.g parent.getAttribute("id"). this will give you id of the parent 4. Then use document.QuerySelectorAll(paret.nodeName.toLowerCase()+"#"_parent.getAttribute("id")+" input " ); if you want input children of the parent node

_x000D_
_x000D_
let parent = document.querySelector("div.classnameofthediv")_x000D_
let parent_node = parent.nodeName.toLowerCase()_x000D_
let parent_clas_arr = parent.getAttribute("class").split(" ");_x000D_
let parent_clas_str = '';_x000D_
  parent_clas_arr.forEach(e=>{_x000D_
     parent_clas_str +=e+'.';_x000D_
  })_x000D_
let parent_class_name = parent_clas_str.substr(0, parent_clas_str.length-1)  //remove the last dot_x000D_
let allchild = document.querySelectorAll(parent_node+"."+parent_class_name+" input")
_x000D_
_x000D_
_x000D_

How to set a Postgresql default value datestamp like 'YYYYMM'?

It's a common misconception that you can denormalise like this for performance. Use date_trunc('month', date) for your queries and add an index expression for this if you find it running slow.

no pg_hba.conf entry for host

Verify the postgres connection hostname/address in pgadmin and use the same in your connection parameter.

DBI connect('database=chaosLRdb;host="keep what is mentioned" ;port=5433','postgres',...)

phpMyAdmin - config.inc.php configuration?

Run This Query:


*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
> 
> -- --------------------------------------------------------
> 
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin`   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> --    'pma'@localhost;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__bookmark`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__bookmark` (   `id` int(10) unsigned
> NOT NULL auto_increment,   `dbase` varchar(255) NOT NULL default '',  
> `user` varchar(255) NOT NULL default '',   `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '',   `query` text NOT NULL, 
> PRIMARY KEY  (`id`) )   COMMENT='Bookmarks'   DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__column_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__column_info` (   `id` int(5) unsigned
> NOT NULL auto_increment,   `db_name` varchar(64) NOT NULL default '', 
> `table_name` varchar(64) NOT NULL default '',   `column_name`
> varchar(64) NOT NULL default '',   `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `transformation` varchar(255)
> NOT NULL default '',   `transformation_options` varchar(255) NOT NULL
> default '',   `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',  
> PRIMARY KEY  (`id`),   UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) )   COMMENT='Column information
> for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__history`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__history` (   `id` bigint(20) unsigned
> NOT NULL auto_increment,   `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '',   `table` varchar(64) NOT NULL
> default '',   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP,   `sqlquery` text NOT NULL,   PRIMARY KEY  (`id`), 
> KEY `username` (`username`,`db`,`table`,`timevalue`) )   COMMENT='SQL
> history for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__pdf_pages`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` (   `db_name` varchar(64)
> NOT NULL default '',   `page_nr` int(10) unsigned NOT NULL
> auto_increment,   `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '',   PRIMARY KEY  (`page_nr`),   KEY `db_name`
> (`db_name`) )   COMMENT='PDF relation pages for phpMyAdmin'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__recent`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__recent` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Recently accessed tables'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__favorite`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__favorite` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Favorite tables'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_uiprefs`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` (   `username`
> varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,   `table_name`
> varchar(64) NOT NULL,   `prefs` text NOT NULL,   `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP,   PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__relation`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__relation` (   `master_db` varchar(64)
> NOT NULL default '',   `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '',   `foreign_db`
> varchar(64) NOT NULL default '',   `foreign_table` varchar(64) NOT
> NULL default '',   `foreign_field` varchar(64) NOT NULL default '',  
> PRIMARY KEY  (`master_db`,`master_table`,`master_field`),   KEY
> `foreign_field` (`foreign_db`,`foreign_table`) )   COMMENT='Relation
> table'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_coords`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_coords` (   `db_name`
> varchar(64) NOT NULL default '',   `table_name` varchar(64) NOT NULL
> default '',   `pdf_page_number` int(11) NOT NULL default '0',   `x`
> float unsigned NOT NULL default '0',   `y` float unsigned NOT NULL
> default '0',   PRIMARY KEY  (`db_name`,`table_name`,`pdf_page_number`)
> )   COMMENT='Table coordinates for phpMyAdmin PDF output'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_info` (   `db_name` varchar(64)
> NOT NULL default '',   `table_name` varchar(64) NOT NULL default '',  
> `display_field` varchar(64) NOT NULL default '',   PRIMARY KEY 
> (`db_name`,`table_name`) )   COMMENT='Table information for
> phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__tracking`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__tracking` (   `db_name` varchar(64)
> NOT NULL,   `table_name` varchar(64) NOT NULL,   `version` int(10)
> unsigned NOT NULL,   `date_created` datetime NOT NULL,  
> `date_updated` datetime NOT NULL,   `schema_snapshot` text NOT NULL,  
> `schema_sql` text,   `data_sql` longtext,   `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL,   `tracking_active`
> int(1) unsigned NOT NULL default '1',   PRIMARY KEY 
> (`db_name`,`table_name`,`version`) )   COMMENT='Database changes
> tracking for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__userconfig`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__userconfig` (   `username`
> varchar(64) NOT NULL,   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,   `config_data` text
> NOT NULL,   PRIMARY KEY  (`username`) )   COMMENT='User preferences
> storage for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__users`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__users` (   `username` varchar(64) NOT
> NULL,   `usergroup` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`usergroup`) )   COMMENT='Users and their assignments to
> user groups'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__usergroups`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__usergroups` (   `usergroup`
> varchar(64) NOT NULL,   `tab` varchar(64) NOT NULL,   `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N',   PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) )   COMMENT='User groups with configured
> menu items'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__navigationhiding`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` (   `username`
> varchar(64) NOT NULL,   `item_name` varchar(64) NOT NULL,  
> `item_type` varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,  
> `table_name` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )  
> COMMENT='Hidden items of navigation tree'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__savedsearches`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` (   `id` int(5)
> unsigned NOT NULL auto_increment,   `username` varchar(64) NOT NULL
> default '',   `db_name` varchar(64) NOT NULL default '',  
> `search_name` varchar(64) NOT NULL default '',   `search_data` text
> NOT NULL,   PRIMARY KEY  (`id`),   UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> )   COMMENT='Saved searches'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__central_columns`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__central_columns` (   `db_name`
> varchar(64) NOT NULL,   `col_name` varchar(64) NOT NULL,   `col_type`
> varchar(64) NOT NULL,   `col_length` text,   `col_collation`
> varchar(64) NOT NULL,   `col_isNull` boolean NOT NULL,   `col_extra`
> varchar(255) default '',   `col_default` text,   PRIMARY KEY
> (`db_name`,`col_name`) )   COMMENT='Central list of columns'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__designer_settings`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` (   `username`
> varchar(64) NOT NULL,   `settings_data` text NOT NULL,   PRIMARY KEY
> (`username`) )   COMMENT='Settings related to Designer'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__export_templates`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__export_templates` (   `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT,   `username` varchar(64) NOT NULL,  
> `export_type` varchar(10) NOT NULL,   `template_name` varchar(64) NOT
> NULL,   `template_data` text NOT NULL,   PRIMARY KEY (`id`),   UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> )   COMMENT='Saved export templates'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*

Open This File :

C:\xampp\phpMyAdmin\config.inc.php

Clear and Past this Code :

> --------------------------------------------------------- <?php /**  * Debian local configuration file  *  * This file overrides the settings
> made by phpMyAdmin interactive setup  * utility.  *  * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz  *  * NOTE:
> do not add security sensitive data to this file (like passwords)  *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still  * want to do this, make sure to properly secure the access to
> this file  * (also on the filesystem level).  */ /**  * Server(s)
> configuration  */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1].  Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
>     /* Authentication type */
>     $cfg['Servers'][$i]['auth_type'] = 'cookie';
>     /* Server parameters */
>     if (empty($dbserver)) $dbserver = 'localhost';
>     $cfg['Servers'][$i]['host'] = $dbserver;
>     if (!empty($dbport)) {
>         $cfg['Servers'][$i]['connect_type'] = 'tcp';
>         $cfg['Servers'][$i]['port'] = $dbport;
>     }
>     //$cfg['Servers'][$i]['compress'] = false;
>     /* Select mysqli if your server has it */
>     $cfg['Servers'][$i]['extension'] = 'mysqli';
>     /* Optional: User for advanced features */
>     $cfg['Servers'][$i]['controluser'] = $dbuser;
>     $cfg['Servers'][$i]['controlpass'] = $dbpass;
>     /* Optional: Advanced phpMyAdmin features */
>     $cfg['Servers'][$i]['pmadb'] = $dbname;
>     $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
>     $cfg['Servers'][$i]['relation'] = 'pma_relation';
>     $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
>     $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
>     $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
>     $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
>     $cfg['Servers'][$i]['history'] = 'pma_history';
>     $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
>     /* Uncomment the following to enable logging in to passwordless accounts,
>      * after taking note of the associated security risks. */
>     // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
>     /* Advance to next server for rest of config */
>     $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';  
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /*  * End of servers
> configuration  */ /*  * Directories for saving/loading files from
> server  */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';

------------------------------------------

i Solve My Problem Through this Method

Tooltip with HTML content without JavaScript

Using the title attribute:

_x000D_
_x000D_
<a href="#" title="Tooltip here">Link</a>
_x000D_
_x000D_
_x000D_

I cannot access tomcat admin console?

For me, it just was that service console restart didn't work after tomcat ran into an error. Only stop/start brought it back.

Play infinitely looping video on-load in HTML5

You can do this the following two ways:

1) Using loop attribute in video element (mentioned in the first answer):

2) and you can use the ended media event:

window.addEventListener('load', function(){
    var newVideo = document.getElementById('videoElementId');
    newVideo.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);

    newVideo.play();

});

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

Why?

You asked why it happens, let's see:

The official language specificaion dictates a call to the internal [[GetValue]] method. Your .attr returns undefined and you're trying to access its length.

If Type(V) is not Reference, return V.

This is true, since undefined is not a reference (alongside null, number, string and boolean)

Let base be the result of calling GetBase(V).

This gets the undefined part of myVar.length .

If IsUnresolvableReference(V), throw a ReferenceError exception.

This is not true, since it is resolvable and it resolves to undefined.

If IsPropertyReference(V), then

This happens since it's a property reference with the . syntax.

Now it tries to convert undefined to a function which results in a TypeError.

How to load specific image from assets with Swift

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :

"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!

In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.

Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."

Could not obtain information about Windows NT group user

I just got this error and it turns out my AD administrator deleted the service account used by EVERY SQL Server instance in the entire company. Thank goodness AD has its own recycle bin.

See if you can run the Active Directory Users and Computers utility (%SystemRoot%\system32\dsa.msc), and check to make sure the account you are relying on still exists.

How to make an app's background image repeat

There is a property in the drawable xml to do it. android:tileMode="repeat"

See this site: http://androidforbeginners.blogspot.com/2010/06/how-to-tile-background-image-in-android.html

Why are elementwise additions much faster in separate loops than in a combined loop?

It's because the CPU doesn't have so many cache misses (where it has to wait for the array data to come from the RAM chips). It would be interesting for you to adjust the size of the arrays continually so that you exceed the sizes of the level 1 cache (L1), and then the level 2 cache (L2), of your CPU and plot the time taken for your code to execute against the sizes of the arrays. The graph shouldn't be a straight line like you'd expect.

How to run SQL script in MySQL?

mysql -uusername -ppassword database-name < file.sql

How to substitute shell variables in complex text files

  1. Define your ENV variable
$ export MY_ENV_VAR=congratulation
  1. Create template file (in.txt) with following content
$MY_ENV_VAR

You can also use all other ENV variables defined by your system like (in linux) $TERM, $SHELL, $HOME...

  1. Run this command to raplace all env-variables in your in.txt file and to write the result to out.txt
$ envsubst "`printf '${%s} ' $(sh -c "env|cut -d'=' -f1")`" < in.txt > out.txt
  1. Check the content of out.txt file
$ cat out.txt

and you should see "congratulation".

maven error: package org.junit does not exist

if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

see JUNIT conflict

Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

So what is the URL that Yii::app()->params['pdfUrl'] gives? You say it should be https, but the log shows it's connecting on port 80... which almost no server is setup to accept https connections on. cURL is smart enough to know https should be on port 443... which would suggest that your URL has something wonky in it like: https://196.41.139.168:80/serve/?r=pdf/generatePdf

That's going to cause the connection to be terminated, when the Apache at the other end cannot do https communication with you on that port.

You realize your first $body definition gets replaced when you set $body to an array two lines later? {Probably just an artifact of you trying to solve the problem} You're also not encoding the client_url and client_id values (the former quite possibly containing characters that need escaping!) Oh and you're appending to $body_str without first initializing it.

From your verbose output we can see cURL is adding a content-length header, but... is it correct? I can see some comments out on the internets of that number being wrong (especially with older versions)... if that number was to small (for example) you'd get a connection-reset before all the data is sent. You can manually insert the header:

curl_setopt ($c, CURLOPT_HTTPHEADER, 
   array("Content-Length: ". strlen($body_str))); 

Oh and there's a handy function http_build_query that'll convert an array of name/value pairs into a URL encoded string for you.

All this rolls up into the final code:

$post=http_build_query(array(
  "client_url"=>Yii::app()->params['pdfClientURL'],
  "client_id"=>Yii::app()->params['pdfClientID'],
  "title"=>$title,
  "content"=>$content));

//Open to URL
$c=curl_init(Yii::app()->params['pdfUrl']);
//Send post
curl_setopt ($c, CURLOPT_POST, true);
//Optional: [try with/without]
curl_setopt ($c, CURLOPT_HTTPHEADER, array("Content-Length: ".strlen($post))); 
curl_setopt ($c, CURLOPT_POSTFIELDS, $post);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT  , 20);
//Collect result
$pdf = curl_exec ($c);
$curlInfo = curl_getinfo($c);
curl_close($c);

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

Get size of a View in React Native

You can directly use the Dimensions module and calc your views sizes. Actually, Dimensions give to you the main window sizes.

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

Hope to help you!

Update: Today using native StyleSheet with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...

Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components

Controlling a USB power supply (on/off) with Linux

USB 5v power is always on (even when the computer is turned off, on some computers and on some ports.) You will probably need to program an Arduino with some sort of switch, and control it via Serial library from USB plugged in to the computer.

In other words, a combination of this switch tutorial and this tutorial on communicating via Serial libary to Arduino plugged in via USB.

How to get full REST request body using Jersey?

You could use the @Consumes annotation to get the full body:

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

@Path("doc")
public class BodyResource
{
  @POST
  @Consumes(MediaType.APPLICATION_XML)
  public void post(Document doc) throws TransformerConfigurationException, TransformerException
  {
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.transform(new DOMSource(doc), new StreamResult(System.out));
  }
}

Note: Don't forget the "Content-Type: application/xml" header by the request.

Connection Strings for Entity Framework

First try to understand how Entity Framework Connection string works then you will get idea of what is wrong.

  1. You have two different models, Entity and ModEntity
  2. This means you have two different contexts, each context has its own Storage Model, Conceptual Model and mapping between both.
  3. You have simply combined strings, but how does Entity's context will know that it has to pickup entity.csdl and ModEntity will pickup modentity.csdl? Well someone could write some intelligent code but I dont think that is primary role of EF development team.
  4. Also machine.config is bad idea.
  5. If web apps are moved to different machine, or to shared hosting environment or for maintenance purpose it can lead to problems.
  6. Everybody will be able to access it, you are making it insecure. If anyone can deploy a web app or any .NET app on server, they get full access to your connection string including your sensitive password information.

Another alternative is, you can create your own constructor for your context and pass your own connection string and you can write some if condition etc to load defaults from web.config

Better thing would be to do is, leave connection strings as it is, give your application pool an identity that will have access to your database server and do not include username and password inside connection string.

Allow only numeric value in textbox using Javascript

Here is a solution which blocks all non numeric input from being entered into the text-field.

html

<input type="text" id="numbersOnly" />

javascript

var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};?

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

Extracting text OpenCV

This is a C# version of the answer from dhanushka using OpenCVSharp

        Mat large = new Mat(INPUT_FILE);
        Mat rgb = new Mat(), small = new Mat(), grad = new Mat(), bw = new Mat(), connected = new Mat();

        // downsample and use it for processing
        Cv2.PyrDown(large, rgb);
        Cv2.CvtColor(rgb, small, ColorConversionCodes.BGR2GRAY);

        // morphological gradient
        var morphKernel = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(3, 3));
        Cv2.MorphologyEx(small, grad, MorphTypes.Gradient, morphKernel);

        // binarize
        Cv2.Threshold(grad, bw, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);

        // connect horizontally oriented regions
        morphKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(9, 1));
        Cv2.MorphologyEx(bw, connected, MorphTypes.Close, morphKernel);

        // find contours
        var mask = new Mat(Mat.Zeros(bw.Size(), MatType.CV_8UC1), Range.All);
        Cv2.FindContours(connected, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));

        // filter contours
        var idx = 0;
        foreach (var hierarchyItem in hierarchy)
        {
            idx = hierarchyItem.Next;
            if (idx < 0)
                break;
            OpenCvSharp.Rect rect = Cv2.BoundingRect(contours[idx]);
            var maskROI = new Mat(mask, rect);
            maskROI.SetTo(new Scalar(0, 0, 0));

            // fill the contour
            Cv2.DrawContours(mask, contours, idx, Scalar.White, -1);

            // ratio of non-zero pixels in the filled region
            double r = (double)Cv2.CountNonZero(maskROI) / (rect.Width * rect.Height);
            if (r > .45 /* assume at least 45% of the area is filled if it contains text */
                 &&
            (rect.Height > 8 && rect.Width > 8) /* constraints on region size */
            /* these two conditions alone are not very robust. better to use something 
            like the number of significant peaks in a horizontal projection as a third condition */
            )
            {
                Cv2.Rectangle(rgb, rect, new Scalar(0, 255, 0), 2);
            }
        }

        rgb.SaveImage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rgb.jpg"));

How do I generate a stream from a string?

Here you go:

private Stream GenerateStreamFromString(String p)
{
    Byte[] bytes = UTF8Encoding.GetBytes(p);
    MemoryStream strm = new MemoryStream();
    strm.Write(bytes, 0, bytes.Length);
    return strm;
}

Unable to find velocity template resources

Great question - I solved my issue today as follows using Ecilpse:

  1. Put your template in the same folder hierarchy as your source code (not in a separate folder hierarchy even if you include it in the build path) as below: Where to put your template file

  2. In your code simply use the following lines of code (assuming you just want the date to be passed as data):

    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    VelocityContext context = new VelocityContext();
    context.put("date", getMyTimestampFunction());
    Template t = ve.getTemplate( "templates/email_html_new.vm" );
    StringWriter writer = new StringWriter();
    t.merge( context, writer );
    

See how first we tell VelocityEngine to look in the classpath. Without this it wouldn't know where to look.

Remove '\' char from string c#

Why not simply this?

resultString = Regex.Replace(subjectString, @"\\", "");

0xC0000005: Access violation reading location 0x00000000

This line looks suspicious:

invaders[i] = inv;

You're never incrementing i, so you keep assigning to invaders[0]. If this is just an error you made when reducing your code to the example, check how you calculate i in the real code; you could be exceeding the size of invaders.

If as your comment suggests, you're creating 55 invaders, then check that invaders has been initialised correctly to handle this number.

is python capable of running on multiple cores?

CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.

Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.

The usual recommendation is to use many processes rather than many threads.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

You can use method shown here and replace isNull with isnan:

from pyspark.sql.functions import isnan, when, count, col

df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
|      0|         0|  3|
+-------+----------+---+

or

df.select([count(when(isnan(c) | col(c).isNull(), c)).alias(c) for c in df.columns]).show()
+-------+----------+---+
|session|timestamp1|id2|
+-------+----------+---+
|      0|         0|  5|
+-------+----------+---+

List files with certain extensions with ls and grep

Here is one example that worked for me.

find <mainfolder path> -name '*myfiles.java' | xargs -n 1 basename

Find the directory part (minus the filename) of a full path in access 97

That's about it. There is no magic built-in function...

Pointer-to-pointer dynamic two-dimensional array

In both cases your inner dimension may be dynamically specified (i.e. taken from a variable), but the difference is in the outer dimension.

This question is basically equivalent to the following:

Is int* x = new int[4]; "better" than int x[4]?

The answer is: "no, unless you need to choose that array dimension dynamically."

Android EditText delete(backspace) key event

I sent 2 days to find a solution and I figured out a working one :) (on soft keys)

public TextWatcher textWatcher = new TextWatcher() {
@Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {   } 

@Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (count == 0) {
        //Put your code here.
        //Runs when delete/backspace pressed on soft key (tested on htc m8)
        //You can use EditText.getText().length() to make if statements here
        }
    }

@Override
    public void afterTextChanged(Editable s) {
    }
}

After add the textwatcher to your EditText:

yourEditText.addTextChangedListener(textWatcher);

I hope it works on another android devices too (samsung, LG, etc).

Why does range(start, end) not include end?

Basically in python range(n) iterates n times, which is of exclusive nature that is why it does not give last value when it is being printed, we can create a function which gives inclusive value it means it will also print last value mentioned in range.

def main():
    for i in inclusive_range(25):
        print(i, sep=" ")


def inclusive_range(*args):
    numargs = len(args)
    if numargs == 0:
        raise TypeError("you need to write at least a value")
    elif numargs == 1:
        stop = args[0]
        start = 0
        step = 1
    elif numargs == 2:
        (start, stop) = args
        step = 1
    elif numargs == 3:
        (start, stop, step) = args
    else:
        raise TypeError("Inclusive range was expected at most 3 arguments,got {}".format(numargs))
    i = start
    while i <= stop:
        yield i
        i += step


if __name__ == "__main__":
    main()

Setting Django up to use MySQL

  1. Install mysqlclient

sudo pip3 install mysqlclient

if you get error:

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-dbljg4tx/mysqlclient/

then:

 1. sudo apt install libmysqlclient-dev python-mysqldb

 2. sudo pip3 install mysqlclient

  1. Modify settings.py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'website',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': '127.0.0.1',
            'PORT': '3306',
            'OPTION': {'init_command':"SET sql_mode='STRICT_TRANS_TABLE',"},
        }
    }
    

How to listen for 'props' changes

@JoeSchr has an answer. Here is another way to do if you don't want deep: true

 mounted() {
    this.yourMethod();
    // re-render any time a prop changes
    Object.keys(this.$options.props).forEach(key => {
      this.$watch(key, this.yourMethod);
    });
  },

Unfortunately Launcher3 has stopped working error in android studio?

  1. Press the Apps menu button on your Android mobile phone device. It will display icons of all the apps installed on your mobile phone device. Press Settings.

  2. Press Apps. (Pressing on Apps button will list down all the apps installed on your mobile phone.

  3. Browse the Apps list and press on the app called "Launcher 3". (Launcher 3 is an app and it will be listed in the App list whenever you access Settings > Apps in your android phone).

  4. Pressing on the "Launcher 3" app will open the "App info screen" which will show some details pertaining to that app. On this App info screen, you will find buttons like "Force Stop", "Uninstall", "Clear Data" and "Clear Cache" etc.

  5. In Android Marshmallow (i.e. Android 6.0) choose Settings > Apps > Launcher3 > STORAGE. Press "Clear Cache". If this fails, press "Clear data". This will eventually restore functionality, but all custom shortcuts will be lost.

Restart the phone and its done. All the home screens along with app shortcuts will appear again and your mobile phone is at your service again.

I hope it explains well on how to solve the launcher problem in Android. Worked for me.

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

Can't find the 'libpq-fe.h header when trying to install pg gem

In my case it was package postgresql-server-dev-8.4 (I am on Ubuntu 11.04 (Natty Narwhal), 64 bits).

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Setting a system environment variable from a Windows batch file?

SetX is the command that you'll need in most of the cases.Though its possible to use REG or REGEDIT

Using registry editing commands you can avoid some of the restrictions of the SetX command - different data types, variables containing = in their name and so on.

@echo off

:: requires admin elevated permissions
::setting system variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v MyVar /D MyVal
::expandable variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /T REG_EXPAND_SZ /v MyVar /D MyVal


:: does not require admin permissions
::setting user variable
REG ADD "HKEY_CURRENT_USER\Environment" /v =C: /D "C:\\test"

REG is the pure registry client but its possible also to import the data with REGEDIT though it allows using only hard coded values (or generation of a temp files). The example here is a hybrid file that contains both batch code and registry data (should be saved as .bat - mind that in batch ; are ignored as delimiters while they are used as comments in .reg files):

REGEDIT4

; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"SystemVariable"="GlobalValue"

[HKEY_CURRENT_USER\Environment]
"UserVariable"="SomeValue"

MySQLi count(*) always returns 1

You have to fetch that one record, it will contain the result of Count()

$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

Slidedown and slideup layout with animation

I use these easy functions, it work like jquery slideUp slideDown, use it in an helper class, just pass your view :

public static void expand(final View v) {
    v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    final int targetHeight = v.getMeasuredHeight();

    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? WindowManager.LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

public static void collapse(final View v) {
    final int initialHeight = v.getMeasuredHeight();

    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if(interpolatedTime == 1){
                v.setVisibility(View.GONE);
            }else{
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

How to COUNT rows within EntityFramework without loading contents?

Well, even the SELECT COUNT(*) FROM Table will be fairly inefficient, especially on large tables, since SQL Server really can't do anything but do a full table scan (clustered index scan).

Sometimes, it's good enough to know an approximate number of rows from the database, and in such a case, a statement like this might suffice:

SELECT 
    SUM(used_page_count) * 8 AS SizeKB,
    SUM(row_count) AS [RowCount], 
    OBJECT_NAME(OBJECT_ID) AS TableName
FROM 
    sys.dm_db_partition_stats
WHERE 
    OBJECT_ID = OBJECT_ID('YourTableNameHere')
    AND (index_id = 0 OR index_id = 1)
GROUP BY 
    OBJECT_ID

This will inspect the dynamic management view and extract the number of rows and the table size from it, given a specific table. It does so by summing up the entries for the heap (index_id = 0) or the clustered index (index_id = 1).

It's quick, it's easy to use, but it's not guaranteed to be 100% accurate or up to date. But in many cases, this is "good enough" (and put much less burden on the server).

Maybe that would work for you, too? Of course, to use it in EF, you'd have to wrap this up in a stored proc or use a straight "Execute SQL query" call.

Marc

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

concatenate two strings

The best way in my eyes is to use the concat() method provided by the String class itself.

The useage would, in your case, look like this:

String myConcatedString = cursor.getString(numcol).concat('-').
       concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));

How to create a directory and give permission in single command

Don't do: mkdir -m 777 -p a/b/c since that will only set permission 777 on the last directory, c; a and b will be created with the default permission from your umask.

Instead to create any new directories with permission 777, run mkdir -p in a subshell where you override the umask:

(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)

Note that this won't change the permissions if any of a, b and c already exist though.

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

Python code to remove HTML tags from a string

There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

How do I remove the old history from a git repository?

Try this method How to truncate git history :

#!/bin/bash
git checkout --orphan temp $1
git commit -m "Truncated history"
git rebase --onto temp $1 master
git branch -D temp

Here $1 is SHA-1 of the commit you want to keep and the script will create new branch that contains all commits between $1 and master and all the older history is dropped. Note that this simple script assumes that you do not have existing branch called temp. Also note that this script does not clear the git data for old history. Run git gc --prune=all && git repack -a -f -F -d after you've verified that you truly want to lose all history. You may also need rebase --preserve-merges but be warned that the git implementation of that feature is not perfect. Inspect the results manually if you use that.

Execute a batch file on a remote PC using a batch file on local PC

Use microsoft's tool for remote commands executions: PsExec

If there isn't your bat-file on remote host, copy it first. For example:

copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\

And then execute:

psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat

Note: filepath for psexec is path to file on remote server, not your local.

Laravel 5 - How to access image uploaded in storage within View?

If you are on windows you can run this command on cmd:

mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars 

from: http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

How do I add options to a DropDownList using jQuery?

Add item to list in the begining

$("#ddlList").prepend('<option selected="selected" value="0"> Select </option>');

Add item to list in the end

$('<option value="6">Java Script</option>').appendTo("#ddlList");

Common Dropdown operation (Get, Set, Add, Remove) using jQuery

How do I get the name of a Ruby class?

In my case when I use something like result.class.name I got something like Module1::class_name. But if we only want class_name, use

result.class.table_name.singularize

Can I call an overloaded constructor from another constructor of the same class in C#?

No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example

class foo
{
    public foo(){}
    public foo(string s ) { }
    public foo (string s1, string s2) : this(s1) {....}

}

How to check whether the user uploaded a file in PHP?

In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully. https://www.php.net/manual/en/reserved.variables.files.php#109648

if ( boolval( $_FILES['image']['error'] === 0 ) ) {
    // ...
}

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

How to dismiss keyboard for UITextView with return key?

There is another solution while using with uitextview, You can add toolbar as InputAccessoryView in "textViewShouldBeginEditing", and from this toolbar's done button you can dismiss keyboard, the code for this is following:

In viewDidLoad

toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; //toolbar is uitoolbar object
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(btnClickedDone:)];
[toolBar setItems:[NSArray arrayWithObject:btnDone]];

In textviewdelegate method

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
     [textView setInputAccessoryView:toolBar];
     return YES;
}

In action of Button Done which is in toolbar is following:

-(IBAction)btnClickedDone:(id)sender
{
    [self.view endEditing:YES];
}

Changing font size and direction of axes text in ggplot2

Adding to previous solutions, you can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  theme_bw() +
  theme(axis.text.x=element_text(size=rel(0.5), angle=90))

opening a window form from another form programmatically

I would do it like this:

var form2 = new Form2();
form2.Show();

and to close current form I would use

this.Hide(); instead of

this.close();

check out this Youtube channel link for easy start-up tutorials you might find it helpful if u are a beginner

Java better way to delete file if exists

This is my solution:

File f = new File("file.txt");
if(f.exists() && !f.isDirectory()) { 
    f.delete();
}

'No JUnit tests found' in Eclipse

In Eclipse Photon you may need to add JUnit 4 or 5 to the build path. Right click @Test and select 'Add JUnit 4 to build path'.

In SQL, is UPDATE always faster than DELETE+INSERT?

I am afraid the body of your question is unrelated to title question.

If to answer the title:

In SQL, is UPDATE always faster than DELETE+INSERT?

then answer is NO!

Just google for

  • "Expensive direct update"* "sql server"
  • "deferred update"* "sql server"

Such update(s) result in more costly (more processing) realization of update through insert+update than direct insert+update. These are the cases when

  • one updates the field with unique (or primary) key or
  • when the new data does not fit (is bigger) in the pre-update row space allocated (or even maximum row size),resulting in fragmentation,
  • etc.

My fast (non-exhaustive) search, not pretending to be covering one, gave me [1], [2]

[1]
Update Operations
(Sybase® SQL Server Performance and Tuning Guide
Chapter 7: The SQL Server Query Optimizer)
http://www.lcard.ru/~nail/sybase/perf/11500.htm
[2]
UPDATE Statements May be Replicated as DELETE/INSERT Pairs
http://support.microsoft.com/kb/238254

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

Android Fragment no view found for ID?

I encountered this problem when I tried to replace view with my fragment in onCreateView(). Like this:

public class MyProjectListFrag extends Fragment {


    private MyProjectListFragment myProjectListFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        FragmentManager mFragmentManager = getFragmentManager();
        myProjectListFragment = new MyProjectListFragment();
        mFragmentManager
                .beginTransaction()
                .replace(R.id.container_for_my_pro_list,
                        myProjectListFragment, "myProjectListFragment")
                .commit();
    }

It told me

11-25 14:06:04.848: E/AndroidRuntime(26040): java.lang.IllegalArgumentException: No view found for id 0x7f05003f (com.example.myays:id/container_for_my_pro_list) for fragment MyProjectListFragment{41692f40 #2 id=0x7f05003f myProjectListFragment}

Then I fixed this issue with putting replace into onActivityCreated(). Like this:

public class MyProjectListFrag extends Fragment {

    private final static String TAG = "lch";

    private MyProjectListFragment myProjectListFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        return inflater
                .inflate(R.layout.frag_my_project_list, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        FragmentManager mFragmentManager = getFragmentManager();
        myProjectListFragment = new MyProjectListFragment();
        mFragmentManager
                .beginTransaction()
                .replace(R.id.container_for_my_pro_list,
                        myProjectListFragment, "myProjectListFragment")
                .commit();

    }
  1. You have to return a view in onCreateView() so that you can replace it later
  2. You can put any operation towards this view in the following function in fragment liftcycle, like onActivityCreated()

Hope this helps!

Getting query parameters from react-router hash fragment

You may get the following error while creating an optimized production build when using query-string module.

Failed to minify the code from this file: ./node_modules/query-string/index.js:8

To overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.

import querySearch from "stringquery";

var query = querySearch(this.props.location.search);

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

WAMP Cannot access on local network 403 Forbidden

I got this answer from here. and its works for me

Require local

Change to

Require all granted
Order Deny,Allow
Allow from all

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

If you use firebase, it will add NSAllowsArbitraryLoadsInWebContent = true in the NSAppTransportSecurity section, and NSAllowsArbitraryLoads = true will not work

How to save DataFrame directly to Hive?

For Hive external tables I use this function in PySpark:

def save_table(sparkSession, dataframe, database, table_name, save_format="PARQUET"):
    print("Saving result in {}.{}".format(database, table_name))
    output_schema = "," \
        .join(["{} {}".format(x.name.lower(), x.dataType) for x in list(dataframe.schema)]) \
        .replace("StringType", "STRING") \
        .replace("IntegerType", "INT") \
        .replace("DateType", "DATE") \
        .replace("LongType", "INT") \
        .replace("TimestampType", "INT") \
        .replace("BooleanType", "BOOLEAN") \
        .replace("FloatType", "FLOAT")\
        .replace("DoubleType","FLOAT")
    output_schema = re.sub(r'DecimalType[(][0-9]+,[0-9]+[)]', 'FLOAT', output_schema)

    sparkSession.sql("DROP TABLE IF EXISTS {}.{}".format(database, table_name))

    query = "CREATE EXTERNAL TABLE IF NOT EXISTS {}.{} ({}) STORED AS {} LOCATION '/user/hive/{}/{}'" \
        .format(database, table_name, output_schema, save_format, database, table_name)
    sparkSession.sql(query)
    dataframe.write.insertInto('{}.{}'.format(database, table_name),overwrite = True)

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

Python how to plot graph sine wave

Yet another way to plot the sine wave.

import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TKAgg (optional)
import matplotlib.pyplot as plt

t = np.linspace(0.0, 5.0, 50000)       # time axis
sig = np.sin(t)
plt.plot(t,sig)

Measure execution time for a Java method

Check this: System.currentTimeMillis.

With this you can calculate the time of your method by doing:

long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

What's the difference between returning value or Promise.resolve from then()

The rule is, if the function that is in the then handler returns a value, the promise resolves/rejects with that value, and if the function returns a promise, what happens is, the next then clause will be the then clause of the promise the function returned, so, in this case, the first example falls through the normal sequence of the thens and prints out values as one might expect, in the second example, the promise object that gets returned when you do Promise.resolve("bbb")'s then is the then that gets invoked when chaining(for all intents and purposes). The way it actually works is described below in more detail.

Quoting from the Promises/A+ spec:

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.

The key thing to notice here is this line:

if x is a promise, adopt its state [3.4]

link: https://promisesaplus.com/#point-49

tmux status bar configuration

The man page has very detailed descriptions of all of the various options (the status bar is highly configurable). Your best bet is to read through man tmux and pay particular attention to those options that begin with status-.

So, for example, status-bg red would set the background colour of the bar.

The three components of the bar, the left and right sections and the window-list in the middle, can all be configured to suit your preferences. status-left and status-right, in addition to having their own variables (like #S to list the session name) can also call custom scripts to display, for example, system information like load average or battery time.

The option to rename windows or panes based on what is currently running in them is automatic-rename. You can set, or disable it globally with:

setw -g automatic-rename [on | off]

The most straightforward way to become comfortable with building your own status bar is to start with a vanilla one and then add changes incrementally, reloading the config as you go.1

You might also want to have a look around on github or bitbucket for other people's conf files to provide some inspiration. You can see mine here2.



1 You can automate this by including this line in your .tmux.conf:

bind R source-file ~/.tmux.conf \; display-message "Config reloaded..."

You can then test your new functionality with Ctrlb,Shiftr. tmux will print a helpful error message—including a line number of the offending snippet—if you misconfigure an option.

2 Note: I call a different status bar depending on whether I am in X or the console - I find this quite useful.

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

Adjust list style image position?

Not really. Your padding is (probably) being applied to the list item, so will only affect the actual content within the list item.

Using a combination of background and padding styles can create something that looks similar e.g.

li {
  background: url(images/bullet.gif) no-repeat left top; /* <-- change `left` & `top` too for extra control */
  padding: 3px 0px 3px 10px;
  /* reset styles (optional): */
  list-style: none;
  margin: 0;
}

You might be looking to add styling to the parent list container (ul) to position your bulleted list items, this A List Apart article has a good starting reference.

Setting up connection string in ASP.NET to SQL SERVER

I JUST FOUND!! You need to put this string connection and point directly to your database. Same case on server.

"Provider=Microsoft.ACE.OLEDB.12.0; 
 Data Source=c:/inetpub/wwwroot/TEST/data/data.mdb;"

It works!! :)

Return 0 if field is null in MySQL

You can use coalesce(column_name,0) instead of just column_name. The coalesce function returns the first non-NULL value in the list.

I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select to the insert/update.

This amortises the cost assuming your database is read more often than written (and most of them are).

What is the behavior of integer division?

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

How do you make strings "XML safe"?

Since PHP 5.4 you can use:

htmlspecialchars($string, ENT_XML1);

You should specify the encoding, such as:

htmlspecialchars($string, ENT_XML1, 'UTF-8');

Update

Note that the above will only convert:

  • & to &amp;
  • < to &lt;
  • > to &gt;

If you want to escape text for use in an attribute enclosed in double quotes:

htmlspecialchars($string, ENT_XML1 | ENT_COMPAT, 'UTF-8');

will convert " to &quot; in addition to &, < and >.


And if your attributes are enclosed in single quotes:

htmlspecialchars($string, ENT_XML1 | ENT_QUOTES, 'UTF-8');

will convert ' to &apos; in addition to &, <, > and ".

(Of course you can use this even outside of attributes).


See the manual entry for htmlspecialchars.

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

Switch on Enum in Java

First, you can switch on an enum in Java. I'm guessing you intended to say you can’t, but you can. chars have a set range of values, so it's easy to compare. Strings can be anything.

A switch statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.

Java 7 and later supports String switches with the same characteristics.

Pure JavaScript Send POST Data Without a Form

navigator.sendBeacon()

If you simply need to POST data and do not require a response from the server, the shortest solution would be to use navigator.sendBeacon():

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

navigator.sendBeacon('example.php', data);

How to check if element is visible after scrolling?

How about

function isInView(elem){
   return $(elem).offset().top - $(window).scrollTop() < $(elem).height() ;
}

After that you can trigger whatever you want once the element is in view like this

$(window).scroll(function(){
   if (isInView($('.classOfDivToCheck')))
      //fire whatever you what 
      dothis();
})

That works for me just fine

How to select top n rows from a datatable/dataview in ASP.NET

myDataTable.AsEnumerable().Take(5).CopyToDataTable()

What is the purpose of a self executing function in javascript?

Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.

Of course, on half the JS implementations out there, they will anyway.

.NET / C# - Convert char[] to string

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );

Debug.Assert( s.Equals( "Rock-&-Roll" ) );

What is the printf format specifier for bool?

There is no format specifier for bool. You can print it using some of the existing specifiers for printing integral types or do something more fancy:

 printf("%s", x?"true":"false");

What is stdClass in PHP?

Actually I tried creating empty stdClass and compared the speed to empty class.

class emp{}

then proceeded creating 1000 stdClasses and emps... empty classes were done in around 1100 microseconds while stdClasses took over 1700 microseconds. So I guess its better to create your own dummy class for storing data if you want to use objects for that so badly (arrays are a lot faster for both writing and reading).

How to present popover properly in iOS 8

Swift 2.0

Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.

import UIKit

class PopOverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()    
        self.preferredContentSize = CGSizeMake(200, 200)    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")    
    }    
    func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}      

See ViewController:

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
    func showPopover(base: UIView)
    {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {    

            let navController = UINavigationController(rootViewController: viewController)
            navController.modalPresentationStyle = .Popover

            if let pctrl = navController.popoverPresentationController {
                pctrl.delegate = self

                pctrl.sourceView = base
                pctrl.sourceRect = base.bounds

                self.presentViewController(navController, animated: true, completion: nil)
            }
        }
    }    
    override func viewDidLoad(){
        super.viewDidLoad()
    }    
    @IBAction func onShow(sender: UIButton)
    {
        self.showPopover(sender)
    }    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None
    }
}  

Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !

Renaming the current file in Vim

I'm doing it with NERDTree plugin:

:NERDTreeFind

then press m

To rename you can choose (m)ove the current node and change file name. Also there are options like delete, copy, move, etc...

Python Save to file

In order to write into a file in Python, we need to open it in write w, append a or exclusive creation x mode.

We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

with open('Failed.py','w',encoding = 'utf-8') as f:
   f.write("Write what you want to write in\n")
   f.write("this file\n\n")

This program will create a new file named Failed.py in the current directory if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish the different lines.

What's the difference between primitive and reference types?

Primitives vs. References

First :-

Primitive types are the basic types of data: byte, short, int, long, float, double, boolean, char. Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String, Scanner, Random, Die, int[], String[], etc. Reference variables store addresses to locations in memory for where the data is stored.

Second:-

Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.

Read more: http://javarevisited.blogspot.com/2015/09/difference-between-primitive-and-reference-variable-java.html#ixzz3xVBhi2cr

maximum value of int

What about (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2)). This is the same as 2^(8*sizeof(int)-2) - 1 + 2^(8*sizeof(int)-2).

If sizeof(int) = 4 => 2^(8*4-2) - 1 + 2^(8*4-2) = 2^30 - 1 + 20^30 = (2^32)/2 - 1 [max signed int of 4 bytes].

You can't use 2*(1 << (8*sizeof(int)-2)) - 1 because it will overflow, but (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2)) works.

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

Insert variable into Header Location PHP

There's nothing here explaining the use of multiple variables, so I'll chuck it in just incase someone needs it in the future.

You need to concatenate multiple variables:

header('Location: http://linkhere.com?var1='.$var1.'&var2='.$var2.'&var3'.$var3);

Key Presses in Python

AutoHotKey is perfect for this kind of tasks (keyboard automation / remapping)

Script to send "A" 100 times:

Send {A 100}

That's all

EDIT: to send the keys to an specific application:

WinActivate Word
Send {A 100}

How do I use Maven through a proxy?

Just to add my own experiences with this: my company's proxy is http://webproxy.intra.companyname.com:3128. For maven to work via this proxy, the settings have to be exactly like this

<settings>
  <proxies>
    <proxy>
      <id>default</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>webproxy.intra.companyname.com</host>
      <port>3128</port>
    </proxy>
  </proxies>
</settings>

Unlike some other proxy-configuration files, the protocol here describes how to connect to the proxy server, not which kinds of protocol should be proxied. The http part of the target has to be split off from the hostname, else it won't work.

'Invalid update: invalid number of rows in section 0

Swift Version --> Remove the object from your data array before you call

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

How do I check if a file exists in Java?

first hit for "java file exists" on google:

import java.io.*;

public class FileTest {
    public static void main(String args[]) {
        File f = new File(args[0]);
        System.out.println(f + (f.exists()? " is found " : " is missing "));
    }
}

Why am I getting "IndentationError: expected an indented block"?

I had this same problem and discovered (via this answer to a similar question) that the problem was that I didn't properly indent the docstring properly. Unfortunately IDLE doesn't give useful feedback here, but once I fixed the docstring indentation, the problem went away.

Specifically --- bad code that generates indentation errors:

def my_function(args):
"Here is my docstring"
    ....

Good code that avoids indentation errors:

def my_function(args):
    "Here is my docstring"
    ....

Note: I'm not saying this is the problem, but that it might be, because in my case, it was!

Why is volatile needed in C?

Volatile is also useful, when you want to force the compiler not to optimize a specific code sequence (e.g. for writing a micro-benchmark).

identifier "string" undefined?

Because string is defined in the namespace std. Replace string with std::string, or add

using std::string;

below your include lines.

It probably works in main.cpp because some other header has this using line in it (or something similar).

Checking if object is empty, works with ng-show but not from controller?

another simple one-liner:

var ob = {};
Object.keys(ob).length // 0

Is there a REAL performance difference between INT and VARCHAR primary keys?

It's not about performance. It's about what makes a good primary key. Unique and unchanging over time. You may think an entity such as a country code never changes over time and would be a good candidate for a primary key. But bitter experience is that is seldom so.

INT AUTO_INCREMENT meets the "unique and unchanging over time" condition. Hence the preference.

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How to get relative path of a file in visual studio?

When it is the case that you want to use any kind of external file, there is certainly a way to put them in a folder within your project, but not as valid as getting them from resources. In a regular Visual Studio project, you should have a Resources.resx file under the Properties section, if not, you can easily add your own Resource.resx file. And add any kind of file in it, you can reach the walkthrough for adding resource files to your project here.

After having resource files in your project, calling them is easy as this:

var myIcon = Resources.MyIconFile;

Of course you should add the using Properties statement like this:

using <namespace>.Properties;

Autoincrement VersionCode with gradle extra properties

Examples shown above don't work for different reasons

Here is my ready-to-use variant based on ideas from this article:

android {
    compileSdkVersion 28

    // https://stackoverflow.com/questions/21405457

    def propsFile = file("version.properties")
    // Default values would be used if no file exist or no value defined
    def customAlias = "Alpha"
    def customMajor = "0"
    def customMinor = "1"
    def customBuild = "1" // To be incremented on release

    Properties props = new Properties()
    if (propsFile .exists())
        props.load(new FileInputStream(propsFile ))

    if (props['ALIAS'] == null) props['ALIAS'] = customAlias else customAlias = props['ALIAS']
    if (props['MAJOR'] == null) props['MAJOR'] = customMajor else customMajor = props['MAJOR']
    if (props['MINOR'] == null) props['MINOR'] = customMinor else customMinor = props['MINOR']
    if (props['BUILD'] == null) props['BUILD'] = customBuild else customBuild = props['BUILD']

    if (gradle.startParameter.taskNames.join(",").contains('assembleRelease')) {
        customBuild = "${customBuild.toInteger() + 1}"
        props['BUILD'] = "" + customBuild

        applicationVariants.all { variant ->
            variant.outputs.all { output ->
                if (output.outputFile != null && (output.outputFile.name == "app-release.apk"))
                    outputFileName = "app-${customMajor}-${customMinor}-${customBuild}.apk"
            }
        }
    }

    props.store(propsFile.newWriter(), "Incremental Build Version")

    defaultConfig {
        applicationId "org.example.app"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode customBuild.toInteger()
        versionName "$customAlias $customMajor.$customMinor ($customBuild)"

        ...
    }
...
}

How can you get the active users connected to a postgreSQL database via SQL?

Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;

Tensorflow import error: No module named 'tensorflow'

The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.

One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder

conda create -n newenvt anaconda python=3.5
activate newenvt

and then install tensorflow into newenvt

I found this primer helpful

Check string for palindrome

IMO, the recursive way is the simplest and clearest.

public static boolean isPal(String s)
{   
    if(s.length() == 0 || s.length() == 1)
        return true; 
    if(s.charAt(0) == s.charAt(s.length()-1))
       return isPal(s.substring(1, s.length()-1));                
   return false;
}

How can I connect to MySQL in Python 3 on Windows?

Oracle/MySQL provides an official, pure Python DBAPI driver: http://dev.mysql.com/downloads/connector/python/

I have used it with Python 3.3 and found it to work great. Also works with SQLAlchemy.

See also this question: Is it still too early to hop aboard the Python 3 train?

Could not find folder 'tools' inside SDK

In my case i was using Ubuntu. Where the was two directories one was /android-sdks and /android-sdk-linux. I used the second one it works for me :)

Find the day of a week

Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:

require(lubridate)
df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)

The result is the days in the interval [0,..,6].

If you want the interval to be [1,..7], use the following:

df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)

... or, alternatively:

df$day = df$day + 1

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

http://www.tripadvisor.com/help/what_type_of_tripadvisor_content_is_available

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to pipes.yahoo.com and do a search for existing hotel pipes and you'll get the idea..

Get each line from textarea

It works for me:

if (isset($_POST['MyTextAreaName'])){
    $array=explode( "\r\n", $_POST['MyTextAreaName'] );

now, my $array will have all the lines I need

    for ($i = 0; $i <= count($array); $i++) 
    {
        echo (trim($array[$i]) . "<br/>");
    }

(make sure to close the if block with another curly brace)

}

Is it possible to use the SELECT INTO clause with UNION [ALL]?

Maybe try this?

SELECT * INTO tmpFerdeen (
SELECT top(100)* 
FROM Customers
UNION All
SELECT top(100)* 
FROM CustomerEurope
UNION All
SELECT top(100)* 
FROM CustomerAsia
UNION All
SELECT top(100)* 
FROM CustomerAmericas)

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

Visual Studio popup: "the operation could not be completed"

For this problem, I resolved it by deleting the .user file which contains the Visual Studio Project User Options. This File can be found in the same place where your .sln file is located. Also, after deleting this file from the project make sure to reload your solution in order for it to take effect.