Programs & Examples On #Ppd

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

Why powershell does not run Angular commands?

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

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

Delete your package-lock.json file and node_modules folder. Then do npm cache clean

npm cache clean --force

do npm install

again and run

"Permission Denied" trying to run Python on Windows 10

I experienced the same issue, but in addition to Python being blocked, all programs in the Scripts folder were too. The other answers about aliases, path and winpty didn't help.

I finally found that it was my antivirus (Avast) which decided overnight for some reason to just block all compiled python scripts for some reason.

The fix is fortunately easy: simply whitelist the whole Python directory. See here for a full explanation.

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

Seems PyAudio is supported by Python 2.7, 3.4, 3.5, and 3.6. Refer https://people.csail.mit.edu/hubert/pyaudio/

Please suggest if there is any alternate way to install PyAudio on Python 3.8.2

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I needed to install from a requirements file and was getting this error, but did not want to use the --user option because I didn't want to install it the location described by @not2qubit. So I ran CMD as administrator and then enabled sharing of the following directory (right click > properties > Sharing > Share...):

C:\Users\<my user name>\AppData\Local\Temp

After doing this, I was able to install from my requirements file into the application directory (where I wanted it) instead of the crazy ..\AppData dir without the error.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

This is because the shell script is formatted in windows we need to change to unix format. You can run the dos2unix command on any Linux system.

dos2unix your-file.sh

If you don’t have access to a Linux system, you may use the Git Bash for Windows which comes with a dos2unix.exe

dos2unix.exe your-file.sh 

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Although I've tried all the previous answers, only the following one worked out:

1 - Open Powershell (as Admin)

2 - Run:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

3 - Run:

Install-PackageProvider -Name NuGet

The author is Niels Weistra: Microsoft Forum

ADB.exe is obsolete and has serious performance problems

I faced the same issue, and I tried following things, which didn't work:

  1. Deleting the existing AVD and creating a new one.

  2. Uninstall latest-existing and older versions (if you have) of SDK-Tools and SDK-Build-Tools and installing new ones.

What worked for me was uninstalling and re-installing latest PLATFORM-TOOLS, where adb actually resides.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

In my case : When I setup AS, my windows was configured with proxy. Later, I disconnect proxy and disable proxy in AS settings, But, in file .gradle\gradle.properties - proxy - present

Just, in text editor clear proxy settings from this file

Flutter.io Android License Status Unknown

Follow these simple steps.

  1. go to tools, then SDK manager, then click on android SDK.
  2. click SDK update sites tab.
  3. check the checkbox that states https://..sources to be fetched using https://.
  4. click apply and ok.
  5. Now restart android studio.
  6. go to SDK tools and check the checkbox that states Hide obsolete packages.
  7. wait for about a minute or so for the packages appear.
  8. then select a package called "android SDK tools (obsolete), and press okay.
  9. continue to install the package.
  10. after installation restart android studio and also restart cmd, then run flutter doctor.
  11. it will take a couple of minutes and it should work

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case, this error happened with a new project.

none of the proposed solutions here worked, so I simply reinstalled all the packages and started working correctly.

Flutter does not find android sdk

Kindly first of all check your latest sdk first step: install latest Sdk platform

second step: Install all these licenses

Now Run

run flutter doctor --android-licenses Press Y against each agreement

run flutter doctor flutter doctor it will work fine.

How to access Anaconda command prompt in Windows 10 (64-bit)

How to add anaconda installation directory to your PATH variables

1. open environmental variables window

Do this by either going to my computer and then right clicking the background for the context menu > "properties". On the left side open "advanced system settings" or just search for "env..." in start menu ([Win]+[s] keys).

Then click on environment variables

If you struggle with this step read this explanation.

2. Edit Path in the user environmental variables section and add three new entries:

  • D:\path\to\anaconda3
  • D:\path\to\anaconda3\Scripts
  • D:\path\to\anaconda3\Library\bin

D:\path\to\anaconda3 should be the folder where you have installed anaconda

Click [OK] on all opened windows.

If you did everything correctly, you can test a conda command by opening a new powershell window.

conda --version

This should output something like: conda 4.8.2

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

ERROR: npm ERR! Unexpected end of JSON input while parsing near '...ore-js":"3.0.0-beta.1

This occurs when installing the expo CLI globally, This works for me!

npm cache clean --force

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

I wanted to run npm install from within my external hard drive as this is where i saved my code workspace. Windows 10 OS.

But I was getting the same error as the original post.None of the previous answers worked for me, I tried all of them:

  1. uninstalling nodejs then re-installing
  2. uninstalling nodejs then downgrading/installing a lower version of nodejs.
  3. npm install -force
  4. deleting the folders from C:\Users{YourUsername}\AppData\Roaming ... npm and npm-cache then re-installing.
  5. npm cache clean --force
  6. npm cache clean
  7. npm install --g or npm install --global

What worked for me was this:

  1. copy the folder from C:\Program Files\nodejs to D:\Program Files\nodejs
  2. Then go to Control Panel\System and Security\System
  3. Advanced System Settings
  4. Environment Variables
  5. System Variables
  6. Double click Path
  7. Add a new path
  8. D:\Program Files\nodejs
  9. Click ok
  10. restart PC.
  11. try npm install from within D: Drive

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.

For asp core 2.2:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;

namespace Project
{
    sealed class Program
    {
        #region Variables
        /// <summary>
        /// Last loaded configuration
        /// </summary>
        private static IConfiguration _Configuration;
        #endregion

        #region Properties
        /// <summary>
        /// Default application configuration
        /// </summary>
        internal static IConfiguration Configuration
        {
            get
            {
                // None configuration yet?
                if (Program._Configuration == null)
                {
                    // Create the builder using a callback class
                    IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();

                    // Build everything but do not initialize it
                    builder.Build();
                }

                // Current configuration
                return Program._Configuration;
            }

            // Update configuration
            set => Program._Configuration = value;
        }
        #endregion

        #region Public
        /// <summary>
        /// Start the webapp
        /// </summary>
        public static void Main(string[] args)
        {
            // Create the builder using the default Startup class
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            // Build everything and run it
            using (IWebHost host = builder.Build())
                host.Run();
        }
        #endregion


        #region CallBackConfiguration
        /// <summary>
        /// Aux class to callback configuration
        /// </summary>
        private class CallBackConfiguration
        {
            /// <summary>
            /// Callback with configuration
            /// </summary>
            public CallBackConfiguration(IConfiguration configuration)
            {
                // Update the last configuration
                Program.Configuration = configuration;
            }

            /// <summary>
            /// Do nothing, just for compatibility
            /// </summary>
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //
            }
        }
        #endregion
    }
}

So now on you just use the static Program.Configuration at any other class you need it.

Pip error: Microsoft Visual C++ 14.0 is required

You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

After you have installed Visual C++, just re-run the original command:

pip install -U steem

To find out what the various install options mean, run this command:

pip help install

The help for the -U option says

-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.

If you do not already have the steem library installed, you can run the command without the -U option.

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

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

You should not add C:\Users\Administrator\AppData\Roaming\npm\node_modules\angular-cli\bin\ng to your PATH. There is only a javascript file which you cannot use in terminal.

You need ng.cmd which is probably located at %AppData%\Roaming\npm. Make sure this path is included in your PATH variable.

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

if you are using python3.x and opencv==4.1.0 then use following commands First of all

python -m pip install --user opencv-contrib-python

after that use this in the python script

cv2.face.LBPHFaceRecognizer_create() 

Unsupported method: BaseConfig.getApplicationIdSuffix()

I also faced the same issue and got a solution very similar:

  1. Changing the classpath to classpath 'com.android.tools.build:gradle:2.3.2'

    Image after adding the classpath

  2. A new message indicating to Update Build Tool version, so just click that message to update. Update

Android Room - simple select query - Cannot access database on the main thread

With the Jetbrains Anko library, you can use the doAsync{..} method to automatically execute database calls. This takes care of the verbosity problem you seemed to have been having with mcastro's answer.

Example usage:

    doAsync { 
        Application.database.myDAO().insertUser(user) 
    }

I use this frequently for inserts and updates, however for select queries I reccommend using the RX workflow.

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Had a similar problem that resolved by adding both these two parameters to ForeignKey: null=True, on_delete=models.SET_NULL

re.sub erroring with "Expected string or bytes-like object"

I suppose better would be to use re.match() function. here is an example which may help you.

import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]  
sentences

Swift error : signal SIGABRT how to solve it

In my case there was no log whatsoever.

My mistake was to push a view controller in a navigation stack that was already part of the navigation stack.

Error: the entity type requires a primary key

I came here with similar error:

System.InvalidOperationException: 'The entity type 'MyType' requires a primary key to be defined.'

After reading answer by hvd, realized I had simply forgotten to make my key property 'public'. This..

namespace MyApp.Models.Schedule
{
    public class MyType
    {
        [Key]
        int Id { get; set; }

        // ...

Should be this..

namespace MyApp.Models.Schedule
{
    public class MyType
    {
        [Key]
        public int Id { get; set; }  // must be public!

        // ...

Running Tensorflow in Jupyter Notebook

For Anaconda users in Windows 10 and those who recently updated Anaconda environment, TensorFlow may cause some issues to activate or initiate. Here is the solution which I explored and which worked for me:

  • Uninstall current Anaconda environment and delete all the existing files associated with Anaconda from your C:\Users or where ever you installed it.
  • Download Anaconda (https://www.anaconda.com/download/?lang=en-us#windows)
  • While installing, check the "Add Anaconda to my PATH environment variable"
  • After installing, open the Anaconda command prompt to install TensorFlow using these steps:
  • Create a conda environment named tensorflow by invoking the following command:

    conda create -n tensorflow python=3.5 (Use this command even if you are using python 3.6 because TensorFlow will get upgraded in the following steps)

  • Activate the conda environment by issuing the following command:

    activate tensorflow After this step, the command prompt will change to (tensorflow)

  • After activating, upgrade tensorflow using this command:

    pip install --ignore-installed --upgrade Now you have successfully installed the CPU version of TensorFlow.

  • Close the Anaconda command prompt and open it again and activate the tensorflow environment using 'activate tensorflow' command.
  • Inside the tensorflow environment, install the following libraries using the commands: pip install jupyter pip install keras pip install pandas pip install pandas-datareader pip install matplotlib pip install scipy pip install sklearn
  • Now your tensorflow environment contains all the common libraries used in deep learning.
  • Congrats, these libraries will make you ready to build deep neural nets. If you need more libraries install using the same command 'pip install libraryname'

ValueError: Wrong number of items passed - Meaning and suggestions?

Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

What is the purpose of "pip install --user ..."?

On macOS, the reason for using the --user flag is to make sure we don't corrupt the libraries the OS relies on. A conservative approach for many macOS users is to avoid installing or updating pip with a command that requires sudo. Thus, this includes installing to /usr/local/bin...

Ref: Installing python for Neovim (https://github.com/zchee/deoplete-jedi/wiki/Setting-up-Python-for-Neovim)

I'm not all clear why installing into /usr/local/bin is a risk on a Mac given the fact that the system only relies on python binaries in /Library/Frameworks/ and /usr/bin. I suspect it's because as noted above, installing into /usr/local/bin requires sudo which opens the door to making a costly mistake with the system libraries. Thus, installing into ~/.local/bin is a sure fire way to avoid this risk.

Ref: Using python on a Mac (https://docs.python.org/2/using/mac.html)

Finally, to the degree there is a benefit of installing packages into the /usr/local/bin, I wonder if it makes sense to change the owner of the directory from root to user? This would avoid having to use sudo while still protecting against making system-dependent changes.* Is this a security default a relic of how Unix systems were more often used in the past (as servers)? Or at minimum, just a good way to go for Mac users not hosting a server?

*Note: Mac's System Integrity Protection (SIP) feature also seems to protect the user from changing the system-dependent libraries.

- E

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

not finding android sdk (Unity)

  1. Delete android sdk "tools" folder : [Your Android SDK root]/tools -> tools

  2. Download SDK Tools: http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip

  3. Extract that to Android SDK root

  4. Build your project

After that it didn't work for me yet, I had to

  1. Go to the Java archives (http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html)

  2. Search for the jdk-8u131 release.

  3. Accept the Licence Agreement,make an account and download the release.

  4. Install it and define it as JDK path in Unity.

source : https://www.reddit.com/r/Unity3D/comments/77azfb/i_cant_get_unity_to_build_run_my_game/

selenium - chromedriver executable needs to be in PATH

try this :

driver = webdriver.Chrome(ChromeDriverManager().install())

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

In my case, this problem occured because I did npm install with another system user in my project folder before. Gulp was already installed globally. After deleting folder /node_modules/ in my project, and running npm install with the current user, it worked.

How do I install PIL/Pillow for Python 3.6?

Pillow is released with installation wheels on Windows:

We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included

https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation

Update: Python 3.6 is now supported by Pillow. Install with pip install pillow and check https://pillow.readthedocs.io/en/latest/installation.html for more information.


However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).

https://travis-ci.org/python-pillow/Pillow/jobs/155605577

If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:

https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source

And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):

https://github.com/python-pillow/Pillow/tree/master/winbuild

Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.

Where Sticky Notes are saved in Windows 10 1607

In windows 10 you can recover in this way, there is no .snt file

  1. Start Run
  2. Go to this %LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  3. Copy this folder Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  4. Replace it with new Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe
  5. Check your sticky notes now, you will get all your data

ng is not recognized as an internal or external command

Add the ng command path from the folder .bin under the node_modules to PATH variable in the system env settings.

e.g: add C:\testProject\node_modules\.bin\ to PATH

Restart your IDE.

Add Favicon with React and Webpack

Replace the favicon.ico in your public folder with yours, that should get you going.

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

Similar error messages will pop up when transitioning from version 5 to 6. Here is an answer for the change to rxjs-6.

Import the individual operators, then use pipe instead of chaining.

import { map, delay, catchError } from 'rxjs/operators'; 

source.pipe(
  map(x => x + x),
  delay(4000),
  catchError(err => of('error found')),
).subscribe(printResult);

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Execution failed for task ':app:processDebugResources' even with latest build tools

Error:Execution failed for task com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException:

finished with non-zero exit value 1

One reason for this error to occure is that the file path to a resource file is to long:

Error: File path too long on Windows, keep below 240 characters 

Fix: Move your project folder closer to the root of your disk

Don't:// folder/folder/folder/folder/very_long_folder_name/MyProject...

Do://folder/short_name/MyProject


Another reason could be duplicated resources or name spaces

Example:

  <style name="MyButton" parent="android:Widget.Button">
      <item name="android:textColor">@color/accent_color</item>
      <item name="android:textColor">#000000</item>
  </style>

And make sure all file names and extensions are in lowercase

Wrong

myimage.PNG
myImage.png

Correct

my_image.png

Make sure to Clean/Rebuild project

(delete the 'build' folder)

ImportError: No module named 'google'

I found a similar error when i tried to access the bigquery from google.cloud.

from google.cloud import bigquery

Error was resolved after i install the google.cloud from conda-forge community.

conda install -c conda-forge google-cloud-bigquery

How to reset settings in Visual Studio Code?

On Linux environment delete the folder "~/.config/Code" to reset Visual Studio Code Settings.

How to run html file using node js

The simplest command by far:

npx http-server

This requires an existing index.html at the dir at where this command is being executed.

This was already mentioned by Vijaya Simha, but I thought using npx is way cleaner and shorter. I am running a webserver with this approach since months.

Docs: https://www.npmjs.com/package/http-server

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

Just delete .npmrc folder in c:users>'username' and try running the command it will be resolved !

Npm install cannot find module 'semver'

On MS Windows, the solution is to remove %APPDATA%\npm and reinstall node

Global npm install location on windows?

According to: https://docs.npmjs.com/files/folders

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.

prefix Configuration

The prefix config defaults to the location where node is installed. On most systems, this is /usr/local. On windows, this is the exact location of the node.exe binary.

The docs might be a little outdated, but they explain why global installs can end up in different directories:

(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"

Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.

This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):

mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm

open a new cmd.exe window and reinstall all global packages.

Explanation (by lineno.):

  1. Create a folder in a sensible location to hold the globals (Microsoft is adamant that you shouldn't write to ProgramFiles, so %PROGRAMDATA% seems like the next logical place.
  2. The directory needs to be on the path, so use setx .. /M to set the system path (under HKEY_LOCAL_MACHINE). This is what requires you to run this in a shell with administrator permissions.
  3. Tell npm to use this new path. (Note: folder isn't visible in %PATH% in this shell, so you must open a new window).

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

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

xcode-select --install
pip install lxml

Which ended up installing lxml-3.5.0

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

ImportError: No module named pandas

If you are running python version 3.9 pandas wont work as of now. So install python version 3.7 or below to mitigate this issue. Or else if you want to stick with python 3.9 try install pandas by compiling the library

failed to find target with hash string android-23

This poblem is solved for me after Run as administrator the Andorid Studio

How do I run pip on python for windows?

First go to the pip documentation if not install before: http://pip.readthedocs.org/en/stable/installing/

and follow the install pip which is first download get-pip.py from https://bootstrap.pypa.io/get-pip.py

Then run the following (which may require administrator access): python get-pip.py

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

  1. Search "sqlLocalDb" from start menu,
  2. Click on the run command,
  3. Go back to VS 2015 tools/connect to database,
  4. select MSSQL server,
  5. enter (localdb)\MSSQLLocalDB as server name

Select your database and ready to go.

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

I have had the same problem with anaconda on windows. It seems that there is an issu with mcAfee antivirus. If you deactivate it while running the updates or the installs, it allows you to properly run the installation.

pip install access denied on Windows

Try to give permission to full control the python folder.

Find the python root directory-->right button click-->properties-->security-->edit-->give users Full Control-->yes and wait the process finished.

It works for me.

Cordova - Error code 1 for command | Command failed for

Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had the same issue and the following fixed my issue:

  1. Set the registry: npm config set registry "http://registry.npmjs.org/"
  2. Removed the entry in hosts file (using Windows 7) => C:\Windows\System32\drivers\etc\hosts

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

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

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

How to use Visual Studio Code as Default Editor for Git

Another useful option is to set EDITOR environment variable. This environment variable is used by many utilities to know what editor to use. Git also uses it if no core.editor is set.

You can set it for current session using:

export EDITOR="code --wait"

This way not only git, but many other applications will use VS Code as an editor.

To make this change permanent, add this to your ~/.profile for example. See this question for more options.


Another advantage of this approach is that you can set different editors for different cases:

  1. When you working from local terminal.
  2. When you are connected through SSH session.

This is useful especially with VS Code (or any other GUI editor) because it just doesn't work without GUI.

On Linux OS, put this into your ~/.profile:

# Preferred editor for local and remote sessions
if [[ -n $SSH_CONNECTION ]]; then # SSH mode
  export EDITOR='vim'
else # Local terminal mode
  export EDITOR='code -w'
fi

This way when you use a local terminal, the $SSH_CONNECTION environment variable will be empty, so the code -w editor will be used, but when you are connected through SSH, then $SSH_CONNECTION environment variable will be a non-empty string, so the vim editor will be used. It is console editor, so it will work even when you are connected through SSH.

Java finished with non-zero exit value 2 - Android Gradle

For me the problem was, i had put a unnecessary complie library code in build.gradle

dependencies {
    compile 'com.google.android.gms:play-services:7.5.0'
}

which was causing over 65k methods, so removed it,gradle sync, cleaned project, and then ran again and then this error stopped. I needed just maps and gcm so i put these lines and synced project

compile 'com.google.android.gms:play-services-gcm:7.5.0'
compile 'com.google.android.gms:play-services-location:7.5.0'

Hi people i again encountered this problem and this time it was because of changing build tools version and it really required me to enable multidex..so i added these my app's build.gradle file..

defaultConfig {
    applicationId "com.am.android"
    minSdkVersion 13
    targetSdkVersion 23
    // Enabling multidex support.
    multiDexEnabled true
}

dexOptions {
    incremental true
    javaMaxHeapSize "2048M"
    jumboMode = true
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
}

And create a class that extends Application class and include this method inside the class..

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

also include in OnCreate method too

@Override
public void onCreate() {
    MultiDex.install(this);
    super.onCreate();
}

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.

//on ubuntu server
sudo /etc/init.d/mysql start

To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.

$ sudo initctl stop mysql
$ sudo initctl start mysql

To verify the working, you can check the status of the service and get the process id (pid), simulate a failure by killing the "mysql" process and verify its status as running with new process id after sometime (typically within 1 minute) using the following commands.

$ sudo initctl status mysql         # get pid
$ sudo kill -9 <pid>                # kill mysql process
$ sudo initctl status mysql         # verify status as running after sometime

Note : In latest Ubuntu version now initctl is replaced by systemctl

finished with non zero exit value

its been a while but hope it helps

For me it was just something missing from @dimens which was used in xml file it was weird that android studio didn't mention it directly in error

Android studio- "SDK tools directory is missing"

Change the SDK directory to C:\Users\username\AppData\Local\Android\Sdk

If you are using the latest android studio you can configure this using Configure -> Project Defaults -> Project Structure

Netbeans 8.0.2 The module has not been deployed

Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

What worked for me was to import the project with "File -> New -> Project from Version Control" then choose your online source (GitHub for example). This way all the .gradle files were created in the import.

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

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

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

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

Installing Node.js (and npm) on Windows 10

New installers (.msi downloaded from https://nodejs.org) have "Add to PATH" option. By default it is selected. Make sure that you leave it checked.

Add to PATH

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

For mysql8 and python 3.7 on windows, I find previous solutions seems not work for me.

Here is what worked for me:

pip install wheel

pip install mysqlclient-1.4.2-cp37-cp37m-win_amd64.whl

python -m pip install mysql-connector-python

python -m pip install SQLAlchemy

Reference: https://mysql.wisborg.dk/2019/03/03/using-sqlalchemy-with-mysql-8/

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

I was facing this issue due to empty space at the end of the password(spring.rabbitmq.password=rabbit ) in spring boot application.properties got resolved on removing the empty space. Hope this checklist helps some one facing this issue.

set initial viewcontroller in appdelegate - swift

iOS 13+

In the SceneDelegate:

var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options 
connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let vc = UIViewController() //Instead of UIViewController() we initilise our initial viewController
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

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

Follow these steps:

  1. Open CMD as administrator
  2. Enter this command : cd..
  3. cd..
  4. cd Program Files\Python38\Scripts
  5. Download the package you want and put it in Python38\Scripts folder.
  6. pip install packagename.whl
  7. Done

You can write your python version instead of "38"

Command failed due to signal: Segmentation fault: 11

Just note for those who might be in the same situation as I was in, since this took me so much hours to resolve...

I encountered this error after I used Find/Replace functionality in Xcode. The problem is that some characters are "overreplaced" due to my carelessness (i.e. replace not only the relevant parts but also the redundant parts) and thus some of variables become undefined ones. Nonetheless those undefined variables weren't caught in the compile (even after making a clean) and finally the signal segmentation error was displayed on the screen.

Xcode 6.1 Missing required architecture X86_64 in file

I use lipo command to combine two built static libraries manually.

EX: I have a static library(libXYZ.a) to build.

I run build for Generic iOS Device and got Product in Debug-iphoneos/

$ lipo -info Debug-iphoneos/libXYZ.a
Architectures in the fat file: Debug-iphoneos/libXYZ.a are: armv7 arm64

Then I run build for any iOS Simulator and got Product in Debug-iphonesimulator/

$ lipo -info Debug-iphonesimulator/libXYZ.a
Architectures in the fat file: Debug-iphonesimulator/libXYZ.a are: i386 x86_64

Finally I combine into one to contain all architectures.

$ lipo -create Debug-iphoneos/libXYZ.a Debug-iphonesimulator/libXYZ.a -output libXYZ.a
$ lipo -info libXYZ.a
Architectures in the fat file: libXYZ.a are: armv7 i386 x86_64 arm64

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

I had to cast the integer equivalent to get around the fact that I'm still using .NET 4.0

System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
/* Note the property type  
   [System.Flags]
   public enum SecurityProtocolType
   {
     Ssl3 = 48,
     Tls = 192,
     Tls11 = 768,
     Tls12 = 3072,
   } 
*/

There is already an object named in the database

In my case, my EFMigrationsHistory table was emptied (somehow) and when trying to run update-database I would get:

There is already an object named 'AspNetUsers' in the database

After seeing the table had been emptied it made sense that it was trying to rerun the initial migration and trying to recreate the tables.

To fix this problem I added rows into my EFMigrationsHistory table. 1 row for each migration that I knew the database was up to date with.

A row will have 2 columns: MigrationId and ProductVersion

MigrationId is the name of your migration file. Example: 20170628112345_Initial

ProductVersion is the ef version you're running. You can find this by typing Get-Package into the Package Manager Console and looking for your ef package.

Hope this is helpful for someone.

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

I had the exact same error message, and tried the suggested solutions in this thread but without success.

what solved the problem for me is opening the .xlsx file and saving it as .xls (excel 2003) file.

maybe the file was corrupted or in a different format, and saving it again fixed it.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

I usually fix this errore following this msdn blog post Using LocalDB with Full IIS

This requires editing applicationHost.config file which is usually located in C:\Windows\System32\inetsrv\config. Following the instructions from KB 2547655 we should enable both flags for Application Pool ASP.NET v4.0, like this:

<add name="ASP.NET v4.0" autoStart="true" managedRuntimeVersion="v4.0"     managedPipelineMode="Integrated">
    <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

I have tried so many approches! the only useful thing is:

if var topController = UIApplication.shared.keyWindow?.rootViewController
{
  while (topController.presentedViewController != nil)
  {
    topController = topController.presentedViewController!
  }
}

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

Short answer

If running into this at home on a corporate machine, try again at work.

Details

I ran into this over the weekend. Pip and conda both broken, unable to install or update. SO was helpful, but many answers were problematic on a corporate machine - the solutions require the ability to pip install (already does not work) or require downloading an installer (the ones I wanted to download were prohibited by firewall settings).

What worked for me was to try again when I was on prem. This worked. It turned out the corporate firewall settings were different when using the machine at home vs at work.

transparent navigation bar ios

If you want to be able to do this programmatically in swift 4 while staying on the same view,

if change {
        navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.navigationBar.backgroundColor = UIColor(displayP3Red: 255/255, green: 206/255, blue: 24/255, alpha: 1)
        navigationController?.navigationBar.barTintColor = UIColor(displayP3Red: 255/255, green: 206/255, blue: 24/255, alpha: 1)
    } else {
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.setBackgroundImage(backgroundImage, for: .default)
        navigationController?.navigationBar.backgroundColor = .clear
        navigationController?.navigationBar.barTintColor = .clear
    }

One important thing to remember though is to click this button in your storyboard. I had an issue with a jumping display for a long time. Make sureyou set this: enter image description here

Then when you change the translucency of the navigation bar it will not cause the views to jump as the views extend all the way to the top, regardless of the visiblity of the navigation bar.

Class 'ViewController' has no initializers in swift

For me was a declaration incomplete. For example:

var isInverted: Bool

Instead the correct way:

var isInverted: Bool = false

Android SDK location

For Mac OS Catalina with zsh:

echo '\nexport PATH="$PATH":"$HOME/Library/Android/sdk"' >> $HOME/.zshrc

restart the terminal and woala :)

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I recommend setting an alternative location for your npm modules.

npm config set prefix C:\Dev\npm-repository\npm --global 
npm config set cache C:\Dev\npm-repository\npm-cache --global  

Of course you can set the location to wherever best suits.

This has worked well for me and gets around any permissions issues that you may encounter.

How to create UILabel programmatically using Swift?

Just to add onto the already great answers, you might want to add multiple labels in your project so doing all of this (setting size, style etc) will be a pain. To solve this, you can create a separate UILabel class.

  import UIKit

  class MyLabel: UILabel {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeLabel()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeLabel()
    }

    func initializeLabel() {

        self.textAlignment = .left
        self.font = UIFont(name: "Halvetica", size: 17)
        self.textColor = UIColor.white

    }

}

To use it, do the following

import UIKit

class ViewController: UIViewController {

     var myLabel: MyLabel()

     override func viewDidLoad() {
          super.viewDidLoad()

          myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20))
          self.view.addSubView(myLabel)
     }


}

Clear Cache in Android Application programmatically

Try this

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

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

Or if you are using PyCharm (2017-03-03) like me, just change directory in terminal and install:

cd C:\Users\{user}\PycharmProjects\test\venv\Scripts
pip install ..

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

if you're working with some kind of subversion: delete the project and re-download it, it worked for me :S

Failed to install Python Cryptography package with PIP and setup.py

Had same issue in Cygwin, this is what helped me

sudo apt-get install python-pip python-dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev zlib1g-dev

but instead of sudo apt-get install, I installed those packages via Cygwin Source of this code

"Could not find a part of the path" error message

I had the same error, although in my case the problem was with the formatting of the DESTINATION path. The comments above are correct with respect to debugging the path string formatting, but there seems to be a bug in the File.Copy exception reporting where it still throws back the SOURCE path instead of the DESTINATION path. So don't forget to look here as well.

-TC

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

This might be the dumbest answer, but this worked for me :

