Programs & Examples On #Roaming

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

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

Deleting the package-lock.json did it for me. I'd suggest you not push package-lock.json to your repo as I wasted hours trying to npm install with the package-lock.json in the folder which gave me helluva errors.

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.

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

Solution:

npm cache clean --force

then try again to create your app (here when creating a react app) or install what you were about to install.

create-react-app myproject

(creating react app)[same npm problem that can occur in different operation]

npm install -g @angular/cli@latest

(installing angular cli (or installing anything else))

It will work.

explanation:

That's a problem related to npm, it's about the cache that get corrupt. Even though in newer versions of npm they implemented self healing, which normally guarantee no corruption, but it seem it's not that efficient. enter image description here Forcing clean cache resolve the problem.

The error happen when parsing one of the cache files, which have a json format. The cache is found at ~/.npm/_cacache (in linux) and %AppData%/npm-cache (windows). For my current npm version and when i checked, there was three directories.
enter image description here

if you check the first or the second, the structure is as follow enter image description here

And each cache file have a json format (and that what get parsed) enter image description here

Here a good link from the doc: https://docs.npmjs.com/cli/cache

[Update] Also if it happen that this didn't solve it, you may check this answer here https://stackoverflow.com/a/50191315/7668448 it show how you can change the npm registry, that can be helpful. Check and see.

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

I tried this solution found at a How to fix Node.js blog

just use

npm cache clean

in windows if it refuses use

npm cache clean --force

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

You should add the path where ng.cmd located. By default, it should be located on C:\Users\user\AppData\Roaming\npm

NB: Here "user" may vary as per your pc username!

pgadmin4 : postgresql application server could not be contacted.

if you are using Mac OS X here is a fix: Open terminal and run this command

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log restart

and for other OS just restart your Postgresql server, it will solve

Then start pgAdmin4, it will start as normal

Share or comment if saved someone

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

Go to My Computer>Properties>Advance System Settings>Environment Variables>

Under the variables of Administrator edit the PATH variable & change its value to "C:\Users\Username\AppData\Roaming\npm". Note: The username in the path will be the current Admin user's name that you have logged in with.

ng is not recognized as an internal or external command

PATH environment variable should be updated by adding following path,

C:\Users\xyzname\AppData\Roaming\npm\node_modules\@angular\cli\bin

Because ng file is in bin folder, once this is added for sure ng will be recognized

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

In my case these steps solved my problem:

  1. terminating npm process (CTRL + C)
  2. deleting entire folder
  3. creating new one
  4. running npm again

Npm install cannot find module 'semver'

I got same error and I solved it.

delete package-lock.json file and node_modules folder then npm install

Global npm install location on windows?

If you're just trying to find out where npm is installing your global module (the title of this thread), look at the output when running npm install -g sample_module

$ npm install -g sample_module C:\Users\user\AppData\Roaming\npm\sample_module -> C:\Users\user\AppData\Roaming\npm\node_modules\sample_module\bin\sample_module.js + [email protected] updated 1 package in 2.821s

Cordova - Error code 1 for command | Command failed for

I removed android platforms and installed again then worked. I wrote these lines in command window:

cordova platform remove android
then
cordova platform add android

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

I would like to propose different solution which wasn't mentioned here which is using .URL files:

set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%

Notes:

  • By default .url files are intended to open web pages but they are working fine for any properly constructed URI
  • Microsoft Windows does not display the .url file extension even if "Hide extensions for known file types" option in Windows Explorer is disabled
  • IconFile and IconIndex are optional
  • For reference you can check An Unofficial Guide to the URL File Format of Edward Blake

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

In my case, it was a .pem file. Turns out holds good for that too. Changed permissions of the file and it worked.

chmod 400 ~/.ssh/dev-shared.pem

Thanks for all of those who helped above.

Installing Node.js (and npm) on Windows 10

In addition to the answer from @StephanBijzitter I would use the following PATH variables instead:

%appdata%\npm
%ProgramFiles%\nodejs

So your new PATH would look like:

[existing stuff];%appdata%\npm;%ProgramFiles%\nodejs

This has the advantage of neiter being user dependent nor 32/64bit dependent.

How to fix request failed on channel 0

It's an old question, but if someone gets here like me...

This might be result of a wrong date in the server. If you are working with an embedded system this might be the cause... So check your date:

$ date

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

Github permission denied: ssh add agent has no identities

Run the following commands:

ssh-keygen -t rsa
ssh-add /Users/*yourUserNameHere*/.ssh/id_rsa** 
pbcopy < ~/.ssh/id_rsa.pub**

Go to your Github account : https://github.com/settings/profile

1) Click : SSH and GPG keys

2) New SSH Key and Past it there

3) Add SSH Key

Done!

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

Install a stable version instead of the latest one, I have downgrade my version to node-v0.10.29-x86.msi from 'node-v0.10.33-x86.msi' and it is working well for me!

http://blog.nodejs.org/2014/06/16/node-v0-10-29-stable/

Could not extract response: no suitable HttpMessageConverter found for response type

As Artem Bilan said, this problem occures because MappingJackson2HttpMessageConverter supports response with application/json content-type only. If you can't change server code, but can change client code(I had such case), you can change content-type header with interceptor:

restTemplate.getInterceptors().add((request, body, execution) -> {
            ClientHttpResponse response = execution.execute(request,body);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response;
        });

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

I had this same issue. You just need to go to your

C:\Python27\Scripts

and add it to environment variables. After path setting just run pip.exe file on C:\Python27\Scripts and then try pip in cmd. But if nothing happens try running all pip applications like pip2.7 and pip2.exe. And pip will work like a charm.

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

There can be one of the two cause for this error:

  1. Path is not correct - but it is less likely as CreateDirectory should create any path unless path itself is not valid, read invalid characters
  2. Account through which your application is running don't have rights to create directory at path location, like if you are trying to create directory on shared drive with not enough privileges etc

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

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

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

Just Download and Install Node.js from here https://nodejs.org/en/

If you run the downloaded file and install it, they will automatically configure for your system

You don't need any other configurations anymore, now you can use the npm command anywhere


If the Nodejs is successfully installed and still displays the message like this:

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

Follow the steps below for Windows users:

  1. Go to My Computer Properties
  2. Click Advanced System Setting from the Left bar of a window.
  3. Now you have a System Properties window. Click Advanced
  4. Then, Click Environment Variable button
  5. Now you have Environment variable window: From System Variable, Select Path
  6. Click Edit
  7. At the end of the Variable value, add ;C:\Program Files\nodejs\

    Note: If you have installed nodejs on other drives then please act accordingly.

  8. Click Ok all the open dialogue box

Very important Note: "Close your Command Prompt And Restart Again" (It's very important because if you didn't restart your command prompt then changes will not be reflected.)

Now you can use the npm command anywhere

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

With the suggestions @jhadesdev and the explanations from others, I've found the issue here.

After adding the code to see what was visible to the various class loaders I found this:

All versions of log4j Logger: 
  zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of log4j visible from the classloader of the OAuthAuthorizer class: 
  zip:<snip>war/WEB-INF/lib/log4j-1.2.17.jar!/org/apache/log4j/Logger.class

All versions of XMLConfigurator: 
  jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

All versions of XMLConfigurator visible from the classloader of the OAuthAuthorizer class: 
  jar:<snip>com.bea.core.bea.opensaml2_1.0.0.0_6-1-0-0.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/ipp-java-aggcat-v1-devkit-1.0.2.jar!/org/opensaml/xml/XMLConfigurator.class
  zip:<snip>war/WEB-INF/lib/xmltooling-1.3.1.jar!/org/opensaml/xml/XMLConfigurator.class

I noticed that another version of XMLConfigurator was possibly getting picked up. I decompiled that class and found this at line 60 (where the error was in the original stack trace) private static final Logger log = Logger.getLogger(XMLConfigurator.class); and that class was importing from org.apache.log4j.Logger!

So it was this class that was being loaded and used. My fix was to rename the jar file that contained this file as I can't find where I explicitly or indirectly load it. Which may pose a problem when I actually deploy.

Thanks for all help and the much needed lesson on class loading.

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

For Visual Studio 2017, 2019. I got this error and able to fix it just by enable the Live Share extension from extensions.

see the VS community page for detail.

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 ERR! Error: ENOENT, open '/Users/feelexit/package.json'

This happens due to missing permissions or unlinked files while npm was working.

Meaning, that executing npm as this user doesn't have enough rights to read/write from a file, in this case package.json.

try adding sudo before the entire command - it should resolve.

$ sudo npm install -g express
$ Password:*******

Password would be your admin password of your mac.

-g flag will install this module (express) in the global context of node - meaning node will/should recognize express module from within any js file without having to provide a full path to the module in use.

Hope this helps!!

nodejs npm global config missing on windows

Have you tried running npm config list? And, if you want to see the defaults, run npm config ls -l.

Repository access denied. access via a deployment key is read-only

I would like to re-emphasize the following:

  • You might have added the SSH key to your repository (e.g. ExampleRepo), but this is NOT where the SSH key goes.
  • It is meant to go into YOUR PROFILE. This is the small avatar on the bottom left corner of the screen. Here, you'll find a different place to put your SSH Keys (under Security) > then you add the key here instead.
  • If you accidentally put your SSH key into the repository (as opposed to your account), then delete the one in the repository.

Took me ages to realise, somehow even after reading the answers here it didn't click.

How to add default signature in Outlook

The existing answers had a few problems for me:

  1. I needed to insert text (e.g. 'Good Day John Doe') with html formatting where you would normally type your message.
  2. At least on my machine, Outlook adds 2 blank lines above the signature where you should start typing. These should obviously be removed (replaced with custom HTML).

The code below does the job. Please note the following:

  1. The 'From' parameter allows you to choose the account (since there could be different default signatures for different email accounts)
  2. The 'Recipients' parameter expects an array of emails, and it will 'Resolve' the added email (i.e. find it in contacts, as if you had typed it in the 'To' box)
  3. Late binding is used, so no references are required
'Opens an outlook email with the provided email body and default signature
'Parameters:
'  from: Email address of Account to send from.  Wildcards are supported e.g. *@example.com
'  recipients: Array of recipients.  Recipient can be a Contact name or email address
'  subject: Email subject
'  htmlBody: Html formatted body to insert before signature (just body markup, should not contain html, head or body tags)
Public Sub CreateMail(from As String, recipients, subject As String, htmlBody As String)
    Dim oApp, oAcc As Object
    
    Set oApp = CreateObject("Outlook.application")
    
    With oApp.CreateItem(0) 'olMailItem = 0
        'Ensure we are sending with the correct account (to insert the correct signature)
        'oAcc is of type Outlook.Account, which has other properties that could be filtered with if required
        'SmtpAddress is usually equal to the raw email address
        .SendUsingAccount = Nothing
        For Each oAcc In oApp.Session.Accounts
            If CStr(oAcc.SmtpAddress) = from Or CStr(oAcc.SmtpAddress) Like from Then
                Set .SendUsingAccount = oAcc
            End If
        Next oAcc
        If .SendUsingAccount Is Nothing Then Err.Raise -1, , "Unknown email account " & from
        For Each addr In recipients
            With .recipients.Add(addr)
                'This will resolve the recipient as if you had typed the name/email and pressed Tab/Enter
                .Resolve
            End With
        Next addr
        .subject = subject
        .Display 'HTMLBody is only populated after this line
        'Remove blank lines at the top of the body
        .htmlBody = Replace(.htmlBody, "<o:p>&nbsp;</o:p>", "")
        'Insert the html at the start of the 'body' tag
        Dim bodyTagEnd As Long: bodyTagEnd = InStr(InStr(1, .htmlBody, "<body"), .htmlBody, ">")
        .htmlBody = Left(.htmlBody, bodyTagEnd) & htmlBody & Right(.htmlBody, Len(.htmlBody) - bodyTagEnd)
    End With
    Set oApp = Nothing
End Sub

Use as follows:

CreateMail from:="*@contoso.com", _
    recipients:= Array("[email protected]", "Jane Doe", "[email protected]"), _
    subject:= "Test Email", _
    htmlBody:= "<p>Good Day All</p><p>Hello <b>World!</b></p>"

Result:

Sample Outlook Email

JSchException: Algorithm negotiation fail

I had the same issue, running Netbeans 8.0 on Windows, and JRE 1.7.

I just installed JRE 1.8 from https://www.java.com/fr/download/ (note that it's called Version 8 but it's version 1.8 when you install it), and it fixed it.

Failed loading english.pickle with nltk.data.load

On Jenkins this can be fixed by adding following like of code to Virtualenv Builder under Build tab:

python -m nltk.downloader punkt

enter image description here

How to decrypt an encrypted Apple iTunes iPhone backup?

Security researchers Jean-Baptiste Bédrune and Jean Sigwald presented how to do this at Hack-in-the-box Amsterdam 2011.

Since then, Apple has released an iOS Security Whitepaper with more details about keys and algorithms, and Charlie Miller et al. have released the iOS Hacker’s Handbook, which covers some of the same ground in a how-to fashion. When iOS 10 first came out there were changes to the backup format which Apple did not publicize at first, but various people reverse-engineered the format changes.

Encrypted backups are great

The great thing about encrypted iPhone backups is that they contain things like WiFi passwords that aren’t in regular unencrypted backups. As discussed in the iOS Security Whitepaper, encrypted backups are considered more “secure,” so Apple considers it ok to include more sensitive information in them.

An important warning: obviously, decrypting your iOS device’s backup removes its encryption. To protect your privacy and security, you should only run these scripts on a machine with full-disk encryption. While it is possible for a security expert to write software that protects keys in memory, e.g. by using functions like VirtualLock() and SecureZeroMemory() among many other things, these Python scripts will store your encryption keys and passwords in strings to be garbage-collected by Python. This means your secret keys and passwords will live in RAM for a while, from whence they will leak into your swap file and onto your disk, where an adversary can recover them. This completely defeats the point of having an encrypted backup.

How to decrypt backups: in theory

The iOS Security Whitepaper explains the fundamental concepts of per-file keys, protection classes, protection class keys, and keybags better than I can. If you’re not already familiar with these, take a few minutes to read the relevant parts.

Now you know that every file in iOS is encrypted with its own random per-file encryption key, belongs to a protection class, and the per-file encryption keys are stored in the filesystem metadata, wrapped in the protection class key.

To decrypt:

  1. Decode the keybag stored in the BackupKeyBag entry of Manifest.plist. A high-level overview of this structure is given in the whitepaper. The iPhone Wiki describes the binary format: a 4-byte string type field, a 4-byte big-endian length field, and then the value itself.

    The important values are the PBKDF2 ITERations and SALT, the double protection salt DPSL and iteration count DPIC, and then for each protection CLS, the WPKY wrapped key.

  2. Using the backup password derive a 32-byte key using the correct PBKDF2 salt and number of iterations. First use a SHA256 round with DPSL and DPIC, then a SHA1 round with ITER and SALT.

    Unwrap each wrapped key according to RFC 3394.

  3. Decrypt the manifest database by pulling the 4-byte protection class and longer key from the ManifestKey in Manifest.plist, and unwrapping it. You now have a SQLite database with all file metadata.

  4. For each file of interest, get the class-encrypted per-file encryption key and protection class code by looking in the Files.file database column for a binary plist containing EncryptionKey and ProtectionClass entries. Strip the initial four-byte length tag from EncryptionKey before using.

    Then, derive the final decryption key by unwrapping it with the class key that was unwrapped with the backup password. Then decrypt the file using AES in CBC mode with a zero IV.

How to decrypt backups: in practice

First you’ll need some library dependencies. If you’re on a mac using a homebrew-installed Python 2.7 or 3.7, you can install the dependencies with:

