Programs & Examples On #Execfile

execfile is a Python 2.x. built-in function that executes Python scripts from files.

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

ImportError: No module named google.protobuf

If you are a windows user and try to start py-script in cmd - don't forget to type python before filename.

python script.py

I have "No module named google" error if forget to type it.

Print: Entry, ":CFBundleIdentifier", Does Not Exist

Adding, it works for me, when nothing above fixes:

  1. Install react-native-git-upgrade and update your project. npm i -g react-native-git-upgrade && react-native-git-upgrade
  2. Open Xcode -> File -> Project settings -> Advanced.
  3. Select "Custom", then select "Relative to Workspace" and then click done, done.
  4. Update your CLI. npm i -g react-native-cli
  5. Update your Nodejs 8 and NPM. nvm install --lts and nvm install-latest-npm
  6. Remove ios/build and node_modules (in your project root path)
  7. Proceed again with npm install and react-native run-ios, and give me a hug :-)

It finally works here.

  • Mac OS High Sierra 10.13.4
  • Xcode 9.3
  • NPM 5.8.0
  • Node 8.11.1
  • RN 0.55.2

ImportError: cannot import name NUMPY_MKL

From your log its clear that numpy package is missing. As mention in the PyPI package:

The SciPy library depends on NumPy, which provides convenient and fast N-dimensional array manipulation.

So, try installing numpy package for python as you did with scipy.

RuntimeError: module compiled against API version a but this version of numpy is 9

I faced the same problem due to documentation inconsistencies. This page says the examples in the docs work best with python 3.x: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_intro/py_intro.html#intro , whereas this installation page has links to python 2.7, and older versions of numpy and matplotlib: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html

My setup was as such: I already had Python 3.6 and 3.5 installed, but since OpenCv-python docs said it works best with 2.7.x, I also installed that version. After I installed numpy (in Python27 directory, without pip but with the default extractor, since pip is not part of the default python 2.7 installation like it is in 3.6), I ran in this RuntimeError: module compiled against API version a but this version of numpy is error. I tried many different versions of both numpy and opencv, but to no avail. Lastly, I simply deleted numpy from python27 (just delete the folder in site-packages as well as any other remaining numpy-named files), and installed the latest versions of numpy, matplotlib, and opencv in the Python3.6 version using pip no problem. Been running opencv ever since.

Hope this saves somebody some time.

TypeError: unsupported operand type(s) for -: 'list' and 'list'

This question has been answered but I feel I should also mention another potential cause. This is a direct result of coming across the same error message but for different reasons. If your list/s are empty the operation will not be performed. check your code for indents and typos

socket.error:[errno 99] cannot assign requested address and namespace in python

when you bind localhost or 127.0.0.1, it means you can only connect to your service from local.

you cannot bind 10.0.0.1 because it not belong to you, you can only bind ip owned by your computer

you can bind 0.0.0.0 because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip

Close pre-existing figures in matplotlib when running from eclipse

You can close a figure by calling matplotlib.pyplot.close, for example:

from numpy import *
import matplotlib.pyplot as plt
from scipy import *

t = linspace(0, 0.1,1000)
w = 60*2*pi


fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)

You can also close all open figures by calling matplotlib.pyplot.close("all")

Adding a module (Specifically pymorph) to Spyder (Python IDE)

One can also follow the below steps : Spyder -> Tools -> Open Command Prompt -> write the command "pip install html5lib"

Execute a file with arguments in Python shell

try this:

import sys
sys.argv = ['arg1', 'arg2']
execfile('abc.py')

Note that when abc.py finishes, control will be returned to the calling program. Note too that abc.py can call quit() if indeed finished.

libxml install error using pip

I work on a Windows machine. And here are some pointers for successful installation of lxml (with python 2.6 and later).

Have the following installed:

  1. MingGW.
  2. libxml2 version 2.7.0 or later.
  3. libxslt version 1.1.23 or later.

All are not available at a pip install.

libxml2's windows binary is found here.

libxslt is found here.

After you are done with the above two,

do : pip install lxml.

Another workaround is using the stable releases from PyPI or the unofficial Windows binaries by Christoph Gohlke (found here).

Run a Python script from another Python script, passing in arguments

Ideally, the Python script you want to run will be set up with code like this near the end:

def main(arg1, arg2, etc):
    # do whatever the script does


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2], sys.argv[3])

In other words, if the module is called from the command line, it parses the command line options and then calls another function, main(), to do the actual work. (The actual arguments will vary, and the parsing may be more involved.)

If you want to call such a script from another Python script, however, you can simply import it and call modulename.main() directly, rather than going through the operating system.

os.system will work, but it is the roundabout (read "slow") way to do it, as you are starting a whole new Python interpreter process each time for no raisin.

How do you properly determine the current script directory?

The os.path... approach was the 'done thing' in Python 2.

In Python 3, you can find directory of script as follows:

from pathlib import Path
cwd = Path(__file__).parents[0]

Unable to install pyodbc on Linux

On Ubuntu, you'll need to install unixodbc-dev:

sudo apt-get install unixodbc-dev

Install pip by using this command:

sudo apt-get install python-pip

once that is installed, you should be able to install pyodbc successfully:

pip install pyodbc

How do I get the path of the current executed file in Python?

If the code is coming from a file, you can get its full name

sys._getframe().f_code.co_filename

You can also retrieve the function name as f_code.co_name

What is an alternative to execfile in Python 3?

If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

If you're using Python 3.1 or later, you should also take a look at importlib.

How do I get the path and name of the file that is currently executing?

import os

import wx


# return the full path of this file
print(os.getcwd())

icon = wx.Icon(os.getcwd() + '/img/image.png', wx.BITMAP_TYPE_PNG, 16, 16)

# put the icon on the frame
self.SetIcon(icon)

In SQL Server, what does "SET ANSI_NULLS ON" mean?

If ANSI_NULLS is set to "ON" and if we apply = , <> on NULL column value while writing select statement then it will not return any result.

Example

create table #tempTable (sn int, ename varchar(50))

insert into #tempTable
values (1, 'Manoj'), (2, 'Pankaj'), (3, NULL), (4, 'Lokesh'), (5, 'Gopal')

SET ANSI_NULLS ON