  • I removed and added all the libraries on my project manually.(One after the other) And voila, it worked.
  • Build -> Rebuild project

Note: No library of mine was compiled twice.

'npm' is not recognized as internal or external command, operable program or batch file

To elaborate on Breno's answer... For Windows 7 these steps worked for me:

  1. Open the Control Panel (Click the Start button, then click Control Panel)
  2. Click User Accounts
  3. Click Change my environment variables
  4. Select PATH and click the Edit... button
  5. At the end of the Variable value, add ;C:\Program Files\nodejs
  6. Click Ok on the "Edit User Variable" window, then click Ok on the "Environment Variables" window
  7. Start a command prompt window (Start button, then type cmd into the search and hit enter)
  8. At the prompt (C:\>) type npm and hit enter; you should now see some help text (Usage: npm <command> etc.) rather than "npm is not recognized..."

Now you can start using npm!

Cannot find firefox binary in PATH. Make sure firefox is installed

I have also face same issue on Windows 10-64 bit OS.

When I am installed firefox on my PC its installed location is "C:\Program Files\Mozilla Firefox\firefox.exe" instead of "C:\Program Files (x86)\Mozilla Firefox", because OS is 64 bit,

So I just copy & paste "Mozilla Firefox" folder in "C:\Program Files (x86)" folder and execute selenium scripts, its work for me.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

java.lang.ClassNotFoundException is indicate that class is not found in class path. it could be the version of log4j is not compatible. check for different log4j version.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

Best practices for Storyboard login screen, handling clearing of data upon logout

Create **LoginViewController** and **TabBarController**.

After creating the LoginViewController and TabBarController, we need to add a StoryboardID as “loginViewController” and “tabBarController” respectively.

Then I prefer to create the Constant struct:

struct Constants {
    struct StoryboardID {
        static let signInViewController = "SignInViewController"
        static let mainTabBarController = "MainTabBarController"
    }

    struct kUserDefaults {
        static let isSignIn = "isSignIn"
    }
}

In LoginViewController add IBAction:

@IBAction func tapSignInButton(_ sender: UIButton) {
    UserDefaults.standard.set(true, forKey: Constants.kUserDefaults.isSignIn)
    Switcher.updateRootViewController()
}

In ProfileViewController add IBAction:

@IBAction func tapSignOutButton(_ sender: UIButton) {
    UserDefaults.standard.set(false, forKey: Constants.kUserDefaults.isSignIn)
    Switcher.updateRootViewController()
}

In AppDelegate add line of code in didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    Switcher.updateRootViewController()

    return true
}

Finally create Switcher class:

import UIKit

class Switcher {

    static func updateRootViewController() {

        let status = UserDefaults.standard.bool(forKey: Constants.kUserDefaults.isSignIn)
        var rootViewController : UIViewController?

        #if DEBUG
        print(status)
        #endif

        if (status == true) {
            let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
            let mainTabBarController = mainStoryBoard.instantiateViewController(withIdentifier: Constants.StoryboardID.mainTabBarController) as! MainTabBarController
            rootViewController = mainTabBarController
        } else {
            let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
            let signInViewController = mainStoryBoard.instantiateViewController(withIdentifier: Constants.StoryboardID.signInViewController) as! SignInViewController
            rootViewController = signInViewController
        }

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = rootViewController

    }

}

That is all!

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

In my case the issue didn't resolve by following any of the above methods. I had all the paths in my package config correct and the dll's were in place as referred, I was still getting run time error for System.Web.WebPages.Razor. I changed the localhost port number and this worked

I am not sure of why I had the issue and why changing the port number resolved it. Just posting this as I feel this might be useful for someone out there.

Change default global installation directory for node.js modules in Windows?

I tried most of the answers here nothing seems to work in my case. So i changed the Temp location in my env variables to C:\npm. Then it started to work. This is not a good idea but a temporary solution.

pip install gives error: Unable to find vcvarsall.bat

You need to have Visual Studio's bin dir in your path. Pip install is trying to compile some C code.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Just to add to these Anniversary Update issues (thanks Microsoft) if the file you are missing is cgi.dll, ie your Event Viewer has

The Module DLL C:\WINDOWS\System32\inetsrv\cgi.dll failed to load.  The data is the error.

Then to fix this:

  1. Go to IIS Manager
  2. Select the very top row in the Connections panel (typically your PC name)
  3. At the very bottom of the right panel, under Management, you should have Web Platform Installer
  4. Once that loads, select Products
  5. In the search type in cgi then hit <Enter>
  6. Select IIS: CGI then click Add on the right and finally Install on the bottom
  7. After installing it should force you to restart your PC and you should be fixed.

R not finding package even after package installation

When you run

install.packages("whatever")

you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:

.libPaths()

If libPaths shows 2 locations, then paste into second one. Load library:

library(whatever)

Fixed.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I solved this problem occurring on OS X with Django both 1.5 and 1.6 by deactivating all active sessions to virtualenv and starting it again.

Will iOS launch my app into the background if it was force-quit by the user?

The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.

In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.

PushKit reference from Apple:

The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.

To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.

What is and how to fix System.TypeInitializationException error?

I experienced the System.TypeInitializationException due to a different error in my .NET framework 4 project's app.config. Thank you to pStan for getting me to look at the app.config. My configSections were properly defined. However, an undefined element within one of the sections caused the exception to be thrown.

Bottom line is that problems in the app.config can generated this very misleading TypeInitializationException.

A more meaningful ConfigurationErrorsException can be generated by the same error in the app.config by waiting to access the config values until you are within a method rather than at the class level of the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;

namespace ConfigTest
{
    class Program
    {
        public static string machinename;
        public static string hostname;
        public static NameValueCollection _AppSettings;

        static void Main(string[] args)
        {
            machinename = System.Net.Dns.GetHostName().ToLower();
            hostname = "abc.com";// System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).HostName.ToLower().Replace(machinename + ".", "");
            _AppSettings = ConfigurationManager.GetSection("domain/" + hostname) as System.Collections.Specialized.NameValueCollection;
        }
    }
}

Exception of type 'System.OutOfMemoryException' was thrown.

Another thing to try is

Tools -> Options -> search for IIS -> tick Use the 64 bit version of IIS Express for web sites and projects.

Use the 64 bit version of IIS Express for web sites and projects screenshot

Change / Add syntax highlighting for a language in Sublime 2/3

This is my recipe

Note: This isn't exactly what OP is asking. These instructions will help you change the colors of items (comments, keywords, etc) that are defined syntax matching rules. For example, use these instructions to change so that all code comments are colored blue instead of green.

I believe the OP is asking how to define this as an item to be colored when found in a JavaScript source file.

  1. Install Package: PackageResourceViewer

  2. Ctrl+Shift+P > [PackageResourceViewer: Open Resource] > [Color Scheme - Default] > [Marina.sublime-color-scheme] (or whichever color scheme you use)

  3. The above command will open a new tab to the file "Marina.sublime-color-scheme".

    • For me, this file was located in my roaming profile %appdata% (C:\Users\walter\AppData\Roaming\Sublime Text 3\Packages\Color Scheme - Default\) .
    • However, if I browse to that path in Windows Explorer, [Color Scheme - Default] is not of a child-dir of [Packages] dir. I suspect that PackageResourceViewer is doing some virtualization.

optional step: On the new color-scheme tab: Ctrl+Shift+P > [Set Syntax: JSON]

  1. Search for the rule you want to change. I wanted to make comments be move visible, so I searched for "Comment"