CFLAGS="-I$(brew --prefix)/opt/openssl/include" \
LDFLAGS="-L$(brew --prefix)/opt/openssl/lib" \    
    pip install biplist fastpbkdf2 pycrypto

In runnable source code form, here is how to decrypt a single preferences file from an encrypted iPhone backup:

#!/usr/bin/env python3.7
# coding: UTF-8

from __future__ import print_function
from __future__ import division

import argparse
import getpass
import os.path
import pprint
import random
import shutil
import sqlite3
import string
import struct
import tempfile
from binascii import hexlify

import Crypto.Cipher.AES # https://www.dlitz.net/software/pycrypto/
import biplist
import fastpbkdf2
from biplist import InvalidPlistException


def main():
    ## Parse options
    parser = argparse.ArgumentParser()
    parser.add_argument('--backup-directory', dest='backup_directory',
                    default='testdata/encrypted')
    parser.add_argument('--password-pipe', dest='password_pipe',
                        help="""\
Keeps password from being visible in system process list.
Typical use: --password-pipe=<(echo -n foo)
""")
    parser.add_argument('--no-anonymize-output', dest='anonymize',
                        action='store_false')
    args = parser.parse_args()
    global ANONYMIZE_OUTPUT
    ANONYMIZE_OUTPUT = args.anonymize
    if ANONYMIZE_OUTPUT:
        print('Warning: All output keys are FAKE to protect your privacy')

    manifest_file = os.path.join(args.backup_directory, 'Manifest.plist')
    with open(manifest_file, 'rb') as infile:
        manifest_plist = biplist.readPlist(infile)
    keybag = Keybag(manifest_plist['BackupKeyBag'])
    # the actual keys are unknown, but the wrapped keys are known
    keybag.printClassKeys()

    if args.password_pipe:
        password = readpipe(args.password_pipe)
        if password.endswith(b'\n'):
            password = password[:-1]
    else:
        password = getpass.getpass('Backup password: ').encode('utf-8')

    ## Unlock keybag with password
    if not keybag.unlockWithPasscode(password):
        raise Exception('Could not unlock keybag; bad password?')
    # now the keys are known too
    keybag.printClassKeys()

    ## Decrypt metadata DB
    manifest_key = manifest_plist['ManifestKey'][4:]
    with open(os.path.join(args.backup_directory, 'Manifest.db'), 'rb') as db:
        encrypted_db = db.read()

    manifest_class = struct.unpack('<l', manifest_plist['ManifestKey'][:4])[0]
    key = keybag.unwrapKeyForClass(manifest_class, manifest_key)
    decrypted_data = AESdecryptCBC(encrypted_db, key)

    temp_dir = tempfile.mkdtemp()
    try:
        # Does anyone know how to get Python’s SQLite module to open some
        # bytes in memory as a database?
        db_filename = os.path.join(temp_dir, 'db.sqlite3')
        with open(db_filename, 'wb') as db_file:
            db_file.write(decrypted_data)
        conn = sqlite3.connect(db_filename)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        # c.execute("select * from Files limit 1");
        # r = c.fetchone()
        c.execute("""
            SELECT fileID, domain, relativePath, file
            FROM Files
            WHERE relativePath LIKE 'Media/PhotoData/MISC/DCIM_APPLE.plist'
            ORDER BY domain, relativePath""")
        results = c.fetchall()
    finally:
        shutil.rmtree(temp_dir)

    for item in results:
        fileID, domain, relativePath, file_bplist = item

        plist = biplist.readPlistFromString(file_bplist)
        file_data = plist['$objects'][plist['$top']['root'].integer]
        size = file_data['Size']

        protection_class = file_data['ProtectionClass']
        encryption_key = plist['$objects'][
            file_data['EncryptionKey'].integer]['NS.data'][4:]

        backup_filename = os.path.join(args.backup_directory,
                                    fileID[:2], fileID)
        with open(backup_filename, 'rb') as infile:
            data = infile.read()
            key = keybag.unwrapKeyForClass(protection_class, encryption_key)
            # truncate to actual length, as encryption may introduce padding
            decrypted_data = AESdecryptCBC(data, key)[:size]

        print('== decrypted data:')
        print(wrap(decrypted_data))
        print()

        print('== pretty-printed plist')
        pprint.pprint(biplist.readPlistFromString(decrypted_data))

##
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/

CLASSKEY_TAGS = [b"CLAS",b"WRAP",b"WPKY", b"KTYP", b"PBKY"]  #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
    1:"NSFileProtectionComplete",
    2:"NSFileProtectionCompleteUnlessOpen",
    3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
    4:"NSFileProtectionNone",
    5:"NSFileProtectionRecovery?",

    6: "kSecAttrAccessibleWhenUnlocked",
    7: "kSecAttrAccessibleAfterFirstUnlock",
    8: "kSecAttrAccessibleAlways",
    9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
    10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
    11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2

class Keybag(object):
    def __init__(self, data):
        self.type = None
        self.uuid = None
        self.wrap = None
        self.deviceKey = None
        self.attrs = {}
        self.classKeys = {}
        self.KeyBagKeys = None #DATASIGN blob
        self.parseBinaryBlob(data)

    def parseBinaryBlob(self, data):
        currentClassKey = None

        for tag, data in loopTLVBlocks(data):
            if len(data) == 4:
                data = struct.unpack(">L", data)[0]
            if tag == b"TYPE":
                self.type = data
                if self.type > 3:
                    print("FAIL: keybag type > 3 : %d" % self.type)
            elif tag == b"UUID" and self.uuid is None:
                self.uuid = data
            elif tag == b"WRAP" and self.wrap is None:
                self.wrap = data
            elif tag == b"UUID":
                if currentClassKey:
                    self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
                currentClassKey = {b"UUID": data}
            elif tag in CLASSKEY_TAGS:
                currentClassKey[tag] = data
            else:
                self.attrs[tag] = data
        if currentClassKey:
            self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey

    def unlockWithPasscode(self, passcode):
        passcode1 = fastpbkdf2.pbkdf2_hmac('sha256', passcode,
                                        self.attrs[b"DPSL"],
                                        self.attrs[b"DPIC"], 32)
        passcode_key = fastpbkdf2.pbkdf2_hmac('sha1', passcode1,
                                            self.attrs[b"SALT"],
                                            self.attrs[b"ITER"], 32)
        print('== Passcode key')
        print(anonymize(hexlify(passcode_key)))
        for classkey in self.classKeys.values():
            if b"WPKY" not in classkey:
                continue
            k = classkey[b"WPKY"]
            if classkey[b"WRAP"] & WRAP_PASSCODE:
                k = AESUnwrap(passcode_key, classkey[b"WPKY"])
                if not k:
                    return False
                classkey[b"KEY"] = k
        return True

    def unwrapKeyForClass(self, protection_class, persistent_key):
        ck = self.classKeys[protection_class][b"KEY"]
        if len(persistent_key) != 0x28:
            raise Exception("Invalid key length")
        return AESUnwrap(ck, persistent_key)

    def printClassKeys(self):
        print("== Keybag")
        print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
        print("Keybag version: %d" % self.attrs[b"VERS"])
        print("Keybag UUID: %s" % anonymize(hexlify(self.uuid)))
        print("-"*209)
        print("".join(["Class".ljust(53),
                    "WRAP".ljust(5),
                    "Type".ljust(11),
                    "Key".ljust(65),
                    "WPKY".ljust(65),
                    "Public key"]))
        print("-"*208)
        for k, ck in self.classKeys.items():
            if k == 6:print("")

            print("".join(
                [PROTECTION_CLASSES.get(k).ljust(53),
                str(ck.get(b"WRAP","")).ljust(5),
                KEY_TYPES[ck.get(b"KTYP",0)].ljust(11),
                anonymize(hexlify(ck.get(b"KEY", b""))).ljust(65),
                anonymize(hexlify(ck.get(b"WPKY", b""))).ljust(65),
            ]))
        print()

def loopTLVBlocks(blob):
    i = 0
    while i + 8 <= len(blob):
        tag = blob[i:i+4]
        length = struct.unpack(">L",blob[i+4:i+8])[0]
        data = blob[i+8:i+8+length]
        yield (tag,data)
        i += 8 + length

def unpack64bit(s):
    return struct.unpack(">Q",s)[0]
def pack64bit(s):
    return struct.pack(">Q",s)

def AESUnwrap(kek, wrapped):
    C = []
    for i in range(len(wrapped)//8):
        C.append(unpack64bit(wrapped[i*8:i*8+8]))
    n = len(C) - 1
    R = [0] * (n+1)
    A = C[0]

    for i in range(1,n+1):
        R[i] = C[i]

    for j in reversed(range(0,6)):
        for i in reversed(range(1,n+1)):
            todec = pack64bit(A ^ (n*j+i))
            todec += pack64bit(R[i])
            B = Crypto.Cipher.AES.new(kek).decrypt(todec)
            A = unpack64bit(B[:8])
            R[i] = unpack64bit(B[8:])

    if A != 0xa6a6a6a6a6a6a6a6:
        return None
    res = b"".join(map(pack64bit, R[1:]))
    return res

ZEROIV = "\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
    if len(data) % 16:
        print("AESdecryptCBC: data length not /16, truncating")
        data = data[0:(len(data)/16) * 16]
    data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
    if padding:
        return removePadding(16, data)
    return data

##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange

anon_random = random.Random(0)
memo = {}
def anonymize(s):
    if type(s) == str:
        s = s.encode('utf-8')
    global anon_random, memo
    if ANONYMIZE_OUTPUT:
        if s in memo:
            return memo[s]
        possible_alphabets = [
            string.digits,
            string.digits + 'abcdef',
            string.ascii_letters,
            "".join(chr(x) for x in range(0, 256)),
        ]
        for a in possible_alphabets:
            if all((chr(c) if type(c) == int else c) in a for c in s):
                alphabet = a
                break
        ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
        memo[s] = ret
        return ret
    else:
        return s

def wrap(s, width=78):
    "Return a width-wrapped repr(s)-like string without breaking on \’s"
    s = repr(s)
    quote = s[0]
    s = s[1:-1]
    ret = []
    while len(s):
        i = s.rfind('\\', 0, width)
        if i <= width - 4: # "\x??" is four characters
            i = width
        ret.append(s[:i])
        s = s[i:]
    return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)

def readpipe(path):
    if stat.S_ISFIFO(os.stat(path).st_mode):
        with open(path, 'rb') as pipe:
            return pipe.read()
    else:
        raise Exception("Not a pipe: {!r}".format(path))

if __name__ == '__main__':
    main()

Which then prints this output:

Warning: All output keys are FAKE to protect your privacy
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES                                                                         4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES                                                                         09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES                                                                         e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES                                                                         902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES                                                                         a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES                                                                         09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES                                                                         0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES                                                                         b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES                                                                         417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES                                                                         b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES                                                                         9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== Passcode key
ee34f5bb635830d698074b1e3e268059c590973b0f1138f1954a2a4e1069e612

== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES        64e8fc94a7b670b0a9c4a385ff395fe9ba5ee5b0d9f5a5c9f0202ef7fdcb386f 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES        22a218c9c446fbf88f3ccdc2ae95f869c308faaa7b3e4fe17b78cbf2eeaf4ec9 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES        1004c6ca6e07d2b507809503180edf5efc4a9640227ac0d08baf5918d34b44ef e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES        2e809a0cd1a73725a788d5d1657d8fd150b0e360460cb5d105eca9c60c365152 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES        9a078d710dcd4a1d5f70ea4062822ea3e9f7ea034233e7e290e06cf0d80c19ca a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES        606e5328816af66736a69dfe5097305cf1e0b06d6eb92569f48e5acac3f294a4 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES        6a4b5292661bac882338d5ebb51fd6de585befb4ef5f8ffda209be8ba3af1b96 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES        c0ed717947ce8d1de2dde893b6026e9ee1958771d7a7282dd2116f84312c2dd2 b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES        80d8c7be8d5103d437f8519356c3eb7e562c687a5e656cfd747532f71668ff99 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES        a875a15e3ff901351c5306019e3b30ed123e6c66c949bdaa91fb4b9a69a3811e b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES        1e7756695d337e0b06c764734a9ef8148af20dcc7a636ccfea8b2eb96a9e9373 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== decrypted data:
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD '
'PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist versi'
'on="1.0">\n<dict>\n\t<key>DCIMLastDirectoryNumber</key>\n\t<integer>100</integ'
'er>\n\t<key>DCIMLastFileNumber</key>\n\t<integer>3</integer>\n</dict>\n</plist'
'>\n'

== pretty-printed plist
{'DCIMLastDirectoryNumber': 100, 'DCIMLastFileNumber': 3}

Extra credit

The iphone-dataprotection code posted by Bédrune and Sigwald can decrypt the keychain from a backup, including fun things like saved wifi and website passwords:

$ python iphone-dataprotection/python_scripts/keychain_tool.py ...

--------------------------------------------------------------------------------------
|                              Passwords                                             |
--------------------------------------------------------------------------------------
|Service           |Account          |Data           |Access group  |Protection class|
--------------------------------------------------------------------------------------
|AirPort           |Ed’s Coffee Shop |<3FrenchRoast  |apple         |AfterFirstUnlock|
...

That code no longer works on backups from phones using the latest iOS, but there are some golang ports that have been kept up to date allowing access to the keychain.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

Use the following Statement:

IF EXISTS(SELECT * FROM prueba )
then
  UPDATE prueba
  SET nombre = '1', apellido = '1' 
  WHERE cedula = 'ct'
ELSE 
  INSERT INTO prueba (cedula, nombre, apellido)
  VALUES ('ct', 'ct', 'ct');

Referencing Row Number in R

Simply:

data$rownumber = 1:nrow(Data)

How to inspect Javascript Objects

This is blatant rip-off of Christian's excellent answer. I've just made it a bit more readable:

/**
 * objectInspector digs through a Javascript object
 * to display all its properties
 *
 * @param object - a Javascript object to inspect
 * @param result - a string of properties with datatypes
 *
 * @return result - the concatenated description of all object properties
 */
function objectInspector(object, result) {
    if (typeof object != "object")
        return "Invalid object";
    if (typeof result == "undefined")
        result = '';

    if (result.length > 50)
        return "[RECURSION TOO DEEP. ABORTING.]";

    var rows = [];
    for (var property in object) {
        var datatype = typeof object[property];

        var tempDescription = result+'"'+property+'"';
        tempDescription += ' ('+datatype+') => ';
        if (datatype == "object")
            tempDescription += 'object: '+objectInspector(object[property],result+'  ');
        else
            tempDescription += object[property];

        rows.push(tempDescription);
    }//Close for

    return rows.join(result+"\n");
}//End objectInspector

What is your favorite C programming trick?

I'm a fan of xor hacks:

Swap 2 pointers without third temp pointer:

int * a;
int * b;
a ^= b;
b ^= a;
a ^= b;