select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (0 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (0 row(s) affected)

SET ANSI_NULLS OFF

select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (1 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (4 row(s) affected)

How to choose between Hudson and Jenkins?

Up front .. I am a Hudson committer and author of the Hudson book, but I was not involved in the whole split of the projects.

In any case here is my advice:

Check out both and see what fits your needs better.

Hudson is going to complete the migration to be a top level Eclipse projects later this year and has gotten a whole bunch of full time developers, QA and others working on the project. It is still going strong and has a lot of users and with being the default CI server at Eclipse it will continue to serve the needs of many Java developers. Looking at the roadmap and plans for the future you can see that after the Maven 3 integration accomplished with the 2.1.0 release a whole bunch of other interesting feature are ahead.

http://www.eclipse.org/hudson

Jenkins on the other side has won over many original Hudson users and has a large user community across multiple technologies and also has a whole bunch of developers working on it.

At this stage both CI servers are great tools to use and depending on your needs in terms of technology to integrate with one or the other might be better. Both products are available as open source and you can get commercial support from various companies for both.

In any case .. if you are not using a CI server yet.. start now with either of them and you will see huge benefits.

Update Jan 2013: After a long process of IP cleanup and further improvements Hudson 3.0 as the first Eclipse foundation approved release is now available.

CertificateException: No name matching ssl.someUrl.de found

If you're looking for a Kafka error, this might because the upgrade of Kafka's version from 1.x to 2.x.

javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... java.security.cert.CertificateException: No name matching *** found

or

[Producer clientId=producer-1] Connection to node -2 failed authentication due to: SSL handshake failed

The default value for ssl.endpoint.identification.algorithm was changed to https, which performs hostname verification (man-in-the-middle attacks are possible otherwise). Set ssl.endpoint.identification.algorithm to an empty string to restore the previous behaviour. Apache Kafka Notable changes in 2.0.0

Solution: SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, ""

How can I use UIColorFromRGB in Swift?

solution for argb format:

//  UIColorExtensions.swift
import UIKit
extension UIColor {

    convenience init(argb: UInt) {
        self.init(
            red: CGFloat((argb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((argb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(argb & 0x0000FF) / 255.0,
            alpha: CGFloat((argb & 0xFF000000) >> 24) / 255.0
        )
    }
}

usage:

var clearColor: UIColor = UIColor.init(argb: 0x00000000)
var redColor: UIColor = UIColor.init(argb: 0xFFFF0000)

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

Validate that a string is a positive integer

(~~a == a) where a is the string.

How To Upload Files on GitHub

Well, there really is a lot to this. I'm assuming you have an account on http://github.com/. If not, go get one.

After that, you really can just follow their guide, its very simple and easy and the explanation is much more clear than mine: http://help.github.com/ >> http://help.github.com/mac-set-up-git/

To answer your specific question: You upload files to github through the git push command after you have added your files you needed through git add 'files' and commmited them git commit -m "my commit messsage"

How do I replace part of a string in PHP?

This is probably what you need:

$text = str_replace(' ', '_', substr($text, 0, 10));

SQL query: Delete all records from the table except latest N?

This should work as well:

DELETE FROM [table] 
INNER JOIN (
    SELECT [id] 
    FROM (
        SELECT [id] 
        FROM [table] 
        ORDER BY [id] DESC
        LIMIT N
    ) AS Temp
) AS Temp2 ON [table].[id] = [Temp2].[id]

Determining if a number is prime

I would guess taking sqrt and running foreach frpm 2 to sqrt+1 if(input% number!=0) return false; once you reach sqrt+1 you can be sure its prime.

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

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

You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step

geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx

Can you recommend a free light-weight MySQL GUI for Linux?

i suggest using phpmyadmin

it’s definitely the best free tool out there and it works on every system with php+mysql

JavaScript/jQuery - How to check if a string contain specific words

_x000D_
_x000D_
var str1 = "STACKOVERFLOW";_x000D_
var str2 = "OVER";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

Converting dictionary to JSON

json.dumps() is used to decode JSON data

  • json.loads take a string as input and returns a dictionary as output.
  • json.dumps take a dictionary as input and returns a string as output.
import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

Here is another solution you could have used. It is working in my app.

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        android.support.v7.app.ActionBar actionBar =getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);            
        setContentView(R.layout.activity_main)

Then you can get rid of that import for the one line ActionBar use.

Difference between window.location.href, window.location.replace and window.location.assign

These do the same thing:

window.location.assign(url);
window.location = url;
window.location.href = url;

They simply navigate to the new URL. The replace method on the other hand navigates to the URL without adding a new record to the history.

So, what you have read in those many forums is not correct. The assign method does add a new record to the history.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

Undo working copy modifications of one file in Git?

For me only this one worked

git checkout -p filename

enter image description here

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

My issue was that you need to have a connection string entry in both your repository layer and web layer. Once I added it to my web.config as well as my app.config, Entity Framework was able to create the migration.

My question is why, does the web.config need it, when there is absolutely no database access there.

What should every programmer know about security?

Also be sure to check out the OWASP Top 10 List for a categorization of all the main attack vectors/vulnerabilities.

These things are fascinating to read about. Learning to think like an attacker will train you of what to think about as you're writing your own code.

How to show current time in JavaScript in the format HH:MM:SS?

You can use moment.js to do this.

var now = new moment();
console.log(now.format("HH:mm:ss"));

Outputs:

16:30:03

How to create two columns on a web page?

I found a real cool Grid which I also use for columns. Check it out Simple Grid. Wich this CSS you can simply use:

<div class="grid">
    <div class="col-1-2">
       <div class="content">
           <p>...insert content left side...</p>
       </div>
    </div>
    <div class="col-1-2">
       <div class="content">
           <p>...insert content right side...</p>
       </div>
    </div>
</div>

I use it for all my projects.

What is the path that Django uses for locating and loading templates?

For Django 1.6.6:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = os.path.join(BASE_DIR, 'templates')

Also static and media for debug and production mode:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
else:
    STATIC_ROOT = %REAL_PATH_TO_PRODUCTION_STATIC_FOLDER%
    MEDIA_ROOT = %REAL_PATH_TO_PRODUCTION_MEDIA_FOLDER%

Into urls.py you must add:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

from news.views import Index

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    ...
    )

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

In Django 1.8 you can set template paths, backend and other parameters for templates in one dictionary (settings.py):

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Official docs.

How do I create a MongoDB dump of my database?

This command will make a dump of given database in json and bson format.

mongodump -d <database name> -o <target directory>

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

How to check if an element exists in the xml using xpath?

take look at my example

<tocheading language="EN"> 
     <subj-group> 
         <subject>Editors Choice</subject> 
         <subject>creative common</subject> 
     </subj-group> 
</tocheading> 

now how to check if creative common is exist

tocheading/subj-group/subject/text() = 'creative common'

hope this help you

Excel formula to reference 'CELL TO THE LEFT'

Please select the entire sheet and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

=A1<>XFD1

Format..., select choice of formatting, OK, OK.

Remove specific characters from a string in Javascript

Regexp solution:

ref = ref.replace(/^F0/, "");

plain solution:

if (ref.substr(0, 2) == "F0")
     ref = ref.substr(2);

How can I split a text file using PowerShell?

Many of these answers were too slow for my source files. My source files were SQL files between 10 MB and 800 MB that needed to split into files of roughly equal line counts.

I found some of the previous answers which use Add-Content to be quite slow. Waiting many hours for a split to finish wasn't uncommon.

I didn't try Typhlosaurus's answer, but it looks to only do splits by file size, not line count.

The following has suited my purposes.

$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
Write-Host "Reading source file..."
$lines = [System.IO.File]::ReadAllLines("C:\Temp\SplitTest\source.sql")
$totalLines = $lines.Length

Write-Host "Total Lines :" $totalLines

$skip = 0
$count = 100000; # Number of lines per file

# File counter, with sort friendly name
$fileNumber = 1
$fileNumberString = $filenumber.ToString("000")

while ($skip -le $totalLines) {
    $upper = $skip + $count - 1
    if ($upper -gt ($lines.Length - 1)) {
        $upper = $lines.Length - 1
    }

    # Write the lines
    [System.IO.File]::WriteAllLines("C:\Temp\SplitTest\result$fileNumberString.txt",$lines[($skip..$upper)])

    # Increment counters
    $skip += $count
    $fileNumber++
    $fileNumberString = $filenumber.ToString("000")
}

$sw.Stop()

Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"

For a 54 MB file, I get the output...

Reading source file...
Total Lines : 910030
Split complete in  1.7056578 seconds

I hope others looking for a simple, line-based splitting script that matches my requirements will find this useful.

How to break line in JavaScript?

I was facing the same problem. For my solution, I added br enclosed between 2 brackets < > enclosed in double quotation marks, and preceded and followed by the + sign:

+"<br>"+

Try this in your browser and see, it certainly works in my Internet Explorer.

Can I have an IF block in DOS batch file?

Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:

if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)

This should provide var3 with the following value:

blue_cheese

but instead yields:

_

because all 3 commands are cached and executed simultaneously upon exiting the code block.

I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.

if %ERRORLEVEL%==0 goto :error0
goto :endif

:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%

:endif

How to switch to the new browser window, which opens after click on the button?

Surya, your way won't work, because of two reasons:

  1. you can't close driver during evaluation of test as it will loose focus, before switching to active element, and you'll get NoSuchWindowException.
  2. if test are run on ChromeDriver you`ll get not a window, but tab on click in your application. As SeleniumDriver can't act with tabs, only switchs between windows, it hangs on click where new tab is being opening, and crashes on timeout.

How do I connect to a MySQL Database in Python?

For python 3.3

CyMySQL https://github.com/nakagami/CyMySQL

I have pip installed on my windows 7, just pip install cymysql

(you don't need cython) quick and painless

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Don't quote the column filename

mysql> INSERT INTO risks (status, subject, reference_id, location, category, team,    technology, owner, manager, assessment, notes,filename) 
VALUES ('san', 'ss', 1, 1, 1, 1, 2, 1, 1, 'sment', 'notes','santu');

Better way to generate array of all letters in the alphabet

with io.vavr

public static char[] alphanumericAlphabet() {
    return CharSeq
            .rangeClosed('0','9')
            .appendAll(CharSeq.rangeClosed('a','z'))
            .appendAll(CharSeq.rangeClosed('A','Z'))
            .toCharArray();
}

UTF-8 encoding in JSP page

The default JSP file encoding is specified by JSR315 as ISO-8859-1. This is the encoding that the JSP engine uses to read the JSP file and it is unrelated to the servlet request or response encoding.

If you have non-latin characters in your JSP files, save the JSP file as UTF-8 with BOM or set pageEncoding in the beginning of the JSP page:

<%@page pageEncoding="UTF-8" %>

However, you might want to change the default to UTF-8 globally for all JSP pages. That can be done via web.xml:

<jsp-config>
    <jsp-property-group>
        <url-pattern>/*</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

Or, when using Spring Boot with an (embedded) Tomcat, via a TomcatContextCustomizer:

@Component
public class JspConfig implements TomcatContextCustomizer {
    @Override
    public void customize(Context context) {
        JspPropertyGroup pg = new JspPropertyGroup();
        pg.addUrlPattern("/*");
        pg.setPageEncoding("UTF-8");
        pg.setTrimWhitespace("true"); // optional, but nice to have
        ArrayList<JspPropertyGroupDescriptor> pgs = new ArrayList<>();
        pgs.add(new JspPropertyGroupDescriptorImpl(pg));
        context.setJspConfigDescriptor(new JspConfigDescriptorImpl(pgs, new ArrayList<TaglibDescriptor>()));
    }
}

For JSP to work with Spring Boot, don't forget to include these dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

And to make a "runnable" .war file, repackage it:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
   . . .

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

I experienced the same problem when I copied a text that has an apostrophe from a Word document to my HTML code.

To resolve the issue, all I did was deleted the particular word in my HTML and typed it directly, including the apostrophe. This action nullified the original copy and paste acton and displayed the newly typed apostrophe correctly

Is there a way to get a list of all current temporary tables in SQL Server?

For SQL Server 2000, this should tell you only the #temp tables in your session. (Adapted from my example for more modern versions of SQL Server here.) This assumes you don't name your tables with three consecutive underscores, like CREATE TABLE #foo___bar:

SELECT 
  name = SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1),
  t.id
FROM tempdb..sysobjects AS t
WHERE t.name LIKE '#%[_][_][_]%'
AND t.id = 
  OBJECT_ID('tempdb..' + SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1));

HTML checkbox onclick called in Javascript

You can also extract the event code from the HTML, like this :

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" />
<label for="check_all_1">Select All</label>

<script>
function selectAll(frmElement, chkElement) {
    // ...
}
document.getElementById("check_all_1").onclick = function() {
    selectAll(document.wizard_form, this);
}
</script>

SQL Error: ORA-01861: literal does not match format string 01861

If you provide proper date format it should work please recheck once if you have given correct date format in insert values

How to convert minutes to hours/minutes and add various time values together using jQuery?

Q1:

$(document).ready(function() {
    var totalMinutes = $('.totalMin').html();

    var hours = Math.floor(totalMinutes / 60);          
    var minutes = totalMinutes % 60;

    $('.convertedHour').html(hours);
    $('.convertedMin').html(minutes);    
});

Q2:

$(document).ready(function() {

    var minutes = 0;

    $('.min').each(function() {
        minutes = parseInt($(this).html()) + minutes;
    });

    var realmin = minutes % 60
    var hours = Math.floor(minutes / 60)

    $('.hour').each(function() {
        hours = parseInt($(this).html()) + hours;
    });


    $('.totalHour').html(hours);
    $('.totalMin').html(realmin);    

});

Can functions be passed as parameters?

You can pass function as parameter to a Go function. Here is an example of passing function as parameter to another Go function:

package main

import "fmt"

type fn func(int) 

func myfn1(i int) {
    fmt.Printf("\ni is %v", i)
}
func myfn2(i int) {
    fmt.Printf("\ni is %v", i)
}
func test(f fn, val int) {
    f(val)
}
func main() {
    test(myfn1, 123)
    test(myfn2, 321)
}

You can try this out at: https://play.golang.org/p/9mAOUWGp0k

Java best way for string find and replace?

Simply include the Apache Commons Lang JAR and use the org.apache.commons.lang.StringUtils class. You'll notice lots of methods for replacing Strings safely and efficiently.

You can view the StringUtils API at the previously linked website.

"Don't reinvent the wheel"

Nexus 5 USB driver

Nexus 5 with Win7 x64

-USB computer connection : Uncheck MTP and PTP

-Use a 2.0 USB port.

-Try to use the original USB cable.

Now device manager will detect nexus 5 as an androide device with ADB driver.

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

Unmarshaling nested JSON objects

Assign the values of nested json to struct until you know the underlying type of json keys:-

package main

import (
    "encoding/json"
    "fmt"
)

// Object
type Object struct {
    Foo map[string]map[string]string `json:"foo"`
    More string `json:"more"`
}

func main(){
    someJSONString := []byte(`{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}`)
    var obj Object
    err := json.Unmarshal(someJSONString, &obj)
    if err != nil{
        fmt.Println(err)
    }
    fmt.Println("jsonObj", obj)
}

Using Python to execute a command on every file in a folder

The new recommend way in Python3 is to use pathlib:

from pathlib import Path

mydir = Path("path/to/my/dir")
for file in mydir.glob('*.mp4'):
    print(file.name)
    # do your stuff

Instead of *.mp4 you can use any filter, even a recursive one like **/*.mp4. If you want to use more than one extension, you can simply iterate all with * or **/* (recursive) and check every file's extension with file.name.endswith(('.mp4', '.webp', '.avi', '.wmv', '.mov'))

How to find the difference in days between two dates?

For MacOS sierra (maybe from Mac OS X yosemate),

To get epoch time(Seconds from 1970) from a file, and save it to a var: old_dt=`date -j -r YOUR_FILE "+%s"`

To get epoch time of current time new_dt=`date -j "+%s"`

To calculate difference of above two epoch time (( diff = new_dt - old_dt ))

To check if diff is more than 23 days (( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days

Progress Bar with HTML and CSS

.bar {
background - color: blue;
height: 40 px;
width: 40 px;
border - style: solid;
border - right - width: 1300 px;
border - radius: 40 px;
animation - name: Load;
animation - duration: 11 s;
position: relative;
animation - iteration - count: 1;
animation - fill - mode: forwards;
}

@keyframes Load {
100 % {
    width: 1300 px;border - right - width: 5;
}

Change type of varchar field to integer: "cannot be cast automatically to type integer"

I got the same problem. Than I realized I had a default string value for the column I was trying to alter. Removing the default value made the error go away :)

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

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

Here you can find the direct download link for Curl.exe

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link but after digging little more I Got it. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

link to download curl generic

http://localhost/phpMyAdmin/ unable to connect

http://localhost:(port number of phpmyadmin)/phpmyadmin/

For example: http://localhost:8080/phpmyadmin/

It works great!

Split Java String by New Line

This should cover you:

String lines[] = string.split("\\r?\\n");

There's only really two newlines (UNIX and Windows) that you need to worry about.

Setting a backgroundImage With React Inline Styles

  1. Copy the image to the React Component's folder where you want to see it.
  2. Copy the following code:
<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>
  1. Give a height to your .welcomer using CSS so that you can see your image in the desired size.

How to find out what character key is pressed?

**check this out** 
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).keypress(function(e)
        {

            var keynum;
            if(window.event)
            { // IE                 
                keynum = e.keyCode;
            }
                else if(e.which)
                    { 
                    // Netscape/Firefox/Opera                   
                    keynum = e.which;
                    }
                    alert(String.fromCharCode(keynum));
                    var unicode=e.keyCode? e.keyCode : e.charCode;
                    alert(unicode);
        });
});  

</script>
</head>
<body>

<input type="text"></input>
</body>
</html>

Drop view if exists

To cater for the schema as well, use this format in SQL 2014

if exists(select 1 from sys.views V inner join sys.[schemas] S on  v.schema_id = s.schema_id where s.name='dbo' and v.name = 'someviewname' and v.type = 'v')
  drop view [dbo].[someviewname];
go

And just throwing it out there, to do stored procedures, because I needed that too:

if exists(select 1
          from sys.procedures p
          inner join sys.[schemas] S on p.schema_id = s.schema_id
          where
              s.name='dbo' and p.name = 'someprocname'
          and p.type in ('p', 'pc')
  drop procedure [dbo].[someprocname];
go

Scroll to bottom of Div on page load (jQuery)

When page is load then scroll is max value .

This is message box when user send message then always show latest chat in down so that scroll value is always is maxium.

$('#message').scrollTop($('#message')[0].scrollHeight);

see image

How do you create a dictionary in Java?

There's an Abstract Class Dictionary

http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html

However this requires implementation.

Java gives us a nice implementation called a Hashtable

http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html

Kill a Process by Looking up the Port being used by it from a .BAT

Similar to Merlyn's response, but this one handles these cases as well:

  • The port number is actually a left substring of another longer port number that you're not looking for. You want to search for an exact port number so that you do not kill a random, innocent process!
  • The script code needs to be able to run more than once and be correct each time, not showing older, incorrect answers.

Here it is:

set serverPid=
for /F "tokens=5 delims= " %%P in ('netstat -a -n -o ^| findstr /E :8080 ') do set serverPid=%%P
if not "%serverPid%" == "" (
  taskkill /PID %serverPid%
) else (
  rem echo Server is not running.
)

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

On the latest version of MacOS Big Sur (clean/first install)

This command works as it should and installs Xcode

xcode-select --install

Determining 32 vs 64 bit in C++

"Compiled in 64 bit" is not well defined in C++.

C++ sets only lower limits for sizes such as int, long and void *. There is no guarantee that int is 64 bit even when compiled for a 64 bit platform. The model allows for e.g. 23 bit ints and sizeof(int *) != sizeof(char *)

There are different programming models for 64 bit platforms.

Your best bet is a platform specific test. Your second best, portable decision must be more specific in what is 64 bit.

Storing Objects in HTML5 localStorage

Another option would be to use an existing plugin.

For example persisto is an open source project that provides an easy interface to localStorage/sessionStorage and automates persistence for form fields (input, radio buttons, and checkboxes).

persisto features

(Disclaimer: I am the author.)

phpMyAdmin allow remote users

Just comment all lines in first Directory. Or you can remove these lines, but better to keep in case later you want to add some restrictions, you will uncomment.

#<Directory /usr/share/phpMyAdmin/>
#   <IfModule mod_authz_core.c>
#     # Apache 2.4
#     <RequireAny>
#       Require ip 127.0.0.1
#       Require ip ::1
#     </RequireAny>
#   </IfModule>
#   <IfModule !mod_authz_core.c>
#     # Apache 2.2
#     Order Deny,Allow
#     Deny from All
#     Allow from 127.0.0.1
#     Allow from ::1
#   </IfModule>
#</Directory>

Change route params without reloading in Angular 2

Use attribute queryParamsHandling: 'merge' while changing the url.

this.router.navigate([], {
        queryParams: this.queryParams,
        queryParamsHandling: 'merge',
        replaceUrl: true,
});

Understanding "VOLUME" instruction in DockerFile

Specifying a VOLUME line in a Dockerfile configures a bit of metadata on your image, but how that metadata is used is important.

First, what did these two lines do:

WORKDIR /usr/src/app
VOLUME . /usr/src/app

The WORKDIR line there creates the directory if it doesn't exist, and updates some image metadata to specify all relative paths, along with the current directory for commands like RUN will be in that location. The VOLUME line there specifies two volumes, one is the relative path ., and the other is /usr/src/app, both just happen to be the same directory. Most often the VOLUME line only contains a single directory, but it can contain multiple as you've done, or it can be a json formatted array.

You cannot specify a volume source in the Dockerfile: A common source of confusion when specifying volumes in a Dockerfile is trying to match the runtime syntax of a source and destination at image build time, this will not work. The Dockerfile can only specify the destination of the volume. It would be a trivial security exploit if someone could define the source of a volume since they could update a common image on the docker hub to mount the root directory into the container and then launch a background process inside the container as part of an entrypoint that adds logins to /etc/passwd, configures systemd to launch a bitcoin miner on next reboot, or searches the filesystem for credit cards, SSNs, and private keys to send off to a remote site.

What does the VOLUME line do? As mentioned, it sets some image metadata to say a directory inside the image is a volume. How is this metadata used? Every time you create a container from this image, docker will force that directory to be a volume. If you do not provide a volume in your run command, or compose file, the only option for docker is to create an anonymous volume. This is a local named volume with a long unique id for the name and no other indication for why it was created or what data it contains (anonymous volumes are were data goes to get lost). If you override the volume, pointing to a named or host volume, your data will go there instead.

VOLUME breaks things: You cannot disable a volume once defined in a Dockerfile. And more importantly, the RUN command in docker is implemented with temporary containers. Those temporary containers will get a temporary anonymous volume. That anonymous volume will be initialized with the contents of your image. Any writes inside the container from your RUN command will be made to that volume. When the RUN command finishes, changes to the image are saved, and changes to the anonymous volume are discarded. Because of this, I strongly recommend against defining a VOLUME inside the Dockerfile. It results in unexpected behavior for downstream users of your image that wish to extend the image with initial data in volume location.

How should you specify a volume? To specify where you want to include volumes with your image, provide a docker-compose.yml. Users can modify that to adjust the volume location to their local environment, and it captures other runtime settings like publishing ports and networking.

Someone should document this! They have. Docker includes warnings on the VOLUME usage in their documentation on the Dockerfile along with advice to specify the source at runtime:

  • Changing the volume from within the Dockerfile: If any build steps change the data within the volume after it has been declared, those changes will be discarded.

...

  • The host directory is declared at container run-time: The host directory (the mountpoint) is, by its nature, host-dependent. This is to preserve image portability, since a given host directory can’t be guaranteed to be available on all hosts. For this reason, you can’t mount a host directory from within the Dockerfile. The VOLUME instruction does not support specifying a host-dir parameter. You must specify the mountpoint when you create or run the container.

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

How to include() all PHP files from a directory?

this is just a modification of Karsten's code

function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        include $filename;
    }
}

include_all_php("my_classes");

jQuery UI Color Picker

Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):

<link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>

If you have those included, try posting your source so we can see what's going on.

Converting Decimal to Binary Java

I just solved this myself, and I wanted to share my answer because it includes the binary reversal and then conversion to decimal. I'm not a very experienced coder but hopefully this will be helpful to someone else.

What I did was push the binary data onto a stack as I was converting it, and then popped it off to reverse it and convert it back to decimal.

import java.util.Scanner;
import java.util.Stack;

public class ReversedBinary 
{
    private Stack<Integer> st;

    public ReversedBinary()
    {
        st = new Stack<>();
    }

    private int decimaltoBinary(int dec)
    {
        if(dec == 0 || dec == 1)
        {
            st.push(dec % 2);
            return dec;
        }

        st.push(dec % 2);

        dec = decimaltoBinary(dec / 2);        

        return dec;
    }

    private int reversedtoDecimal()
    {
        int revDec = st.pop();
        int i = 1;

        while(!st.isEmpty())
        {
            revDec += st.pop() * Math.pow(2, i++);
        }

        return revDec;
    }

    public static void main(String[] args)
    {
        ReversedBinary rev = new ReversedBinary();

        System.out.println("Please enter a positive integer:");

        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine())
        {
            int input = Integer.parseInt(sc.nextLine());
            if(input < 1 || input > 1000000000)
            {
                System.out.println("Integer must be between 1 and 1000000000!");
            }
            else
            {
                rev.decimaltoBinary(input);
                System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
            }
        }

    }
}

Return Index of an Element in an Array Excel VBA

Is this what you are looking for?

public function GetIndex(byref iaList() as integer, byval iInteger as integer) as integer

dim i as integer

 for i=lbound(ialist) to ubound(ialist)
  if iInteger=ialist(i) then
   GetIndex=i
   exit for
  end if
 next i

end function

How to urlencode a querystring in Python?

Note that the urllib.urlencode does not always do the trick. The problem is that some services care about the order of arguments, which gets lost when you create the dictionary. For such cases, urllib.quote_plus is better, as Ricky suggested.

Does VBA have Dictionary Structure?

Yes. For VB6, VBA (Excel), and VB.NET

How do I convert two lists into a dictionary?

You can also use dictionary comprehensions in Python = 2.7:

>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> {k: v for k, v in zip(keys, values)}
{'food': 'spam', 'age': 42, 'name': 'Monty'}

jQuery: Scroll down page a set increment (in pixels) on click?

You can do that using animate like in the following link:

http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery

If you want to do it using scrollTo plugin, then take a look the following:

How to scroll the window using JQuery $.scrollTo() function

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

If you are into following Google's style guide:

Test, [ and [[

[[ ... ]] reduces errors as no path name expansion or word splitting takes place between [[ and ]], and [[ ... ]] allows for regular expression matching where [ ... ] does not.

# This ensures the string on the left is made up of characters in the
# alnum character class followed by the string name.
# Note that the RHS should not be quoted here.
# For the gory details, see
# E14 at https://tiswww.case.edu/php/chet/bash/FAQ
if [[ "filename" =~ ^[[:alnum:]]+name ]]; then
  echo "Match"
fi

# This matches the exact pattern "f*" (Does not match in this case)
if [[ "filename" == "f*" ]]; then
  echo "Match"
fi

# This gives a "too many arguments" error as f* is expanded to the
# contents of the current directory
if [ "filename" == f* ]; then
  echo "Match"
fi

Java reflection: how to get field value from an object, not knowing its class

public abstract class Refl {
    /** Use: Refl.<TargetClass>get(myObject,"x.y[0].z"); */
    public static<T> T get(Object obj, String fieldPath) {
        return (T) getValue(obj, fieldPath);
    }
    public static Object getValue(Object obj, String fieldPath) {
        String[] fieldNames = fieldPath.split("[\\.\\[\\]]");
        String success = "";
        Object res = obj;
        for (String fieldName : fieldNames) {
            if (fieldName.isEmpty()) continue;
            int index = toIndex(fieldName);
            if (index >= 0) {
                try {
                    res = ((Object[])res)[index];
                } catch (ClassCastException cce) {
                    throw new RuntimeException("cannot cast "+res.getClass()+" object "+res+" to array, path:"+success, cce);
                } catch (IndexOutOfBoundsException iobe) {
                    throw new RuntimeException("bad index "+index+", array size "+((Object[])res).length +" object "+res +", path:"+success, iobe);
                }
            } else {
                Field field = getField(res.getClass(), fieldName);
                field.setAccessible(true);
                try {
                    res = field.get(res);
                } catch (Exception ee) {
                    throw new RuntimeException("cannot get value of ["+fieldName+"] from "+res.getClass()+" object "+res +", path:"+success, ee);
                }
            }
            success += fieldName + ".";
        }
        return res;
    }

    public static Field getField(Class<?> clazz, String fieldName) {
        Class<?> tmpClass = clazz;
        do {
            try {
                Field f = tmpClass.getDeclaredField(fieldName);
                return f;
            } catch (NoSuchFieldException e) {
                tmpClass = tmpClass.getSuperclass();
            }
        } while (tmpClass != null);

        throw new RuntimeException("Field '" + fieldName + "' not found in class " + clazz);
    }

    private static int toIndex(String s) {
        int res = -1;
        if (s != null && s.length() > 0 && Character.isDigit(s.charAt(0))) {
            try {
                res = Integer.parseInt(s);
                if (res < 0) {
                    res = -1;
                }
            } catch (Throwable t) {
                res = -1;
            }
        }
        return res;
    }
}

It supports fetching fields and array items, e.g.:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y"));

there is no difference between dots and braces, they are just delimiters, and empty field names are ignored:

System.out.println(""+Refl.getValue(b,"x.q[0].z.y[value]"));
System.out.println(""+Refl.getValue(b,"x.q.1.y.z.value"));
System.out.println(""+Refl.getValue(b,"x[q.1]y]z[value"));

Disable all Database related auto configuration in Spring Boot

I had the same problem here, solved like this:

Just add another application-{yourprofile}.yml where "yourprofile" could be "client".

In my case I just wanted to remove Redis in a Dev profile, so I added a application-dev.yml next to the main application.yml and it did the job.

In this file I put:

spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

this should work with properties files as well.

I like the fact that there is no need to change the application code to do that.

Set content of iframe

Why not use

$iframe.load(function () {
    var $body = $('body', $iframe.get(0).contentWindow.document);
    $body.html(contentDiv);
});

instead of timer ?

Flattening a shallow list in Python

This solution works for arbitrary nesting depths - not just the "list of lists" depth that some (all?) of the other solutions are limited to:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

It's the recursion which allows for arbitrary depth nesting - until you hit the maximum recursion depth, of course...

Converting double to string

double total = 44;
String total2= new Double(total).toString();

this code works

React JSX: selecting "selected" on selected <select> option

Use defaultValue to preselect the values for Select.

<Select defaultValue={[{ value: category.published, label: 'Publish' }]} options={statusOptions} onChange={handleStatusChange} />

Generator expressions vs. list comprehensions

When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:

>>> mylist = ["a", "b", "c"]
>>> gen = (elem + "1" for elem in mylist)
>>> mylist.clear()
>>> for x in gen: print (x)
# nothing

If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.

How do I use sudo to redirect output to a location I don't have permission to write to?

How about writing a script?

Filename: myscript

#!/bin/sh

/bin/ls -lah /root > /root/test.out

# end script

Then use sudo to run the script:

sudo ./myscript

How do I convert a string to a double in Python?

The decimal operator might be more in line with what you are looking for:

>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434

How can I make my string property nullable?

Strings are nullable in C# anyway because they are reference types. You can just use public string CMName { get; set; } and you'll be able to set it to null.

How to calculate md5 hash of a file using javascript

Apart from the impossibility to get file system access in JS, I would not put any trust at all in a client-generated checksum. So generating the checksum on the server is mandatory in any case. – Tomalak Apr 20 '09 at 14:05

Which is useless in most cases. You want the MD5 computed at client side, so that you can compare it with the code recomputed at server side and conclude the upload went wrong if they differ. I have needed to do that in applications working with large files of scientific data, where receiving uncorrupted files were key. My cases was simple, cause users had the MD5 already computed from their data analysis tools, so I just needed to ask it to them with a text field.

How to unit test abstract classes: extend with stubs?

This is the pattern I usually follow when setting up a harness for testing an abstract class:

public abstract class MyBase{
  /*...*/
  public abstract void VoidMethod(object param1);
  public abstract object MethodWithReturn(object param1);
  /*,,,*/
}

And the version I use under test:

public class MyBaseHarness : MyBase{
  /*...*/
  public Action<object> VoidMethodFunction;
  public override void VoidMethod(object param1){
    VoidMethodFunction(param1);
  }
  public Func<object, object> MethodWithReturnFunction;
  public override object MethodWithReturn(object param1){
    return MethodWihtReturnFunction(param1);
  }
  /*,,,*/
}

If the abstract methods are called when I don't expect it, the tests fail. When arranging the tests, I can easily stub out the abstract methods with lambdas that perform asserts, throw exceptions, return different values, etc.

IF/ELSE Stored Procedure

try

IF(@Trans_type = 'subscr_signup')    
BEGIN 
 set @tmpType = 'premium' 
 END
ELSE iF(@Trans_type = 'subscr_cancel')  
  begin
     set    @tmpType = 'basic'  
  END

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

Ctrl+click doesn't work in Eclipse Juno

This bug is really annoying..

The only thing that did the trick for me is deleting the project from the workspace, then deleting the .project and .classpath files and then re import it back to the workspace.

Hope it will help others.

Can an AJAX response set a cookie?

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

How to convert JSON string to array

If you pass the JSON in your post to json_decode, it will fail. Valid JSON strings have quoted keys:

json_decode('{foo:"bar"}');         // this fails
json_decode('{"foo":"bar"}', true); // returns array("foo" => "bar")
json_decode('{"foo":"bar"}');       // returns an object, not an array.

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

Private pages for a private Github repo

This is finally possible for GitHub Enterprise Cloud customers: Access control for GitHub Pages.

To enable access control on Pages, navigate to your repository settings, and click the dropdown menu to toggle between public and private visibility for your site.

enter image description here

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

WordPress overrides PHP's memory limit to 256M, with the assumption that whatever it was set to before is going to be too low to render the dashboard. You can override this by defining WP_MAX_MEMORY_LIMIT in wp-config.php:

define( 'WP_MAX_MEMORY_LIMIT' , '512M' );

I agree with DanFromGermany, 256M is really a lot of memory for rendering a dashboard page. Changing the memory limit is really putting a bandage on the problem.

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.


  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.


So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
      
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.


Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

How do I compare two hashes?

Here is algorithm to deeply compare two Hashes, which also will compare nested Arrays:

    HashDiff.new(
      {val: 1, nested: [{a:1}, {b: [1, 2]}] },
      {val: 2, nested: [{a:1}, {b: [1]}] }
    ).report
# Output:
val:
- 1
+ 2
nested > 1 > b > 1:
- 2

Implementation:

class HashDiff

  attr_reader :left, :right

  def initialize(left, right, config = {}, path = nil)
    @left  = left
    @right = right
    @config = config
    @path = path
    @conformity = 0
  end

  def conformity
    find_differences
    @conformity
  end

  def report
    @config[:report] = true
    find_differences
  end

  def find_differences
    if hash?(left) && hash?(right)
      compare_hashes_keys
    elsif left.is_a?(Array) && right.is_a?(Array)
      compare_arrays
    else
      report_diff
    end
  end

  def compare_hashes_keys
    combined_keys.each do |key|
      l = value_with_default(left, key)
      r = value_with_default(right, key)
      if l == r
        @conformity += 100
      else
        compare_sub_items l, r, key
      end
    end
  end

  private

  def compare_sub_items(l, r, key)
    diff = self.class.new(l, r, @config, path(key))
    @conformity += diff.conformity
  end

  def report_diff
    return unless @config[:report]

    puts "#{@path}:"
    puts "- #{left}" unless left == NO_VALUE
    puts "+ #{right}" unless right == NO_VALUE
  end

  def combined_keys
    (left.keys + right.keys).uniq
  end

  def hash?(value)
    value.is_a?(Hash)
  end

  def compare_arrays
    l, r = left.clone, right.clone
    l.each_with_index do |l_item, l_index|
      max_item_index = nil
      max_conformity = 0
      r.each_with_index do |r_item, i|
        if l_item == r_item
          @conformity += 1
          r[i] = TAKEN
          break
        end

        diff = self.class.new(l_item, r_item, {})
        c = diff.conformity
        if c > max_conformity
          max_conformity = c
          max_item_index = i
        end
      end or next

      if max_item_index
        key = l_index == max_item_index ? l_index : "#{l_index}/#{max_item_index}"
        compare_sub_items l_item, r[max_item_index], key
        r[max_item_index] = TAKEN
      else
        compare_sub_items l_item, NO_VALUE, l_index
      end
    end

    r.each_with_index do |item, index|
      compare_sub_items NO_VALUE, item, index unless item == TAKEN
    end
  end

  def path(key)
    p = "#{@path} > " if @path
    "#{p}#{key}"
  end

  def value_with_default(obj, key)
    obj.fetch(key, NO_VALUE)
  end

  module NO_VALUE; end
  module TAKEN; end

end

Python Iterate Dictionary by Index

There are some very good answers here. I'd like to add the following here as well:

some_dict = {
    "foo": "bar",
    "lorem": "ipsum"
}

for index, (key, value) in enumerate(some_dict.items()):
    print(index, key, value)

results in

0 foo bar
1 lorem ipsum

Appears to work with Python 2.7 and 3.5

How get the base URL via context path in JSF?

URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.

There are several ways to soften the pain:

JSF EL offers a shorthand to ${pageContext.request} in flavor of #{request}:

<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>

You can if necessary use <c:set> tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:

<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>

JSF 2.x offers the <h:link> which can take a view ID relative to the context root in outcome and it will append the context path and FacesServlet mapping automatically:

<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>

HTML offers the <base> tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>.

<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>

(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring(), see also this answer)

This should end up in the generated HTML something like as

<base href="http://example.com/webname/" />

Note that the <base> tag has a caveat: it makes all jump anchors in the page like <a href="#top"> relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a> or <h:link value="top" fragment="top" />.

Set scroll position

Also worth noting window.scrollBy(dx,dy) (ref)

Downloading a file from spring controllers

something like below

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getFile(HttpServletResponse response) {
    try {
        DefaultResourceLoader loader = new DefaultResourceLoader();
        InputStream is = loader.getResource("classpath:META-INF/resources/Accepted.pdf").getInputStream();
        IOUtils.copy(is, response.getOutputStream());
        response.setHeader("Content-Disposition", "attachment; filename=Accepted.pdf");
        response.flushBuffer();
    } catch (IOException ex) {
        throw new RuntimeException("IOError writing file to output stream");
    }
}

You can display PDF or download it examples here

How to calculate probability in a normal distribution given mean & standard deviation?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the probability density function (pdf - likelihood that a random sample X will be near the given value x) for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=100, sigma=12).pdf(98)
# 0.032786643008494994

Also note that the NormalDist object also provides the cumulative distribution function (cdf - probability that a random sample X will be less than or equal to x):

NormalDist(mu=100, sigma=12).cdf(98)
# 0.43381616738909634

How to store token in Local or Session Storage in Angular 2?

As a general rule, the token should not be stored on the localStorage neither the sessionStorage. Both places are accessible from JS and the JS should not care about the authentication token.

IMHO The token should be stored on a cookie with the HttpOnly and Secure flag as suggested here: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Multi-Column Join in Hibernate/JPA Annotations

If this doesn't work I'm out of ideas. This way you get the 4 columns in both tables (as Bar owns them and Foo uses them to reference Bar) and the generated IDs in both entities. The set of 4 columns has to be unique in Bar so the many-to-one relation doesn't become a many-to-many.

@Embeddable
public class AnEmbeddedObject
{
    @Column(name = "column_1")
    private Long column1;
    @Column(name = "column_2")
    private Long column2;
    @Column(name = "column_3")
    private Long column3;
    @Column(name = "column_4")
    private Long column4;
}

@Entity
public class Foo
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name = "column_1", referencedColumnName = "column_1"),
        @JoinColumn(name = "column_2", referencedColumnName = "column_2"),
        @JoinColumn(name = "column_3", referencedColumnName = "column_3"),
        @JoinColumn(name = "column_4", referencedColumnName = "column_4")
    })
    private Bar bar;
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
    "column_1",
    "column_2",
    "column_3",
    "column_4"
}))
public class Bar
{
    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "seqGen")
    @SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1)
    private Long id;
    @Embedded
    private AnEmbeddedObject anEmbeddedObject;
}

How can I check if a MySQL table exists with PHP?

You can use many different queries to check if a table exists. Below is a comparison between several:

mysql_query('select 1 from `table_name` group by 1'); or  
mysql_query('select count(*) from `table_name`');

mysql_query("DESCRIBE `table_name`");  
70000   rows: 24ms  
1000000 rows: 24ms  
5000000 rows: 24ms

mysql_query('select 1 from `table_name`');  
70000   rows: 19ms  
1000000 rows: 23ms  
5000000 rows: 29ms

mysql_query('select 1 from `table_name` group by 1'); or  
mysql_query('select count(*) from `table_name`');  
70000   rows: 18ms  
1000000 rows: 18ms  
5000000 rows: 18ms  

These benchmarks are only averages:

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

For Mojave

Uninstall Any old version of Command Line Tools:

sudo rm -rf /Library/Developer/CommandLineTools

Download and Install Command Line Tools 10.14 Mojave.

Mercurial — revert back to old version and continue from there

I just encountered a case of needing to revert just one file to previous revision, right after I had done commit and push. Shorthand syntax for specifying these revisions isn't covered by the other answers, so here's command to do that

hg revert path/to/file -r-2

That -2 will revert to the version before last commit, using -1 would just revert current uncommitted changes.

Disable elastic scrolling in Safari

I had solved it on iPad. Try, if it works also on OSX.

body, html { position: fixed; }

Works only if you have content smaller then screen or you are using some layout framework (Angular Material in my case).

In Angular Material it is great, that you will disable over-scroll effect of whole page, but inner sections <md-content> can be still scrollable.

How to format a number as percentage in R?

You can use the scales package just for this operation (without loading it with require or library)

scales::percent(m)

How to change the ROOT application?

Not a very good solution but one way is to redirect from the ROOT app to YourWebApp. For this you need to modify the ROOT index.html.

<html>
    <head>
        <title>Redirecting to /YourWebApp</title>
    </head>
    <body onLoad="javascript:window.location='YourWebApp';">
    </body>
</html>

OR

<html>
    <head>
        <title>Redirecting to /YourWebApp</title>
        <meta http-equiv="refresh" content="0;url=YourWebApp" />
    </head>
    <body>
    </body>
</html>

Reference : http://staraphd.blogspot.com/2009/10/change-default-root-folder-in-tomcat.html

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

If you are trying to export display using su and it still doesn't work. This is what worked for me. Try X11 forwarding for sudo users.

Connect the remote host using the -X option with ssh.

# ssh -X root@remote-host

Now list the coockie set for the current user.

# xauth list $DISPLAY
    node01.thegeekdiary.com/unix:10  MIT-MAGIC-COOKIE-1  dacbc5765ec54a1d7115a172147866aa
# echo $DSIPLAY
    localhost:10.0

Switch to another user account using sudo. Add the cookie from the command output above to the sudo user.

# sudo su - [user]
# xauth add node01.thegeekdiary.com/unix:10  MIT-MAGIC-COOKIE-1  dacbc5765ec54a1d7115a172147866aa

Export the display from step 2 again for the sudo user. Try the command xclock to verify if the x client applications are working as expected.

# export DISPLAY=localhost:10.0

source: https://www.thegeekdiary.com/how-to-set-x11-forwarding-export-remote-display-for-users-who-switch-accounts-using-sudo/

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

You're not adding columns to your DataGridView

DataGridView dataGridView1 = new DataGridView();//Create new grid

dataGridView1.Columns[0].Name = "ItemID";// refer to column which is not there 

Is it clear now why you get an exception?

Add this line before you use columns to fix the error

dataGridView1.ColumnCount = 5;

MVC 4 - Return error message from Controller - Show in View

If you want to do a redirect, you can either:

ViewBag.Error = "error message";

or

TempData["Error"] = "error message";

Unable to preventDefault inside passive event listener

For me

document.addEventListener("mousewheel", this.mousewheel.bind(this), { passive: false });

did the trick (the { passive: false } part).

Class has no objects member

This issue happend when I use pylint_runner

So what I do is open .pylintrc file and add this

# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=objects

Get img src with PHP

I know people say you shouldn't use regular expressions to parse HTML, but in this case I find it perfectly fine.

$string = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';
preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $string, $result);
$foo = array_pop($result);

CSS scale down image to fit in containing div, without specifing original size

Hope this will answer the age old problem (Without using CSS background property)

Html

<div class="card-cont">
 <img src="demo.png" />
</div>

Css

.card-cont{
  width:100%;
  height:150px;
}

.card-cont img{
  max-width: 100%;
  min-width: 100%;
  min-height: 150px;
}

Capitalize first letter. MySQL

 select  CONCAT(UCASE(LEFT('CHRIS', 1)),SUBSTRING(lower('CHRIS'),2));

Above statement can be used for first letter CAPS and rest as lower case.

.htaccess not working on localhost with XAMPP

Without seeing your system it's hard to tell what's wrong but try the following (comment answer if these didn't work WITH log error messages)

[STOP your Apache server instance. Ensure it's not running!]

1) move apache server/install to a folder that has no long file names and spaces

2) check httpd.conf in install\conf folder and look for AccessFileName. If it's .htaccess change it to a file name windows accepts (e.g. conf.htaccess)

3) double-check that your htaccess file gets read: add some uninterpretable garbage to it and start server: you should get an Error 500. If you don't, file is not getting read, re-visit httpd.conf file (if that looks OK, check if this is the only file which defines htaccess and it's location and it does at one place -within the file- only; also check if both httpd.conf and htaccess files are accessible: not encrypted, file access rights are not limited, drive/path available -and no long folder path and file names-)
STOP Apache again, then go on:
4) If you have IIS too on your system, stop it (uninstall it too if you can) from services.msc

5) Add the following to the top of your valid htaccess file:
RewriteEngine On
RewriteLog "/path/logs/rewrite.log" #make sure path is there!
RewriteLogLevel 9

6) Empty your [apache]\logs folder (if you use another folder, then that one :)

7) Check the following entries are set and correct:
Action application/x-httpd-php "c:/your-php5-path/php-cgi.exe"
LoadModule php5_module "c:/your-php5-path/php5apache2.dll"
LoadModule rewrite_module modules/mod_rewrite.so
Avoid long path names and spaces in folder names for phpX install too!

8) START apache server

You can do all the steps above or go one-by-one, your call. But at the end of the day make sure you tried everything above!
If system still blows up and you can't fix it, copy&paste error message(s) from log folder for further assistance

How to swap two variables in JavaScript

In ES6 now there is destructuring assignment and you can do:

let a = 1;
let b = 2;
[b, a] = [a, b]  // a = 2, b = 1

Spring cron expression for every after 30 minutes

Graphically, the cron syntax for Quarz is (source):

+-------------------- second (0 - 59)
|  +----------------- minute (0 - 59)
|  |  +-------------- hour (0 - 23)
|  |  |  +----------- day of month (1 - 31)
|  |  |  |  +-------- month (1 - 12)
|  |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
|  |  |  |  |  |  +-- year [optional]
|  |  |  |  |  |  |
*  *  *  *  *  *  * command to be executed 

So if you want to run a command every 30 minutes you can say either of these:

0 0/30 * * * * ?
0 0,30 * * * * ?

You can check crontab expressions using either of these:

  • crontab.guru — (disclaimer: I am not related to that page at all, only that I find it very useful). This page uses UNIX style of cron that does not have seconds in it, while Spring does as the first field.
  • Cron Expression Generator & Explainer - Quartz — cron formatter, allowing seconds also.

Which characters need to be escaped when using Bash?

Characters that need escaping are different in Bourne or POSIX shell than Bash. Generally (very) Bash is a superset of those shells, so anything you escape in shell should be escaped in Bash.

A nice general rule would be "if in doubt, escape it". But escaping some characters gives them a special meaning, like \n. These are listed in the man bash pages under Quoting and echo.

Other than that, escape any character that is not alphanumeric, it is safer. I don't know of a single definitive list.

The man pages list them all somewhere, but not in one place. Learn the language, that is the way to be sure.

One that has caught me out is !. This is a special character (history expansion) in Bash (and csh) but not in Korn shell. Even echo "Hello world!" gives problems. Using single-quotes, as usual, removes the special meaning.

Insert entire DataTable into database at once instead of row by row?

Consider this approach, you don't need a for loop:

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
    bulkCopy.DestinationTableName = 
        "dbo.BulkCopyDemoMatchingColumns";

    try
    {
        // Write from the source to the destination.
        bulkCopy.WriteToServer(ExitingSqlTableName);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

z-index not working with position absolute

Opacity changes the context of your z-index, as does the static positioning. Either add opacity to the element that doesn't have it or remove it from the element that does. You'll also have to either make both elements static positioned or specify relative or absolute position. Here's some background on contexts: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

How do implement a breadth first traversal?

Breadth first is a queue, depth first is a stack.

For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.

For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.

How to get last 7 days data from current datetime to last 7 days in sql server

If you want to do it using Pentaho DI, you can use "Modified JavaScript" Step and write the below function:

dateAdd(d1, "d", -7);  // d1 is the current date and "d" is the date identifier

Check the image below: [Assuming current date is : 22 December 2014]

enter image description here

Hope it helps :)

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

0. Is there any difference between the two errors?

Not really. "Cannot find symbol", "Cannot resolve symbol" and "Symbol not found" all mean the same thing. Different Java compilers use different phraseology.

1. What does a "Cannot find symbol" error mean?

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

  • Keywords: like true, false, class, while, and so on.
  • Literals: like 42 and 'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +, =, {, and so on.
  • Identifiers: like Reader, i, toString, processEquibalancedElephants, and so on.
  • Comments and whitespace.

A "Cannot find symbol" error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

2. What can cause a "Cannot find symbol" error?

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition. This could be caused by a number of things. The common ones are as follows:

  • For identifiers in general:

    • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
    • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
    • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake ...)
    • Perhaps you are trying to use something that was declared "somewhere else"; i.e. in a different context to where you have implicitly told the compiler to look. (A different class? A different scope? A different package? A different code-base?)
  • For identifiers that should refer to variables:

    • Perhaps you forgot to declare the variable.
    • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • For identifiers that should be method or field names:

    • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.

    • Perhaps you are trying to refer to a method or field that does not exist (i.e. has not been declared) in the type you are using; e.g. "someString".push()2.

    • Perhaps you are trying to use a method as a field, or vice versa; e.g. "someString".length or someArray.length().

    • Perhaps you are mistakenly operating on an array rather than array element; e.g.

          String strings[] = ...
          if (strings.charAt(3)) { ... }
          // maybe that should be 'strings[0].charAt(3)'
      
  • For identifiers that should be class names:

    • Perhaps you forgot to import the class.

    • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.

    • Perhaps you forgot a new as in:

          String s = String();  // should be 'new String()'
      
  • For cases where type or instance doesn't appear to have the member you were expecting it to have:

    • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
    • Perhaps you are shadowing a static or instance variable.
    • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction.
    • Perhaps you are using (compiling against) the wrong version of an API.
    • Perhaps you forgot to cast your object to an appropriate subclass.

The problem is often a combination of the above. For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io. Or maybe you meant to write File ... which is a class in java.io.


Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:

List<String> strings = ...

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)


Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:

for (int i = 0; i < 100; i++); {
    System.out.println("i is " + i);
}

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon ( ; ) before the {. The Java language syntax defines a semicolon in that context to be an empty statement. The empty statement then becomes the body of the for loop. So that code actually means this:

for (int i = 0; i < 100; i++); 

// The previous and following are separate statements!!

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, and therefore the previous declaration of i in the for statement is out of scope in the block.


Here is another example of "Cannot find symbol" error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won't find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can't find the symbol Bar. The simple answer is to compile Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

There are some other more obscure causes too ... which I will deal with below.

3. How do I fix these errors ?

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every "correction" is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j. There are many ways I could "fix" that:

  • I could change the inner for to for (int j = 1; j < 10; j++) - probably correct.
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
  • I could change j to i in the inner for loop - probably wrong!
  • and so on.

The point is that you need to understand what your code is trying to do in order to find the right fix.

4. Obscure causes

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.

  1. Incorrect dependencies: If you are using an IDE or a build tool that manages the build path and project dependencies, you may have made a mistake with the dependencies; e.g. left out a dependency, or selected the wrong version. If you are using a build tool (Ant, Maven, Gradle, etc), check the project's build file. If you are using an IDE, check the project's build path configuration.

  2. You are not recompiling: It sometimes happens that new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like ...

  3. An earlier build problem: It is possible that an earlier build failed in a way that gave a JAR file with missing classes. Such a failure would typically be noticed if you were using a build tool. However if you are getting JAR files from someone else, you are dependent on them building properly, and noticing errors. If you suspect this, use tar -tvf to list the contents of the suspect JAR file.

  4. IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation.

    • This could happen if the IDE has been configured with the wrong JDK version.

    • This could happen if the IDE's caches get out of sync with the file system. There are IDE specific ways to fix that.

    • This could be an IDE bug. For instance @Joel Costigliola describes a scenario where Eclipse does not handle a Maven "test" tree correctly: see this answer.

  5. Android issues: When you are programming for Android, and you have "Cannot find symbol" errors related to R, be aware that the R symbols are defined by the context.xml file. Check that your context.xml file is correct and in the correct place, and that the corresponding R class file has been generated / compiled. Note that the Java symbols are case sensitive, so the corresponding XML ids are be case sensitive too.

    Other symbol errors on Android are likely to be due to previously mention reasons; e.g. missing or incorrect dependencies, incorrect package names, method or fields that don't exist in a particular API version, spelling / typing errors, and so on.

  6. Redefining system classes: I've seen cases where the compiler complains that substring is an unknown symbol in something like the following

    String s = ...
    String s1 = s.substring(1);
    

    It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.

    Lesson: Don't define your own classes with the same names as common library classes!

  7. Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.

    You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.


1 - If, perchance, you do see this in a runtime exception or error message, then either you have configured your IDE to run code with compilation errors, or your application is generating and compiling code .. at runtime.

2 - The three basic principles of Civil Engineering: water doesn't flow uphill, a plank is stronger on its side, and you can't push on a string.

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Assume n=2. Then we have 2-1 = 1 on the left side and 2*1/2 = 1 on the right side.

Denote f(n) = (n-1)+(n-2)+(n-3)+...+1

Now assume we have tested up to n=k. Then we have to test for n=k+1.

on the left side we have k+(k-1)+(k-2)+...+1, so it's f(k)+k

On the right side we then have (k+1)*k/2 = (k^2+k)/2 = (k^2 +2k - k)/2 = k+(k-1)k/2 = kf(k)

So this have to hold for every k, and this concludes the proof.

How to obtain Telegram chat_id for a specific user?

Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:

#!/usr/bin/perl

use Data::Dumper;
use WWW::Telegram::BotAPI;

my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
    token => $TOKEN
) or die "I can't connect";

my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";

The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.

You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:

$ sudo cpan WWW::Telegram::BotAPI

Hope this helps

How to swap String characters in Java?

s = s.substring(0, firstChar)
            +s.charAt(secondChar)
            +s.substring(firstChar + 1, secondChar)
            +s.charAt(firstChar)
            +s.substring(secondChar+1);

Turn off axes in subplots

You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.

Rather than using plt.axis('off') you should use ax.axis('off') where ax is a matplotlib.axes object. To do this for your code you simple need to add axarr[0,0].axis('off') and so on for each of your subplots.

The code below shows the result (I've removed the prune_matrix part because I don't have access to that function, in the future please submit fully working code.)

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm

img = mpimg.imread("stewie.jpg")

f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')

axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')

axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')

axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')

plt.show()

Stewie example

Note: To turn off only the x or y axis you can use set_visible() e.g.:

axarr[0,0].xaxis.set_visible(False) # Hide only x axis

Storing JSON in database vs. having a new column for each key

Like most things "it depends". It's not right or wrong/good or bad in and of itself to store data in columns or JSON. It depends on what you need to do with it later. What is your predicted way of accessing this data? Will you need to cross reference other data?

Other people have answered pretty well what the technical trade-off are.

Not many people have discussed that your app and features evolve over time and how this data storage decision impacts your team.

Because one of the temptations of using JSON is to avoid migrating schema and so if the team is not disciplined, it's very easy to stick yet another key/value pair into a JSON field. There's no migration for it, no one remembers what it's for. There is no validation on it.

My team used JSON along side traditional columns in postgres and at first it was the best thing since sliced bread. JSON was attractive and powerful, until one day we realized that flexibility came at a cost and it's suddenly a real pain point. Sometimes that point creeps up really quickly and then it becomes hard to change because we've built so many other things on top of this design decision.

Overtime, adding new features, having the data in JSON led to more complicated looking queries than what might have been added if we stuck to traditional columns. So then we started fishing certain key values back out into columns so that we could make joins and make comparisons between values. Bad idea. Now we had duplication. A new developer would come on board and be confused? Which is the value I should be saving back into? The JSON one or the column?

The JSON fields became junk drawers for little pieces of this and that. No data validation on the database level, no consistency or integrity between documents. That pushed all that responsibility into the app instead of getting hard type and constraint checking from traditional columns.

Looking back, JSON allowed us to iterate very quickly and get something out the door. It was great. However after we reached a certain team size it's flexibility also allowed us to hang ourselves with a long rope of technical debt which then slowed down subsequent feature evolution progress. Use with caution.

Think long and hard about what the nature of your data is. It's the foundation of your app. How will the data be used over time. And how is it likely TO CHANGE?

What's the difference between a temp table and table variable in SQL Server?

In which scenarios does one out-perform the other?

For smaller tables (less than 1000 rows) use a temp variable, otherwise use a temp table.

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

Single controller with multiple GET methods in ASP.NET Web API

In ASP.NET Core 2.0 you can add Route attribute to the controller:

[Route("api/[controller]/[action]")]
public class SomeController : Controller
{
    public SomeValue GetItems(CustomParam parameter) { ... }

    public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}

Copy folder recursively, excluding some folders

You can use find with the -prune option.

An example from man find:

       cd /source-dir
       find . -name .snapshot -prune -o \( \! -name *~ -print0 \)|
       cpio -pmd0 /dest-dir

       This command copies the contents of /source-dir to /dest-dir, but omits
       files  and directories named .snapshot (and anything in them).  It also
       omits files or directories whose name ends in ~,  but  not  their  con-
       tents.  The construct -prune -o \( ... -print0 \) is quite common.  The
       idea here is that the expression before -prune matches things which are
       to  be  pruned.  However, the -prune action itself returns true, so the
       following -o ensures that the right hand side  is  evaluated  only  for
       those  directories  which didn't get pruned (the contents of the pruned
       directories are not even visited, so their  contents  are  irrelevant).
       The  expression on the right hand side of the -o is in parentheses only
       for clarity.  It emphasises that the -print0 action  takes  place  only
       for  things  that  didn't  have  -prune  applied  to them.  Because the
       default `and' condition between tests binds more tightly than -o,  this
       is  the  default anyway, but the parentheses help to show what is going
       on.

What does the 'export' command do?

export in sh and related shells (such as bash), marks an environment variable to be exported to child-processes, so that the child inherits them.

export is defined in POSIX:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

Which MySQL data type to use for storing boolean values

I use TINYINT(1) in order to store boolean values in Mysql.

I don't know if there is any advantage to use this... But if i'm not wrong, mysql can store boolean (BOOL) and it store it as a tinyint(1)

http://dev.mysql.com/doc/refman/5.0/en/other-vendor-data-types.html

How to access Winform textbox control from another class?

I was also facing the same problem where I was not able to appendText to richTextBox of Form class. So I created a method called update, where I used to pass a message from Class1.

class: Form1.cs

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            _Form1 = this;
        }
        public static Form1 _Form1;

        public void update(string message)
        {
            textBox1.Text = message;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 sample = new Class1();            
        }
    }

class: Class1.cs

public class Class1
    {        
        public Class1()
        {
            Form1._Form1.update("change text");
        }        
    }

Determine if char is a num or letter

If (theChar >= '0' && theChar <='9') it's a digit. You get the idea.

React - Preventing Form Submission

No JS needed really ... Just add a type attribute to the button with a value of button

<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>&nbsp;

By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any). Changing the type to "button" prevents that.