    • I found it in the "rules" section
 "rules":
    [
        {
            "name": "Comment",
            "scope": "comment, punctuation.definition.comment",
            "foreground": "var(blue6)"
        },
  1. Search for the string "blue6": to find the color variable definitions section. I found it in the "variables" section.

  2. Pick a new color using a tool like http://hslpicker.com/ .

  3. Either define a new color variable, or overwrite the color setting for blue6.

    • Warning: overwriting blue6 will affect all other text-elements in that color scheme which also use blue6 ("Punctuation" "Accessor").
  4. Save your file, the changes will be applied instantly to any open files/tabs.

NOTES

Sublime will handle any of these color styles. Possibly more.

hsla = hue, saturation, lightness, alpha rgba = red, green, blue, alpha

hsla(151, 100%, 41%, 1) - last param is the alpha level (transparency) 1 = opaque, 0.5 = half-transparent, 0 = full-transparent

hsl(151, 100%, 41%) - no alpha channel

rgba(0, 209, 108, 1) - rgb with an alpha channel

rgb(0, 209, 108) - no alpha channel

Phonegap Cordova installation Windows

Phonegap Cordova Installation on Windows

Requirements

  • Eclipse + ADT Plugin
  • Android SDK Tool
  • Android Platform Tools
  • Latest PhoneGap zip folder. Extract its contents.

Supported Android Devices

Android 2.2 Android 2.3 Android 4.x Phonegap Cordova Installation

Set PATH environment variable for android

  1. From desktop, right click My Computer and click Properties.

  2. Click Advance System Settings link in the left column.

  3. In the system properties window click the environment variables button.

  4. Select the PATH variable from the System variables section. Select the Edit button. You need to add the path to your Android SDK platform-tools and tools directory. For Example: D:\adt-bundle-windows-x86_64-20130219\sdk\platform-tools;D:\adt-bundle-windows-x86_64-20130219\sdk\tools Save your Edit. Close the Environment Variable dialog.

  5. Additionally, you may need to include %JAVA_HOME%\bin to your PATH as well. To check to see if this is required run a command prompt and type java. If the program could not be found add %JAVA_HOME%\bin to the PATH. You may need to specify the full path instead of using %JAVA_HOME% environment variable.
  6. Finally, you may need to include %ANT_HOME%\bin to your PATH as well. To check to see if this is required run a command prompt and type ant. If program cannot be found then add %ANT_HOME%\bin to the PATH. You may need to specify the full path instead of using the %ANT_HOME% environment variable. Set-up New Project

Open Command Prompt, navigate to bin directory within the android sub-folder of the Cordova distribution.

Type in: ./create

Then press Enter.Launch Eclipse. In File Menu Item and select to Import…

Import Select “Existing Android Code into Workspace” and click ‘Next >’.

Browse the project created through command prompt. And click ‘Finish’. Deploy to Emulator From within Eclipse, press this toolbar icon.

Once open, the Android SDK Manager displays various runtime libraries Install the APIs as per requirement from here. From within Eclipse, press this toolbar icon.

Choose and device definition from the list which comes. (There is only one item in the current list.) Press New… in the above window to create new Android Virtual Device(AVD) and use it to run your project.

To open the emulator as a separate application, Select the AVD and press Start. It launches much as it would on device, with additional controls available for hardware buttons:

Deploy to Device:

Make sure USB debugging is enabled on your device and plug it into your system. Right Click the Project and go to Run As > Android Application.

Read more ...

Unable to connect to any of the specified mysql hosts. C# MySQL

Sometime the problem could be on your windows firewall, make sure your server allow access to all port associated with your mysql database.

Can't install via pip because of egg_info error

I'll add this in here as my problem had something todo with my virtualenv:

I hadn't activated my virtual environment and was trying to install my requirements, this ultimately led to my install failing and throwing this error message.

So make sure you activate your virtualenv!

Specified argument was out of the range of valid values. Parameter name: site

  • Navigate to Control Panel > Programs > Programs and Features and repair the IIS Express.
  • Restart the visual studio.

To turn on the IIS is not recommended as other comments suggests if you are not using your system as a live server. For development purpose only IIS Express is adequate.

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

  1. Find the ComponentModelCache folder
  2. Delete Microsoft.VisualStudio.Default.cache
  3. Restart Visual Studio

Enjoy using Visual Studio.

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

Node.js Error: Cannot find module express

npm install --save express

This worked for me. Just run express.js installation again.

How to change UINavigationBar background color from the AppDelegate

Swift:

self.navigationController?.navigationBar.barTintColor = UIColor.red
self.navigationController?.navigationBar.isTranslucent = false

jQuery click event not working after adding class

You should use the following:

$('#gentab').on('click', 'a.tabclick', function(event) {
    event.preventDefault();
    var liId = $(this).closest("li").attr("id");
    alert(liId);  
});

This will attach your event to any anchors within the #gentab element, reducing the scope of having to check the whole document element tree and increasing efficiency.

How to install PyQt5 on Windows?

To install the GPL version of PyQt5, run (see PyQt5 Project):

pip3 install pyqt5

This will install the Python wheel for your platform and your version of Python (assuming both are supported).

(The wheel will be automatically downloaded from the Python Package Index.)

The PyQt5 wheel includes the necessary parts of the LGPL version of Qt. There is no need to install Qt yourself.

(The required sip is packaged as a separate wheel and will be downloaded and installed automatically.)


Note:

If you get an error message saying something as

No downloads could be found that satisfy the requirement 

then you are probably using an unsupported version of Python.

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Easiest way on Safari 11.0 macOS SIERRA 10.12.6: Reload Page From Origin, you can use help to find out where in the menu it is located, or you can use the shortcut option(alt) + command + R.

nodejs npm global config missing on windows

It looks like the files npm uses to edit its config files are not created on a clean install, as npm has a default option for each one. This is why you can still get options with npm config get <option>: having those files only overrides the defaults, it doesn't create the options from scratch.

I had never touched my npm config stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc (on a Windows 8.1 machine with Git Bash), yet I could run npm config get <something> and, if it was a correct npm option, it returned a value. When I ran npm config set <option> <value>, the file ~/.npmrc seemed to be created automatically, with the option & its value as the only non-commented-out line.

As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc is deleted, too, and recreated if you set anything else later.

In your case (assuming it is still the same over a year later), it looks like you never set the proxy option in npm. Therefore, as npm's config help page says, it is set to whatever your http_proxy (case-insensitive) environment variable is. This means there is nothing to delete, unless you want to "delete" your HTTP proxy, although you could set the option or environment variable to something else and hope neither breaks your set-up somehow.

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

C# Foreach statement does not contain public definition for GetEnumerator

Your CarBootSaleList class is not a list. It is a class that contain a list.

You have three options:

Make your CarBootSaleList object implement IEnumerable

or

make your CarBootSaleList inherit from List<CarBootSale>

or

if you are lazy this could almost do the same thing without extra coding

List<List<CarBootSale>>

Setting DEBUG = False causes 500 Error

Django 1.5 introduced the allowed hosts setting that is required for security reasons. A settings file created with Django 1.5 has this new section which you need to add:

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.9/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

Add your host here like ['www.beta800.net'] or ['*'] for a quick test, but don't use ['*'] for production.

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

Please make sure you have done this,if you are getting black screen after copying the storyboard from another project enter image description here

Opening Chrome From Command Line

if you want to open incognito window, put the command below:

start chrome /incognito

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case I had an issue around using Microsoft.ReportViewer.WebForms. I removed validate=true from add verb line in web.config and it started working:

<system.web>
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

how to set width for PdfPCell in ItextSharp

Try something like this

PdfPCell cell;
PdfPTable tableHeader;
PdfPTable tmpTable;
PdfPTable table = new PdfPTable(10) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_LTR, ExtendLastRow = false };

// row 1 / cell 1 (merge)
PdfPCell _c = new PdfPCell(new Phrase("SER. No")) { Rotation = -90, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 };
_c.Rowspan = 2;

table.AddCell(_c);

// row 1 / cell 2
_c = new PdfPCell(new Phrase("TYPE OF SHIPPING")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 3
_c = new PdfPCell(new Phrase("ORDER NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 4
_c = new PdfPCell(new Phrase("QTY.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 5
_c = new PdfPCell(new Phrase("DISCHARGE PPORT")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 6 (merge)
_c = new PdfPCell(new Phrase("DESCRIPTION OF GOODS")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);

// row 1 / cell 7
_c = new PdfPCell(new Phrase("LINE DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 1 / cell 8 (merge)
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);

// row 1 / cell 9 (merge)
_c = new PdfPCell(new Phrase("CLEARANCE DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);

// row 1 / cell 10 (merge)
_c = new PdfPCell(new Phrase("CUSTOM PERMIT NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);


// row 2 / cell 2
_c = new PdfPCell(new Phrase("AWB / BL NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 3
_c = new PdfPCell(new Phrase("COMPLEX NAME")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 4
_c = new PdfPCell(new Phrase("G.W Kgs.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 5
_c = new PdfPCell(new Phrase("DESTINATON")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

// row 2 / cell 7
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);

_doc.Add(table);
///////////////////////////////////////////////////////////
_doc.Close();

You might need to re-adjust slightly on the widths and borders but that is a one shot to do.

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Despite the number of answers I'll add another one which IMHO makes the things a bit clearer.

As Rob and wrightmail already mentioned Microsoft.Web.Infrastructure is a NuGet package (link not needed, you have it in NuGet Package Manager).

Apparently, it was referenced by your project and suddenly disappeared. A number of reason may exists but the important thing is that despite you may have enabled Automatic Package Restore in Visual Studio by:

  • Manage NuGet packages for solution (context menu in Solution Explorer),
  • Allow NuGet to download missing packages (settings),
  • Automatically check for missing packages during build in Visual Studio (settings),

certain packages may require a manual reinstall. I am not aware what confuses NuGet, maybe manually removing a reference, but here is the solution I usually apply in such cases. The following PM Console helps restoring a package while preserving the original version (not updating to possibly existing new one):

Update-Package Microsoft.Web.Infrastructure -Reinstall

Version preservation may be required if you do not want to accidentally overwrite an existing package with its newer version which possibly removes "old" functionality you may have used in your project.

And, as a proof, despite a bit lengthy one, that the version does not change, here's the output when the command is executed:

PM> Update-Package Microsoft.Web.Infrastructure -Reinstall
Attempting to gather dependencies information for multiple packages with respect to project 'Samples.NuGet\DemoApp\DemoApp', targeting '.NETFramework,Version=v4.5.2'
Attempting to resolve dependencies for multiple packages
Resolving actions install multiple packages
...
Package removal starts here...
...
Removed package 'Microsoft.AspNet.Web.Optimization 1.1.3' from 'packages.config'
Successfully uninstalled 'Microsoft.AspNet.Web.Optimization 1.1.3' from DemoApp
Removed package 'WebGrease 1.5.2' from 'packages.config'
Executing script file 'D:\Projects\DemoApp\packages\WebGrease.1.5.2\tools\uninstall.ps1'
Successfully uninstalled 'WebGrease 1.5.2' from DemoApp
...
More package removals here. Omitted for brevity...
...
Removed package 'Microsoft.Web.Infrastructure 1.0.0.0' from 'packages.config'
Successfully uninstalled 'Microsoft.Web.Infrastructure 1.0.0.0' from DemoApp
...
More package removals here. Omitted for brevity...
...
Removed package 'Antlr 3.4.1.9004' from 'packages.config'
Successfully uninstalled 'Antlr 3.4.1.9004' from MvcLenseApp
Package 'Antlr.3.4.1.9004' already exists in folder 'D:\Projects\Lense.Mvc5\packages'
--- Install packages (in reverse order) ---
Package 'Antlr.3.4.1.9004' already exists in folder 'D:\Projects\DemoApp\packages'
Added package 'Antlr.3.4.1.9004' to 'packages.config'
Successfully installed 'Antlr 3.4.1.9004' to DemoApp
...
More package installs here. Omitted for brevity...
...
Package 'Microsoft.Web.Infrastructure.1.0.0' already exists in folder 'D:\Projects\Lense.Mvc5\packages'
Added package 'Microsoft.Web.Infrastructure.1.0.0' to 'packages.config'
Successfully installed 'Microsoft.Web.Infrastructure 1.0.0' to MvcLenseApp
...
More package installs here. Omitted for brevity...
...
Package 'WebGrease.1.5.2' already exists in folder 'D:\Projects\DemoApp\packages'
Added package 'WebGrease.1.5.2' to 'packages.config'
Executing script file 'D:\Projects\DemoApp\packages\WebGrease.1.5.2\tools\install.ps1'
Successfully installed 'WebGrease 1.5.2' to DemoApp
Package 'Microsoft.AspNet.Web.Optimization.1.1.3' already exists in folder 'D:\Projects\DemoApp\packages'
Added package 'Microsoft.AspNet.Web.Optimization.1.1.3' to 'packages.config'
...
End of package re-install. 
...
Successfully installed 'Microsoft.AspNet.Web.Optimization 1.1.3' to DemoApp
PM> 

Of course if you wish to reinstall all packages you may need to get familiar with update/install commands in NuGet here and here.

Cannot open Windows.h in Microsoft Visual Studio

1) Go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A for VS2013

2) Copy the folders Include and Lib (you should check where are your folders in folder windows such as v7.1, v8, v6, etc.)

3) Paste them into C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC

I solved my problems like:

error lnk1104: cannot open file 'kernel32.lib'.
error c1083: Cannot open Windows.h

Thanks.

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

I had the same issue, was having the same error and for me it worked like this:

[self.tableView registerNib:[UINib nibWithNibName:CELL_NIB_HERE bundle: nil] forCellReuseIdentifier:CELL_IDENTIFIER_HERE];

Maybe it will be usefull for someone else.

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

Well, I think the error says that it can't find a nib file named "RootViewController" in your project.

You are writing these lines of code,

self.viewController = [[RootViewController alloc]      initWithNibName:@"RootViewController_iPhone.xib" bundle:nil];

self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController_iPad.xib" bundle:nil];

At the same time you are asking it to load a nib file named "RootviewController"..!! Where is it..? Do you have a xib file named "Rootviewcontroller"..?

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

I know that its late but it might be helpful for people who need to change the Bundle Identifier of the app. In the finder go to the project folder:

the project file --> Right click on your project file '*.xcodeproj' 

enter image description here

--> choose 'Show Package Contents' 
--> Double click to open 'project.pbxproj' file 

enter image description here

--> find 'productName = NAME_YOU_WANT_TO_CHANGE' in the 
    '/* Begin PBXNativeTarget section */'

The ${PRODUCT_NAME:rfc1034identifier} variable will be replaced with the name you have entered and new Bundle Identifier will be updated to what you need it to be.

The module was expected to contain an assembly manifest

First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

For those of you who with Nexus 5x who only see Kedacom usb device in Device Manager and cannot get adb to see the phone...the trick is to Update driver... on the Kedacom device and change it to "Android ADB interface/device"

Get the current displaying UIViewController on the screen in AppDelegate.m

I have found that iOS 8 has screwed everything up. In iOS 7 there is a new UITransitionView on the view hierarchy whenever you have a modally presented UINavigationController. Anyway, here's my code that finds gets the topmost VC. Calling getTopMostViewController should return a VC that you should be able to send a message like presentViewController:animated:completion. It's purpose is to get you a VC that you can use to present a modal VC, so it will most likely stop and return at container classes like UINavigationController and NOT the VC contained within them. Should not be hard to adapt the code to do that too. I've tested this code in various situations in iOS 6, 7 and 8. Please let me know if you find bugs.

+ (UIViewController*) getTopMostViewController
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(window in windows) {
            if (window.windowLevel == UIWindowLevelNormal) {
                break;
            }
        }
    }

    for (UIView *subView in [window subviews])
    {
        UIResponder *responder = [subView nextResponder];

        //added this block of code for iOS 8 which puts a UITransitionView in between the UIWindow and the UILayoutContainerView
        if ([responder isEqual:window])
        {
            //this is a UITransitionView
            if ([[subView subviews] count])
            {
                UIView *subSubView = [subView subviews][0]; //this should be the UILayoutContainerView
                responder = [subSubView nextResponder];
            }
        }

        if([responder isKindOfClass:[UIViewController class]]) {
            return [self topViewController: (UIViewController *) responder];
        }
    }

    return nil;
}

+ (UIViewController *) topViewController: (UIViewController *) controller
{
    BOOL isPresenting = NO;
    do {
        // this path is called only on iOS 6+, so -presentedViewController is fine here.
        UIViewController *presented = [controller presentedViewController];
        isPresenting = presented != nil;
        if(presented != nil) {
            controller = presented;
        }

    } while (isPresenting);

    return controller;
}

AppFabric installation failed because installer MSI returned with error code : 1603

I also hit this error…

The installation msi will try to create a new task in the Windows Task scheduler to remind you to give customer feedback. This install step executes regardless of whether you do or do not click the check box to participate in customer feedback. In many corporate environments (including mine) creating new windows tasks is denied to all but domain administrators. As a result, running as a local admin is not sufficient and the entire installation fails when adding the task returns “access denied”. This shows up in the install log as a 1603.

The only workaround we could find was to manually pull all the files out of the msi, remove the “add schedule task” from the install script, and then create a new msi. After that one line change, it worked fine.

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

What is the target platform of your application? I think you should set the platform to x86, do not set it to Any CPU.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

Short:
In you have this problem with a pure Web API project (and thus don't need razor), try to add it anyway, rebuild, then remove it.

Long story:
I had this problem with a brand-new pure Web API project, except that the stacktrace pointed "System.Web.Mvc" as Calling assembly (see Darin's answer). No reference to MVC, Razor or anything like that in my project though...
I decided to add the MVC packages (AspNet.Mvc, AspNet.WebPages and AspNet.Razor) to check if there was any subsequent problem.
The WebApi app then launched perfectly fine. Then I removed the exact same packages and everything was still OK.

Hope it helps someone.

Getting activity from context in android

And in Kotlin:

tailrec fun Context.activity(): Activity? = when {
  this is Activity -> this
  else -> (this as? ContextWrapper)?.baseContext?.activity()
}

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Troubleshooting BadImageFormatException

It can typically occur when you changed the target framework of .csproj and reverted it back to what you started with.

Make sure 1 if supportedRuntime version="a different runtime from cs project target" under startup tag in app.config.

Make sure 2 That also means checking other autogenerated or other files in may be properties folder to see if there is no more runtime mismatch between these files and one that is defined in .csproj file.

These might just save you lot of time before you start trying different things with project properties to overcome the error.

How to add default signature in Outlook

Most of the other answers are simply concatenating their HTML body with the HTML signature. However, this does not work with images, and it turns out there is a more "standard" way of doing this.1

Microsoft Outlook pre-2007 which is configured with WordEditor as its editor, and Microsoft Outlook 2007 and beyond, use a slightly cut-down version of the Word Editor to edit emails. This means we can use the Microsoft Word Document Object Model to make changes to the email.

Set objMsg = Application.CreateItem(olMailItem)
objMsg.GetInspector.Display 'Displaying an empty email will populate the default signature
Set objSigDoc = objMsg.GetInspector.WordEditor
Set objSel = objSigDoc.Windows(1).Selection
With objSel
   .Collapse wdCollapseStart
   .MoveEnd WdUnits.wdStory, 1
   .Copy 'This will copy the signature
End With
objMsg.HTMLBody = "<p>OUR HTML STUFF HERE</p>"
With objSel
   .Move WdUnits.wdStory, 1 'Move to the end of our new message
   .PasteAndFormat wdFormatOriginalFormatting 'Paste the copied signature
End With 
'I am not a VB programmer, wrote this originally in another language so if it does not
'compile it is because this is my first VB method :P

Microsoft Outlook 2007 Programming (S. Mosher)> Chapter 17, Working with Item Bodies: Working with Outlook Signatures

How can I specify a [DllImport] path at runtime?

DllImport will work fine without the complete path specified as long as the dll is located somewhere on the system path. You may be able to temporarily add the user's folder to the path.

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

There are other ways to parse it rather than the first answer. To parse it:

(1) If you want to grab information about date and time, you can parse it to a ZonedDatetime(since Java 8) or Date(old) object:

// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);

or

// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";

// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);

Date myDate = df.parse("2011-08-12T20:17:46.384Z");

(2) If you don't care the date and time and just want to treat the information as a moment in nanoseconds, then you can use Instant:

// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

"Application tried to present modally an active controller"?

Instead of using:

self.present(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?)

you can use:

self.navigationController?.pushViewController(viewController: UIViewController, animated: Bool)

How to solve error message: "Failed to map the path '/'."

~I've gone to the Internet Information Services Manager

~Click the sites

~Right click on your website

~Click Manage Website > Advance Settings

~Change the application pool to DefaultAppPool

And it works fine to me.

Batch file. Delete all files and folders in a directory

I just put this together from what morty346 posted:

set folder="C:\test"
IF EXIST "%folder%" (
    cd /d %folder%
    for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
)

It adds a quick check that the folder defined in the variable exists first, changes directory to the folder, and deletes the contents.

Best way to get application folder path

AppDomain.CurrentDomain.BaseDirectory is probably the most useful for accessing files whose location is relative to the application install directory.

In an ASP.NET application, this will be the application root directory, not the bin subfolder - which is probably what you usually want. In a client application, it will be the directory containing the main executable.

In a VSTO 2005 application, it will be the directory containing the VSTO managed assemblies for your application, not, say, the path to the Excel executable.

The others may return different directories depending on your environment - for example see @Vimvq1987's answer.

CodeBase is the place where a file was found and can be a URL beginning with http://. In which case Location will probably be the assembly download cache. CodeBase is not guaranteed to be set for assemblies in the GAC.

UPDATE These days (.NET Core, .NET Standard 1.3+ or .NET Framework 4.6+) it's better to use AppContext.BaseDirectory rather than AppDomain.CurrentDomain.BaseDirectory. Both are equivalent, but multiple AppDomains are no longer supported.

program cant start because php5.dll is missing

What you can do to solve this is:

  1. Download PHP5.dll or PHP7.dll from: http://windows.php.net/download/.
  2. Copy the downloaded php5.dll or php7.dll to C:\xampp\php.
  3. Start Apache and MySQL from XAMPP Control Panel.

Error: The type exists in both directories

If your are migrating ASP.NET 2.0 Website to .NET Web APP 4.5, you can have that issue too. And puting batch=false, adding a namespace etc... can not work.

The workaround is to rename the old App_Code folder (or any problematic folder) to Old_App_Code (like the automatic process do it), or any other name.

Manually adding a Userscript to Google Chrome

This parameter is is working for me:

--enable-easy-off-store-extension-install

Do the following:

  1. Right click on your "Chrome" icon.
  2. Choose properties
  3. At the end of your target line, place these parameters: --enable-easy-off-store-extension-install
  4. It should look like: chrome.exe --enable-easy-off-store-extension-install
  5. Start Chrome by double-clicking on the icon

How would I run an async Task<T> method synchronously?

I've faced it a few times, mostly in unit testing or in a windows service development. Currently I always use this feature:

        var runSync = Task.Factory.StartNew(new Func<Task>(async () =>
        {
            Trace.WriteLine("Task runSync Start");
            await TaskEx.Delay(2000); // Simulates a method that returns a task and
                                      // inside it is possible that there
                                      // async keywords or anothers tasks
            Trace.WriteLine("Task runSync Completed");
        })).Unwrap();
        Trace.WriteLine("Before runSync Wait");
        runSync.Wait();
        Trace.WriteLine("After runSync Waited");

It's simple, easy and I had no problems.

Failed loading english.pickle with nltk.data.load

In Python-3.6 I can see the suggestion in the traceback. That's quite helpful. Hence I will say you guys to pay attention to the error you got, most of the time answers are within that problem ;).

enter image description here

And then as suggested by other folks here either using python terminal or using a command like python -c "import nltk; nltk.download('wordnet')" we can install them on the fly. You just need to run that command once and then it will save the data locally in your home directory.

How to deselect a selected UITableView cell?

What I've found is that on top of setting the cell as selected, you have to let the table view know to select the row at the given index path.

// Swift 3+  

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if appDelegate.indexPathDelegate.row == indexPath.row {
        self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
        cell.setSelected(true, animated: true)
    }
}

ObjectiveC Parse Integer from String

Basically, the third parameter in loggedIn should not be an integer, it should be an object of some kind, but we can't know for sure because you did not name the parameters in the method call. Provide the method signature so we can see for sure. Perhaps it takes an NSNumber or something.

Python base64 data decode

import base64
coded_string = '''Q5YACgA...'''
base64.b64decode(coded_string)

worked for me. At the risk of pasting an offensively-long result, I got:

>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]
\xbb\x00\x00\x00\x00D\xc5!7\x00\x00\x00\x00D\xc5!\xb2\x00\x00\x00\x00D\xc7\x14x\x00\x00\x00\x00D\xc7\x14\xf6\x00\x00\x00\x00D\xc7\x15t\x00\x00\x00\x00D\xc7\x15\xf2\x00\x00\x00\x00D\xc7\x16pC5\x9f\xf9D\xc7\x16\xeeC[\xb5\xf5D\xc7\x17lCG\x1b;D\xc7\x17\xeaB\xe3\x0b\xa6D\xc7\x18h\x00\x00\x00\x00D\xc7\x18\xe6\x00\x00\x00\x00D\xc7\x19d\x00\x00\x00\x00D\xc7\x19\xe2\x00\x00\x00\x00D\xc7\xfe\xb4\x00\x00\x00\x00D\xc7\xff3\x00\x00\x00\x00D\xc7\xff\xb2\x00\x00\x00\x00D\xc8\x001\x00\x00\x00\x00'

What problem are you having, specifically?

.NET Global exception handler in console application

You also need to handle exceptions from threads:

static void Main(string[] args) {
Application.ThreadException += MYThreadHandler;
}

private void MYThreadHandler(object sender, Threading.ThreadExceptionEventArgs e)
{
    Console.WriteLine(e.Exception.StackTrace);
}

Whoop, sorry that was for winforms, for any threads you're using in a console application you will have to enclose in a try/catch block. Background threads that encounter unhandled exceptions do not cause the application to end.

How does one check if a table exists in an Android SQLite database?

You mentioned that you've created an class that extends SQLiteOpenHelper and implemented the onCreate method. Are you making sure that you're performing all your database acquire calls with that class? You should only be getting SQLiteDatabase objects via the SQLiteOpenHelper#getWritableDatabase and getReadableDatabase otherwise the onCreate method will not be called when necessary. If you are doing that already check and see if th SQLiteOpenHelper#onUpgrade method is being called instead. If so, then the database version number was changed at some point in time but the table was never created properly when that happened.

As an aside, you can force the recreation of the database by making sure all connections to it are closed and calling Context#deleteDatabase and then using the SQLiteOpenHelper to give you a new db object.

Executable directory where application is running from?

You could use the static StartupPath property of the Application class.

How to store custom objects in NSUserDefaults

Synchronize the data/object that you have saved into NSUserDefaults

-(void)saveCustomObject:(Player *)object
{ 
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [prefs setObject:myEncodedObject forKey:@"testing"];
    [prefs synchronize];
}

Hope this will help you. Thanks

How to decrypt an encrypted Apple iTunes iPhone backup?

You should grab a copy of Erica Sadun's mdhelper command line utility (OS X binary & source). It supports listing and extracting the contents of iPhone/iPod Touch backups, including address book & SMS databases, and other application metadata and settings.

Could not load file or assembly 'System.Data.SQLite'

As someone who's had to deal with quite a few bug reports on Roadkill Wiki with exactly the same issue, this is what you need to do:

  • Are you using x64 or x86? Sqlite comes with DLLs for separate architectures - copy the right one to your bin folder, there are two DLLS for the official provider: System.Data.SQLite.dll System.Data.SQLite.Linq.dll
  • If you can't be bothered hunting around for these assemblies, enable 32 bit mode for your App Pool (a solution for dev machines only usually)
  • If you're hosting on a server, you'll need the Microsoft C++ Runtime redistributable - it's not installed on Server 2008 R2 by default. x64 version, x86 version

It's a real pain in the ass how many hoops you have to jump through when re-distributing the SQLite .NET binaries, my solution for Roadkill in the end was to copy the correct binaries to the ~/bin folder based on the architecture your using. Unfortunately that doesn't solve the C++ runtime issue.

Getting the application's directory from a WPF application

Try this. Don't forget using System.Reflection.

string baseDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Ubuntu 9.10 -> Ubuntu 12.04 with mono 2.10.8.1:

SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles: 
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.System: 

SpecialFolder.Personal: /home/$USER

Output on Ubuntu 16.04 with mono 4.2.1

SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles:
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.Desktop: /home/$USER/Desktop
SpecialFolder.Personal: /home/$USER

SpecialFolder.System: 
SpecialFolder.Programs: 
SpecialFolder.Favorites: 
SpecialFolder.Startup: 
SpecialFolder.Recent: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.MyMusic: /home/$USER/Music
SpecialFolder.MyVideos: /home/$USER/Videos
SpecialFolder.MyComputer: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.Fonts: /home/$USER/.fonts
SpecialFolder.Templates: /home/$USER/Templates
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.InternetCache: 
SpecialFolder.Cookies: 
SpecialFolder.History: 
SpecialFolder.Windows: 
SpecialFolder.MyPictures: /home/$USER/Pictures
SpecialFolder.UserProfile: /home/$USER
SpecialFolder.SystemX86: 
SpecialFolder.ProgramFilesX86: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonTemplates: /usr/share/templates
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.AdminTools: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonVideos: 
SpecialFolder.Resources: 
SpecialFolder.LocalizedResources: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CDBurning: 

where $USER is the current user

Output on Ubuntu 16.04 using dotnet core (3.0.100)

ApplicationData: /home/$USER/.config
CommonApplicationData: /usr/share
ProgramFiles: 
DesktopDirectory: /home/$USER/Desktop
LocalApplicationData: /home/$USER/.local/share
MyDocuments: /home/$USER
System: 
Personal: /home/$USER

Output on Android 6 using Xamarin 7.2

Environment.SpecialFolder.ApplicationData: /data/user/0/$APPNAME/files/.config
Environment.SpecialFolder.CommonApplicationData: /usr/share
Environment.SpecialFolder.ProgramFiles: 
Environment.SpecialFolder.DesktopDirectory: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.LocalApplicationData: /data/user/0/$APPNAME/files/.local/share
Environment.SpecialFolder.MyDocuments: /data/user/0/$APPNAME/files
Environment.SpecialFolder.Desktop: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.Personal: /data/user/0/$APPNAME/files

Environment.SpecialFolder.Startup: 
Environment.SpecialFolder.Recent: 
Environment.SpecialFolder.SendTo: 
Environment.SpecialFolder.StartMenu: 
Environment.SpecialFolder.MyMusic: /data/user/0/$APPNAME/files/Music
Environment.SpecialFolder.MyVideos: /data/user/0/$APPNAME/files/Videos
Environment.SpecialFolder.MyComputer: 
Environment.SpecialFolder.NetworkShortcuts: 
Environment.SpecialFolder.Fonts: /data/user/0/$APPNAME/files/.fonts
Environment.SpecialFolder.Templates: /data/user/0/$APPNAME/files/Templates
Environment.SpecialFolder.CommonStartMenu: 
Environment.SpecialFolder.CommonPrograms: 
Environment.SpecialFolder.CommonStartup: 
Environment.SpecialFolder.CommonDesktopDirectory: 
Environment.SpecialFolder.PrinterShortcuts: 
Environment.SpecialFolder.InternetCache: 
Environment.SpecialFolder.Cookies: 
Environment.SpecialFolder.History: 
Environment.SpecialFolder.Windows: 
Environment.SpecialFolder.MyPictures: /data/user/0/$APPNAME/files/Pictures
Environment.SpecialFolder.UserProfile: /data/user/0/$APPNAME/files
Environment.SpecialFolder.SystemX86: 
Environment.SpecialFolder.ProgramFilesX86: 
Environment.SpecialFolder.CommonProgramFiles: 
Environment.SpecialFolder.CommonProgramFilesX86: 
Environment.SpecialFolder.CommonTemplates: /usr/share/templates
Environment.SpecialFolder.CommonDocuments: 
Environment.SpecialFolder.CommonAdminTools: 
Environment.SpecialFolder.AdminTools: 
Environment.SpecialFolder.CommonMusic: 
Environment.SpecialFolder.CommonPictures: 
Environment.SpecialFolder.CommonVideos: 
Environment.SpecialFolder.Resources: 
Environment.SpecialFolder.LocalizedResources: 
Environment.SpecialFolder.CommonOemLinks: 
Environment.SpecialFolder.CDBurning: 

Where $APPNAME is the name of your Xamarin application (eg. MyApp.Droid)

Output on iOS Simulator 10.3 using Xamarin 7.2

ApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.config
CommonApplicationData: /usr/share
ProgramFiles: /Applications
DesktopDirectory: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
LocalApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Desktop: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Startup: 
Recent: 
SendTo: 
StartMenu: 
MyMusic: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Music
MyVideos: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Videos
MyComputer: 
NetworkShortcuts: 
Fonts: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.fonts
Templates: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Templates
CommonStartMenu: 
CommonPrograms: 
CommonStartup: 
CommonDesktopDirectory: 
PrinterShortcuts: 
InternetCache: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library/Caches
Cookies: 
History: 
Windows: 
MyPictures: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Pictures
UserProfile: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID
SystemX86: 
ProgramFilesX86: 
CommonProgramFiles: 
CommonProgramFilesX86: 
CommonTemplates: /usr/share/templates
CommonDocuments: 
CommonAdminTools: 
AdminTools: 
CommonMusic: 
CommonPictures: 
CommonVideos: 
Resources: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library
LocalizedResources: 
CommonOemLinks: 
CDBurning: 

Where $DEVICEGUID is the simulator GUID (depending on the selected simulator)

Output on ipad 10.3 using Xamarin 7.2

SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents

Output on ipad 13.3 using Xamarin 16.4

SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents
SpecialFolder.UserProfile: /private/var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents

Output on windows 10 using .net core 3.1

SpecialFolder.MyDocuments: C:\Users\$USER\Documents

Output on Ubuntu 18.04 using .net core 3.1

SpecialFolder.MyDocuments: /home/$USER

Output on MacOS Catalina using .net core 3.1

SpecialFolder.MyDocuments: /Users/$USER

C# getting the path of %AppData%

This is working for me in a console application -

string appData = System.Environment.GetEnvironmentVariable("APPDATA");

How to resolve 'unrecognized selector sent to instance'?

Very weird, but. You have to declare the class for your application instance as myApplication: UIApplication instead of myApplication: NSObject . It seems that the UIApplicationDelegate protocol doesn't implement the +registerForSystemEvents message. Crazy Apple APIs, again.

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

This solution works well for me, on Develop and also on TEST and PROD servers with ASP.NET MVC5 via C#:

var projectDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);

If you need project directory in project configuration file use:

$(ProjectDir)

How to Load an Assembly to AppDomain with all references recursively?

You need to handle the AppDomain.AssemblyResolve or AppDomain.ReflectionOnlyAssemblyResolve events (depending on which load you're doing) in case the referenced assembly is not in the GAC or on the CLR's probing path.

AppDomain.AssemblyResolve

AppDomain.ReflectionOnlyAssemblyResolve

What is the App_Data folder used for in Visual Studio?

The App_Data folder is a folder, which your asp.net worker process has files sytem rights too, but isn't published through the web server.

For example we use it to update a local CSV of a contact us form. If the preferred method of emails fails or any querying of the data source is required, the App_Data files are there.

It's not ideal, but it it's a good fall-back.

"unmappable character for encoding" warning in Java

For those wondering why this happens on some systems and not on others (with the same source, build parameters, and so on), check your LANG environment variable. I get the warning/error when LANG=C.UTF-8, but not when LANG=en_US.UTF-8.

How do I list all loaded assemblies?

Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values.

foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){                      
            System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
            foreach(Type type in asm.GetTypes()){   
                //PROPERTIES
                foreach (System.Reflection.PropertyInfo property in type.GetProperties()){
                    if (property.CanRead){
                        Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name);       
                    }
                }
                //METHODS
                var methods = type.GetMethods();
                foreach (System.Reflection.MethodInfo method in methods){               
                    Response.Write("<br><b>" + an.ToString() + "."  + type.ToString() + "." + method.Name  + "</b>");   
                    foreach (System.Reflection.ParameterInfo param in method.GetParameters())
                    {
                        Response.Write("<br><i>Param=" + param.Name.ToString());
                        Response.Write("<br>  Type=" + param.ParameterType.ToString());
                        Response.Write("<br>  Position=" + param.Position.ToString());
                        Response.Write("<br>  Optional=" + param.IsOptional.ToString() + "</i>");
                    }
                }
            }
        }

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

 <uses-permission android:name="android.permission.INTERNET" />

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Resetting MySQL Root Password with XAMPP on Localhost

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command within the Shell:

mysqladmin.exe -u root password WhateverPassword

where WhateverPassword is your new password.

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Maintaining the final state at end of a CSS3 animation

Try adding animation-fill-mode: forwards;. For example like this:

-webkit-animation: bubble 1.0s forwards; /* for less modern browsers */
        animation: bubble 1.0s forwards;

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Reverse a string in Python

def reverse_string(string):
    length = len(string)
    temp = ''
    for i in range(length):
        temp += string[length - i - 1]
    return temp

print(reverse_string('foo')) #prints "oof"

This works by looping through a string and assigning its values in reverse order to another string.

'int' object has no attribute '__getitem__'

Some of the problems:

for i in range[6]:
            for j in range[6]:

should be:

range(6)

How to get multiline input from user

raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:

Python 3

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
    try:
        line = input()
    except EOFError:
        break
    contents.append(line)

Python 2

print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
    try:
        line = raw_input("")
    except EOFError:
        break
    contents.append(line)

.NET code to send ZPL to Zebra printers

Here is how to do it using TCP IP protocol :

// Printer IP Address and communication port
    string ipAddress = "10.3.14.42";
   int port = 9100;

// ZPL Command(s)
   string ZPLString =
    "^XA" +
    "^FO50,50" +
    "^A0N50,50" +
    "^FDHello, World!^FS" +
    "^XZ";

   try
   {
    // Open connection
    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
    client.Connect(ipAddress, port);

    // Write ZPL String to connection
    System.IO.StreamWriter writer =
    new System.IO.StreamWriter(client.GetStream());
    writer.Write(ZPLString);
    writer.Flush();

    // Close Connection
    writer.Close();
    client.Close();
}
catch (Exception ex)
{
    // Catch Exception
}

Source : ZEBRA WEBSITE

Understanding Spring @Autowired usage

TL;DR

The @Autowired annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.

Full explanation

The @Autowired annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies you have to put this tag in your XML (application context file):

<context:component-scan base-package="com.mycompany.movies" />

This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component (for simple bean) or @Controller (for a servlet control) or @Repository (for DAO classes) and these classes are somewhere under the package com.mycompany.movies, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration class (or any combination of the three).

The @Autowired annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder it understands (by the prefix set + the @Autowired annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception. To avoid the Exception, you can use the @Qualifier annotation and tell it which of the two beans to inject in the following manner:

@Qualifier("redBean")
class Red implements Color {
   // Class code here
}

@Qualifier("blueBean")
class Blue implements Color {
   // Class code here
}

Or if you prefer to declare the beans in your XML, it would look something like this:

<bean id="redBean" class="com.mycompany.movies.Red"/>

<bean id="blueBean" class="com.mycompany.movies.Blue"/>

In the @Autowired declaration, you need to also add the @Qualifier to tell which of the two color beans to inject:

@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
  this.color = color;
}

If you don't want to use two annotations (the @Autowired and @Qualifier) you can use @Resource to combine these two:

@Resource(name="redBean")
public void setColor(Color color) {
  this.color = color;
}

The @Resource (you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.

I'll just add two more comments:

  1. Good practice would be to use @Inject instead of @Autowired because it is not Spring-specific and is part of the JSR-330 standard.
  2. Another good practice would be to put the @Inject / @Autowired on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException when you need to actually use the bean.

Update: To complete the picture, I created a new question about the @Configuration class.

Duplicate symbols for architecture x86_64 under Xcode

I also have this fault today.That's because I defined a const value in a .m file.But I defined another .m file that also included this const value.That's means it has two same const values.So this error appears. And my solution is adding a keyword "static" before the const value.such as:

static CGFloat const btnConunt = 9;

And then I build the project it won't report this error.

How to get screen width without (minus) scrollbar?

None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Try this:

tar -czf my.tar.gz dir/

But are you sure you are not compressing some .exe file or something? Maybe the problem is not with te compression, but with the files you are compressing?

List to array conversion to use ravel() function

create an int array and a list

from array import array
listA = list(range(0,50))
for item in listA:
    print(item)
arrayA = array("i", listA)
for item in arrayA:
    print(item)

javascript find and remove object in array based on key value

Maybe you are looking for $.grep() function:

arr = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

id = 88;
arr = $.grep(arr, function(data, index) {
   return data.id != id
});

Get first day of week in PHP?

$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date))));

You have to get next monday first then get the 'last monday' of next monday. So if the given date is monday it will return the same date not last week monday.

Git: Installing Git in PATH with GitHub client for Windows

To get this to work I had to combine many of the above answers, to anyone who this might help here is my much simpler process.

If you have Windows 10 just start typing "edit environmental..." and it'll pop up right away. Click path and Edit… then paste the ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd at the end of the path already there, don't forget the ; to separate your new github path from the current path.

You do not need the guid but if you want to know how to find it open bash, type git --man-path

JPA Query selecting only specific columns without using Criteria Query?

Projections can be used to select only specific properties(columns) of an entity object.

From the docs

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.

Define an interface with only the getters you want.

interface CustomObject {  
    String getA(); // Actual property name is A
    String getB(); // Actual property name is B 
}

Now return CustomObject from your repository like so :

public interface YOU_REPOSITORY_NAME extends JpaRepository<YOUR_ENTITY, Long> {
    CustomObject findByObjectName(String name);
}

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

Create a tar.xz in one command

Quick Solution

tarxz() { tar cf - "$1" | xz -4e > "$1".tar.xz ; }
tarxz name_of_directory

(Notice, not name_of_directory/)


Using xz compression options

If you want to use compression options for xz, or if you are using tar on MacOS, you probably want to avoid the tar -cJf syntax.

According to man xz, the way to do this is:

tar cf - filename | xz -4e > filename.tar.xz

Because I liked Wojciech Adam Koszek's format, but not information:

  1. c creates a new archive for the specified files.
  2. f reads from a directory (best to put this second because -cf != -fc)
  3. - outputs to Standard Output
  4. | pipes output to the next command
  5. xz -4e calls xz with the -4e compression option. (equal to -4 --extreme)
  6. > filename.tar.xz directs the tarred and compressed file to filename.tar.xz

where -4e is, use your own compression options. I often use -k to --keep the original file and -9 for really heavy compression. -z to manually set xz to zip, though it defaults to zipping if not otherwise directed.

To uncompress and untar

To echo Rafael van Horn, to uncompress & untar (see note below):

xz -dc filename.tar.xz | tar x

Note: unlike Rafael's answer, use xz -dc instead of catxz. The docs recommend this in case you are using this for scripting. Best to have a habit of using -d or --decompress instead of unxz as well. However, if you must, using those commands from the command line is fine.

Using subprocess to run Python script on Windows

Just found sys.executable - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)

import sys
import subprocess

theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()

How do I create a file AND any folders, if the folders don't exist?

DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
    Directory.GetCreationTime(path));

See this MSDN page.

Hope that helps out!

How to make blinking/flashing text with CSS 3

@-webkit-keyframes blinker {  
  0% { opacity: 1.0; }
  50% { opacity: 0.0; }
  100% { opacity: 1.0; }
}

_x000D_
_x000D_
@-webkit-keyframes blinker {  _x000D_
  0% { opacity: 1.0; }_x000D_
  50% { opacity: 0.0; }_x000D_
  100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
.blink {_x000D_
  width: 10px;_x000D_
  height: 10px;_x000D_
  border-radius: 10px;_x000D_
  animation: blinker 2s linear infinite;_x000D_
  background-color: red;_x000D_
  margin-right: 5px;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
}
_x000D_
<div class="content">_x000D_
  <i class="blink"></i>_x000D_
  LIVE_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java generating non-repeating random numbers

HashSet<Integer>hashSet=new HashSet<>();
Random random = new Random();
//now add random number to this set
while(true)
{
    hashSet.add(random.nextInt(1000));
    if(hashSet.size()==1000)
        break;
}

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

Just a supplement here.

The following question is that what if I want more subplots in the figure?

As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2) to set a group of subplots with grid(2,2) in one figure object.

Then as we know, the fig, ax = plt.subplots() returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2) firstly.

ValueError: not enough values to unpack (expected 4, got 2)

It raises a error, but no worry, because we now see that plt.subplots() actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.

So let's try this again:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

and check the type:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.

Hope this would be helpful for you.

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

How to update Identity Column in SQL Server?

Complete solution for C# programmers using command builder

First of all, you have to know this facts:

  • In any case, you cannot modify an identity column, so you have to delete the row and re-add with new identity.
  • You cannot remove the identity property from the column (you would have to remove to column)
  • The custom command builder from .net always skips the identity column, so you cannot use it for this purpose.

So, once knowing that, what you have to do is. Either program your own SQL Insert statement, or program you own insert command builder. Or use this one that I'be programmed for you. Given a DataTable, generates the SQL Insert script:

public static string BuildInsertSQLText ( DataTable table )
{
    StringBuilder sql = new StringBuilder(1000,5000000);
    StringBuilder values = new StringBuilder ( "VALUES (" );
    bool bFirst = true;
    bool bIdentity = false;
    string identityType = null;

    foreach(DataRow myRow in table.Rows) 
    {
        sql.Append( "\r\nINSERT INTO " + table.TableName + " (" );

        foreach ( DataColumn column in table.Columns )
        {
            if ( column.AutoIncrement )
            {
                bIdentity = true;

                switch ( column.DataType.Name )
                {
                    case "Int16":
                        identityType = "smallint";
                        break;
                    case "SByte":
                        identityType = "tinyint";
                        break;
                    case "Int64":
                        identityType = "bigint";
                        break;
                    case "Decimal":
                        identityType = "decimal";
                        break;
                    default:
                        identityType = "int";
                        break;
                }
            }
            else
            {
                if ( bFirst )
                    bFirst = false;
                else
                {
                    sql.Append ( ", " );
                    values.Append ( ", " );
                }
                sql.Append ("[");
                sql.Append ( column.ColumnName );
                sql.Append ("]");

                //values.Append (myRow[column.ColumnName].ToString() );

                if (myRow[column.ColumnName].ToString() == "True")
                    values.Append("1");
                else if (myRow[column.ColumnName].ToString() == "False")
                    values.Append("0");
                else if(myRow[column.ColumnName] == System.DBNull.Value)    
                    values.Append ("NULL");
                else if(column.DataType.ToString().Equals("System.String"))
                {
                    values.Append("'"+myRow[column.ColumnName].ToString()+"'");
                }
                else
                    values.Append (myRow[column.ColumnName].ToString());
                    //values.Append (column.DataType.ToString() );
            }
        }
        sql.Append ( ") " );
        sql.Append ( values.ToString () );
        sql.Append ( ")" );

        if ( bIdentity )
        {
            sql.Append ( "; SELECT CAST(scope_identity() AS " );
            sql.Append ( identityType );
            sql.Append ( ")" );
        }
        bFirst = true;
        sql.Append(";");
        values = new StringBuilder ( "VALUES (" );
    } //fin foreach
    return sql.ToString ();
}

Starting iPhone app development in Linux?

You need to get mac for it. There are several tool chains available (like win-chain) that actually lets you write and build i Phone applications on windows. There are several associated tutorials to build the Objective C code on Windows. But there is a problem, the apps hence developed will work on Jail broken i Phones only.

We’ve seen few hacks to get over that and make it to App Store, but as Apple keeps on updating SDKs, tool chains need regular updates. It’s a hassle to make it up all the time.If you want to get ready app you can also take help from arcapps its launches apps at a reasonable price. iphone app development

Prevent HTML5 video from being downloaded (right-click saved)?

We could make that not so easy by hiding context menu, like this:

<video oncontextmenu="return false;"  controls>
  <source src="https://yoursite.com/yourvideo.mp4" >
</video>

How to style dt and dd so they are on the same line?

Here is one possible flex-based solution (SCSS):

dl {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  dt {
    width: 150px;
  }
  dd {
    margin: 0;
    flex: 1 0 calc(100% - 150px);
  }
}

that works for the following HTML (pug)

dl
  dt item 1
  dd desc 1
  dt item 2
  dd desc 2

Cannot make a static reference to the non-static method

There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.

A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.

public class NonActivity {

    public static void doStuff(Context context) {
        String TTT = context.getText(R.string.TTT);
        ...
    }
}

And to call this from your Activity:

NonActivity.doStuff(this);

This will allow you to access your String resource without needing to use a public static field.

Read .mat files in Python

Having MATLAB 2014b or newer installed, the MATLAB engine for Python could be used:

import matlab.engine
eng = matlab.engine.start_matlab()
content = eng.load("example.mat", nargout=1)

How do I script a "yes" response for installing programs?

echo y | command should work.

Also, some installers have an "auto-yes" flag. It's -y for apt-get on Ubuntu.

can't access mysql from command line mac

On OSX 10.11, you can sudo nano /etc/paths and add the path(s) you want here, one per line. Way simpler than figuring which of ~/.bashrc, /etc/profile, '~/.bash_profile` etc... you should add to. Besides, why export and append $PATH to itself when you can just go and modify PATH directly...?

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

You can do this go to Settings > Storage, clicking on the setting menu icon in the top right hand corner and selecting "USB computer connection". I then changed the storage mode to "Camera (PTP)". Done try re installing the driver from device manager.

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

How to print an unsigned char in C?

The range of char is 127 to -128. If you assign 212, ch stores -44 (212-128-128) not 212.So if you try to print a negative number as unsigned you get (MAX value of unsigned int)-abs(number) which in this case is 4294967252

So if you want to store 212 as it is in ch the only thing you can do is declare ch as

unsigned char ch;

now the range of ch is 0 to 255.

WooCommerce: Finding the products in database

The following tables are store WooCommerce products database :

  • wp_posts -

    The core of the WordPress data is the posts. It is stored a post_type like product or variable_product.

  • wp_postmeta-

    Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id of product in wp_postmeta table.

Product categories, subcategories stored in this table :

  • wp_terms
  • wp_termmeta
  • wp_term_taxonomy
  • wp_term_relationships
  • wp_woocommerce_termmeta

following Query Return a list of product categories

SELECT wp_terms.* 
    FROM wp_terms 
    LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
    WHERE wp_term_taxonomy.taxonomy = 'product_cat';

for more reference -

Get table name by constraint name

SELECT owner, table_name
  FROM dba_constraints
 WHERE constraint_name = <<your constraint name>>

will give you the name of the table. If you don't have access to the DBA_CONSTRAINTS view, ALL_CONSTRAINTS or USER_CONSTRAINTS should work as well.

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

How to Sort Date in descending order From Arraylist Date in android?

Just add like this in case 1: like this

 case 0:
     list = DBAdpter.requestUserData(assosiatetoken);
     Collections.sort(list, byDate);
     for (int i = 0; i < list.size(); i++) {
         if (list.get(i).lastModifiedDate != null) {
             lv.setAdapter(new MyListAdapter(
                     getApplicationContext(), list));
         }
     }
     break;

and put this method at end of the your class

static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

    public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = sdf.parse(ord1.lastModifiedDate);
            d2 = sdf.parse(ord2.lastModifiedDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return (d1.getTime() > d2.getTime() ? -1 : 1);     //descending
    //  return (d1.getTime() > d2.getTime() ? 1 : -1);     //ascending
    }
};

Angular - Use pipes in services and components

If you want to use your custom pipe in your components, you can add

@Injectable({
  providedIn: 'root'
})

annotation to your custom pipe. Then, you can use it as a service

Finding multiple occurrences of a string within a string in Python

For your list example:

In [1]: x = ['ll','ok','ll']

In [2]: for idx, value in enumerate(x):
   ...:     if value == 'll':
   ...:         print idx, value       
0 ll
2 ll

If you wanted all the items in a list that contained 'll', you could also do that.

In [3]: x = ['Allowed','Hello','World','Hollow']

In [4]: for idx, value in enumerate(x):
   ...:     if 'll' in value:
   ...:         print idx, value
   ...:         
   ...:         
0 Allowed
1 Hello
3 Hollow

What is the difference between compare() and compareTo()?

There is a technical aspect that should be emphasized, too. Say you need comparison behavior parameterization from a client class, and you are wondering whether to use Comparable or Comparator for a method like this:

class Pokemon {
    int healthPoints;
    int attackDamage;
    public void battle (Comparable<Pokemon> comparable, Pokemon opponent) {
        if (comparable.compareTo(opponent) > 0) { //comparable needs to, but cannot, access this.healthPoints for example
            System.out.println("battle won");
        } else {
            System.out.println("battle lost");
        }
    }
}

comparable would a lambda or an object, and there is no way for comparable to access the fields of this Pokemon. (In a lambda, this refers to the outer class instance in the lambda's scope, as defined in the program text.) So this doesn't fly, and we have to use a Comparator with two arguments.

How can I convert a DateTime to an int?

string date = DateTime.Now.ToString();

date = date.Replace("/", "");
date = date.Replace(":", "");
date = date.Replace(" ", "");
date = date.Replace("AM", "");
date = date.Replace("PM", "");            
return date;

Find and replace entire mysql database

Another option (depending on the use case) would be to use DataMystic's TextPipe and DataPipe products. I've used them in the past, and they've worked great in the complex replacement scenarios, and without having to export data out of the database for find-and-replace.

Finding second occurrence of a substring in a string in Java

int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);

This overload starts looking for the substring from the given index.

<button> background image

Replace button #rock With #rock

No need for additional selector scope. You're using an id which is as specific as you can be.

JsBin example: http://jsbin.com/idobar/1/edit

FB OpenGraph og:image not pulling images (possibly https?)

In my case, it seems that the crawler is just having a bug. I've tried:

  • Changing links to http only
  • Removing end white space
  • Switching back to http completely
  • Reinstalling the website
  • Installing a bunch of OG plugins (I use WordPress)
  • Suspecting the server has a weird misconfiguration that blocks the bots (because all the OG checkers are unable to fetch tags, and other requests to my sites are unstable)

None of these works. This costed me a week. And suddenly out of nowhere it seems to work again.

Here are my research, if someone meets this problem again:

Also, there are more checkers other than the Facebook's Object Debugger for you to check: OpenGraphCheck.com, Abhinay Rathore's Open Graph Tester, Iframely's Embed Codes, Card Validator | Twitter Developers.

How can I close a browser window without receiving the "Do you want to close this window" prompt?

_x000D_
_x000D_
window.open('', '_self', '').close();
_x000D_
_x000D_
_x000D_

Sorry a bit late here, but i found the solution, at least for my case. Tested on Safari 11.0.3 and Google Chrome 64.0.3282.167

Format certain floating dataframe columns into percentage in pandas

Just another way of doing it should you require to do it over a larger range of columns

using applymap

df[['var1','var2']] = df[['var1','var2']].applymap("{0:.2f}".format)
df['var3'] = df['var3'].applymap(lambda x: "{0:.2f}%".format(x*100))

applymap is useful if you need to apply the function over multiple columns; it's essentially an abbreviation of the below for this specific example:

df[['var1','var2']].apply(lambda x: map(lambda x:'{:.2f}%'.format(x),x),axis=1)

Great explanation below of apply, map applymap:

Difference between map, applymap and apply methods in Pandas

Call PHP function from jQuery?

Yes, this is definitely possible. You'll need to have the php function in a separate php file. Here's an example using $.post:

$.post( 
    'yourphpscript.php', // location of your php script
    { name: "bob", user_id: 1234 }, // any data you want to send to the script
    function( data ){  // a function to deal with the returned information

        $( 'body ').append( data );

    });

And then, in your php script, just echo the html you want. This is a simple example, but a good place to get started:

<?php
    echo '<div id="test">Hello, World!</div>';
?>

Deep cloning objects

It's unbelievable how much effort you can spend with IClonable interface - especially if you have heavy class hierarchies. Also MemberwiseClone works somehow oddly - it does not exactly clone even normal List type kind of structures.

And of course most interesting dilemma for serialization is to serialize back references - e.g. class hierarchies where you have child-parent relationships. I doubt that binary serializer will be able to help you in this case. (It will end up with recursive loops + stack overflow).

I somehow liked solution proposed here: How do you do a deep copy of an object in .NET (C# specifically)?

however - it did not support Lists, added that support, also took into account re-parenting. For parenting only rule which I have made that field or property should be named "parent", then it will be ignored by DeepClone. You might want to decide your own rules for back-references - for tree hierarchies it might be "left/right", etc...

Here is whole code snippet including test code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TestDeepClone
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.name = "main_A";
            a.b_list.Add(new B(a) { name = "b1" });
            a.b_list.Add(new B(a) { name = "b2" });

            A a2 = (A)a.DeepClone();
            a2.name = "second_A";

            // Perform re-parenting manually after deep copy.
            foreach( var b in a2.b_list )
                b.parent = a2;


            Debug.WriteLine("ok");

        }
    }

    public class A
    {
        public String name = "one";
        public List<String> list = new List<string>();
        public List<String> null_list;
        public List<B> b_list = new List<B>();
        private int private_pleaseCopyMeAsWell = 5;

        public override string ToString()
        {
            return "A(" + name + ")";
        }
    }

    public class B
    {
        public B() { }
        public B(A _parent) { parent = _parent; }
        public A parent;
        public String name = "two";
    }


    public static class ReflectionEx
    {
        public static Type GetUnderlyingType(this MemberInfo member)
        {
            Type type;
            switch (member.MemberType)
            {
                case MemberTypes.Field:
                    type = ((FieldInfo)member).FieldType;
                    break;
                case MemberTypes.Property:
                    type = ((PropertyInfo)member).PropertyType;
                    break;
                case MemberTypes.Event:
                    type = ((EventInfo)member).EventHandlerType;
                    break;
                default:
                    throw new ArgumentException("member must be if type FieldInfo, PropertyInfo or EventInfo", "member");
            }
            return Nullable.GetUnderlyingType(type) ?? type;
        }

        /// <summary>
        /// Gets fields and properties into one array.
        /// Order of properties / fields will be preserved in order of appearance in class / struct. (MetadataToken is used for sorting such cases)
        /// </summary>
        /// <param name="type">Type from which to get</param>
        /// <returns>array of fields and properties</returns>
        public static MemberInfo[] GetFieldsAndProperties(this Type type)
        {
            List<MemberInfo> fps = new List<MemberInfo>();
            fps.AddRange(type.GetFields());
            fps.AddRange(type.GetProperties());
            fps = fps.OrderBy(x => x.MetadataToken).ToList();
            return fps.ToArray();
        }

        public static object GetValue(this MemberInfo member, object target)
        {
            if (member is PropertyInfo)
            {
                return (member as PropertyInfo).GetValue(target, null);
            }
            else if (member is FieldInfo)
            {
                return (member as FieldInfo).GetValue(target);
            }
            else
            {
                throw new Exception("member must be either PropertyInfo or FieldInfo");
            }
        }

        public static void SetValue(this MemberInfo member, object target, object value)
        {
            if (member is PropertyInfo)
            {
                (member as PropertyInfo).SetValue(target, value, null);
            }
            else if (member is FieldInfo)
            {
                (member as FieldInfo).SetValue(target, value);
            }
            else
            {
                throw new Exception("destinationMember must be either PropertyInfo or FieldInfo");
            }
        }

        /// <summary>
        /// Deep clones specific object.
        /// Analogue can be found here: https://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically
        /// This is now improved version (list support added)
        /// </summary>
        /// <param name="obj">object to be cloned</param>
        /// <returns>full copy of object.</returns>
        public static object DeepClone(this object obj)
        {
            if (obj == null)
                return null;

            Type type = obj.GetType();

            if (obj is IList)
            {
                IList list = ((IList)obj);
                IList newlist = (IList)Activator.CreateInstance(obj.GetType(), list.Count);

                foreach (object elem in list)
                    newlist.Add(DeepClone(elem));

                return newlist;
            } //if

            if (type.IsValueType || type == typeof(string))
            {
                return obj;
            }
            else if (type.IsArray)
            {
                Type elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));
                var array = obj as Array;
                Array copied = Array.CreateInstance(elementType, array.Length);

                for (int i = 0; i < array.Length; i++)
                    copied.SetValue(DeepClone(array.GetValue(i)), i);

                return Convert.ChangeType(copied, obj.GetType());
            }
            else if (type.IsClass)
            {
                object toret = Activator.CreateInstance(obj.GetType());

                MemberInfo[] fields = type.GetFieldsAndProperties();
                foreach (MemberInfo field in fields)
                {
                    // Don't clone parent back-reference classes. (Using special kind of naming 'parent' 
                    // to indicate child's parent class.
                    if (field.Name == "parent")
                    {
                        continue;
                    }

                    object fieldValue = field.GetValue(obj);

                    if (fieldValue == null)
                        continue;

                    field.SetValue(toret, DeepClone(fieldValue));
                }

                return toret;
            }
            else
            {
                // Don't know that type, don't know how to clone it.
                if (Debugger.IsAttached)
                    Debugger.Break();

                return null;
            }
        } //DeepClone
    }

}

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

For Mac OS X just install https://postgresapp.com/ and follow steps for command line section and ruby

sudo mkdir -p /etc/paths.d &&
echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp

Then

sudo ARCHFLAGS="-arch x86_64" gem install pg

Converting between java.time.LocalDateTime and java.util.Date

Much more convenient way if you are sure you need a default timezone :

Date d = java.sql.Timestamp.valueOf( myLocalDateTime );

How to pass credentials to the Send-MailMessage command for sending emails

PSH> $cred = Get-Credential

PSH> $cred | Export-CliXml c:\temp\cred.clixml

PSH> $cred2 = Import-CliXml c:\temp\cred.clixml

That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.

How to install node.js as windows service?

The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.

Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable machine-wide.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

JavaScript: Global variables after Ajax requests

AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.post out into the longer $.ajax call and adds the async option).

var it_works = false;

$.ajax({
  type: 'POST',
  async: false,
  url: "some_file.php",
  data: "",
  success: function() {it_works = true;}
});

alert(it_works);

Hope this helps!

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


How do I pass a method as a parameter in Python

Yes; functions (and methods) are first class objects in Python. The following works:

def foo(f):
    print "Running parameter f()."
    f()

def bar():
    print "In bar()."

foo(bar)

Outputs:

Running parameter f().
In bar().

These sorts of questions are trivial to answer using the Python interpreter or, for more features, the IPython shell.

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

Eclipse 3.5 Unable to install plugins

I had to turn off my personal firewall and Windows firewall as well, and it worked in the end.

Difference between two dates in Python

I tried the code posted by larsmans above but, there are a couple of problems:

1) The code as is will throw the error as mentioned by mauguerra 2) If you change the code to the following:

...
    d1 = d1.strftime("%Y-%m-%d")
    d2 = d2.strftime("%Y-%m-%d")
    return abs((d2 - d1).days)

This will convert your datetime objects to strings but, two things

1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and 2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings

What I found is that you literally only need the following:

import datetime

end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)

print difference_in_days

Best way to check for "empty or null value"

Checking for the length of the string also works and is compact:

where length(stringexpression) > 0;

When to use throws in a Java method declaration?

The code that you looked at is not ideal. You should either:

  1. Catch the exception and handle it; in which case the throws is unnecesary.

  2. Remove the try/catch; in which case the Exception will be handled by a calling method.

  3. Catch the exception, possibly perform some action and then rethrow the exception (not just the message)

ASP.NET DateTime Picker

Since it's the only one I've used, I would suggest the CalendarExtender from http://www.ajaxcontroltoolkit.com/

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

How to convert an int to a hex string?

With format(), as per format-examples, we can do:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

Loading cross-domain endpoint with AJAX

Your URL doesn't work these days, but your code can be updated with this working solution:

_x000D_
_x000D_
var url = "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P@ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute";_x000D_
_x000D_
url = 'https://google.com'; // TEST URL_x000D_
_x000D_
$.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=" + encodeURI(url), function(data) {_x000D_
    $('div.ajax-field').html(data);_x000D_
});
_x000D_
<div class="ajax-field"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