Or I really like the xor linked list with only one pointer. (http://en.wikipedia.org/wiki/XOR_linked_list)

Each node in the linked list is the Xor of the previous node and the next node. To traverse forward, the address of the nodes are found in the following manner :

LLNode * first = head;
LLNode * second = first.linked_nodes;
LLNode * third = second.linked_nodes ^ first;
LLNode * fourth = third.linked_nodes ^ second;

etc.

or to traverse backwards:

LLNode * last = tail;
LLNode * second_to_last = last.linked_nodes;
LLNode * third_to_last = second_to_last.linked_nodes ^ last;
LLNode * fourth_to_last = third_to_last.linked_nodes ^ second_to_last;

etc.

While not terribly useful (you can't start traversing from an arbitrary node) I find it to be very cool.

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

HTML.ActionLink method

Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item") 

How to rename a class and its corresponding file in Eclipse?

Just rename the class in the source code. Eclipse will point out an error by underlining the class name with a red squiggly line. Hover on that line with your mouse pointer and eclipse will give you the option to rename compilation unit. Click on that.

Try-catch-finally-return clarification

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

updating nodejs on ubuntu 16.04

sudo npm install npm@latest -g

C# DataTable.Select() - How do I format the filter criteria to include null?

The way to check for null is to check for it:

DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");

You can use and and or in the Select statement.

Wavy shape with css

I like ThomasA's answer, but wanted a more realistic context with the wave being used to separate two divs. So I created a more complete demo where the separator SVG gets positioned perfectly between the two divs.

css wavy divider in CSS

Now I thought it would be cool to take it further. What if we could do this all in CSS without the need for the inline SVG? The point being to avoid extra markup. Here's how I did it:

Two simple <div>:

_x000D_
_x000D_
/** CSS using pseudo-elements: **/_x000D_
_x000D_
#A {_x000D_
  background: #0074D9;_x000D_
}_x000D_
_x000D_
#B {_x000D_
  background: #7FDBFF;_x000D_
}_x000D_
_x000D_
#A::after {_x000D_
  content: "";_x000D_
  position: relative;_x000D_
  left: -3rem;_x000D_
  /* padding * -1 */_x000D_
  top: calc( 3rem - 4rem / 2);_x000D_
  /* padding - height/2 */_x000D_
  float: left;_x000D_
  display: block;_x000D_
  height: 4rem;_x000D_
  width: 100vw;_x000D_
  background: hsla(0, 0%, 100%, 0.5);_x000D_
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 70 500 60' preserveAspectRatio='none'%3E%3Crect x='0' y='0' width='500' height='500' style='stroke: none; fill: %237FDBFF;' /%3E%3Cpath d='M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z' style='stroke: none; fill: %230074D9;'%3E%3C/path%3E%3C/svg%3E");_x000D_
  background-size: 100% 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/** Cosmetics **/_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#A,_x000D_
#B {_x000D_
  padding: 3rem;_x000D_
}_x000D_
_x000D_
div {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.2rem;_x000D_
  line-height: 1.2;_x000D_
}_x000D_
_x000D_
#A {_x000D_
  color: white;_x000D_
}
_x000D_
<div id="A">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec quam tincidunt, iaculis mi non, hendrerit felis. Nulla pretium lectus et arcu tempus, quis luctus ex imperdiet. In facilisis nulla suscipit ornare finibus. …_x000D_
</div>_x000D_
_x000D_
<div id="B" class="wavy">… In iaculis fermentum lacus vel porttitor. Vestibulum congue elementum neque eget feugiat. Donec suscipit diam ligula, aliquam consequat tellus sagittis porttitor. Sed sodales leo nisl, ut consequat est ornare eleifend. Cras et semper mi, in porta nunc.</div>
_x000D_
_x000D_
_x000D_

Demo Wavy divider (with CSS pseudo-elements to avoid extra markup)

It was a bit trickier to position than with an inline SVG but works just as well. (Could use CSS custom properties or pre-processor variables to keep the height and padding easy to read.)

To edit the colors, you need to edit the URL-encoded SVG itself.

Pay attention (like in the first demo) to a change in the viewBox to get rid of unwanted spaces in the SVG. (Another option would be to draw a different SVG.)

Another thing to pay attention to here is the background-size set to 100% 100% to get it to stretch in both directions.

How to remove the querystring and get only the url?

You can use the parse_url build in function like that:

$baseUrl = $_SERVER['SERVER_NAME'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

Postman - How to see request with headers and body data with variables substituted

Update 2018-12-12 - Chrome App v Chrome Plugin - Most recent updates at top

With the deprecation of the Postman Chrome App, assuming that you are now using the Postman Native App, the options are now:

  1. Hover over variables with mouse
  2. Generate "Code" button/link
  3. Postman Console

See below for full details on each option.

Personally, I still go for 2) Generate "Code" button/link as it allows me to see the variables without actually having to send.

Demo Request Demo Request

Demo Environment Demo Environment

1) Hover over variables with mouse Hover over variables with mouse

2) Generate "Code" button/link Generate "Code" button/link

3) Postman Console enter image description here

Update: 2016-06-03

Whilst the method described above does work, in practice, I now normally use the "Generate Code" link on the Postman Request screen. The generated code, no matter what code language you choose, contains the substituted variables. Hitting the "Generate Code" link is just faster, additionally, you can see the substituted variables without actually making the request.

Original Answer below

To see the substituted variables in the Headers and Body, you need to use Chrome Developer tools. To enable Chrome Developer Tools from within Postman do the following, as per http://blog.getpostman.com/2015/06/13/debugging-postman-requests/.

I have copied the instructions from the link above in case the link gets broken in the future:

  1. Type chrome://flags inside your Chrome URL window

  2. Search for “packed” or try to find the “Enable debugging for packed apps”

  3. Enable the setting

  4. Restart Chrome

You can access the Developer Tools window by right clicking anywhere inside Postman and selecting “inspect element”. You can also go to chrome://inspect/#apps and then click “inspect” just below requester.html under the Postman heading.

Once enabled, you can use the Network Tools tab for even more information on your requests or the console while writing test scripts. If something goes wrong with your test scripts, it’ll show up here.

How to get the jQuery $.ajax error response text?

This is what worked for me

    function showErrorMessage(xhr, status, error) {
        if (xhr.responseText != "") {

            var jsonResponseText = $.parseJSON(xhr.responseText);
            var jsonResponseStatus = '';
            var message = '';
            $.each(jsonResponseText, function(name, val) {
                if (name == "ResponseStatus") {
                    jsonResponseStatus = $.parseJSON(JSON.stringify(val));
                     $.each(jsonResponseStatus, function(name2, val2) {
                         if (name2 == "Message") {
                             message = val2;
                         }
                     });
                }
            });

            alert(message);
        }
    }

Assign a login to a user created without login (SQL Server)

Through trial and error, it seems if the user was originally created "without login" then this query

select * from sys.database_principals

will show authentication_type = 0 (NONE).

Apparently these users cannot be re-linked to any login (pre-existing or new, SQL or Windows) since this command:

alter user [TempUser] with login [TempLogin]

responds with the Remap Error "Msg 33016" shown in the question.

Also these users do not show up in classic (deprecating) SP report:

exec sp_change_users_login 'Report'

If anyone knows a way around this or how to change authentication_type, please comment.

SQL: sum 3 columns when one column has a null value?

SELECT sum(isnull(TotalHoursM,0)) 
         + isnull(TotalHoursT,0) 
         + isnull(TotalHoursW,0) 
         + isnull(TotalHoursTH,0) 
         + isnull(TotalHoursF,0))
AS TOTAL FROM LeaveRequest

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

public class MainActivity extends Activity
        implements View.OnClickListener {
    private Button btnForward, btnBackword, btnPause, btnPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initControl();
    }

    private void initControl() {
        btnForward = (Button) findViewById(R.id.btnForward);
        btnBackword = (Button) findViewById(R.id.btnBackword);
        btnPause = (Button) findViewById(R.id.btnPause);
        btnPlay = (Button) findViewById(R.id.btnPlay);
        btnForward.setOnClickListener(this);
        btnBackword.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnForward:
                break;
            case R.id.btnBackword:
                break;
            case R.id.btnPause:
                break;
            case R.id.btnPlay:
                break;
        }
    }
}

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

Change import React from 'react-dom to import React, {Component} from 'react'
And change class Classname extends React.Component to class Classname extends Component
If you are using the latest version of React(16.8.6 as of now).

How to retrieve a single file from a specific revision in Git?

You need to provide the full path to the file:

git show 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8:full/repo/path/to/my_file.txt

Common MySQL fields and their appropriate data types

Any Table ID

Use: INT(11).

MySQL indexes will be able to parse through an int list fastest.

Anything Security

Use: BINARY(x), or BLOB(x).

You can store security tokens, etc., as hex directly in BINARY(x) or BLOB(x). To retrieve from binary-type, use SELECT HEX(field)... or SELECT ... WHERE field = UNHEX("ABCD....").

Anything Date

Use: DATETIME, DATE, or TIME.

Always use DATETIME if you need to store both date and time (instead of a pair of fields), as a DATETIME indexing is more amenable to date-comparisons in MySQL.

Anything True-False

Use: BIT(1) (MySQL 8-only.) Otherwise, use BOOLEAN(1).

BOOLEAN is actually just an alias of TINYINT(1), which actually stores 0 to 255 (not exactly a true/false, is it?).

Anything You Want to call `SUM()`, `MAX()`, or similar functions on

Use: INT(11).

VARCHAR or other types of fields won't work with the SUM(), etc., functions.

Anything Over 1,000 Characters

Use: TEXT.

Max limit is 65,535.

Anything Over 65,535 Characters

Use: MEDIUMTEXT.

Max limit is 16,777,215.

Anything Over 16,777,215 Characters

Use: LONGTEXT.

Max limit is 4,294,967,295.

FirstName, LastName

Use : VARCHAR(255).

UTF-8 characters can take up three characters per visible character, and some cultures do not distinguish firstname and lastname. Additionally, cultures may have disagreements about which name is first and which name is last. You should name these fields Person.GivenName and Person.FamilyName.

Email Address

Use : VARCHAR(256).

The definition of an e-mail path is set in RFC821 in 1982. The maximum limit of an e-mail was set by RFC2821 in 2001, and these limits were kept unchanged by RFC5321 in 2008. (See the section: 4.5.3.1. Size Limits and Minimums.) RFC3696, published 2004, mistakenly cites the email address limit as 320 characters, but this was an "info-only" RFC that explicitly "defines no standards" according to its intro, so disregard it.

Phone

Use: VARCHAR(255).

You never know when the phone number will be in the form of "1800...", or "1-800", or "1-(800)", or if it will end with "ext. 42", or "ask for susan".

ZipCode

Use: VARCHAR(10).

You'll get data like 12345 or 12345-6789. Use validation to cleanse this input.

URL

Use: VARCHAR(2000).

Official standards support URL's much longer than this, but few modern browsers support URL's over 2,000 characters. See this SO answer: What is the maximum length of a URL in different browsers?

Price

Use: DECIMAL(11,2).

It goes up to 11.

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

How do I set a path in Visual Studio?

You have a couple of options:

  • You can add the path to the DLLs to the Executable files settings under Tools > Options > Projects and Solutions > VC++ Directories (but only for building, for executing or debugging here)
  • You can add them in your global PATH environment variable
  • You can start Visual Studio using a batch file as I described here and manipulate the path in that one
  • You can copy the DLLs into the executable file's directory :-)

Add Keypair to existing EC2 instance

You can just add a new key to the instance by the following command:

ssh-copy-id -i ~/.ssh/id_rsa.pub domain_alias

You can configure domain_alias in ~/.ssh config

host domain_alias
  User ubuntu
  Hostname domain.com
  IdentityFile ~/.ssh/ec2.pem

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

See the details about entryComponent:

If you are loading any component dynamically then you need to put it in both declarations and entryComponent:

@NgModule({
  imports: [...],
  exports: [...],
  entryComponents: [ConfirmComponent,..],
  declarations: [ConfirmComponent,...],
  providers: [...]
})

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

The complete article that works for me: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

The part where we encode from Unicode/UTF-8 is

function utf8_to_b64( str ) {
   return window.btoa(unescape(encodeURIComponent( str )));
}

function b64_to_utf8( str ) {
   return decodeURIComponent(escape(window.atob( str )));
}