Using the HTML5 "required" attribute for a group of checkboxes?

Really simple way to verify if at least one checkbox is checked:

function isAtLeastOneChecked(name) {
    let checkboxes = Array.from(document.getElementsByName(name));
    return checkboxes.some(e => e.checked);
}

Then you can implement whatever logic you want to display an error.

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

Install opencv for Python 3.3

A full instruction relating to James Fletcher's answer can be found here

Particularly for Anaconda distribution I had to modify it this way:

 cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D PYTHON3_PACKAGES_PATH=/anaconda/lib/python3.4/site-packages/ \
    -D PYTHON3_LIBRARY=/anaconda/lib/libpython3.4m.dylib \
    -D PYTHON3_INCLUDE_DIR=/anaconda/include/python3.4m \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D BUILD_EXAMPLES=ON \
    -D BUILD_opencv_python3=ON \
    -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ..

Last line can be ommited (see link above)

How do I declare a namespace in JavaScript?

In JavaScript there are no predefined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. Here is a procedure we follow in Oodles technologies.

Register a NameSpace Following is the function to register a name space

//Register NameSpaces Function
function registerNS(args){
 var nameSpaceParts = args.split(".");
 var root = window;

 for(var i=0; i < nameSpaceParts.length; i++)
 {
  if(typeof root[nameSpaceParts[i]] == "undefined")
   root[nameSpaceParts[i]] = new Object();

  root = root[nameSpaceParts[i]];
 }
}