What are FTL files

FTL stands for FreeMarker Template.

It is very useful when you want to follow the MVC (Model View Controller) pattern.

The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers.

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 

where

P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

Can't connect to localhost on SQL Server Express 2012 / 2016

According to Aaron Bertand:

  1. You need to verify that the SQL Server service is running. You can do this by going to Start > Control Panel > Administrative Tools > Services, and checking that the service SQL Server (SQLEXPRESS) is running. If not, start it.

  2. While you're in the services applet, also make sure that the service SQL Browser is started. If not, start it.

  3. You need to make sure that SQL Server is allowed to use TCP/IP or named pipes. You can turn these on by opening the SQL Server Configuration Manager in Start > Programs > Microsoft SQL Server 2012 > Configuration Tools (or SQL Server Configuration Manager), and make sure that TCP/IP and Named Pipes are enabled. If you don't find the SQL Server Configuration Manager in the Start Menu you can launch the MMC snap-in manually. Check SQL Server Configuration Manager for the path to the snap-in according to your version.

    SQL Server Configuration Manager

  4. Verify your SQL Server connection authentication mode matches your connection string:

    • If you're connecting using a username and password, you need to configure SQL Server to accept "SQL Server Authentication Mode":

      -- YOU MUST RESTART YOUR SQL SERVER AFTER RUNNING THIS!
      USE [master]
      GO
      DECLARE @SqlServerAndWindowsAuthenticationMode INT = 2;
      EXEC xp_instance_regwrite
        N'HKEY_LOCAL_MACHINE',
        N'Software\Microsoft\MSSQLServer\MSSQLServer',
        N'LoginMode',
        REG_DWORD,
        @SqlServerAndWindowsAuthenticationMode;
      GO
      
    • If you're connecting using "Integrated Security=true" (Windows Mode), and this error only comes up when debugging in web applications, then you need to add the ApplicationPoolIdentity as a SQL Server login:
  5. otherwise, run Start -> Run -> Services.msc If so, is it running?