// Usage:
utf8_to_b64('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"

This is one of the most used methods nowadays.

Advantage of switch over if-else statement

I'm not sure about best-practise, but I'd use switch - and then trap intentional fall-through via 'default'

javascript regex : only english letters allowed

_x000D_
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
_x000D_
_x000D_

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

Python import csv to list

Unfortunately I find none of the existing answers particularly satisfying.

Here is a straightforward and complete Python 3 solution, using the csv module.

import csv

with open('../resources/temp_in.csv', newline='') as f:
    reader = csv.reader(f, skipinitialspace=True)
    rows = list(reader)

print(rows)

Notice the skipinitialspace=True argument. This is necessary since, unfortunately, OP's CSV contains whitespace after each comma.

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

How to improve a case statement that uses two columns

Just change your syntax ever so slightly:

CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
     WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
     WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
     ELSE '"DECLINED"'
END

If you don't put the field expression before the CASE statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.

jquery can't get data attribute value

Use plain javascript methods

$x10Device = this.dataset("x10");

How to fix "Headers already sent" error in PHP

No output before sending headers!

Functions that send/modify HTTP headers must be invoked before any output is made. summary ? Otherwise the call fails:

Warning: Cannot modify header information - headers already sent (output started at script:line)

Some functions modifying the HTTP header are:

Output can be:

  • Unintentional:

    • Whitespace before <?php or after ?>
    • The UTF-8 Byte Order Mark specifically
    • Previous error messages or notices
  • Intentional:

    • print, echo and other functions producing output
    • Raw <html> sections prior <?php code.

Why does it happen?

To understand why headers must be sent before output it's necessary to look at a typical HTTP response. PHP scripts mainly generate HTML content, but also pass a set of HTTP/CGI headers to the webserver:

HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8

<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>

The page/output always follows the headers. PHP has to pass the headers to the webserver first. It can only do that once. After the double linebreak it can nevermore amend them.

When PHP receives the first output (print, echo, <html>) it will flush all collected headers. Afterwards it can send all the output it wants. But sending further HTTP headers is impossible then.

How can you find out where the premature output occured?

The header() warning contains all relevant information to locate the problem cause:

Warning: Cannot modify header information - headers already sent by (output started at /www/usr2345/htdocs/auth.php:52) in /www/usr2345/htdocs/index.php on line 100

Here "line 100" refers to the script where the header() invocation failed.

The "output started at" note within the parenthesis is more significant. It denominates the source of previous output. In this example it's auth.php and line 52. That's where you had to look for premature output.

Typical causes:

  1. Print, echo

    Intentional output from print and echo statements will terminate the opportunity to send HTTP headers. The application flow must be restructured to avoid that. Use functions and templating schemes. Ensure header() calls occur before messages are written out.

    Functions that produce output include

    • print, echo, printf, vprintf
    • trigger_error, ob_flush, ob_end_flush, var_dump, print_r
    • readfile, passthru, flush, imagepng, imagejpeg


    among others and user-defined functions.

  2. Raw HTML areas

    Unparsed HTML sections in a .php file are direct output as well. Script conditions that will trigger a header() call must be noted before any raw <html> blocks.

    <!DOCTYPE html>
    <?php
        // Too late for headers already.
    

    Use a templating scheme to separate processing from output logic.

    • Place form processing code atop scripts.
    • Use temporary string variables to defer messages.
    • The actual output logic and intermixed HTML output should follow last.

  3. Whitespace before <?php for "script.php line 1" warnings

    If the warning refers to output in line 1, then it's mostly leading whitespace, text or HTML before the opening <?php token.

     <?php
    # There's a SINGLE space/newline before <? - Which already seals it.
    

    Similarly it can occur for appended scripts or script sections:

    ?>
    
    <?php
    

    PHP actually eats up a single linebreak after close tags. But it won't compensate multiple newlines or tabs or spaces shifted into such gaps.

  4. UTF-8 BOM

    Linebreaks and spaces alone can be a problem. But there are also "invisible" character sequences which can cause this. Most famously the UTF-8 BOM (Byte-Order-Mark) which isn't displayed by most text editors. It's the byte sequence EF BB BF, which is optional and redundant for UTF-8 encoded documents. PHP however has to treat it as raw output. It may show up as the characters  in the output (if the client interprets the document as Latin-1) or similar "garbage".

    In particular graphical editors and Java based IDEs are oblivious to its presence. They don't visualize it (obliged by the Unicode standard). Most programmer and console editors however do:

    joes editor showing UTF-8 BOM placeholder, and MC editor a dot

    There it's easy to recognize the problem early on. Other editors may identify its presence in a file/settings menu (Notepad++ on Windows can identify and remedy the problem), Another option to inspect the BOMs presence is resorting to an hexeditor. On *nix systems hexdump is usually available, if not a graphical variant which simplifies auditing these and other issues:

    beav hexeditor showing utf-8 bom

    An easy fix is to set the text editor to save files as "UTF-8 (no BOM)" or similar such nomenclature. Often newcomers otherwise resort to creating new files and just copy&pasting the previous code back in.

    Correction utilities

    There are also automated tools to examine and rewrite text files (sed/awk or recode). For PHP specifically there's the phptags tag tidier. It rewrites close and open tags into long and short forms, but also easily fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:

    phptags  --whitespace  *.php
    

    It's sane to use on a whole include or project directory.

  5. Whitespace after ?>

    If the error source is mentioned as behind the closing ?> then this is where some whitespace or raw text got written out. The PHP end marker does not terminate script executation at this point. Any text/space characters after it will be written out as page content still.

    It's commonly advised, in particular to newcomers, that trailing ?> PHP close tags should be omitted. This eschews a small portion of these cases. (Quite commonly include()d scripts are the culprit.)

  6. Error source mentioned as "Unknown on line 0"

    It's typically a PHP extension or php.ini setting if no error source is concretized.

    • It's occasionally the gzip stream encoding setting or the ob_gzhandler.
    • But it could also be any doubly loaded extension= module generating an implicit PHP startup/warning message.

  7. Preceding error messages

    If another PHP statement or expression causes a warning message or notice being printeded out, that also counts as premature output.

    In this case you need to eschew the error, delay the statement execution, or suppress the message with e.g. isset() or @() - when either doesn't obstruct debugging later on.

No error message

If you have error_reporting or display_errors disabled per php.ini, then no warning will show up. But ignoring errors won't make the problem go away. Headers still can't be sent after premature output.

So when header("Location: ...") redirects silently fail it's very advisable to probe for warnings. Reenable them with two simple commands atop the invocation script:

error_reporting(E_ALL);
ini_set("display_errors", 1);

Or set_error_handler("var_dump"); if all else fails.

Speaking of redirect headers, you should often use an idiom like this for final code paths:

exit(header("Location: /finished.html"));

Preferrably even a utility function, which prints a user message in case of header() failures.

Output buffering as workaround

PHPs output buffering is a workaround to alleviate this issue. It often works reliably, but shouldn't substitute for proper application structuring and separating output from control logic. Its actual purpose is minimizing chunked transfers to the webserver.

  1. The output_buffering= setting nevertheless can help. Configure it in the php.ini or via .htaccess or even .user.ini on modern FPM/FastCGI setups.
    Enabling it will allow PHP to buffer output instead of passing it to the webserver instantly. PHP thus can aggregate HTTP headers.

  2. It can likewise be engaged with a call to ob_start(); atop the invocation script. Which however is less reliable for multiple reasons:

    • Even if <?php ob_start(); ?> starts the first script, whitespace or a BOM might get shuffled before, rendering it ineffective.

    • It can conceal whitespace for HTML output. But as soon as the application logic attempts to send binary content (a generated image for example), the buffered extraneous output becomes a problem. (Necessitating ob_clean() as furher workaround.)

    • The buffer is limited in size, and can easily overrun when left to defaults. And that's not a rare occurence either, difficult to track down when it happens.

Both approaches therefore may become unreliable - in particular when switching between development setups and/or production servers. Which is why output buffering is widely considered just a crutch / strictly a workaround.

See also the basic usage example in the manual, and for more pros and cons:

But it worked on the other server!?

If you didn't get the headers warning before, then the output buffering php.ini setting has changed. It's likely unconfigured on the current/new server.

Checking with headers_sent()

You can always use headers_sent() to probe if it's still possible to... send headers. Which is useful to conditionally print an info or apply other fallback logic.

if (headers_sent()) {
    die("Redirect failed. Please click on this link: <a href=...>");
}
else{
    exit(header("Location: /user.php"));
}

Useful fallback workarounds are:

  • HTML <meta> tag

    If your application is structurally hard to fix, then an easy (but somewhat unprofessional) way to allow redirects is injecting a HTML <meta> tag. A redirect can be achieved with:

     <meta http-equiv="Location" content="http://example.com/">
    

    Or with a short delay:

     <meta http-equiv="Refresh" content="2; url=../target.html">
    

    This leads to non-valid HTML when utilized past the <head> section. Most browsers still accept it.

  • JavaScript redirect

    As alternative a JavaScript redirect can be used for page redirects:

     <script> location.replace("target.html"); </script>
    

    While this is often more HTML compliant than the <meta> workaround, it incurs a reliance on JavaScript-capable clients.

Both approaches however make acceptable fallbacks when genuine HTTP header() calls fail. Ideally you'd always combine this with a user-friendly message and clickable link as last resort. (Which for instance is what the http_redirect() PECL extension does.)

Why setcookie() and session_start() are also affected

Both setcookie() and session_start() need to send a Set-Cookie: HTTP header. The same conditions therefore apply, and similar error messages will be generated for premature output situations.

(Of course they're furthermore affected by disabled cookies in the browser, or even proxy issues. The session functionality obviously also depends on free disk space and other php.ini settings, etc.)

Further links

how to stop a for loop

To achieve this you would do something like:

n=L[0][0]
m=len(A)
for i in range(m):
    for j in range(m):
        if L[i][j]==n:
            //do some processing
        else:
            break;

What is correct content-type for excel files?

For BIFF .xls files

application/vnd.ms-excel

For Excel2007 and above .xlsx files

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

How do you uninstall all dependencies listed in package.json (NPM)?

Another SIMPLE option is to delete the node_modules and package-lock.json

rm -rf node_modules
rm -rf package-lock.json

After this you can try reinstalling the npm packages

Comparing arrays for equality in C++

If you are reluctant to change your existing code to std::array, then use a couple of methods instead which takes non-type template arguments :

//Passed arrays store different data types
template <typename T, typename U, int size1, int size2>
bool equal(T (&arr1)[size1], U (&arr2)[size2] ){
    return false;
}

//Passed arrays store SAME data types
template <typename T, int size1, int size2>
bool equal(T (&arr1)[size1], T (&arr2)[size2] ){
    if(size1 == size2) {
        for(int i = 0 ; i < size1; ++i){
            if(arr1[i] != arr2[i]) return false;
        }
        return true;
    }
    return false;
}

Here is the demo. Note that, while calling, we just need to pass the array variables e.g. equal(iar1, iar2) in your case, no need to pass the size of arrays.

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);

Getting the "real" Facebook profile picture URL from graph API

I realize this is late, but there is another way to obtain the URL of the profile image.

To your original url, you can add the parameter redirect=false to obtain the actual URL of the image you'd normally be redirected to.

So, the new request would look like http://graph.facebook.com/517267866/picture?type=large&redirect=false. This will return a JSON object containing the URL of the picture and a boolean is_silhouette (true if the picture is the default Facebook picture).

The picture will be of the size you specified, as well. You can test this additionally by adding dimensions: http://graph.facebook.com/517267866/picture?type=large&redirect=false&width=400&height=400

What happens if you don't commit a transaction to a database (say, SQL Server)?

The behaviour is not defined, so you must explicit set a commit or a rollback:

http://docs.oracle.com/cd/B10500_01/java.920/a96654/basic.htm#1003303

"If auto-commit mode is disabled and you close the connection without explicitly committing or rolling back your last changes, then an implicit COMMIT operation is executed."

Hsqldb makes a rollback

con.setAutoCommit(false);
stmt.executeUpdate("insert into USER values ('" +  insertedUserId + "','Anton','Alaf')");
con.close();

result is

2011-11-14 14:20:22,519 main INFO [SqlAutoCommitExample:55] [AutoCommit enabled = false] 2011-11-14 14:20:22,546 main INFO [SqlAutoCommitExample:65] [Found 0# users in database]

HTML 'td' width and height

Following width worked well in HTML5: -

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

Please note that

  • TD tag is without CSS style.

Pause Console in C++ program

There is no good way to do that, but you should use portable solution, so avoid system() calls, in your case you could use cin.get() or getch() as you mentioned in your question, also there is one advice. Make all pauses controlled by one (or very few) preprocessor definitions.

For example:

Somewhere in global file:

#define USE_PAUSES
#ifndef _DEBUG    //I asume you have _DEBUG definition for debug and don't have it for release build
#undef USE_PAUSES
#endif

Somewhere in code

#ifdef USE_PAUSES
cin.get();
#endif

This is not universal advice, but you should protect yourself from putting pauses in release builds and these should have easy control, my mentioned global file may not be so global, because changes in that may cause really long compilation.

How to make a website secured with https

@balalakshmi mentioned about the correct authentication settings. Authentication is only half of the problem, the other half is authorization.

If you're using Forms Authentication and standard controls like <asp:Login> there are a couple of things you'll need to do to ensure that only your authenticated users can access secured pages.

In web.config, under the <system.web> section you'll need to disable anonymous access by default:

<authorization>
 <deny users="?" />
</authorization>

Any pages that will be accessed anonymously (such as the Login.aspx page itself) will need to have an override that re-allows anonymous access. This requires a <location> element and must be located at the <configuration> level (outside the <system.web> section), like this:

<!-- Anonymous files -->
<location path="Login.aspx">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Note that you'll also need to allow anonymous access to any style sheets or scripts that are used by the anonymous pages:

<!-- Anonymous folders -->
<location path="styles">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Be aware that the location's path attribute is relative to the web.config folder and cannot have a ~/ prefix, unlike most other path-type configuration attributes.

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

Guzzlehttp - How get the body of a response from Guzzle 6?

If expecting JSON back, the simplest way to get it:

$data = json_decode($response->getBody()); // returns an object

// OR

$data = json_decode($response->getBody(), true); // returns an array

json_decode() will automatically cast the body to string, so there is no need to call getContents().

How to randomly pick an element from an array

You can also try this approach..

public static <E> E[] pickRandom_(int n,E ...item) {
        List<E> copy = Arrays.asList(item);
        Collections.shuffle(copy);
        if (copy.size() > n) {
            return (E[]) copy.subList(0, n).toArray();
        } else {
            return (E[]) copy.toArray();
        }

    }

Where is the documentation for the values() method of Enum?

Run this

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

you will see

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

These are all public methods that "sex" class has. They are not in the source code, javac.exe added them

Notes:

  1. never use sex as a class name, it's difficult to read your code, we use Sex in Java

  2. when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class

How to add percent sign to NSString

seems if %% followed with a %@, the NSString will go to some strange codes try this and this worked for me

NSString *str = [NSString stringWithFormat:@"%@%@%@", @"%%", 
                 [textfield text], @"%%"]; 

Rest-assured. Is it possible to extract value from request json?

I found the answer :)

Use JsonPath or XmlPath (in case you have XML) to get data from the response body.

In my case:

JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");

Kill Attached Screen in Linux

This worked for me very well. Get the screen id via:

screen -r

or

screen -ls

then kill the screen: kill -9 <screenID> it now becomes a dead screen, then wipe it out with: screen -wipe

Best way to include CSS? Why use @import?

using the link method, the stylesheets are loaded parallel (faster and better), and nearly all browsers support link

import loads any extra css files one-by-one (slower), and could give you Flash Of Unstyled Content

How to write log base(2) in c/c++

All the above answers are correct. This answer of mine below can be helpful if someone needs it. I have seen this requirement in many questions which we are solving using C.

log2 (x) = logy (x) / logy (2)

However, if you are using C language and you want the result in integer, you can use the following:

int result = (int)(floor(log(x) / log(2))) + 1;

Hope this helps.

Type converting slices of interfaces

Convert interface{} into any type.

Syntax:

result := interface.(datatype)

Example:

var employee interface{} = []string{"Jhon", "Arya"}
result := employee.([]string)   //result type is []string.

Is it possible to log all HTTP request headers with Apache?

If you're interested in seeing which specific headers a remote client is sending to your server, and you can cause the request to run a CGI script, then the simplest solution is to have your server script dump the environment variables into a file somewhere.

e.g. run the shell command "env > /tmp/headers" from within your script

Then, look for the environment variables that start with HTTP_...

You will see lines like:

HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.5
HTTP_CACHE_CONTROL=max-age=0

Each of those represents a request header.

Note that the header names are modified from the actual request. For example, "Accept-Language" becomes "HTTP_ACCEPT_LANGUAGE", and so on.

How to convert a boolean array to an int array

The 1*y method works in Numpy too:

>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]

Or using list comprehensions:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

Launch an app on OS X with command line

An application bundle (a .app file) is actually a bunch of directories. Instead of using open and the .app name, you can actually move in to it and start the actual binary. For instance:

$ cd /Applications/LittleSnapper.app/
$ ls
Contents
$ cd Contents/MacOS/
$ ./LittleSnapper

That is the actual binary that might accept arguments (or not, in LittleSnapper's case).

PHP Check for NULL

Make sure that the value of the column is really NULL and not an empty string or 0.

Changing the size of a column referenced by a schema-bound view in SQL Server

See this link

Resize or Modify a MS SQL Server Table Column with Default Constraint using T-SQL Commands

the solution for such a SQL Server problem is going to be

Dropping or disabling the DEFAULT Constraint on the table column.

Modifying the table column data type and/or data size.

Re-creating or enabling the default constraint back on the sql table column.

Bye

Why use multiple columns as primary keys (composite primary key)

Your understanding is correct.

You would do this in many cases. One example is in a relationship like OrderHeader and OrderDetail. The PK in OrderHeader might be OrderNumber. The PK in OrderDetail might be OrderNumber AND LineNumber. If it was either of those two, it would not be unique, but the combination of the two is guaranteed unique.

The alternative is to use a generated (non-intelligent) primary key, for example in this case OrderDetailId. But then you would not always see the relationship as easily. Some folks prefer one way; some prefer the other way.

Check if textbox has empty value

Use the following to check if text box is empty or have more than 1 white spaces

var name = jQuery.trim($("#ContactUsName").val());

if ((name.length == 0))
{
    Your code 
}
else
{
    Your code
}

How do I delete specific lines in Notepad++?

Notepad++ v6.5

  1. Search menu -> Find... -> Mark tab -> Find what: your search text, check Bookmark Line, then Mark All. This will bookmark all the lines with the search term, you'll see the blue circles in the margin.

  2. Then Search menu -> Bookmark -> Remove Bookmarked Lines. This will delete all the bookmarked lines.

You can also use a regex to search. This method won't result in a blank line like John's and will actually delete the line.

Older Versions

  1. Search menu -> Find... -> Find what: your search text, check Bookmark Line and click Find All.
  2. Then Search -> Bookmark -> Remove Bookmarked Lines

React - How to get parameter value from query string?

React router from v4 onwards no longer gives you the query params directly in its location object. The reason being

There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".

Having included that, It would just make more sense to just parse location.search in your view components that are expecting a query object.

You can do this generically by overriding the withRouter from react-router like

customWithRouter.js

import { compose, withPropsOnChange } from 'recompose';
import { withRouter } from 'react-router';
import queryString from 'query-string';

const propsWithQuery = withPropsOnChange(
    ['location', 'match'],
    ({ location, match }) => {
        return {
            location: {
                ...location,
                query: queryString.parse(location.search)
            },
            match
        };
    }
);

export default compose(withRouter, propsWithQuery)

How to use an image for the background in tkinter?

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

How to convert an Array to a Set in Java

Like this:

Set<T> mySet = new HashSet<>(Arrays.asList(someArray));

In Java 9+, if unmodifiable set is ok:

Set<T> mySet = Set.of(someArray);

In Java 10+, the generic type parameter can be inferred from the arrays component type:

var mySet = Set.of(someArray);

How to draw a standard normal distribution in R

I am pretty sure this is a duplicate. Anyway, have a look at the following piece of code

x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=3)
plot(x, y, type="l", lwd=1)