To register a Namespace just call the above function with the argument as name space separated by '.' (dot). For Example Let your application name is oodles. You can make a namespace by following method

registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;

Basically it will create your NameSpaces structure like below in backend:

var oodles = {
    "HomeUtilities": {},
    "GlobalUtilities": {}
};

In the above function you have register a namespace called "oodles.HomeUtilities" and "oodles.GlobalUtilities". To call these namespaces we make an variable i.e. var $OHU and var $OGU.

These variables are nothing but an alias to Intializing the namespace. Now, Whenever you declare a function that belong to HomeUtilities you will declare it like following:

$OHU.initialization = function(){
    //Your Code Here
};

Above is the function name initialization and it is put into an namespace $OHU. and to call this function anywhere in the script files. Just use following code.

$OHU.initialization();

Similarly, with the another NameSpaces.

Hope it helps.

How to change the commit author for one specific commit?

The answers in the question to which you linked are good answers and cover your situation (the other question is more general since it involves rewriting multiple commits).

As an excuse to try out git filter-branch, I wrote a script to rewrite the Author Name and/or Author Email for a given commit:

#!/bin/sh

#
# Change the author name and/or email of a single commit.
#
# change-author [-f] commit-to-change [branch-to-rewrite [new-name [new-email]]]
#
#     If -f is supplied it is passed to "git filter-branch".
#
#     If <branch-to-rewrite> is not provided or is empty HEAD will be used.
#     Use "--all" or a space separated list (e.g. "master next") to rewrite
#     multiple branches.
#
#     If <new-name> (or <new-email>) is not provided or is empty, the normal
#     user.name (user.email) Git configuration value will be used.
#