If it's not running then

It sounds like you didn't get everything installed. Launch the install file and chose the option "New installation or add features to an existing installation". From there you should be able to make sure the database engine service gets installed.

How to evaluate a math expression given in string form?

How about something like this:

String st = "10+3";
int result;
for(int i=0;i<st.length();i++)
{
  if(st.charAt(i)=='+')
  {
    result=Integer.parseInt(st.substring(0, i))+Integer.parseInt(st.substring(i+1, st.length()));
    System.out.print(result);
  }         
}

and do the similar thing for every other mathematical operator accordingly ..

webpack: Module not found: Error: Can't resolve (with relative path)

I met this problem with typescript but forgot to add ts and tsx suffix to resolve entry.

module.exports = {
  ...
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx'],
  },
};

This does the job for me

Connect to Oracle DB using sqlplus

if you want to connect with oracle database

  1. open sql prompt
  2. connect with sysdba for XE- conn / as sysdba for IE- conn sys as sysdba
  3. then start up database by below command startup;

once it get start means you can access oracle database now. if you want connect another user you can write conn username/password e.g. conn scott/tiger; it will show connected........

Enable UTF-8 encoding for JavaScript

This is a quite old request to reply but I want to give a short answer for newcommers. I had the same problem while working on an eight-languaged site. The problem is IDE based. The solution is to use Komodo Edit as code-editor. I tried many editors until I found one which doesnt change charset-settings of my pages. Dreamweaver (or almost all of others) change all pages code-page/charset settings whenever you change it for page. When you have changes in more than one page and have changed charset of any file then clicked "Save all", all open pages (including unchanged but assumed changed by editor because of charset) are silently re-assigned the new charset and all mismatching pages are broken down. I lost months on re-translating messages again and again until I discovered that Komodo Edit keeps settings separately for each file.

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'
        });
    });
});

Most efficient way to concatenate strings in JavaScript?

Three years past since this question was answered but I will provide my answer anyway :)

Actually, accepted answer is not fully correct. Jakub's test uses hardcoded string which allows JS engine to optimize code execution (Google's V8 is really good in this stuff!). But as soon as you use completely random strings (here is JSPerf) then string concatenation will be on a second place.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Read JSON data in a shell script

Here is a crude way to do it: Transform JSON into bash variables to eval them.

This only works for:

  • JSON which does not contain nested arrays, and
  • JSON from trustworthy sources (else it may confuse your shell script, perhaps it may even be able to harm your system, You have been warned)

Well, yes, it uses PERL to do this job, thanks to CPAN, but is small enough for inclusion directly into a script and hence is quick and easy to debug:

json2bash() {
perl -MJSON -0777 -n -E 'sub J {
my ($p,$v) = @_; my $r = ref $v;
if ($r eq "HASH") { J("${p}_$_", $v->{$_}) for keys %$v; }
elsif ($r eq "ARRAY") { $n = 0; J("$p"."[".$n++."]", $_) foreach @$v; }
else { $v =~ '"s/'/'\\\\''/g"'; $p =~ s/^([^[]*)\[([0-9]*)\](.+)$/$1$3\[$2\]/;
$p =~ tr/-/_/; $p =~ tr/A-Za-z0-9_[]//cd; say "$p='\''$v'\'';"; }
}; J("json", decode_json($_));'
}

use it like eval "$(json2bash <<<'{"a":["b","c"]}')"

Not heavily tested, though. Updates, warnings and more examples see my GIST.

Update

(Unfortunately, following is a link-only-solution, as the C code is far too long to duplicate here.)

For all those, who do not like the above solution, there now is a C program json2sh which (hopefully safely) converts JSON into shell variables. In contrast to the perl snippet, it is able to process any JSON, as long as it is well formed.

Caveats:

  • json2sh was not tested much.
  • json2sh may create variables, which start with the shellshock pattern () {

I wrote json2sh to be able to post-process .bson with Shell:

bson2json()
{
printf '[';
{ bsondump "$1"; echo "\"END$?\""; } | sed '/^{/s/$/,/';
echo ']';
};

bsons2json()
{
printf '{';
c='';
for a;
do
  printf '%s"%q":' "$c" "$a";
  c=',';
  bson2json "$a";
done;
echo '}';
};

bsons2json */*.bson | json2sh | ..

Explained:

  • bson2json dumps a .bson file such, that the records become a JSON array
    • If everything works OK, an END0-Marker is applied, else you will see something like END1.
    • The END-Marker is needed, else empty .bson files would not show up.
  • bsons2json dumps a bunch of .bson files as an object, where the output of bson2json is indexed by the filename.

This then is postprocessed by json2sh, such that you can use grep/source/eval/etc. what you need, to bring the values into the shell.

This way you can quickly process the contents of a MongoDB dump on shell level, without need to import it into MongoDB first.

How to kill a running SELECT statement

As you keep getting pages of results I'm assuming you started the session in SQL*Plus. If so, the easy thing to do is to bash ctrl + break many, many times until it stops.

The more complicated and the more generic way(s) I detail below in order of increasing ferocity / evil. The first one will probably work for you but if it doesn't you can keep moving down the list.

Most of these are not recommended and can have unintended consequences.


1. Oracle level - Kill the process in the database

As per ObiWanKenobi's answer and the ALTER SESSION documentation

alter system kill session 'sid,serial#';

To find the sid, session id, and the serial#, serial number, run the following query - summarised from OracleBase - and find your session:

select s.sid, s.serial#, p.spid, s.username, s.schemaname
     , s.program, s.terminal, s.osuser
  from v$session s
  join v$process p
    on s.paddr = p.addr
 where s.type != 'BACKGROUND'

If you're running a RAC then you need to change this slightly to take into account the multiple instances, inst_id is what identifies them:

select s.inst_id, s.sid, s.serial#, p.spid, s.username
     , s.schemaname, s.program, s.terminal, s.osuser
  from Gv$session s
  join Gv$process p
    on s.paddr = p.addr
   and s.inst_id = p.inst_id
 where s.type != 'BACKGROUND'

This query would also work if you're not running a RAC.

If you're using a tool like PL/SQL Developer then the sessions window will also help you find it.

For a slightly stronger "kill" you can specify the IMMEDIATE keyword, which instructs the database to not wait for the transaction to complete:

alter system kill session 'sid,serial#' immediate;

2. OS level - Issue a SIGTERM

kill pid

This assumes you're using Linux or another *nix variant. A SIGTERM is a terminate signal from the operating system to the specific process asking it to stop running. It tries to let the process terminate gracefully.

Getting this wrong could result in you terminating essential OS processes so be careful when typing.

You can find the pid, process id, by running the following query, which'll also tell you useful information like the terminal the process is running from and the username that's running it so you can ensure you pick the correct one.

select p.*
  from v$process p
  left outer join v$session s
    on p.addr = s.paddr
 where s.sid = ?
   and s.serial# = ?

Once again, if you're running a RAC you need to change this slightly to:

select p.*
  from Gv$process p
  left outer join Gv$session s
    on p.addr = s.paddr
 where s.sid = ?
   and s.serial# = ?

Changing the where clause to where s.status = 'KILLED' will help you find already killed process that are still "running".

3. OS - Issue a SIGKILL

kill -9 pid

Using the same pid you picked up in 2, a SIGKILL is a signal from the operating system to a specific process that causes the process to terminate immediately. Once again be careful when typing.

This should rarely be necessary. If you were doing DML or DDL it will stop any rollback being processed and may make it difficult to recover the database to a consistent state in the event of failure.

All the remaining options will kill all sessions and result in your database - and in the case of 6 and 7 server as well - becoming unavailable. They should only be used if absolutely necessary...

4. Oracle - Shutdown the database

shutdown immediate

This is actually politer than a SIGKILL, though obviously it acts on all processes in the database rather than your specific process. It's always good to be polite to your database.

Shutting down the database should only be done with the consent of your DBA, if you have one. It's nice to tell the people who use the database as well.

It closes the database, terminating all sessions and does a rollback on all uncommitted transactions. It can take a while if you have large uncommitted transactions that need to be rolled back.

5. Oracle - Shutdown the database ( the less nice way )

shutdown abort

This is approximately the same as a SIGKILL, though once again on all processes in the database. It's a signal to the database to stop everything immediately and die - a hard crash. It terminates all sessions and does no rollback; because of this it can mean that the database takes longer to startup again. Despite the incendiary language a shutdown abort isn't pure evil and can normally be used safely.

As before inform people the relevant people first.

6. OS - Reboot the server

reboot

Obviously, this not only stops the database but the server as well so use with caution and with the consent of your sysadmins in addition to the DBAs, developers, clients and users.

7. OS - The last stage

I've had reboot not work... Once you've reached this stage you better hope you're using a VM. We ended up deleting it...

How to clear an EditText on click?

//To clear When Clear Button is Clicked

firstName = (EditText) findViewById(R.id.firstName);

    clear = (Button) findViewById(R.id.clearsearchSubmit);

    clear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.clearsearchSubmit);
            firstName.setText("");
        }
    });

This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps

SQL how to make null values come last when sorting ascending

USE NVL function

  select * from MyTable order by NVL(MyDate, to_date('1-1-1','DD-MM-YYYY'))

Here's the alternative of NVL in most famous DBMS

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

how to get session id of socket.io client in Client

For some reason

socket.on('connect', function() {
    console.log(socket.io.engine.id);
}); 

did not work for me. However

socket.on('connect', function() {
    console.log(io().id);
}); 

did work for me. Hopefully this is helpful for people who also had issues with getting the id. I use Socket IO >= 1.0, by the way.

Open a local HTML file using window.open in Chrome

This worked for me fine:

File 1:

    <html>
    <head></head>
    <body>
        <a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
    </body>
    <footer></footer>
    </html>

File 2:

    <html>
        ...
    </html>

This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.

For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.

Enable CORS in Web API 2

 var cors = new EnableCorsAttribute("*","*","*");
 config.EnableCors(cors);

 var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

Code coverage with Mocha

Blanket.js works perfect too.

npm install --save-dev blanket

in front of your test/tests.js

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

run mocha -R html-cov > coverage.html

Certificate is trusted by PC but not by Android

could be that you're missing the certificate on your device.

try looking at this answer: How to install trusted CA certificate on Android device? to see how to install the CA on your own device.

Could not find method android() for arguments

guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:

Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.

So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.

I solved my problem just follow this steps:

? Copy .aar package in app/libs.

? Add this in app/build.gradle file:

repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):

dependencies {
    compile(name:'package_name', ext:'aar')
}

So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.

Get loop counter/index using for…of syntax in JavaScript

That's my version of a composite iterator that yields an index and any passed generator function's value with an example of (slow) prime search:

_x000D_
_x000D_
const eachWithIndex = (iterable) => {_x000D_
  return {_x000D_
    *[Symbol.iterator]() {_x000D_
      let i = 0_x000D_
      for(let val of iteratable) {_x000D_
        i++_x000D_
          yield [i, val]_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
const isPrime = (n) => {_x000D_
  for (i = 2; i < Math.floor(Math.sqrt(n) + 1); i++) {_x000D_
    if (n % i == 0) {_x000D_
      return false_x000D_
    }_x000D_
  }_x000D_
  return true_x000D_
}_x000D_
_x000D_
let primes = {_x000D_
  *[Symbol.iterator]() {_x000D_
    let candidate = 2_x000D_
    while (true) {_x000D_
      if (isPrime(candidate)) yield candidate_x000D_
        candidate++_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
for (const [i, prime] of eachWithIndex(primes)) {_x000D_
  console.log(i, prime)_x000D_
  if (i === 100) break_x000D_
}
_x000D_
_x000D_
_x000D_

How to output messages to the Eclipse console when developing for Android

Log.v("blah", "blah blah");

You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).

jQuery UI 1.10: dialog and zIndex option

Add in your CSS:

 .ui-dialog { z-index: 1000 !important ;}

Convert DataSet to List

                DataSet ds = new DataSet();
                ds = obj.getXmlData();// get the multiple table in dataset.

                Employee objEmp = new Employee ();// create the object of class Employee 
                List<Employee > empList = new List<Employee >();
                int table = Convert.ToInt32(ds.Tables.Count);// count the number of table in dataset
                for (int i = 1; i < table; i++)// set the table value in list one by one
                {
                    foreach (DataRow dr in ds.Tables[i].Rows)
                    {
                        empList.Add(new Employee { Title1 = Convert.ToString(dr["Title"]), Hosting1 = Convert.ToString(dr["Hosting"]), Startdate1 = Convert.ToString(dr["Startdate"]), ExpDate1 = Convert.ToString(dr["ExpDate"]) });
                    }
                }
                dataGridView1.DataSource = empList;

enter image description here

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Sometimes this error comes because it's simply the wrong folder. :-(

It shall be the folder which contains the pom.xml.

CSS Background image not loading

here is another image url result..working fine...i'm just put only a image path..please check it..

Fiddel:http://jsfiddle.net/287Kw/

body 
{
background-image: url('http://www.birds.com/wp-content/uploads/home/bird4.jpg');
padding-left: 11em;
padding-right: 20em;
font-family:
Georgia, "Times New Roman",
Times, serif; 
color: red;


}

#1062 - Duplicate entry for key 'PRIMARY'

The DB I was importing had a conflict during the import due to the presence of a column both autoincrement and primary key.

The problem was that in the .sql file the table was chopped into multiple "INSERT INTO" and during the import these queries were executed all together.

MY SOLUTION was to deselect the "Run multiple queries in each execution" on Navicat and it worked perfectly

How to check if an user is logged in Symfony2 inside a controller?

Warning: Checking for 'IS_AUTHENTICATED_FULLY' alone will return false if the user has logged in using "Remember me" functionality.

According to Symfony 2 documentation, there are 3 possibilities:

IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.

IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.

IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.

Those roles represent three levels of authentication:

If you have the IS_AUTHENTICATED_REMEMBERED role, then you also have the IS_AUTHENTICATED_ANONYMOUSLY role. If you have the IS_AUTHENTICATED_FULLY role, then you also have the other two roles. In other words, these roles represent three levels of increasing "strength" of authentication.

I ran into an issue where users of our system that had used "Remember Me" functionality were being treated as if they had not logged in at all on pages that only checked for 'IS_AUTHENTICATED_FULLY'.

The answer then is to require them to re-login if they are not authenticated fully, or to check for the remembered role:

$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
    // authenticated REMEMBERED, FULLY will imply REMEMBERED (NON anonymous)
}

Hopefully, this will save someone out there from making the same mistake I made. I used this very post as a reference when looking up how to check if someone was logged in or not on Symfony 2.

Source: http://symfony.com/doc/2.3/cookbook/security/remember_me.html#forcing-the-user-to-re-authenticate-before-accessing-certain-resources

SQL search multiple values in same field

Yes, you can use SQL IN operator to search multiple absolute values:

SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );

If you want to use LIKE you will need to use OR instead:

SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';

Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.

live output from subprocess command

All of the above solutions I tried failed either to separate stderr and stdout output, (multiple pipes) or blocked forever when the OS pipe buffer was full which happens when the command you are running outputs too fast (there is a warning for this on python poll() manual of subprocess). The only reliable way I found was through select, but this is a posix-only solution:

import subprocess
import sys
import os
import select
# returns command exit status, stdout text, stderr text
# rtoutput: show realtime output while running
def run_script(cmd,rtoutput=0):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    poller = select.poll()
    poller.register(p.stdout, select.POLLIN)
    poller.register(p.stderr, select.POLLIN)

    coutput=''
    cerror=''
    fdhup={}
    fdhup[p.stdout.fileno()]=0
    fdhup[p.stderr.fileno()]=0
    while sum(fdhup.values()) < len(fdhup):
        try:
            r = poller.poll(1)
        except select.error, err:
            if err.args[0] != EINTR:
                raise
            r=[]
        for fd, flags in r:
            if flags & (select.POLLIN | select.POLLPRI):
                c = os.read(fd, 1024)
                if rtoutput:
                    sys.stdout.write(c)
                    sys.stdout.flush()
                if fd == p.stderr.fileno():
                    cerror+=c
                else:
                    coutput+=c
            else:
                fdhup[fd]=1
    return p.poll(), coutput.strip(), cerror.strip()

How can I count the number of elements of a given value in a matrix?

This is a very good function file available on Matlab Central File Exchange.

countmember.m link

This function file is totally vectorized and hence very quick. Plus, in comparison to the function being referred to in aioobe's answer, this function doesn't use the accumarray function, which is why this is even compatible with older versions of Matlab. Also, it works for cell arrays as well as numeric arrays.

SOLUTION : You can use this function in conjunction with the built in matlab function, "unique".

occurance_count = countmember(unique(M),M)

occurance_count will be a numeric array with the same size as that of unique(M) and the different values of occurance_count array will correspond to the count of corresponding values (same index) in unique(M).

"No such file or directory" but it exists

I got this error “No such file or directory” but it exists because my file was created in Windows and I tried to run it on Ubuntu and the file contained invalid 15\r where ever a new line was there. I just created a new file truncating unwanted stuff

sleep: invalid time interval ‘15\r’
Try 'sleep --help' for more information.
script.sh: 5: script.sh: /opt/ag/cont: not found
script.sh: 6: script.sh: /opt/ag/cont: not found
root@Ubuntu14:/home/abc12/Desktop# vi script.sh 
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \r  \n   w   g   e   t       h   t   t   p   :   /

0000400   :   4   1   2   0   /  \r  \n
0000410
root@Ubuntu14:/home/abc12/Desktop# tr -d \\015 < script.sh > script.sh.fixed
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh.fixed 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \n   w   g   e   t       h   t   t   p   :   /   /

0000400   /  \n
0000402
root@Ubuntu14:/home/abc12/Desktop# sh -x script.sh.fixed 

Shell Script Syntax Error: Unexpected End of File

Indentation when using a block can cause this error and is very hard to find.

if [ ! -d /var/lib/mysql/mysql ]; then
   /usr/bin/mysql --protocol=socket --user root << EOSQL
        SET @@SESSION.SQL_LOG_BIN=0;
        CREATE USER 'root'@'%';
   EOSQL
fi

=> Example above will cause an error because EOSQL is indented. Remove indentation as shown below. Posting this because it took me over an hour to figure out the error.

if [ ! -d /var/lib/mysql/mysql ]; then
   /usr/bin/mysql --protocol=socket --user root << EOSQL
        SET @@SESSION.SQL_LOG_BIN=0;
        CREATE USER 'root'@'%';
EOSQL
fi

Is there a way to perform "if" in python's lambda

what you need exactly is

def fun():
    raise Exception()
f = lambda x:print x if x==2 else fun()

now call the function the way you need

f(2)
f(3)

How to get input type using jquery?

  <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script type="text/javascript" src="hs/jquery1.js"></script>
        <title>Document</title>
    </head>
    <body>
        <form>
            <input type="text" class="tamil">
            <input type="button" class="english">
        </form>
        <script>
            $("input").addClass(function(index){
                    console.log($(this).attr('type'));
            })
        </script>
    </body>
    </html>

i get wright form type

Match groups in Python

You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()

How do I get which JRadioButton is selected from a ButtonGroup

import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 
public class MyJRadioButton extends JFrame implements ActionListener
{
    JRadioButton rb1,rb2;  //components
    ButtonGroup bg;
    MyJRadioButton()
{
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    rb1=new JRadioButton("male");
    rb2=new JRadioButton("female");

    //add radio button to button group
    bg=new ButtonGroup();
    bg.add(rb1);
    bg.add(rb2);

    //add radio buttons to frame,not button group
    add(rb1);
    add(rb2);
    //add action listener to JRadioButton, not ButtonGroup
    rb1.addActionListener(this);
    rb2.addActionListener(this);
    pack();
    setVisible(true);
}
public static void main(String[] args)
{
    new MyJRadioButton(); //calling constructor
}
@Override
public void actionPerformed(ActionEvent e) 
{
    System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}

}

No signing certificate "iOS Distribution" found

I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)

I was also using Fastlane. My fix was to set generate_apple_certs to false when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3

Match documentation - https://docs.fastlane.tools/actions/match/

This is the relevant section of my Fastfile:

platform :ios do
  lane :certs do
    force = false
    match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
    match(type: "adhoc",       generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
    match(type: "appstore",    generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
  end

  ...

HTML form with multiple "actions"

As @AliK mentioned, this can be done easily by looking at the value of the submit buttons.

When you submit a form, unset variables will evaluate false. If you set both submit buttons to be part of the same form, you can just check and see which button has been set.

HTML:

<form action="handle_user.php" method="POST" />
  <input type="submit" value="Save" name="save" />
  <input type="submit" value="Submit for Approval" name="approve" />
</form>

PHP

if($_POST["save"]) {
  //User hit the save button, handle accordingly
}
//You can do an else, but I prefer a separate statement
if($_POST["approve"]) {
  //User hit the Submit for Approval button, handle accordingly
}

EDIT


If you'd rather not change your PHP setup, try this: http://pastebin.com/j0GUF7MV
This is the JavaScript method @AliK was reffering to.

Related:

How can I exclude all "permission denied" messages from "find"?

I had to use:

find / -name expect 2>/dev/null

specifying the name of what I wanted to find and then telling it to redirect all errors to /dev/null

expect being the location of the expect program I was searching for.

Android Percentage Layout Height

android:layout_weight=".YOURVALUE" is best way to implement in percentage

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/logTextBox"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".20"
        android:maxLines="500"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:text="@string/logText" >
    </TextView>

</LinearLayout>

Remove specific characters from a string in Python

#!/usr/bin/python
import re

strs = "how^ much for{} the maple syrup? $20.99? That's[] ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!|a|b]',r' ',strs)#i have taken special character to remove but any #character can be added here
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)#for removing special character
print nestr

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Remove elements from collection while iterating

Old Timer Favorite (it still works):

List<String> list;

for(int i = list.size() - 1; i >= 0; --i) 
{
        if(list.get(i).contains("bad"))
        {
                list.remove(i);
        }
}

Benefits:

  1. It only iterates over the list once
  2. No extra objects created, or other unneeded complexity
  3. No problems with trying to use the index of a removed item, because... well, think about it!

The model backing the <Database> context has changed since the database was created

Just found out the answer and thought of updating here. Just need to do the following.

public class AddressBook: DbContext
{
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
    modelBuilder.IncludeMetadataInDatabase = false;
   }
}

Confirm button before running deleting routine from website

Call this function onclick of button

/*pass whatever you want instead of id */
function doConfirm(id) {
    var ok = confirm("Are you sure to Delete?");
    if (ok) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                window.location = "create_dealer.php";
            }
        }

        xmlhttp.open("GET", "delete_dealer.php?id=" + id);
        // file name where delete code is written
        xmlhttp.send();
    }
}

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