I'm sure you can work the rest out yourself, for the title you might want to look for something called main= and y-axis labels are also up to you.

If you want to see more of the tails of the distribution, why don't you try playing with the seq(5, 15, ) section? Finally, if you want to know more about what dnorm is doing I suggest you look here

Display/Print one column from a DataFrame of Series in Pandas

By using to_string

print(df.Name.to_string(index=False))


 Adam
  Bob
Cathy

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

In case anyone is setting a ForeignKey, you can just allow nullable fields without setting a default:

new_field = models.ForeignKey(model, null=True)

If you already have data stored within the database, you can also set a default value:

new_field = models.ForeignKey(model, default=<existing model id here>)

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

Generate preview image from Video file?

Solution #1 (Older) (not recommended)

Firstly install ffmpeg-php project (http://ffmpeg-php.sourceforge.net/)

And then you can use of this simple code:

<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
    $gd_image = $frame->toGDImage();
    if ($gd_image) {
        imagepng($gd_image, $thumbnail);
        imagedestroy($gd_image);
        echo '<img src="'.$thumbnail.'">';
    }
}
?>

Description: This project use binary extension .so file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg or PHP.


Solution #2 (Update 2018) (recommended)

Firstly install PHP-FFMpeg project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg)

And then you can use of this simple code:

<?php
require 'vendor/autoload.php';

$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';

Description: It's newer and more modern project and works with latest version of FFMpeg and PHP. Note that it's required to proc_open() PHP function.

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.

Is it possible to change the location of packages for NuGet?

The solution proposed in release notes for 2.1 doesn't work out-of-the-box. They forgot to mention that there is code:

internal string ResolveInstallPath()
{
    if (!string.IsNullOrEmpty(this.OutputDirectory))
    {
        return this.OutputDirectory;
    }
    ISettings settings = this._configSettings;

    ...
}

which prevents it from working. To fix this you need to modify your NuGet.targets file and remove 'OutputDirectory' parameter:

    <RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)"  $(RequireConsentSwitch)</RestoreCommand>

So now, if you add 'repositoryPath' config somewhere in NuGet.config (see the release notes for a description of valid places to put the config files), it will restore all packages into single location, but... Your .csproj still contains hints to assemblies written as relative paths...

I still don't understand why they went hard way instead of changing PackageManager so it would add hint paths relative to PackagesDir. That's the way I do manually to have different package locations locally (on my desktop) and on build agent.

<Reference Include="Autofac.Configuration, Version=2.6.3.862, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
  <Private>True</Private>
  <HintPath>$(PackagesDir)\Autofac.2.6.3.862\lib\NET40\Autofac.Configuration.dll</HintPath>
</Reference>

How to read Excel cell having Date with Apache POI?

Try this code.

XSSFWorkbook workbook = new XSSFWorkbook(new File(result));
    XSSFSheet sheet = workbook.getSheetAt(0);

    // Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        // For each row, iterate through all the columns
        Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                if (cell.getNumericCellValue() != 0) {
                    //Get date
                    Date date = row.getCell(0).getDateCellValue();



                    //Get datetime
                    cell.getDateCellValue()


                    System.out.println(date.getTime());
                }
                break;
            }
        }
    }

Hope is help.

How do I remove leading whitespace in Python?

To remove everything before a certain character, use a regular expression:

re.sub(r'^[^a]*', '')

to remove everything up to the first 'a'. [^a] can be replaced with any character class you like, such as word characters.

How to remove the arrows from input[type="number"] in Opera

I've been using some simple CSS and it seems to remove them and work fine.

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    appearance: none;_x000D_
    margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

This tutorial from CSS Tricks explains in detail & also shows how to style them

gradlew command not found?

If you are using mac, try giving root access to gradlew by doing

chmod +x ./gradlew

Changing the color of an hr element

Well, I am new in HTML, CSS and in Java but I tried my way which worked for me in all browsers. I have used JS instead of CSS which doesn't work with some browsers.

First of all I have given id="myHR" to HR element and used it in Java Script.
Here is the Code.

x = document.getElementById("myHR");
y = x.style.width = "600px";
y = x.style.color = "white";
y = x.style.height = "2px";
y = x.style.border = "none";
y = x.style.backgroundColor = "lightgrey";

Start ssh-agent on login

I solved it by adding this to the /etc/profile - system wide (or to user local .profile, or _.bash_profile_):

# SSH-AGENT 
#!/usr/bin/env bash
SERVICE='ssh-agent'
WHOAMI=`who am i |awk '{print $1}'`

if pgrep -u $WHOAMI $SERVICE >/dev/null
then
    echo $SERVICE running.
else
    echo $SERVICE not running.
    echo starting
    ssh-agent > ~/.ssh/agent_env
fi
. ~/.ssh/agent_env

This starts a new ssh-agent if not running for the current user, or re-sets the ssh-agent env parameter if running.

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

How to view hierarchical package structure in Eclipse package explorer

For Eclipse in Macbook it is just 2 click process:

  • Click on view menu (3 dot symbol) in package explorer -> hover over package presentation -> Click on Hierarchical

enter image description here

How to convert an object to a byte array in C#

To convert an object to a byte array:

// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

You just need copy this function to your code and send to it the object that you need to convert to a byte array. If you need convert the byte array to an object again you can use the function below:

// Convert a byte array to an Object
public static Object ByteArrayToObject(byte[] arrBytes)
{
    using (var memStream = new MemoryStream())
    {
        var binForm = new BinaryFormatter();
        memStream.Write(arrBytes, 0, arrBytes.Length);
        memStream.Seek(0, SeekOrigin.Begin);
        var obj = binForm.Deserialize(memStream);
        return obj;
    }
}

You can use these functions with custom classes. You just need add the [Serializable] attribute in your class to enable serialization

SCRIPT5: Access is denied in IE9 on xmlhttprequest

  $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This code will work https sites too

Add vertical whitespace using Twitter Bootstrap?

In Bootstrap 4 there are spacing utilites.

Citing the documentation for used notation:

Spacing utilities that apply to all breakpoints, from xs to xl, have no breakpoint abbreviation in them. This is because those classes are applied from min-width: 0 and up, and thus are not bound by a media query. The remaining breakpoints, however, do include a breakpoint abbreviation.

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Where property is one of:

  • m - for classes that set margin
  • p - for classes that set padding

Where sides is one of:

  • t - for classes that set margin-top or padding-top
  • b - for classes that set margin-bottom or padding-bottom
  • l - for classes that set margin-left or padding-left
  • r - for classes that set margin-right or padding-right
  • x - for classes that set both *-left and *-right
  • y - for classes that set both *-top and *-bottom
  • blank - for classes that set a margin or padding on all 4 sides of the element

Where size is one of:

  • 0 - for classes that eliminate the margin or padding by setting it to 0
  • 1 - (by default) for classes that set the margin or padding to $spacer * .25
  • 2 - (by default) for classes that set the margin or padding to $spacer * .5
  • 3 - (by default) for classes that set the margin or padding to $spacer
  • 4 - (by default) for classes that set the margin or padding to $spacer * 1.5
  • 5 - (by default) for classes that set the margin or padding to $spacer * 3

So to have some extra vertical space above and below an element you would use my-5 class.

Restart pods when configmap updates in Kubernetes?

The best way I've found to do it is run Reloader

It allows you to define configmaps or secrets to watch, when they get updated, a rolling update of your deployment is performed. Here's an example:

You have a deployment foo and a ConfigMap called foo-configmap. You want to roll the pods of the deployment every time the configmap is changed. You need to run Reloader with:

kubectl apply -f https://raw.githubusercontent.com/stakater/Reloader/master/deployments/kubernetes/reloader.yaml

Then specify this annotation in your deployment:

kind: Deployment
metadata:
  annotations:
    configmap.reloader.stakater.com/reload: "foo-configmap"
  name: foo
...

jQuery: How to get to a particular child of a parent?

$(this).parent()

Tree traversal is fun

$(this).parent().siblings(".something1");

$(this).parent().prev(); // if you always want the parent's previous sibling

$(this).parents(".box").children(".something1");

And much more ways, you might find these docs helpful.

Get the number of rows in a HTML table

In the DOM, a tr element is (implicitly or explicitly) a child of tbody, thead, or tfoot, not a child of table (hence the 0 you got). So a general answer is:

var count = $('#gvPerformanceResult > * > tr').length;

This includes the rows of the table but excludes rows of any inner table.

How to change font size on part of the page in LaTeX?

To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.

\fontsize{10}{12}\selectfont This is the text you need to be in 10px

More info: https://tug.org/TUGboat/tb33-3/tb105thurnherr.pdf

Chain-calling parent initialisers in python

Python 3 includes an improved super() which allows use like this:

super().__init__(args)

How to create an exit message

If you want to denote an actual error in your code, you could raise a RuntimeError exception:

raise RuntimeError, 'Message goes here'

This will print a stacktrace, the type of the exception being raised and the message that you provided. Depending on your users, a stacktrace might be too scary, and the actual message might get lost in the noise. On the other hand, if you die because of an actual error, a stacktrace will give you additional information for debugging.

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

jQuery datepicker years shown

 $("#DateOfBirth").datepicker({
        yearRange: "-100:+0",
        changeMonth: true,
        changeYear: true,
    });

yearRange: '1950:2013', // specifying a hard coded year range or this way

yearRange: "-100:+0", // last hundred years

It will help to show drop down for year and month selection.

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

0000 0000 -> this is an 8-bit binary number. A digit represents a bit.

You count like so:

0000 0000 ? (0)

0000 0001 ? (1)

0000 0010 ? (2)

0000 0011 ? (3)

Each bit can be one of two values: on or off. The total highest number can be represented by multiplication:

2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 - 1 = 255

Or

2^8 - 1. 

We subtract one because the first number is 0.

255 can hold quite a bit (no pun intended) of values.

As we use more bits the max value goes up exponentially. Therefore for many purposes, adding more bits is overkill.

Executing multiple commands from a Windows cmd script

You can use the && symbol between commands to execute the second command only if the first succeeds. More info here http://commandwindows.com/command1.htm

How do JavaScript closures work?

Maybe you should consider an object-oriented structure instead of inner functions. For example:

    var calculate = {
        number: 0,
        init: function (num) {
            this.number = num;
        },
        add: function (val) {
            this.number += val;
        },
        rem: function (val) {
            this.number -= val;
        }
    };

And read the result from the calculate.number variable, who needs "return" anyway.


//Addition
First think about scope which defines what variable you have to access to (In Javascript);

//there are two kinds of scope
Global Scope which include variable declared outside function or curly brace

let globalVariable = "foo";

one thing to keep in mind is once yo've declared a globalVariable you can use it anywhere in your code even in function;

Local Scope which include variable that are usable only in a specific part of your code

//lets break it 

function scope is when you declare a variable in a function  you can access the variable only within the function

function User(){
    let name = "foo";
    alert(name);
}
    alert(name);//error

//Block scope is when you declare a variable within a block then you can  access that variable only within a block 
{
let user = "foo";
alert(user);
}
alert(user);
//Uncaught ReferenceError: user is not defined at.....

//A Closure

function User(fname){
return function(lname){
 return fname + " " lname;
}
}
let names = User("foo");
alert(names("bar"));

//When you create a function within a function you've created a closure, in our example above since the outer function is returned the inner function got access to outer function's scope

How to align this span to the right of the div?

The solution using flexbox without justify-content: space-between.

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first <span>, it takes up the entire remaining space and moves the second <span> to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/

Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first <span>.

How to enable authentication on MongoDB through Docker?

a. You can use environment variables via terminal:

$ docker run -d --name container_name \
      -e MONGO_INITDB_ROOT_USERNAME=admin \
      -e MONGO_INITDB_ROOT_PASSWORD=password \
      mongo

If you like to test if everything works:

// ssh into the running container
// Change container name if necessary
$ docker exec -it mongo /bin/bash

// Enter into mongo shell
$ mongo

// Caret will change when you enter successfully
// Switch to admin database
$> use admin
$> db.auth("admin", passwordPrompt())

// Show available databases
$> show dbs

If you like to instantiate a database on first run, check option b.

b. You can use environment variables in your docker stack deploy file or compose file for versions 3.4 through 4.1.

As it is explained on the quick reference section of the official mongo image set MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your yaml file:

mongo:
    image: mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password

docker-entrypoint.sh file in mongo image checks for the existence of these two variables and sets --auth flag accordingly.

c. You can also use docker secrets.

MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD is set indirectly by docker-entrypoint.sh from MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE variables:

mongo:
    image: mongo
    environment:
        - MONGO_INITDB_ROOT_USERNAME_FILE=/run/secrets/db_root_username
        - MONGO_INITDB_ROOT_PASSWORD_FILE=/run/secrets/db_root_password
    secrets:
      - db_root_username
      - db_root_password

docker-entrypoint.sh converts MONGO_INITDB_ROOT_USERNAME_FILE and MONGO_INITDB_ROOT_PASSWORD_FILE to MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD.

You can use MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD in your .sh or .js scripts in docker-entrypoint-initdb.d folder while initializing database instance.

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

This last method is not in the reference docs, so it may not survive an update.

Converting List<String> to String[] in Java

String[] strarray = strlist.toArray(new String[0]);

if u want List convert to string use StringUtils.join(slist, '\n');

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.

Here is the code - The code is in asp.net core 2.0 but should work in above versions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;

namespace UnityAssets.Website.Services
{
    public class EmailSender : IEmailSender
    {
        public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
        {
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
            email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
            email.Subject = subject;

            var body = new BodyBuilder
            {
                HtmlBody = htmlMessage
            };

            email.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //provider specific settings
                await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);

                await client.SendAsync(email).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
    }
}

Avoid printStackTrace(); use a logger call instead

In Simple,e.printStackTrace() is not good practice,because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes.

Difference between JSON.stringify and JSON.parse

Firstly, JSON.stringify() function converts a JavaScript value to a JavaScript Object Notation (JSON) string. JSON.parse() function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.

https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx

Secondly, the following sample will be helpful for you to understand these two functions.

<form id="form1" runat="server">
    <div>
        <div id="result"></div>
    </div>
</form>

<script>
    $(function () {
        //define a json object
        var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };

        //use JSON.stringify to convert it to json string
        var jsonstring = JSON.stringify(employee);
        $("#result").append('<p>json string: ' + jsonstring + '</p>');

        //convert json string to json object using JSON.parse function
        var jsonobject = JSON.parse(jsonstring);
        var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';

        $("#result").append('<p>json object:</p>');
        $("#result").append(info);
    });
</script>

Firefox "ssl_error_no_cypher_overlap" error

What worked for me is I:

  1. Went to about:config.
  2. Typed "security" in the search box.
  3. Set all of the returned entries to their defaults.
  4. Typed "ssl" in the search box.
  5. Set all of the returned results to their defaults.
  6. Enabled ssl2.
  7. Disabled ssl3.
  8. Restarted Firefox.

Note about restarting Firefox: When I do start it very soon after closing it, it often has a file access problem, which requires me to delete places.sqlite and places.sqlite-journal in C:\WINDOWS\Application Data\Mozilla\Firefox\Profiles\n18091xv.default. This causes me to lose my history, plus bookmarks have to be restored from a backup each time this happens. I wait from five to ten minutes or more to avoid this hassle.