force=''
if test "x$1" = "x-f"; then
    force='-f'
    shift
fi

die() {
    printf '%s\n' "$@"
    exit 128
}
targ="$(git rev-parse --verify "$1" 2>/dev/null)" || die "$1 is not a commit"
br="${2:-HEAD}"

TARG_COMMIT="$targ"
TARG_NAME="${3-}"
TARG_EMAIL="${4-}"
export TARG_COMMIT TARG_NAME TARG_EMAIL

filt='

    if test "$GIT_COMMIT" = "$TARG_COMMIT"; then
        if test -n "$TARG_EMAIL"; then
            GIT_AUTHOR_EMAIL="$TARG_EMAIL"
            export GIT_AUTHOR_EMAIL
        else
            unset GIT_AUTHOR_EMAIL
        fi
        if test -n "$TARG_NAME"; then
            GIT_AUTHOR_NAME="$TARG_NAME"
            export GIT_AUTHOR_NAME
        else
            unset GIT_AUTHOR_NAME
        fi
    fi

'

git filter-branch $force --env-filter "$filt" -- $br

Find if current time falls in a time range

Try using the TimeRange object in C# to complete your goal.

TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");

bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);

Here is where I got that example of using TimeRange

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

Counting the number of option tags in a select tag in jQuery

In a multi-select option box, you can use $('#input1 :selected').length; to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.