Remove a git commit which has not been pushed

IF you have NOT pushed your changes to remote

git reset HEAD~1

Check if the working copy is clean by git status.

ELSE you have pushed your changes to remote

git revert HEAD

This command will revert/remove the local commits/change and then you can push

How to add Python to Windows registry

I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):

reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"

I find this easier than using Registry Editor but that's solely a personal preference.

The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.

How to sum array of numbers in Ruby?

Just for the sake of diversity, you can also do this if your array is not an array of numbers, but rather an array of objects that have properties that are numbers (e.g. amount):

array.inject(0){|sum,x| sum + x.amount}

Read the package name of an Android APK

You can use Analyze APK... from the Build menu in Android Studio, it will display the package name at the top of new window.

Store JSON object in data attribute in HTML jQuery

For me it work like that, as I need to store it in template...

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

How to check if current thread is not main thread

Xamarin.Android port: (C#)

public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
    ? Looper.MainLooper.IsCurrentThread
    : Looper.MyLooper() == Looper.MainLooper;

Usage:

if (IsMainThread) {
    // you are on UI/Main thread
}

How to add multiple font files for the same font?

/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'), /* Duplicated name with hyphen */
        url('dejavu/DejaVuSans.ttf') 
        format('truetype');
}
/*bold version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Bold.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Bold.ttf') 
        format('truetype');
    font-weight: bold;
}
/*italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-Oblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-Oblique.ttf') 
        format('truetype');
    font-style: italic;
}
/*bold italic version*/
@font-face {
    font-family: 'DejaVu Sans';
    src: url('dejavu/DejaVuSans-BoldOblique.ttf'); 
    src: 
        local('DejaVu Sans'),
        local('DejaVu-Sans'),
        url('dejavu/DejaVuSans-BoldOblique.ttf') 
        format('truetype');
    font-weight: bold;
    font-style: italic;
}

What is a "slug" in Django?

Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.

Slug can create using SlugField

Ex:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

If you want to use title as slug, django has a simple function called slugify

from django.template.defaultfilters import slugify

class Article(models.Model):
    title = models.CharField(max_length=100)

    def slug(self):
        return slugify(self.title)

If it needs uniqueness, add unique=True in slug field.

for instance, from the previous example:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug

Sum the digits of a number

you can also try this with built_in_function called divmod() ;

number = int(input('enter any integer: = '))
sum = 0
while number!=0: 
    take = divmod(number, 10) 
    dig = take[1] 
    sum += dig 
    number = take[0] 
print(sum) 

you can take any number of digit

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

How to get an enum value from a string value in Java?

My 2 cents here: using Java8 Streams + checking an exact string:

public enum MyEnum {
    VALUE_1("Super"),
    VALUE_2("Rainbow"),
    VALUE_3("Dash"),
    VALUE_3("Rocks");

    private final String value;

    MyEnum(String value) {
        this.value = value;
    }

    /**
     * @return the Enum representation for the given string.
     * @throws IllegalArgumentException if unknown string.
     */
    public static MyEnum fromString(String s) throws IllegalArgumentException {
        return Arrays.stream(MyEnum.values())
                .filter(v -> v.value.equals(s))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("unknown value: " + s));
    }
}

** EDIT **

Renamed the function to fromString() since naming it using that convention, you'll obtain some benefits from Java language itself; for example:

  1. Direct conversion of types at HeaderParam annotation

Server Error in '/' Application. ASP.NET

Have you configured the virtual directory as an ASP.NET application for the right framework version?

See IIS Setup

How to generate .angular-cli.json file in Angular Cli?

I couldn't see .angular-cli.json too. Because my Angular version is 6. ng version -> Angular CLI : 6.0.7. Check your Angular version.

How to find all occurrences of a substring?

>>> help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub [,start [,end]]) -> int

Thus, we can build it ourselves:

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]

No temporary strings or regexes required.

How do you install Boost on MacOS?

Try +universal

One thing to note: in order for that to make a difference you need to have built python with +universal, if you haven't or you're not sure you can just rebuild python +universal. This applies to both brew as well as macports.

$ brew reinstall python
$ brew install boost

OR

$ sudo port -f uninstall python
$ sudo port install python +universal
$ sudo port install boost +universal

css transform, jagged edges in chrome

I've been having an issue with a CSS3 gradient with -45deg. The background slanted, was badly jagged similar to but worse than the original post. So I started playing with both the background-size. This would stretch out the jaggedness, but it was still there. Then in addition I read that other people are having issues too at 45deg increments so I adjusted from -45deg to -45.0001deg and my problem was solved.

In my CSS below, background-size was initially 30px and the deg for the background gradient was exactly -45deg, and all keyframes were 30px 0.

    @-webkit-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-moz-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-ms-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-o-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-webkit-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-moz-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-ms-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-o-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    .pro-bar-candy {
        width: 100%;
        height: 15px;

        -webkit-border-radius:  3px;
        -moz-border-radius:     3px;
        border-radius:          3px;

        background: rgb(187, 187, 187);
        background: -moz-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -webkit-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -o-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -ms-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -webkit-gradient(
                        linear,
                        right bottom,
                        right top,
                        color-stop(
                            25%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            25%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            50%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            50%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            75%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            75%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            rgba(0, 0, 0, 0.00)
                        )
                    );

        background-repeat: repeat-x;
        -webkit-background-size:    60px 60px;
        -moz-background-size:       60px 60px;
        -o-background-size:         60px 60px;
        background-size:            60px 60px;
        }

    .pro-bar-candy.candy-ltr {
        -webkit-animation:  progressStripeLTR .6s linear infinite;
        -moz-animation:     progressStripeLTR .6s linear infinite;
        -ms-animation:      progressStripeLTR .6s linear infinite;
        -o-animation:       progressStripeLTR .6s linear infinite;
        animation:          progressStripeLTR .6s linear infinite;
        }

    .pro-bar-candy.candy-rtl {
        -webkit-animation:  progressStripeRTL .6s linear infinite;
        -moz-animation:     progressStripeRTL .6s linear infinite;
        -ms-animation:      progressStripeRTL .6s linear infinite;
        -o-animation:       progressStripeRTL .6s linear infinite;
        animation:          progressStripeRTL .6s linear infinite;
        }

Best practice for partial updates in a RESTful service

For modifying the status I think a RESTful approach is to use a logical sub-resource which describes the status of the resources. This IMO is pretty useful and clean when you have a reduced set of statuses. It makes your API more expressive without forcing the existing operations for your customer resource.

Example:

POST /customer/active  <-- Providing entity in the body a new customer
{
  ...  // attributes here except status
}

The POST service should return the newly created customer with the id:

{
    id:123,
    ...  // the other fields here
}

The GET for the created resource would use the resource location:

GET /customer/123/active

A GET /customer/123/inactive should return 404

For the PUT operation, without providing a Json entity it will just update the status

PUT /customer/123/inactive  <-- Deactivating an existing customer

Providing an entity will allow you to update the contents of the customer and update the status at the same time.

PUT /customer/123/inactive
{
    ...  // entity fields here except id and status
}

You are creating a conceptual sub-resource for your customer resource. It is also consistent with Roy Fielding's definition of a resource: "...A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time..." In this case the conceptual mapping is active-customer to customer with status=ACTIVE.

Read operation:

GET /customer/123/active 
GET /customer/123/inactive

If you make those calls one right after the other one of them must return status 404, the successful output may not include the status as it is implicit. Of course you can still use GET /customer/123?status=ACTIVE|INACTIVE to query the customer resource directly.

The DELETE operation is interesting as the semantics can be confusing. But you have the option of not publishing that operation for this conceptual resource, or use it in accordance with your business logic.

DELETE /customer/123/active

That one can take your customer to a DELETED/DISABLED status or to the opposite status (ACTIVE/INACTIVE).

Can I give a default value to parameters or optional parameters in C# functions?

Yes, but you'll need to be using .NET 3.5 and C# 4.0 to get this functionality.

This MSDN page has more information.

How to copy directories with spaces in the name

After some trial and error and observing the results (in other words, I hacked it), I got it to work.

Quotes ARE required to use a path name with spaces. The trick is there MUST be a space after the path names before the closing quote...like this...

robocopy "C:\Source Path " "C:\Destination Path " /option1 /option2...

This almost seems like a bug and certainly not very intuitive.

Todd K.

java.net.URL read stream to byte[]

byte[] b = IOUtils.toByteArray((new URL( )).openStream()); //idiom

Note however, that stream is not closed in the above example.

if you want a (76-character) chunk (using commons codec)...

byte[] b = Base64.encodeBase64(IOUtils.toByteArray((new URL( )).openStream()), true);

How to use PrintWriter and File classes in Java?

If you want to use PrintWrite then try this code

public class PrintWriter {
    public static void main(String[] args) throws IOException {

        java.io.PrintWriter pw=new java.io.PrintWriter("file.txt");
        pw.println("hello world");
        pw.flush();
        pw.close();

    }

}

How can I match a string with a regex in Bash?

Since you are using bash, you don't need to create a child process for doing this. Here is one solution which performs it entirely within bash:

[[ $TEST =~ ^(.*):\ +(.*)$ ]] && TEST=${BASH_REMATCH[1]}:${BASH_REMATCH[2]}

Explanation: The groups before and after the sequence "colon and one or more spaces" are stored by the pattern match operator in the BASH_REMATCH array.

Diff files present in two different directories

diff can not only compare two files, it can, by using the -r option, walk entire directory trees, recursively checking differences between subdirectories and files that occur at comparable points in each tree.

$ man diff

...

-r  --recursive
        Recursively compare any subdirectories found.

...

Public class is inaccessible due to its protection level

Also if you want to do something like ClassB.Run("thing");, make sure the Method Run(); is static or you could call it like this: thing.Run("thing");.

How do I auto-hide placeholder text upon focus using css or jquery?

<input 
type="text" 
placeholder="enter your text" 
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'enter your text'" />

SMTP connect() failed PHPmailer - PHP

The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2 authentication mechanism which google start using since 2014. remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.

what you really need to do is .. log into your google account and open up following address https://www.google.com/settings/security/lesssecureapps and check turn on . you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go.. here is the code which worked fine for me..

require_once 'C:\xampp\htdocs\email\vendor\autoload.php';

define ('GUSER','[email protected]');
define ('GPWD','your password');


// make a separate file and include this file in that. call this function in that file.

function smtpmailer($to, $from, $from_name, $subject, $body) { 
    global $error;
    $mail = new PHPMailer();  // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;  // authentication enabled
    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
    $mail->SMTPAutoTLS = false;
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;

    $mail->Username = GUSER;  
    $mail->Password = GPWD;           
    $mail->SetFrom($from, $from_name);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddAddress($to);
    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo; 
        return false;
    } else {
        $error = 'Message sent!';
        return true;
    }
}

JavaScript: undefined !== undefined?

The problem is that undefined compared to null using == gives true. The common check for undefined is therefore done like this:

typeof x == "undefined"

this ensures the type of the variable is really undefined.

Using PowerShell to remove lines from a text file if it contains a string

Suppose you want to write that in the same file, you can do as follows:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)

Convert .pem to .crt and .key

To extract the key and cert from a pem file:

Extract key

openssl pkey -in foo.pem -out foo.key

Another method of extracting the key...

openssl rsa -in foo.pem -out foo.key

Extract all the certs, including the CA Chain

openssl crl2pkcs7 -nocrl -certfile foo.pem | openssl pkcs7 -print_certs -out foo.cert

Extract the textually first cert as DER

openssl x509 -in foo.pem -outform DER -out first-cert.der

How to validate IP address in Python?

Don't parse it. Just ask.

import socket

try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

OpenSSL: unable to verify the first certificate for Experian URL

Adding additional information to emboss's answer.

To put it simply, there is an incorrect cert in your certificate chain.

For example, your certificate authority will have most likely given you 3 files.

  • your_domain_name.crt
  • DigiCertCA.crt # (Or whatever the name of your certificate authority is)
  • TrustedRoot.crt

You most likely combined all of these files into one bundle.