Running Firefox v3.5.1 on WinMe

jQuery and AJAX response header

try this:

type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
    var headers = XMLHttpRequest.getAllResponseHeaders();
}

The difference between "require(x)" and "import x"

Not an answer here and more like a comment, sorry but I can't comment.

In node V10, you can use the flag --experimental-modules to tell Nodejs you want to use import. But your entry script should end with .mjs.

Note this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Ref 1 - Nodejs Doc

Ref 2 - github issue

How to use table variable in a dynamic sql statement?

Your EXEC executes in a different context, therefore it is not aware of any variables that have been declared in your original context. You should be able to use a temp table instead of a table variable as shown in the simple demo below.

create table #t (id int)

declare @value nchar(1)
set @value = N'1'

declare @sql nvarchar(max)
set @sql = N'insert into #t (id) values (' + @value + N')'

exec (@sql)

select * from #t

drop table #t

How can I simulate an anchor click via jquery?

If you don't need to use JQuery, as I don't. I've had problems with the cross browser func of .click(). So I use:

eval(document.getElementById('someid').href)

How to set up ES cluster?

It is usually handled automatically.

If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

Node 1:

    cluster.name: mycluster
    node.name: "node1"
    node.master: true
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2:

    cluster.name: mycluster
    node.name: "node2"
    node.master: false
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

How to dynamic new Anonymous Class?

Of cause it's possible to create dynamic classes using very cool ExpandoObject class. But recently I worked on project and faced that Expando Object is serealized in not the same format on xml as an simple Anonymous class, it was pity =( , that is why I decided to create my own class and share it with you. It's using reflection and dynamic directive , builds Assembly, Class and Instance truly dynamicly. You can add, remove and change properties that is included in your class on fly Here it is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using static YourNamespace.DynamicTypeBuilderTest;

namespace YourNamespace
{

    /// This class builds Dynamic Anonymous Classes

    public class DynamicTypeBuilderTest
    {    
        ///   
        /// Create instance based on any Source class as example based on PersonalData
        ///
        public static object CreateAnonymousDynamicInstance(PersonalData personalData, Type dynamicType, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            var obj = Activator.CreateInstance(dynamicType);

            var propInfos = dynamicType.GetProperties();

            classDescriptionList.ForEach(x => SetValueToProperty(obj, propInfos, personalData, x));

            return obj;
        }

        private static void SetValueToProperty(object obj, PropertyInfo[] propInfos, PersonalData aisMessage, ClassDescriptorKeyValue description)
        {
            propInfos.SingleOrDefault(x => x.Name == description.Name)?.SetValue(obj, description.ValueGetter(aisMessage), null);
        }

        public static dynamic CreateAnonymousDynamicType(string entityName, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            AssemblyName asmName = new AssemblyName();
            asmName.Name = $"{entityName}Assembly";
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule($"{asmName.Name}Module");

            TypeBuilder typeBuilder = moduleBuilder.DefineType($"{entityName}Dynamic", TypeAttributes.Public);

            classDescriptionList.ForEach(x => CreateDynamicProperty(typeBuilder, x));

            return typeBuilder.CreateTypeInfo().AsType();
        }

        private static void CreateDynamicProperty(TypeBuilder typeBuilder, ClassDescriptorKeyValue description)
        {
            CreateDynamicProperty(typeBuilder, description.Name, description.Type);
        }

        ///
        ///Creation Dynamic property (from MSDN) with some Magic
        ///
        public static void CreateDynamicProperty(TypeBuilder typeBuilder, string name, Type propType)
        {
            FieldBuilder fieldBuider = typeBuilder.DefineField($"{name.ToLower()}Field",
                                                            propType,
                                                            FieldAttributes.Private);

            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name,
                                                             PropertyAttributes.HasDefault,
                                                             propType,
                                                             null);

            MethodAttributes getSetAttr =
                MethodAttributes.Public | MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig;

            MethodBuilder methodGetBuilder =
                typeBuilder.DefineMethod($"get_{name}",
                                           getSetAttr,
                                           propType,
                                           Type.EmptyTypes);

            ILGenerator methodGetIL = methodGetBuilder.GetILGenerator();

            methodGetIL.Emit(OpCodes.Ldarg_0);
            methodGetIL.Emit(OpCodes.Ldfld, fieldBuider);
            methodGetIL.Emit(OpCodes.Ret);

            MethodBuilder methodSetBuilder =
                typeBuilder.DefineMethod($"set_{name}",
                                           getSetAttr,
                                           null,
                                           new Type[] { propType });

            ILGenerator methodSetIL = methodSetBuilder.GetILGenerator();

            methodSetIL.Emit(OpCodes.Ldarg_0);
            methodSetIL.Emit(OpCodes.Ldarg_1);
            methodSetIL.Emit(OpCodes.Stfld, fieldBuider);
            methodSetIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(methodGetBuilder);
            propertyBuilder.SetSetMethod(methodSetBuilder);

        }

        public class ClassDescriptorKeyValue
        {
            public ClassDescriptorKeyValue(string name, Type type, Func<PersonalData, object> valueGetter)
            {
                Name = name;
                ValueGetter = valueGetter;
                Type = type;
            }

            public string Name;
            public Type Type;
            public Func<PersonalData, object> ValueGetter;
        }

        ///
        ///Your Custom class description based on any source class for example
        /// PersonalData
        public static IEnumerable<ClassDescriptorKeyValue> GetAnonymousClassDescription(bool includeAddress, bool includeFacebook)
        {
            yield return new ClassDescriptorKeyValue("Id", typeof(string), x => x.Id);
            yield return new ClassDescriptorKeyValue("Name", typeof(string), x => x.FirstName);
            yield return new ClassDescriptorKeyValue("Surname", typeof(string), x => x.LastName);
            yield return new ClassDescriptorKeyValue("Country", typeof(string), x => x.Country);
            yield return new ClassDescriptorKeyValue("Age", typeof(int?), x => x.Age);
            yield return new ClassDescriptorKeyValue("IsChild", typeof(bool), x => x.Age < 21);

            if (includeAddress)
                yield return new ClassDescriptorKeyValue("Address", typeof(string), x => x?.Contacts["Address"]);
            if (includeFacebook)
                yield return new ClassDescriptorKeyValue("Facebook", typeof(string), x => x?.Contacts["Facebook"]);
        }

        ///
        ///Source Data Class for example
        /// of cause you can use any other class
        public class PersonalData
        { 
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Country { get; set; }
            public int Age { get; set; }

            public Dictionary<string, string> Contacts { get; set; }
        }

    }
}

It is also very simple to use DynamicTypeBuilder, you just need put few lines like this:

    public class ExampleOfUse
    {
        private readonly bool includeAddress;
        private readonly bool includeFacebook;
        private readonly dynamic dynamicType;
        private readonly List<ClassDescriptorKeyValue> classDiscriptionList;
        public ExampleOfUse(bool includeAddress = false, bool includeFacebook = false)
        {
            this.includeAddress = includeAddress;
            this.includeFacebook = includeFacebook;
            this.classDiscriptionList = DynamicTypeBuilderTest.GetAnonymousClassDescription(includeAddress, includeFacebook).ToList();
            this.dynamicType = DynamicTypeBuilderTest.CreateAnonymousDynamicType("VeryPrivateData", this.classDiscriptionList);
        }

        public object Map(PersonalData privateInfo)
        {
            object dynamicObject = DynamicTypeBuilderTest.CreateAnonymousDynamicInstance(privateInfo, this.dynamicType, classDiscriptionList);

            return dynamicObject;
        }

    }

I hope that this code snippet help somebody =) Enjoy!

WAMP Server doesn't load localhost

I faced a similar problem. I tried everything with ports, hosts and config files.But nothing helped.

I checked apache error logs. They showed the following error

(OS 10038)An operation was attempted on something that is not a socket.  : AH00332: winnt_accept: getsockname error on listening socket, is IPv6 available?

Finally this is what solved my problem.

1) Goto command prompt and run it in administrative mode. In windows 7 you can do it by typing cmd in run and then pressing ctrl+shift+enter

2) run the following command: netsh winsock reset

3) Restart the system

Installing mcrypt extension for PHP on OSX Mountain Lion

sudo apt-get install php5-mcrypt

ln -s /etc/php5/mods-available/mcrypt.ini /etc/php5/fpm/conf.d/mcrypt.ini

service php5-fpm restart

service nginx restart

jQuery to loop through elements with the same class

More precise:

$.each($('.testimonal'), function(index, value) { 
    console.log(index + ':' + value); 
});

Calling a PHP function from an HTML form in the same file

That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.

To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.

Entity Framework Migrations renaming tables and columns

If you don't like writing/changing the required code in the Migration class manually, you can follow a two-step approach which automatically make the RenameColumn code which is required:

Step One Use the ColumnAttribute to introduce the new column name and then add-migration (e.g. Add-Migration ColumnChanged)

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Group_Id{get;set}
}

Step-Two change the property name and again apply to same migration (e.g. Add-Migration ColumnChanged -force) in the Package Manager Console

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Section_Id{get;set}
}

If you look at the Migration class you can see the automatically code generated is RenameColumn.

How does Python manage int and long?

On my machine:

>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>

Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.

Setting up enviromental variables in Windows 10 to use java and javac

Just set the path variable to JDK bin in environment variables.

Variable Name : PATH 
Variable Value : C:\Program Files\Java\jdk1.8.0_31\bin

But the best practice is to set JAVA_HOME and PATH as follow.

Variable Name : JAVA_HOME
Variable Value : C:\Program Files\Java\jdk1.8.0_31

Variable Name : PATH 
Variable Value : %JAVA_HOME%\bin

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

<img>: Unsafe value used in a resource URL context

import {DomSanitizationService} from '@angular/platform-browser';
@Component({
 templateUrl: 'build/pages/veeu/veeu.html'
 })
  export class VeeUPage {
     trustedURL:any;
      static get parameters() {
               return [NavController, App, MenuController, 
              DomSanitizationService];
        }
      constructor(nav, app, menu, sanitizer) {
        this.app = app;
        this.nav = nav;
        this.menu = menu;
        this.sanitizer = sanitizer;  
        this.trustedURL  = sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
        } 
 }



 <iframe [src]='trustedURL' width="640" height="360" frameborder="0"
   webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>


User property binding instead of function.

How do I split a string in Rust?

There is a special method split for struct String:

fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>

Split by char:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

Split by string:

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

Split by closure:

let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

How to permanently add a private key with ssh-add on Ubuntu?

I had the same issue on Ubuntu 16.04: some keys were added permanently, for others I had to execute ssh-add on every session. I found out that the keys which were added permanently had both private and public key located in ~/.ssh and the keys which were forgotten on every session had only private keys in ~/.ssh dir. So solution is simple: you should copy both private and public key to ~/.ssh before executing ssh-add.

P.S.: As far as I understand from Gnome wiki my method works thanks to gnome-keyring tool which is part of the Gnome Desktop Environment. Therefore my method should probably work only if you use Gnome or Gnome-based DE.

Get JSON object from URL

Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
    return false;
}

$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
    return false;
}

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

JavaScript hide/show element

you can use hidden property of element:

document.getElementById("test").hidden=true;
document.getElementById("test").hidden=false

Exception of type 'System.OutOfMemoryException' was thrown. Why?

Where does it fail?

I agree that your issue is probably that your dataset of 600,000 rows is probably just too large. I see that you are then adding it to Session. If you are using Sql session state, it will have to serialize that data as well.

Even if you dispose of your objects properly, you will always have at least 2 copies of this dataset in memory if you run it twice, once in session, once in procedural code. This will never scale in a web application.

Do the math, 600,000 rows, at even 1-128 bit guid per row would yield 9.6 megabytes (600k * 128 / 8) of just data, not to mention the dataset overhead.

Trim down your results.

How to call URL action in MVC with javascript function?

try:

var url = '/Home/Index/' + e.value;
 window.location = window.location.host + url; 

That should get you where you want.

Remove folder and its contents from git/GitHub's history

In addition to the popular answer above I would like to add a few notes for Windows-systems. The command

git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
  • works perfectly without any modification! Therefore, you must not use Remove-Item, del or anything else instead of rm -rf.

  • If you need to specify a path to a file or directory use slashes like ./path/to/node_modules

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

Select first and last row from grouped data

I know the question specified dplyr. But, since others already posted solutions using other packages, I decided to have a go using other packages too:

Base package:

df <- df[with(df, order(id, stopSequence, stopId)), ]
merge(df[!duplicated(df$id), ], 
      df[!duplicated(df$id, fromLast = TRUE), ], 
      all = TRUE)

data.table:

df <-  setDT(df)
df[order(id, stopSequence)][, .SD[c(1,.N)], by=id]

sqldf:

library(sqldf)
min <- sqldf("SELECT id, stopId, min(stopSequence) AS StopSequence
      FROM df GROUP BY id 
      ORDER BY id, StopSequence, stopId")
max <- sqldf("SELECT id, stopId, max(stopSequence) AS StopSequence
      FROM df GROUP BY id 
      ORDER BY id, StopSequence, stopId")
sqldf("SELECT * FROM min
      UNION
      SELECT * FROM max")

In one query:

sqldf("SELECT * 
        FROM (SELECT id, stopId, min(stopSequence) AS StopSequence
              FROM df GROUP BY id 
              ORDER BY id, StopSequence, stopId)
        UNION
        SELECT *
        FROM (SELECT id, stopId, max(stopSequence) AS StopSequence
              FROM df GROUP BY id 
              ORDER BY id, StopSequence, stopId)")

Output:

  id stopId StopSequence
1  1      a            1
2  1      c            3
3  2      b            1
4  2      c            4
5  3      a            3
6  3      b            1

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

Laravel Eloquent: How to get only certain columns from joined tables

For Laravel >= 5.2

Use the ->pluck() method

$roles = DB::table('roles')->pluck('title');

If you would like to retrieve an array containing the values of a single column, you may use the pluck method


For Laravel <= 5.1

Use the ->lists() method

$roles = DB::table('roles')->lists('title');

This method will return an array of role titles. You may also specify a custom key column for the returned array:

Can a class member function template be virtual?

From C++ Templates The Complete Guide:

Member function templates cannot be declared virtual. This constraint is imposed because the usual implementation of the virtual function call mechanism uses a fixed-size table with one entry per virtual function. However, the number of instantiations of a member function template is not fixed until the entire program has been translated. Hence, supporting virtual member function templates would require support for a whole new kind of mechanism in C++ compilers and linkers. In contrast, the ordinary members of class templates can be virtual because their number is fixed when a class is instantiated

What's the fastest way to do a bulk insert into Postgres?

One way to speed things up is to explicitly perform multiple inserts or copy's within a transaction (say 1000). Postgres's default behavior is to commit after each statement, so by batching the commits, you can avoid some overhead. As the guide in Daniel's answer says, you may have to disable autocommit for this to work. Also note the comment at the bottom that suggests increasing the size of the wal_buffers to 16 MB may also help.

Is it possible to create a File object from InputStream

Easy Java 9 solution with try with resources block

public static void copyInputStreamToFile(InputStream input, File file) {  

    try (OutputStream output = new FileOutputStream(file)) {
        input.transferTo(output);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

java.io.InputStream#transferTo is available since Java 9.

How do I set Java's min and max heap size through environment variables?

You can use JAVA_TOOL_OPTIONS.

Example:

export JAVA_TOOL_OPTIONS=-Xmx512m

It has been mentioned in some comments, and in another answer.

The OP's question is quite old, but as it is the first google result for the question, I thought i would add the answer here for clarity's sake.

Applying .gitignore to committed files

Follow these steps:

  1. Add path to gitignore file

  2. Run this command

    git rm -r --cached foldername
    
  3. commit changes as usually.

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

Handling a timeout error in python sockets

Here is a solution I use in one of my project.

network_utils.telnet

import socket
from timeit import default_timer as timer

def telnet(hostname, port=23, timeout=1):
    start = timer()
    connection = socket.socket()
    connection.settimeout(timeout)
    try:
        connection.connect((hostname, port))
        end = timer()
        delta = end - start
    except (socket.timeout, socket.gaierror) as error:
        logger.debug('telnet error: ', error)
        delta = None
    finally:
        connection.close()

    return {
        hostname: delta
    }

Tests

def test_telnet_is_null_when_host_unreachable(self):
    hostname = 'unreachable'

    response = network_utils.telnet(hostname)

    self.assertDictEqual(response, {'unreachable': None})

def test_telnet_give_time_when_reachable(self):
    hostname = '127.0.0.1'

    response = network_utils.telnet(hostname, port=22)

    self.assertGreater(response[hostname], 0)

How to check radio button is checked using JQuery?

Radio buttons are,

<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">

to check on click,

$('.radioButtons').click(function(){
    if($("#radio_1")[0].checked){
       //logic here
    }
});

Python, compute list difference

You would want to use a set instead of a list.

How to print without newline or space?

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There's also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

How do I check if file exists in Makefile so I can delete it?

Or just put it on one line, as make likes it:

if [ -a myApp ]; then rm myApp; fi;

Can we execute a java program without a main() method?

Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.

{
    static
    {
        System.out.println("Hello World!");
        System.exit(0); // prevents “main method not found” error
    }
}

But this will not execute with JAVA 7 version.

How do I set an absolute include path in PHP?

There is nothing in include/require that prohibits you from using absolute an path. so your example

include('/includes/header.php'); 

should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)

This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.

This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.

as for the '.' syntax:

/home/username/public_html <- absolute path  
public_html <- relative path  
./public_html <- same as the path above  
../username/public_html <- another relative path  

However, I usually use a slightly different option:

require_once(__DIR__ . '/Factories/ViewFactory.php');

With this edition, you specify an absolute path, relative to the file that contains the require_once() statement.

java.lang.IllegalArgumentException: No converter found for return value of type

In my case, I was returning Boolean in Response Entity and had :

produces = MediaType.TEXT_PLAIN_VALUE,

When i changed it to below

produces = MediaType.APPLICATION_JSON_VALUE

It worked!

Example of what i had.

@PostMapping(value = "/xxx-xxxx",
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Boolean> yyyy(

Search and replace part of string in database

Update database and Set fieldName=Replace (fieldName,'FindString','ReplaceString')

Visual Studio 2017 errors on standard headers

If anyone's still stuck on this, the easiest solution I found was to "Retarget Solution". In my case, the project was built of SDK 8.1, upgrading to VS2017 brought with it SDK 10.0.xxx.

To retarget solution: Project->Retarget Solution->"Select whichever SDK you have installed"->OK

From there on you can simply build/debug your solution. Hope it helps

enter image description here

How to reset radiobuttons in jQuery so that none is checked

$('#radio1').removeAttr('checked');
$('#radio2').removeAttr('checked');
$('#radio3').removeAttr('checked');
$('#radio4').removeAttr('checked');

Or

$('input[name="correctAnswer"]').removeAttr('checked');

What causes this error? "Runtime error 380: Invalid property value"

Many really silly things can cause this error. The one I've encountered is a font no longer included with Windows 8 by default - Courier New. The VB6 application had its name hard-coded in one of the forms, hence the message on start-up.

How do I setup the InternetExplorerDriver so it works

Another way to resolve this problem is:

Let's assume:

path_to_driver_directory = C:\Work\drivers\

driver = IEDriverServer.exe

When getting messsage about path you can always add path_to_driver_directory containing driver to the PATH environment variable. Check: http://java.com/en/download/help/path.xml

Then simply check in cmd window if driver is available - just run cmd in any location and type name of driver.

If everything works fine then you get:

C:\Users\A>IEDriverServer.exe
Started InternetExplorerDriver server (32-bit)
2.28.0.0
Listening on port 5555

Thats it.

JavaScript: filter() for Objects

I have created an Object.filter() which does not only filter by a function, but also accepts an array of keys to include. The optional third parameter will allow you to invert the filter.

Given:

var foo = {
    x: 1,
    y: 0,
    z: -1,
    a: 'Hello',
    b: 'World'
}

Array:

Object.filter(foo, ['z', 'a', 'b'], true);

Function:

Object.filter(foo, function (key, value) {
    return Ext.isString(value);
});

Code

Disclaimer: I chose to use Ext JS core for brevity. Did not feel it was necessary to write type checkers for object types as it was not part of the question.

_x000D_
_x000D_
// Helper function_x000D_
function print(obj) {_x000D_
    document.getElementById('disp').innerHTML += JSON.stringify(obj, undefined, '  ') + '<br />';_x000D_
    console.log(obj);_x000D_
}_x000D_
_x000D_
Object.filter = function (obj, ignore, invert) {_x000D_
    let result = {}; // Returns a filtered copy of the original list_x000D_
    if (ignore === undefined) {_x000D_
        return obj;   _x000D_
    }_x000D_
    invert = invert || false;_x000D_
    let not = function(condition, yes) { return yes ? !condition : condition; };_x000D_
    let isArray = Ext.isArray(ignore);_x000D_
    for (var key in obj) {_x000D_
        if (obj.hasOwnProperty(key) &&_x000D_
                !(isArray && not(!Ext.Array.contains(ignore, key), invert)) &&_x000D_
                !(!isArray && not(!ignore.call(undefined, key, obj[key]), invert))) {_x000D_
            result[key] = obj[key];_x000D_
        }_x000D_
    }_x000D_
    return result;_x000D_
};_x000D_
_x000D_
let foo = {_x000D_
    x: 1,_x000D_
    y: 0,_x000D_
    z: -1,_x000D_
    a: 'Hello',_x000D_
    b: 'World'_x000D_
};_x000D_
_x000D_
print(Object.filter(foo, ['z', 'a', 'b'], true));_x000D_
print(Object.filter(foo, (key, value) => Ext.isString(value)));
_x000D_
#disp {_x000D_
    white-space: pre;_x000D_
    font-family: monospace_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/builds/ext-core.min.js"></script>_x000D_
<div id="disp"></div>
_x000D_
_x000D_
_x000D_

Doctrine 2 ArrayCollection filter method

Your use case would be :

    $ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
                        return $user->getActive() === TRUE;
                    });

if you add ->first() you'll get only the first entry returned, which is not what you want.

@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:

    $member->getComments()->filter( function($entry) use ($idsToFilter) {
        return in_array($entry->getId(), $idsToFilter);
    });

Is module __file__ attribute absolute or relative?

From the documentation:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

From the mailing list thread linked by @kindall in a comment to the question:

I haven't tried to repro this particular example, but the reason is that we don't want to have to call getpwd() on every import nor do we want to have some kind of in-process variable to cache the current directory. (getpwd() is relatively slow and can sometimes fail outright, and trying to cache it has a certain risk of being wrong.)

What we do instead, is code in site.py that walks over the elements of sys.path and turns them into absolute paths. However this code runs before '' is inserted in the front of sys.path, so that the initial value of sys.path is ''.

For the rest of this, consider sys.path not to include ''.

So, if you are outside the part of sys.path that contains the module, you'll get an absolute path. If you are inside the part of sys.path that contains the module, you'll get a relative path.

If you load a module in the current directory, and the current directory isn't in sys.path, you'll get an absolute path.

If you load a module in the current directory, and the current directory is in sys.path, you'll get a relative path.

PHP - add 1 day to date format mm-dd-yyyy

$date = DateTime::createFromFormat('m-d-Y', '04-15-2013');
$date->modify('+1 day');
echo $date->format('m-d-Y');

See it in action

Or in PHP 5.4+

echo (DateTime::createFromFormat('m-d-Y', '04-15-2013'))->modify('+1 day')->format('m-d-Y');

reference

Setting up maven dependency for SQL Server

I believe you are looking for the Microsoft SQL Server JDBC driver: http://msdn.microsoft.com/en-us/sqlserver/aa937724

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

This is a slightly improvised answer to ajsp answer using XML-RPC.

On the server-side when you convert the data, convert the numpy data to a string using the '.tostring()' method. This encodes the numpy ndarray as bytes string. On the client-side when you receive the data decode it using '.fromstring()' method. I wrote two simple functions for this. Hope this is helpful.

  1. ndarray2str -- Converts numpy ndarray to bytes string.
  2. str2ndarray -- Converts binary str back to numpy ndarray.
    def ndarray2str(a):
        # Convert the numpy array to string 
        a = a.tostring()

        return a

On the receiver side, the data is received as a 'xmlrpc.client.Binary' object. You need to access the data using '.data'.

    def str2ndarray(a):
        # Specify your data type, mine is numpy float64 type, so I am specifying it as np.float64
        a = np.fromstring(a.data, dtype=np.float64)
        a = np.reshape(a, new_shape)

        return a

Note: Only problem with this approach is that XML-RPC is very slow while sending large numpy arrays. It took me around 4 secs to send and receive a (10, 500, 500, 3) size numpy array for me.

I am using python 3.7.4.

How can I write these variables into one line of code in C#?

If you want to use something similar to the JavaScript, you just need to convert to strings first:

Console.WriteLine(mon.ToString() + "." + da.ToString() + "." + yer.ToString());

But a (much) better way would be to use the format option:

Console.WriteLine("{0}.{1}.{2}", mon, da, yer);

How do I convert a org.w3c.dom.Document object to a String?

use some thing like

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
{
    try
    {
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    }
    catch(TransformerException ex)
    {
       ex.printStackTrace();
       return null;
    }
} 

Have border wrap around text

Not sure, if that's what you want, but you could make the inner div an inline-element. This way the border should be wrapped only around the text. Even better than that is to use an inline-element for your title.

Solution 1

<div id="page" style="width: 600px;">
    <div id="title" style="display: inline; border...">Title</div>
</div>

Solution 2

<div id="page" style="width: 600px;">
    <span id="title" style="border...">Title</span>
</div>

Edit: Strange, SO doesn't interpret my code-examples correctly as block, so I had to use inline-code-method.

C/C++ Struct vs Class

One more difference in C++, when you inherit a class from struct without any access specifier, it become public inheritance where as in case of class it's private inheritance.

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

Here's the quote on AssemblyInfo.cs from MSDN:

You can specify all the values or you can accept the default build number, revision number, or both by using an asterisk (). For example, [assembly:AssemblyVersion("2.3.25.1")] indicates 2 as the major version, 3 as the minor version, 25 as the build number, and 1 as the revision number. A version number such as [assembly:AssemblyVersion("1.2.")] specifies 1 as the major version, 2 as the minor version, and accepts the default build and revision numbers. A version number such as [assembly:AssemblyVersion("1.2.15.*")] specifies 1 as the major version, 2 as the minor version, 15 as the build number, and accepts the default revision number. The default build number increments daily. The default revision number is random

This effectively says, if you put a 1.1.* into assembly info, only build number will autoincrement, and it will happen not after every build, but daily. Revision number will change every build, but randomly, rather than in an incrementing fashion.

This is probably enough for most use cases. If that's not what you're looking for, you're stuck with having to write a script which will autoincrement version # on pre-build step

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

How do I make a PHP form that submits to self?

I guess , you means $_SERVER['PHP_SELF']. And if so , you really shouldn't use it without sanitizing it first. This leaves you open to XSS attacks.

The if(isset($_POST['submit'])) condition should be above all the HTML output, and should contain a header() function with a redirect to current page again (only now , with some nice notice that "emails has been sent" .. or something ). For that you will have to use $_SESSION or $_COOKIE.

And please. Stop using $_REQUEST. It too poses a security threat.

Javascript Get Element by Id and set the value

<html>
<head>
<script>
function updateTextarea(element)
{
document.getElementById(element).innerText = document.getElementById("ment").value;
}
</script>
</head>
<body>

<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"  

onKeyUp="updateTextarea('myDiv')" />

<br>

<textarea id="myDiv" ></textarea>

</body>
</html>

CONVERT Image url to Base64

You Can Used This :

function ViewImage(){
 function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}

Add To Your Input onchange=ViewImage();

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

change

public static final String URL = "http://api-Location";

to

public static final String URL = "https://api-Location"

it's happen because i'm using 000webhostapp app

What is the difference between "is None" and "== None"

In this case, they are the same. None is a singleton object (there only ever exists one None).

is checks to see if the object is the same object, while == just checks if they are equivalent.

For example:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q # True because they are both pointing to the same "None"

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_

In .NET, which loop runs faster, 'for' or 'foreach'?

It seems a bit strange to totally forbid the use of something like a for loop.

There's an interesting article here that covers a lot of the performance differences between the two loops.

I would say personally I find foreach a bit more readable over for loops but you should use the best for the job at hand and not have to write extra long code to include a foreach loop if a for loop is more appropriate.

How to iterate through two lists in parallel?

Building on the answer by @unutbu, I have compared the iteration performance of two identical lists when using Python 3.6's zip() functions, Python's enumerate() function, using a manual counter (see count() function), using an index-list, and during a special scenario where the elements of one of the two lists (either foo or bar) may be used to index the other list. Their performances for printing and creating a new list, respectively, were investigated using the timeit() function where the number of repetitions used was 1000 times. One of the Python scripts that I had created to perform these investigations is given below. The sizes of the foo and bar lists had ranged from 10 to 1,000,000 elements.

Results:

  1. For printing purposes: The performances of all the considered approaches were observed to be approximately similar to the zip() function, after factoring an accuracy tolerance of +/-5%. An exception occurred when the list size was smaller than 100 elements. In such a scenario, the index-list method was slightly slower than the zip() function while the enumerate() function was ~9% faster. The other methods yielded similar performance to the zip() function.

    Print loop 1000 reps

  2. For creating lists: Two types of list creation approaches were explored: using the (a) list.append() method and (b) list comprehension. After factoring an accuracy tolerance of +/-5%, for both of these approaches, the zip() function was found to perform faster than the enumerate() function, than using a list-index, than using a manual counter. The performance gain by the zip() function in these comparisons can be 5% to 60% faster. Interestingly, using the element of foo to index bar can yield equivalent or faster performances (5% to 20%) than the zip() function.

    Creating List - 1000reps

Making sense of these results:

A programmer has to determine the amount of compute-time per operation that is meaningful or that is of significance.

For example, for printing purposes, if this time criterion is 1 second, i.e. 10**0 sec, then looking at the y-axis of the graph that is on the left at 1 sec and projecting it horizontally until it reaches the monomials curves, we see that lists sizes that are more than 144 elements will incur significant compute cost and significance to the programmer. That is, any performance gained by the approaches mentioned in this investigation for smaller list sizes will be insignificant to the programmer. The programmer will conclude that the performance of the zip() function to iterate print statements is similar to the other approaches.

Conclusion

Notable performance can be gained from using the zip() function to iterate through two lists in parallel during list creation. When iterating through two lists in parallel to print out the elements of the two lists, the zip() function will yield similar performance as the enumerate() function, as to using a manual counter variable, as to using an index-list, and as to during the special scenario where the elements of one of the two lists (either foo or bar) may be used to index the other list.

The Python3.6 Script that was used to investigate list creation.

import timeit
import matplotlib.pyplot as plt
import numpy as np


def test_zip( foo, bar ):
    store = []
    for f, b in zip(foo, bar):
        #print(f, b)
        store.append( (f, b) ) 

def test_enumerate( foo, bar ):
    store = []
    for n, f in enumerate( foo ):
        #print(f, bar[n])
        store.append( (f, bar[n]) ) 

def test_count( foo, bar ):
    store = []
    count = 0
    for f in foo:
        #print(f, bar[count])
        store.append( (f, bar[count]) )
        count += 1

def test_indices( foo, bar, indices ):
    store = []
    for i in indices:
        #print(foo[i], bar[i])
        store.append( (foo[i], bar[i]) )

def test_existing_list_indices( foo, bar ):
    store = []
    for f in foo:
        #print(f, bar[f])
        store.append( (f, bar[f]) )


list_sizes = [ 10, 100, 1000, 10000, 100000, 1000000 ]
tz = []
te = []
tc = []
ti = []
tii= []

tcz = []
tce = []
tci = []
tcii= []

for a in list_sizes:
    foo = [ i for i in range(a) ]
    bar = [ i for i in range(a) ]
    indices = [ i for i in range(a) ]
    reps = 1000

    tz.append( timeit.timeit( 'test_zip( foo, bar )',
                              'from __main__ import test_zip, foo, bar',
                              number=reps
                              )
               )
    te.append( timeit.timeit( 'test_enumerate( foo, bar )',
                              'from __main__ import test_enumerate, foo, bar',
                              number=reps
                              )
               )
    tc.append( timeit.timeit( 'test_count( foo, bar )',
                              'from __main__ import test_count, foo, bar',
                              number=reps
                              )
               )
    ti.append( timeit.timeit( 'test_indices( foo, bar, indices )',
                              'from __main__ import test_indices, foo, bar, indices',
                              number=reps
                              )
               )
    tii.append( timeit.timeit( 'test_existing_list_indices( foo, bar )',
                               'from __main__ import test_existing_list_indices, foo, bar',
                               number=reps
                               )
                )

    tcz.append( timeit.timeit( '[(f, b) for f, b in zip(foo, bar)]',
                               'from __main__ import foo, bar',
                               number=reps
                               )
                )
    tce.append( timeit.timeit( '[(f, bar[n]) for n, f in enumerate( foo )]',
                               'from __main__ import foo, bar',
                               number=reps
                               )
                )
    tci.append( timeit.timeit( '[(foo[i], bar[i]) for i in indices ]',
                               'from __main__ import foo, bar, indices',
                               number=reps
                               )
                )
    tcii.append( timeit.timeit( '[(f, bar[f]) for f in foo ]',
                                'from __main__ import foo, bar',
                                number=reps
                                )
                 )

print( f'te  = {te}' )
print( f'ti  = {ti}' )
print( f'tii = {tii}' )
print( f'tc  = {tc}' )
print( f'tz  = {tz}' )

print( f'tce  = {te}' )
print( f'tci  = {ti}' )
print( f'tcii = {tii}' )
print( f'tcz  = {tz}' )

fig, ax = plt.subplots( 2, 2 )
ax[0,0].plot( list_sizes, te, label='enumerate()', marker='.' )
ax[0,0].plot( list_sizes, ti, label='index-list', marker='.' )
ax[0,0].plot( list_sizes, tii, label='element of foo', marker='.' )
ax[0,0].plot( list_sizes, tc, label='count()', marker='.' )
ax[0,0].plot( list_sizes, tz, label='zip()', marker='.')
ax[0,0].set_xscale('log')
ax[0,0].set_yscale('log')
ax[0,0].set_xlabel('List Size')
ax[0,0].set_ylabel('Time (s)')
ax[0,0].legend()
ax[0,0].grid( b=True, which='major', axis='both')
ax[0,0].grid( b=True, which='minor', axis='both')

ax[0,1].plot( list_sizes, np.array(te)/np.array(tz), label='enumerate()', marker='.' )
ax[0,1].plot( list_sizes, np.array(ti)/np.array(tz), label='index-list', marker='.' )
ax[0,1].plot( list_sizes, np.array(tii)/np.array(tz), label='element of foo', marker='.' )
ax[0,1].plot( list_sizes, np.array(tc)/np.array(tz), label='count()', marker='.' )
ax[0,1].set_xscale('log')
ax[0,1].set_xlabel('List Size')
ax[0,1].set_ylabel('Performances ( vs zip() function )')
ax[0,1].legend()
ax[0,1].grid( b=True, which='major', axis='both')
ax[0,1].grid( b=True, which='minor', axis='both')

ax[1,0].plot( list_sizes, tce, label='list comprehension using enumerate()',  marker='.')
ax[1,0].plot( list_sizes, tci, label='list comprehension using index-list()',  marker='.')
ax[1,0].plot( list_sizes, tcii, label='list comprehension using element of foo',  marker='.')
ax[1,0].plot( list_sizes, tcz, label='list comprehension using zip()',  marker='.')
ax[1,0].set_xscale('log')
ax[1,0].set_yscale('log')
ax[1,0].set_xlabel('List Size')
ax[1,0].set_ylabel('Time (s)')
ax[1,0].legend()
ax[1,0].grid( b=True, which='major', axis='both')
ax[1,0].grid( b=True, which='minor', axis='both')

ax[1,1].plot( list_sizes, np.array(tce)/np.array(tcz), label='enumerate()', marker='.' )
ax[1,1].plot( list_sizes, np.array(tci)/np.array(tcz), label='index-list', marker='.' )
ax[1,1].plot( list_sizes, np.array(tcii)/np.array(tcz), label='element of foo', marker='.' )
ax[1,1].set_xscale('log')
ax[1,1].set_xlabel('List Size')
ax[1,1].set_ylabel('Performances ( vs zip() function )')
ax[1,1].legend()
ax[1,1].grid( b=True, which='major', axis='both')
ax[1,1].grid( b=True, which='minor', axis='both')

plt.show()

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

Get first row of dataframe in Python Pandas based on criteria

For existing matches, use query:

df.query(' A > 3' ).head(1)
Out[33]: 
   A  B  C
2  4  6  3

df.query(' A > 4 and B > 3' ).head(1)
Out[34]: 
   A  B  C
4  5  4  5

df.query(' A > 3 and (B > 3 or C > 2)' ).head(1)
Out[35]: 
   A  B  C
2  4  6  3

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Click events on Pie Charts in Chart.js

Working fine chartJs sector onclick

ChartJS : pie Chart - Add options "onclick"

              options: {
                    legend: {
                        display: false
                    },
                    'onClick' : function (evt, item) {
                        console.log ('legend onClick', evt);
                        console.log('legd item', item);
                    }
                }

Cannot declare instance members in a static class in C#

public static class Employee
{
    public static string SomeSetting
    {
        get 
        {
            return ConfigurationManager.AppSettings["SomeSetting"];    
        }
    }
}

Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.

If you feel that you must store a reference to appsettings, try

public static class Employee
{
    private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;

    public static NameValueCollection AppSettings { get { return _appSettings; } }

}

It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.

Bind TextBox on Enter-key press

You could easily create your own control inheriting from TextBox and reuse it throughout your project.

Something similar to this should work:

public class SubmitTextBox : TextBox
{
    public SubmitTextBox()
        : base()
    {
        PreviewKeyDown += new KeyEventHandler(SubmitTextBox_PreviewKeyDown);
    }

    void SubmitTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            BindingExpression be = GetBindingExpression(TextBox.TextProperty);
            if (be != null)
            {
                be.UpdateSource();
            }
        }
    }
}

There may be a way to get around this step, but otherwise you should bind like this (using Explicit):

<custom:SubmitTextBox
    Text="{Binding Path=BoundProperty, UpdateSourceTrigger=Explicit}" />

How do I see active SQL Server connections?

MS's query explaining the use of the KILL command is quite useful providing connection's information:

SELECT conn.session_id, host_name, program_name,
    nt_domain, login_name, connect_time, last_request_end_time 
FROM sys.dm_exec_sessions AS sess
JOIN sys.dm_exec_connections AS conn
   ON sess.session_id = conn.session_id;

HTML input arrays

As far as I know, there isn't anything on the HTML specs because browsers aren't supposed to do anything different for these fields. They just send them as they normally do and PHP is the one that does the parsing into an array, as do other languages.

How to get base URL in Web API controller?

In the action method of the request to the url "http://localhost:85458/api/ctrl/"

var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;

this will get you http://localhost:85458

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

'Missing contentDescription attribute on image' in XML

Follow this link for solution: Android Lint contentDescription warning

Resolved this warning by setting attribute android:contentDescription for my ImageView

android:contentDescription="@string/desc"

Android Lint support in ADT 16 throws this warning to ensure that image widgets provide a contentDescription

This defines text that briefly describes the content of the view. This property is used primarily for accessibility. Since some views do not have textual representation this attribute can be used for providing such.

Non-textual widgets like ImageViews and ImageButtons should use the contentDescription attribute to specify a textual description of the widget such that screen readers and other accessibility tools can adequately describe the user interface.

This link for explanation: Accessibility, It's Impact and Development Resources

Many Android users have disabilities that require them to interact with their Android devices in different ways. These include users who have visual, physical or age-related disabilities that prevent them from fully seeing or using a touchscreen.

Android provides accessibility features and services for helping these users navigate their devices more easily, including text-to-speech, haptic feedback, trackball and D-pad navigation that augments their experience. Android application developers can take advantage of these services to make their applications more accessible and also build their own accessibility services.

This guide is for making your app accessible: Making Apps More Accessible

Making sure your application is accessible to all users is relatively easy, particularly when you use framework-provided user interface components. If you only use these standard components for your application, there are just a few steps required to ensure your application is accessible:

  1. Label your ImageButton, ImageView, EditText, CheckBox and other user interface controls using the android:contentDescription attribute.

  2. Make all of your user interface elements accessible with a directional controller, such as a trackball or D-pad.

  3. Test your application by turning on accessibility services like TalkBack and Explore by Touch, and try using your application using only directional controls.

Function for C++ struct

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};

Listing all permutations of a string/integer

Here is the simplest solution I can think of:

let rec distribute e = function
  | [] -> [[e]]
  | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]

let permute xs = Seq.fold (fun ps x -> List.collect (distribute x) ps) [[]] xs

The distribute function takes a new element e and an n-element list and returns a list of n+1 lists each of which has e inserted at a different place. For example, inserting 10 at each of the four possible places in the list [1;2;3]:

> distribute 10 [1..3];;
val it : int list list =
  [[10; 1; 2; 3]; [1; 10; 2; 3]; [1; 2; 10; 3]; [1; 2; 3; 10]]

The permute function folds over each element in turn distributing over the permutations accumulated so far, culminating in all permutations. For example, the 6 permutations of the list [1;2;3]:

> permute [1;2;3];;
val it : int list list =
  [[3; 2; 1]; [2; 3; 1]; [2; 1; 3]; [3; 1; 2]; [1; 3; 2]; [1; 2; 3]]

Changing the fold to a scan in order to keep the intermediate accumulators sheds some light on how the permutations are generated an element at a time:

> Seq.scan (fun ps x -> List.collect (distribute x) ps) [[]] [1..3];;
val it : seq<int list list> =
  seq
    [[[]]; [[1]]; [[2; 1]; [1; 2]];
     [[3; 2; 1]; [2; 3; 1]; [2; 1; 3]; [3; 1; 2]; [1; 3; 2]; [1; 2; 3]]]

LOAD DATA INFILE Error Code : 13

OLD:

LOAD DATA INFILE '/home/root12/Downloads/task1.csv' INTO TABLE test.task FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS;

File '/home/root12/Downloads/task1.csv' not found (Errcode: 13 - Permission denied)

NEW WORKING FOR ME:

LOAD DATA LOCAL INFILE '/home/root12/Downloads/task1.csv' INTO TABLE test.task FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS;

Query OK, 500 rows affected, 284 warnings (1.24 sec)
Query OK, 5000 rows affected, 2846 warnings (1.24 sec)

how to configure lombok in eclipse luna

For Gradle users, if you are using Eclipse or one of its offshoots(I am using STS 4.5.1.RELEASE), all that you need to do is:

  • In build.gradle, you ONLY need these 2 "extra" instructions:

    dependencies {
      compileOnly 'org.projectlombok:lombok'  
      annotationProcessor 'org.projectlombok:lombok'
    }
    
  • Right-click on your project > Gradle > Refresh Gradle Project. The lombok-"version".jar will appear inside your project's Project and External Dependencies

  • Right-click on that lombok-"version".jar > Run As > Java Application (similar to double-clicking on the actual jar or running java -jar lombok-"version".jar on the command line.)

  • A GUI will appear, follow the instructions and one of the thing it does is to copy lombok.jar to your IDE's root.

  • The only other thing you will need to do(outside of the GUI) is to add that lombok.jar to your project build path



That's it!

Gradient text color

The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.

For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):

  • The gradient starts at color #f22 at 0% (that is the left edge of the element). First color is always assumed to start at 0% even though the percentage is not mentioned explicitly.
  • Between 0% to 14.25%, the color changes from #f22 to #f2f gradually. The percenatge is set at 14.25 because there are seven color changes and we are looking for equal splits.
  • At 14.25% (of the container's size), the color will exactly be #f2f as per the gradient specified.
  • Similarly the colors change from one to another depending on the bands specified by color stop percentages. Each band should be a step of 14.25%.

So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
  color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
_x000D_
_x000D_

Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text.

(Note that the background-clip: text is an experimental property and is not supported widely.)


Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:

  • First parameter is the direction of the gradient. If the color should be red at left side and brown at the right side then use the direction as to right. If it should be red at right and brown at left then give the direction as to left.
  • Next step is to define the colors of the gradient. Since our gradient should start as red on the left side, just specify red as the first color (percentage is assumed to be 0%).
  • Now, since we have two color changes (red - orange and orange - brown), the percentages must be set as 100 / 2 for equal splits. If equal splits are not required, we can assign the percentages as we wish.
  • So at 50% the color should be orange and then the final color would be brown. The position of the final color is always assumed to be at 100%.

Thus the gradient's specification should read as follows:

background-image: linear-gradient(to right, red, orange 50%, brown).

If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.

_x000D_
_x000D_
.red-orange-brown {_x000D_
  background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
  background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
_x000D_
_x000D_

JavaFX "Location is required." even though it is in the same package

I had sometimes the same Exception.

When i create a FXML-File with the Wizard in Eclipse, i write example.fxml in the name field. Eclipse creates a file, like example.fxml.fxml. With this mistake, the FXMLLoader can't find the right FXML-File. So, my tip, check the name of the FXML-Filename in your start-Method and the real Name of File.

Hopes i could help. Good luck.

How can I install a CPAN module into a local directory?

local::lib will help you. It will convince "make install" (and "Build install") to install to a directory you can write to, and it will tell perl how to get at those modules.

In general, if you want to use a module that is in a blib/ directory, you want to say perl -Mblib ... where ... is how you would normally invoke your script.

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

If using the docker-compose file, Based on docker compose version 2.x We can set like as below, by overriding the default config.

ulimits:
  nproc: 65535
  nofile:
    soft: 26677
    hard: 46677

https://docs.docker.com/compose/compose-file/

How to get Time from DateTime format in SQL?

Assuming Sql server

SELECT CONVERT(VARCHAR(8),GETDATE(),108)

Execute command on all files in a directory

Based on @Jim Lewis's approach:

Here is a quick solution using find and also sorting files by their modification date:

$ find  directory/ -maxdepth 1 -type f -print0 | \
  xargs -r0 stat -c "%y %n" | \
  sort | cut -d' ' -f4- | \
  xargs -d "\n" -I{} cmd -op1 {} 

For sorting see:

http://www.commandlinefu.com/commands/view/5720/find-files-and-list-them-sorted-by-modification-time

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

assign function return value to some variable using javascript

Or just...

var response = (function() {
    var a;
    // calculate a
    return a;
})();  

In this case, the response variable receives the return value of the function. The function executes immediately.

You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}