function refreshButtons () {
    if ($('#input :selected').length == 0)
    {
        $('#submit').attr ('disabled', 'disabled');
    }
    else
    {
        $('#submit').removeAttr ('disabled');
    }
}

How do you make a deep copy of an object?

A safe way is to serialize the object, then deserialize. This ensures everything is a brand new reference.

Here's an article about how to do this efficiently.

Caveats: It's possible for classes to override serialization such that new instances are not created, e.g. for singletons. Also this of course doesn't work if your classes aren't Serializable.

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

How set maximum date in datepicker dialog in android?

      Calendar cal = Calendar.getInstance();
      datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
    //To set make max 7days date selection on current year and month
    datePickerDialog.getDatePicker().setMaxDate((cal.getTimeInMillis())+(1000*60*60*24*6));

    datePickerDialog.setTitle("Select Date");
    datePickerDialog.show();

Can I get the name of the current controller in the view?

controller_path holds the path of the controller used to serve the current view. (ie: admin/settings).

and

controller_name holds the name of the controller used to serve the current view. (ie: settings).

Problems with jQuery getJSON using local files in Chrome

Another way to do it is to start a local HTTP server on your directory. On Ubuntu and MacOs with Python installed, it's a one-liner.

Go to the directory containing your web files, and :

python -m SimpleHTTPServer