-----BEGIN CERTIFICATE----- 
(Your Primary SSL certificate: your_domain_name.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Intermediate certificate: DigiCertCA.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Root certificate: TrustedRoot.crt) 
-----END CERTIFICATE-----

If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.

Redownload all certs from your certificate authority and make a fresh bundle.

Android Endless List

Best solution so far that I have seen is in FastAdapter library for recycler views. It has a EndlessRecyclerOnScrollListener.

Here is an example usage: EndlessScrollListActivity

Once I used it for endless scrolling list I have realised that the setup is a very robust. I'd definitely recommend it.

Checking if form has been submitted - PHP

Try this

 <form action="" method="POST" id="formaddtask">
      Add Task: <input type="text"name="newtaskname" />
      <input type="submit" value="Submit"/>
 </form>

    //Check if the form is submitted
    if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['newtaskname'])){

    }

Problems with a PHP shell script: "Could not open input file"

When you use php CLI argument -q doesn't exist.

I had the same problem when I wrote script in the Windows (eclipse) and I tried run them on Linux. Every line in file from Windows is ended by \r\n. I had to delete \r in first line that contained parser path:

When \r was deleted from first line (mcedit shown \r as ^M) script ran correctly.

Using Docker-Compose, how to execute multiple commands

Another idea:

If, as in this case, you build the container just place a startup script in it and run this with command. Or mount the startup script as volume.

use jQuery's find() on JSON object

jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}

Use like so:

getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects

How do I break out of a loop in Scala?

This has changed in Scala 2.8 which has a mechanism for using breaks. You can now do the following:

import scala.util.control.Breaks._
var largest = 0
// pass a function to the breakable method
breakable { 
    for (i<-999 to 1  by -1; j <- i to 1 by -1) {
        val product = i * j
        if (largest > product) {
            break  // BREAK!!
        }
        else if (product.toString.equals(product.toString.reverse)) {
            largest = largest max product
        }
    }
}

box-shadow on bootstrap 3 container

For those wanting the box-shadow on the col-* container itself and not on the .container, you can add another div just inside the col-* element, and add the shadow to that. This element will not have the padding, and therefor not interfere.

The first image has the box-shadow on the col-* element. Because of the 15px padding on the col element, the shadow is pushed to the outside of the div element rather than on the visual edges of it.

box-shadow on col-* element

<div class="col-md-4" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
    <div class="thumbnail">
        {!! HTML::image('images/sampleImage.png') !!}
    </div>
</div>

The second image has a wrapper div with the box-shadow on it. This will place the box-shadow on the visual edges of the element.

box-shadow on wrapper div

<div class="col-md-4">
    <div id="wrapper-div" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
        <div class="thumbnail">
            {!! HTML::image('images/sampleImage.png') !!}
        </div>
    </div>
</div>

Get scroll position using jquery

cross browser variant

$(document).scrollTop();

How should I pass multiple parameters to an ASP.Net Web API GET?

 [Route("api/controller/{one}/{two}")]
    public string Get(int One, int Two)
    {
        return "both params of the root link({one},{two}) and Get function parameters (one, two)  should be same ";
    }

Both params of the root link({one},{two}) and Get function parameters (one, two) should be same

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

If you are using arrow functions:

it('should do something', async () => {
  // do your testing
}).timeout(15000)

Selenium Webdriver move mouse to Point

Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.

Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .moveByOffset( 10, 25 );
   .click(someOtherElement)
   .keyUp(Keys.CONTROL).build().perform();

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

If you want to correct some error in the last commit a good alternative would be using git commit --amend command. If the last commit is not pointed by any reference, this will do the trick, as it create a commit with the same parent as the last commit. If there is no reference to the last commit, it will simply be discarded and this commit will be the last commit. This is a good way of correcting commits without reverting commits. However it has its own limitations.

Display image at 50% of its "native" size

It's somewhat weird, but it seems that Webkit, at least in newest stable version of Chrome, supports Microsoft's zoom property. The good news is that its behaviour is closer to what you want.

Unfortunately DOM clientWidth and similar properties still return the original values as if the image was not resized.

_x000D_
_x000D_
// hack: wait a moment for img to load_x000D_
setTimeout(function() {_x000D_
   var img = document.getElementsByTagName("img")[0];_x000D_
   document.getElementById("c").innerHTML = "clientWidth, clientHeight = " + img.clientWidth + ", " +_x000D_
      img.clientHeight;_x000D_
}, 1000);
_x000D_
img {_x000D_
  zoom: 50%;_x000D_
}_x000D_
/* -- not important below -- */_x000D_
#t {_x000D_
  width: 400px;_x000D_
  height: 300px;_x000D_
  background-color: #F88;_x000D_
}_x000D_
#s {_x000D_
  width: 200px;_x000D_
  height: 150px;_x000D_
  background-color: #8F8;_x000D_
}
_x000D_
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAEsCAIAAABi1XKVAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKuGlDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjarZZnVFPZHsX/9970QktAQEroTZAiXXoNIEQ6iEpIKIEQY0hAERWVwREcUVREsAzgKIiCjSJjQSzYBsUC9gEZFJRxsCAqKu8DQ3jvrfc+vLXe/6671m/tdc4++9z7ZQPQHnDFYiGqBJApkkrCA7xZsXHxLOLvgAMKqAIFlLi8LLEXhxMC/3kQgI89gAAA3LXkisVC+N9GmZ+cxQNAOACQxM/iZQIgpwCQdp5YIgXApABgkCMVSwGwcgBgSmLj4gGwIwDATJ3idgBgJk3xPQBgSiLDfQCwIQASjcuVpAJQPwAAK5uXKgWgMQHAWsQXiABovgDgzkvj8gFoBQAwJzNzGR+AdgwATJP+ySf1XzyT5J5cbqqcp+4CAAAkX0GWWMhdCf/vyRTKps/QBwBamiQwHADUAZDajGXBchYlhYZNs4APMM1pssCoaeZl+cRPM5/rGzzNsowor2nmSmb2CqTsyGmWLAuX+ydn+UXI/ZPZIfIMwlA5pwj82dOcmxYZM83ZgujQac7KiAieWeMj1yWycHnmFIm//I6ZWTPZeNyZDNK0yMCZbLHyDPxkXz+5LoqSrxdLveWeYiFHvj5ZGCDXs7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">div with explicit size for comparison 200px by 150px</div>_x000D_
<div id="t">div with explicit size for comparison 400px by 300px</div>_x000D_
<div id="c"></div>
_x000D_
_x000D_
_x000D_

Spring Boot Rest Controller how to return different HTTP status codes?

In case you want to return a custom defined status code, you can use the ResponseEntity as here:

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
    int customHttpStatusValue = 499;
    Foo foo = bar();
    return ResponseEntity.status(customHttpStatusValue).body(foo);
}

The CustomHttpStatusValue could be any integer within or outside of standard HTTP Status Codes.

How to disable sort in DataGridView?

You can disable it in the ColumnAdded event:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    dataGridView1.Columns[e.Column.Index].SortMode = DataGridViewColumnSortMode.NotSortable;
}

How to prepend a string to a column value in MySQL?

That's a simple one

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);

What datatype to use when storing latitude and longitude data in SQL databases?

You can easily store a lat/lon decimal number in an unsigned integer field, instead of splitting them up in a integer and decimal part and storing those separately as somewhat suggested here using the following conversion algorithm:

as a stored mysql function:

CREATE DEFINER=`r`@`l` FUNCTION `PositionSmallToFloat`(s INT) 
RETURNS decimal(10,7)
DETERMINISTIC
RETURN if( ((s > 0) && (s >> 31)) , (-(0x7FFFFFFF - 
(s & 0x7FFFFFFF))) / 600000, s / 600000)

and back

CREATE DEFINER=`r`@`l` FUNCTION `PositionFloatToSmall`(s DECIMAL(10,7)) 
RETURNS int(10)
DETERMINISTIC
RETURN s * 600000

That needs to be stored in an unsigned int(10), this works in mysql as well as in sqlite which is typeless.

through experience, I find that this works really fast, if all you need to to is store coordinates and retrieve those to do some math with.

in php those 2 functions look like

function LatitudeSmallToFloat($LatitudeSmall){
   if(($LatitudeSmall>0)&&($LatitudeSmall>>31)) 
     $LatitudeSmall=-(0x7FFFFFFF-($LatitudeSmall&0x7FFFFFFF))-1;
   return (float)$LatitudeSmall/(float)600000;
}

and back again:

function LatitudeFloatToSmall($LatitudeFloat){
   $Latitude=round((float)$LatitudeFloat*(float)600000);
   if($Latitude<0) $Latitude+=0xFFFFFFFF;
   return $Latitude;
}

This has some added advantage as well in term of creating for example memcached unique keys with integers. (ex: to cache a geocode result). Hope this adds value to the discussion.

Another application could be when you are without GIS extensions and simply want to keep a few million of those lat/lon pairs, you can use partitions on those fields in mysql to benefit from the fact they are integers:

Create Table: CREATE TABLE `Locations` (
  `lat` int(10) unsigned NOT NULL,
  `lon` int(10) unsigned NOT NULL,
  `location` text,
  PRIMARY KEY (`lat`,`lon`) USING BTREE,
  KEY `index_location` (`locationText`(30))
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/*!50100 PARTITION BY KEY ()
PARTITIONS 100 */

Is it possible to use "return" in stored procedure?

Use FUNCTION:

CREATE OR REPLACE FUNCTION test_function
RETURN VARCHAR2 IS

BEGIN
  RETURN 'This is being returned from a function';
END test_function;

Angularjs - simple form submit

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

How to ignore deprecation warnings in Python

I had these:

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/persisted/sob.py:12:
DeprecationWarning: the md5 module is deprecated; use hashlib instead import os, md5, sys

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/python/filepath.py:12:
DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha

Fixed it with:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    import md5, sha

yourcode()

Now you still get all the other DeprecationWarnings, but not the ones caused by:

import md5, sha

How to clear text area with a button in html using javascript?

<input type="button" value="Clear" onclick="javascript: functionName();" >

you just need to set the onclick event, call your desired function on this onclick event.

function functionName()
{
    $("#output").val("");
}

Above function will set the value of text area to empty string.

Where does Console.WriteLine go in ASP.NET?

System.Diagnostics.Debug.WriteLine(...); gets it into the Immediate Window in Visual Studio 2008.

Go to menu Debug -> Windows -> Immediate:

Enter image description here

Get list of all tables in Oracle?

Execute the below commands:

Show all tables in the Oracle Database

sql> SELECT table_name FROM dba_tables;

Show tables owned by the current user

sql> SELECT table_name FROM user_tables;

Show tables that are accessible by the current user

sql> SELECT table_name FROM all_tables ORDER BY table_name; The following picture illustrates the tables that can be returned from the user_tables, all_tables, and dba_tables views:

How to set JAVA_HOME in Mac permanently?

To set your Java path on mac:

  1. Open terminal on mac, change path to the root cd ~
  2. vi .bash_profile (This opens the bash_profile file)
  3. Click I to insert text and use the following text to set JAVA_HOME and PATH

    • export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home'
    • export PATH=$JAVA_HOME/bin:$PATH

      1. Type :wq to save and exit the file.
      2. Type source .bash_profile to execute the .bash_profile file.
      3. You can type echo $JAVA_HOME or echo $PATH

Nginx 403 error: directory index of [folder] is forbidden

Because you're using php-fpm, you should make sure that php-fpm user is the same as nginx user.

Check /etc/php-fpm.d/www.conf and set php user and group to nginx if it's not.

The php-fpm user needs write permission.

Creating a Menu in Python

There were just a couple of minor amendments required:

ans=True
while ans:
    print ("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ") 
    if ans=="1": 
      print("\n Student Added") 
    elif ans=="2":
      print("\n Student Deleted") 
    elif ans=="3":
      print("\n Student Record Found") 
    elif ans=="4":
      print("\n Goodbye") 
    elif ans !="":
      print("\n Not Valid Choice Try again") 

I have changed the four quotes to three (this is the number required for multiline quotes), added a closing bracket after "What would you like to do? " and changed input to raw_input.

CMD: Export all the screen content to a text file

If you want to append a file instead of constantly making a new one/deleting the old one's content, use double > marks. A single > mark will overwrite all the file's content.

Overwrite file

MyCommand.exe>file.txt

^This will open file.txt if it already exists and overwrite the data, or create a new file and fill it with your output

Append file from its end-point

MyCommand.exe>>file.txt

^This will append file.txt from its current end of file if it already exists, or create a new file and fill it with your output.


Update #1 (advanced):

My batch-fu has improved over time, so here's some minor updates.

If you want to differentiate between error output and normal output for a program that correctly uses Standard streams, STDOUT/STDERR, you can do this with minor changes to the syntax. I'll just use > for overwriting for these examples, but they work perfectly fine with >> for append, in regards to file-piping output re-direction.

The 1 before the >> or > is the flag for STDOUT. If you need to actually output the number one or two before the re-direction symbols, this can lead to strange, unintuitive errors if you don't know about this mechanism. That's especially relevant when outputting a single result number into a file. 2 before the re-direction symbols is for STDERR.

Now that you know that you have more than one stream available, this is a good time to show the benefits of outputting to nul. Now, outputting to nul works the same way conceptually as outputting to a file. You don't see the content in your console. Instead of it going to file or your console output, it goes into the void.

STDERR to file and suppress STDOUT

MyCommand.exe 1>nul 2>errors.txt

STDERR to file to only log errors. Will keep STDOUT in console

MyCommand.exe 2>errors.txt

STDOUT to file and suppress STDERR

MyCommand.exe 1>file.txt 2>nul

STDOUT only to file. Will keep STDERR in console

MyCommand.exe 1>file.txt

STDOUT to one file and STDERR to another file

MyCommand.exe 1>stdout.txt 2>errors.txt

The only caveat I have here is that it can create a 0-byte file for an unused stream if one of the streams never gets used. Basically, if no errors occurred, you might end up with a 0-byte errors.txt file.

Update #2

I started noticing weird behavior when writing console apps that wrote directly to STDERR, and realized that if I wanted my error output to go to the same file when using basic piping, I either had to combine streams 1 and 2 or just use STDOUT. The problem with that problem is I didn't know about the correct way to combine streams, which is this:

%command% > outputfile 2>&1

Therefore, if you want all STDOUT and STDERR piped into the same stream, make sure to use that like so:

MyCommand.exe > file.txt 2>&1

The redirector actually defaults to 1> or 1>>, even if you don't explicitly use 1 in front of it if you don't use a number in front of it, and the 2>&1 combines the streams.

Update #3 (simple)

Null for Everything

If you want to completely suppress STDOUT and STDERR you can do it this way. As a warning not all text pipes use STDOUT and STDERR but it will work for a vast majority of use cases.

STD* to null MyCommand.exe>nul 2>&1

Copying a CMD or Powershell session's command output

If all you want is the command output from a CMD or Powershell session that you just finished up, or any other shell for that matter you can usually just select that console from that session, CTRL + A to select all content, then CTRL + C to copy the content. Then you can do whatever you like with the copied content while it's in your clipboard.

Importing large sql file to MySql via command line

+1 to @MartinNuc, you can run the mysql client in batch mode and then you won't see the long stream of "OK" lines.

The amount of time it takes to import a given SQL file depends on a lot of things. Not only the size of the file, but the type of statements in it, how powerful your server server is, and how many other things are running at the same time.

@MartinNuc says he can load 4GB of SQL in 4-5 minutes, but I have run 0.5 GB SQL files and had it take 45 minutes on a smaller server.

We can't really guess how long it will take to run your SQL script on your server.


Re your comment,

@MartinNuc is correct you can choose to make the mysql client print every statement. Or you could open a second session and run mysql> SHOW PROCESSLIST to see what's running. But you probably are more interested in a "percentage done" figure or an estimate for how long it will take to complete the remaining statements.

Sorry, there is no such feature. The mysql client doesn't know how long it will take to run later statements, or even how many there are. So it can't give a meaningful estimate for how much time it will take to complete.

Why do python lists have pop() but not push()

Push and Pop make sense in terms of the metaphor of a stack of plates or trays in a cafeteria or buffet, specifically the ones in type of holder that has a spring underneath so the top plate is (more or less... in theory) in the same place no matter how many plates are under it.

If you remove a tray, the weight on the spring is a little less and the stack "pops" up a little, if you put the plate back, it "push"es the stack down. So if you think about the list as a stack and the last element as being on top, then you shouldn't have much confusion.

installing python packages without internet and using source code as .tar.gz and .whl

This is how I handle this case:

On the machine where I have access to Internet:

mkdir keystone-deps
pip download python-keystoneclient -d "/home/aviuser/keystone-deps"
tar cvfz keystone-deps.tgz keystone-deps

Then move the tar file to the destination machine that does not have Internet access and perform the following:

tar xvfz keystone-deps.tgz
cd keystone-deps
pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index

You may need to add --no-deps to the command as follows:

pip install python_keystoneclient-2.3.1-py2.py3-none-any.whl -f ./ --no-index --no-deps

How can I set selected option selected in vue.js 2?

Handling the errors

You are binding properties to nothing. :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

If you set the code like so, your errors should be gone:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Getting the select tags to have a default value

  1. you would now need to have a data property called selected so that v-model works. So,

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If that seems like too much work, you can also do it like:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

When to use which method?

  1. You can use the v-model approach if your default value depends on some data property.

  2. You can go for the second method if your default selected value happens to be the first option.

  3. You can also handle it programmatically by doing so:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

gson throws MalformedJsonException

From my recent experience, JsonReader#setLenient basically makes the parser very tolerant, even to allow malformed JSON data.

But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim the data would avoid the error:

String trimmed = result1.trim();

Then gson.fromJson(trimmed, T) might work. Surely this only covers a special case, so YMMV.

How do you load custom UITableViewCells from Xib files?

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cellReuseIdentifier = "collabCell"
            var cell:collabCell! = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as? collabCell
            if cell == nil {
                tableView.register(UINib(nibName: "collabCell", bundle: nil), forCellReuseIdentifier: cellReuseIdentifier)
                cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! collabCell!
            }


            return cell

}

How do I add my new User Control to the Toolbox or a new Winform?

One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity

Understanding MongoDB BSON Document size limit

Perhaps storing a blog post -> comments relation in a non-relational database is not really the best design.

You should probably store comments in a separate collection to blog posts anyway.

[edit]

See comments below for further discussion.

Promise Error: Objects are not valid as a React child

You can't do this: {this.state.arrayFromJson} As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map to do that.

I am pasting a link from where you can learn how to render elements from an array with React.

http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

Hope it helps!

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

How do I set a variable to the output of a command in Bash?

You can use backticks (also known as accent graves) or $().

Like:

OUTPUT=$(x+2);
OUTPUT=`x+2`;

Both have the same effect. But OUTPUT=$(x+2) is more readable and the latest one.

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});

SQL Server function to return minimum date (January 1, 1753)

You could write a User Defined Function that returns the min date value like this:

select cast(-53690 as datetime)

Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.

Alternately, you could use this query if you prefer it for better readability:

select cast('1753-1-1' as datetime)

Example Function

create function dbo.DateTimeMinValue()
returns datetime as
begin
    return (select cast(-53690 as datetime))
end

Usage

select dbo.DateTimeMinValue() as DateTimeMinValue

DateTimeMinValue
-----------------------
1753-01-01 00:00:00.000

How to determine total number of open/active connections in ms sql server 2005

Use this to get an accurate count for each connection pool (assuming each user/host process uses the same connection string)

SELECT 
DB_NAME(dbid) as DBName, 
COUNT(dbid) as NumberOfConnections,
loginame as LoginName, hostname, hostprocess
FROM
sys.sysprocesses with (nolock)
WHERE 
dbid > 0
GROUP BY 
dbid, loginame, hostname, hostprocess