Then connect to http://localhost:8000/index.html with any web browser to test your page.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

How can I copy columns from one sheet to another with VBA in Excel?

Selecting is often unnecessary. Try this

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

How do I determine the size of my array in C?

Beside the answers already provided, I want to point out a special case by the use of

sizeof(a) / sizeof (a[0])

If a is either an array of char, unsigned char or signed char you do not need to use sizeof twice since a sizeof expression with one operand of these types do always result to 1.

Quote from C18,6.5.3.4/4:

"When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1."

Thus, sizeof(a) / sizeof (a[0]) would be equivalent to NUMBER OF ARRAY ELEMENTS / 1 if a is an array of type char, unsigned char or signed char. The division through 1 is redundant.

In this case, you can simply abbreviate and do:

sizeof(a)

For example:

char a[10];
size_t length = sizeof(a);

If you want a proof, here is a link to GodBolt.


Nonetheless, the division maintains safety, if the type significantly changes (although these cases are rare).

Declaration of Methods should be Compatible with Parent Methods in PHP

Just to expand on this error in the context of an interface, if you are type hinting your function parameters like so:

interface A

use Bar;

interface A
{
    public function foo(Bar $b);
}

Class B

class B implements A
{
    public function foo(Bar $b);
}

If you have forgotten to include the use statement on your implementing class (Class B), then you will also get this error even though the method parameters are identical.

How to remove outliers from a dataset

OK, you should apply something like this to your dataset. Do not replace & save or you'll destroy your data! And, btw, you should (almost) never remove outliers from your data:

remove_outliers <- function(x, na.rm = TRUE, ...) {
  qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
  H <- 1.5 * IQR(x, na.rm = na.rm)
  y <- x
  y[x < (qnt[1] - H)] <- NA
  y[x > (qnt[2] + H)] <- NA
  y
}

To see it in action:

set.seed(1)
x <- rnorm(100)
x <- c(-10, x, 10)
y <- remove_outliers(x)
## png()
par(mfrow = c(1, 2))
boxplot(x)
boxplot(y)
## dev.off()

And once again, you should never do this on your own, outliers are just meant to be! =)

EDIT: I added na.rm = TRUE as default.

EDIT2: Removed quantile function, added subscripting, hence made the function faster! =)

enter image description here

C# code to validate email address

What about this?

bool IsValidEmail(string email)
{
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch {
        return false;
    }
}

Per Stuart's comment, this compares the final address with the original string instead of always returning true. MailAddress tries to parse a string with spaces into "Display Name" and "Address" portions, so the original version was returning false positives.


To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.

Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:

  • cog@wheel
  • "cogwheel the orange"@example.com
  • 123@$.xyz

For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.

Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow as an email address."


As for using exception handling for business logic, I agree that is a thing to be avoided. But this is one of those cases where the convenience and clarity may outweigh the dogma.

Besides, if you do anything else with the e-mail address, it's probably going to involve turning it to a MailAddress. Even if you don't use this exact function, you will probably want to use the same pattern. You can also check for specific kinds of failure by catching different exceptions: null, empty, or invalid format.


--- Further reading ---

Documentation for System.Net.Mail.MailAddress

Explanation of what makes up a valid email address

How to add custom method to Spring Data JPA

I extends the SimpleJpaRepository:

public class ExtendedRepositoryImpl<T extends EntityBean> extends SimpleJpaRepository<T, Long>
    implements ExtendedRepository<T> {

    private final JpaEntityInformation<T, ?> entityInformation;

    private final EntityManager em;

    public ExtendedRepositoryImpl(final JpaEntityInformation<T, ?> entityInformation,
                                                      final EntityManager entityManager) {
       super(entityInformation, entityManager);
       this.entityInformation = entityInformation;
       this.em = entityManager;
    }
}

and adds this class to @EnableJpaRepositoryries repositoryBaseClass.

while EOF in JAVA?

while(inFile.hasNext())

This is correct in java programming language

Oracle PL/SQL - How to create a simple array variable?

Sample programs as follows and provided on link also https://oracle-concepts-learning.blogspot.com/

plsql table or associated array.

        DECLARE 
            TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20); 
            salary_list salary; 
            name VARCHAR2(20); 
        BEGIN 
           -- adding elements to the table 
           salary_list('Rajnish') := 62000; salary_list('Minakshi') := 75000; 
           salary_list('Martin') := 100000; salary_list('James') := 78000; 
           -- printing the table name := salary_list.FIRST; WHILE name IS NOT null 
            LOOP 
               dbms_output.put_line ('Salary of ' || name || ' is ' || 
               TO_CHAR(salary_list(name))); 
               name := salary_list.NEXT(name); 
            END LOOP; 
        END; 
        /

How to Make A Chevron Arrow Using CSS?

Responsive Chevrons / arrows

they resize automatically with your text and are colored the same color. Plug and play :)
jsBin demo playground

enter image description here

_x000D_
_x000D_
body{
  font-size: 25px; /* Change font and  see the magic! */
  color: #f07;     /* Change color and see the magic! */
} 

/* RESPONSIVE ARROWS */
[class^=arr-]{
  border:       solid currentColor;
  border-width: 0 .2em .2em 0;
  display:      inline-block;
  padding:      .20em;
}
.arr-right {transform:rotate(-45deg);}
.arr-left  {transform:rotate(135deg);}
.arr-up    {transform:rotate(-135deg);}
.arr-down  {transform:rotate(45deg);}
_x000D_
This is <i class="arr-right"></i> .arr-right<br>
This is <i class="arr-left"></i> .arr-left<br>
This is <i class="arr-up"></i> .arr-up<br>
This is <i class="arr-down"></i> .arr-down
_x000D_
_x000D_
_x000D_

DataGrid get selected rows' column values

UPDATED

To get the selected rows try:

IList rows = dg.SelectedItems;

You should then be able to get to the column value from a row item.

OR

DataRowView row = (DataRowView)dg.SelectedItems[0];

Then:

row["ColumnName"];

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

Web API Put Request generates an Http 405 Method Not Allowed error

Another cause of this could be if you don't use the default variable name for the "id" which is actually: id.

Using grep to help subset a data frame in R

You may also use the stringr package

library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))

You may not use '^' (starts with) in this case, to obtain the results you need

insert echo into the specific html element like div which has an id or class

Have you tried this?:

    $string = '';
    while($row = mysql_fetch_array($result))
    {
    //this will combine all the results into one string
    $string .= '<img src="'.$row['name'].'" />
                <div>'.$row['name'].'</div>
                <div>'.$row['title'].'</div>
                <div>'.$row['description'].'</div>
                <div>'.$row['link'].'</div><br />';

    //or this will add the individual result in an array
 /*
     $yourHtml[] = $row;
*/
    }

then you echo the $tring to the place you want it to be

<div id="place_here">
   <?php echo $string; ?>
   <?php 
     //or
    /*
      echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
    */
    ?>
</div>

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

How to get the currently logged in user's user id in Django?

Assuming you are referring to Django's Auth User, in your view:

def game(request):
  user = request.user

  gta = Game.objects.create(name="gta", owner=user)

How to create a zip file in Java

There is another option by using zip4j at https://github.com/srikanth-lingala/zip4j

Creating a zip file with single file in it / Adding single file to an existing zip

new ZipFile("filename.zip").addFile("filename.ext"); Or

new ZipFile("filename.zip").addFile(new File("filename.ext"));

Creating a zip file with multiple files / Adding multiple files to an existing zip

new ZipFile("filename.zip").addFiles(Arrays.asList(new File("first_file"), new File("second_file")));

Creating a zip file by adding a folder to it / Adding a folder to an existing zip

new ZipFile("filename.zip").addFolder(new File("/user/myuser/folder_to_add"));

Creating a zip file from stream / Adding a stream to an existing zip new ZipFile("filename.zip").addStream(inputStream, new ZipParameters());

Waiting for HOME ('android.process.acore') to be launched

None of these solutions worked for me. Instead, what worked was to go to a command line tool (or terminal in Mac), CD into the SDK/platform-tools directory, and then run this:

adb kill-server

then run this:

adb start-server

After I did this everything worked again. Why? Who knows.

On my MAC the path to the platform-tools folder was $HOME/Installations/adt-bundle-mac-x86_64-20130522/sdk/platform-tools It will probably be somewhere else on your machine.

I also found this page that presents some helpful steps:

http://android.okhelp.cz/android-emulator-wont-run-application-started-from-eclipse/

How to run Gulp tasks sequentially one after the other

I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):

gulp.task('develop', ['clean'], function () {
  gulp.start('coffee');
});

How to get first and last element in an array in java?

Check this

double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

How to pass a value from one Activity to another in Android?

Thats trivial, use Intent.putExtra to pass data to activity you start. Use then Bundle.getExtra to retrieve it.

There are lots of such questions already https://stackoverflow.com/search?q=How+to+pass+a+value+from+one+Activity+to+another+in+Android be sure to use search first next time.

Angular 1 - get current URL parameters

Better would have been generate url like

app.dev/backend?type=surveys&id=2

and then use

var type=$location.search().type;
var id=$location.search().id;

and inject $location in controller.

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

Django CSRF Cookie Not Set

I had the same error, in my case adding method_decorator helps:

from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator

method_decorator(csrf_protect)
def post(self, request):
    ...

How do I install chkconfig on Ubuntu?

The command chkconfig is no longer available in Ubuntu.The equivalent command to chkconfig is update-rc.d.This command nearly supports all the new versions of ubuntu.

The similar commands are

update-rc.d <service> defaults

update-rc.d <service> start 20 3 4 5

update-rc.d -f <service>  remove

React.js: onChange event for contentEditable

This probably isn't exactly the answer you're looking for, but having struggled with this myself and having issues with suggested answers, I decided to make it uncontrolled instead.

When editable prop is false, I use text prop as is, but when it is true, I switch to editing mode in which text has no effect (but at least browser doesn't freak out). During this time onChange are fired by the control. Finally, when I change editable back to false, it fills HTML with whatever was passed in text:

/** @jsx React.DOM */
'use strict';

var React = require('react'),
    escapeTextForBrowser = require('react/lib/escapeTextForBrowser'),
    { PropTypes } = React;

var UncontrolledContentEditable = React.createClass({
  propTypes: {
    component: PropTypes.func,
    onChange: PropTypes.func.isRequired,
    text: PropTypes.string,
    placeholder: PropTypes.string,
    editable: PropTypes.bool
  },

  getDefaultProps() {
    return {
      component: React.DOM.div,
      editable: false
    };
  },

  getInitialState() {
    return {
      initialText: this.props.text
    };
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.editable && !this.props.editable) {
      this.setState({
        initialText: nextProps.text
      });
    }
  },

  componentWillUpdate(nextProps) {
    if (!nextProps.editable && this.props.editable) {
      this.getDOMNode().innerHTML = escapeTextForBrowser(this.state.initialText);
    }
  },

  render() {
    var html = escapeTextForBrowser(this.props.editable ?
      this.state.initialText :
      this.props.text
    );

    return (
      <this.props.component onInput={this.handleChange}
                            onBlur={this.handleChange}
                            contentEditable={this.props.editable}
                            dangerouslySetInnerHTML={{__html: html}} />
    );
  },

  handleChange(e) {
    if (!e.target.textContent.trim().length) {
      e.target.innerHTML = '';
    }

    this.props.onChange(e);
  }
});

module.exports = UncontrolledContentEditable;

How to add a "open git-bash here..." context menu to the windows explorer?

Add the gitpath to the Environment-path variable (e.g. C:\Program Files\Git\cmd) by which you can access git from any folder using command line.

Is there a shortcut to make a block comment in Xcode?

In XCode 10 (and up) use Option + Command + Slash (that is ? + ? + /)

to write a beautiful comment for your function or class like below:

XCode screenshot of doc comment

Change <select>'s option and trigger events with JavaScript

You can fire the event manually after changing the selected option on the onclick event doing: document.getElementById("sel").onchange();

Spring Boot - How to get the running port

Starting with Spring Boot 1.4.0 you can use this in your test:

import org.springframework.boot.context.embedded.LocalServerPort;

@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {

  @LocalServerPort
  int randomPort;

  // ...
}

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

Is there a way to get the XPath in Google Chrome?

press Cntl + Shift + C
select the element you wish to get its XPath by clicking on it
right click on the highlighted part in the console
copy -> copy XPath

enter image description here

How to create a database from shell command?

Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

What is bootstrapping?

As the question is answered. For web develoment. I came so far and found a good explanation about bootsrapping in Laravel doc. Here is the link

In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes.

hope it will help someone who learning web application development.

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

How to pass a JSON array as a parameter in URL

& is a keyword for the next parameter like this ur?param1=1&param2=2

so effectively you send a second param named R". You should urlencode your string. Isn't POST an option?