Programs & Examples On #Undo

Undo is a command in many computer programs. It erases the last change done to the document reverting it to an older state. In some more advanced programs such as graphic processing, undo will negate the last command done to the file being edited.

How do I "un-revert" a reverted Git commit?

After the initial panic of accidentally deleting all my files, I used the following to get my data back

git reset HEAD@{1}         
git fsck --lost-found      
git show 
git revert <sha that deleted the files>

How do I undo the most recent local commits in Git?

You can use git revert <commit-id>.

And for getting the commit ID, just use git log.

How to recover the deleted files using "rm -R" command in linux server?

Not possible with standard unix commands. You might have luck with a file recovery utility. Also, be aware, using rm changes the table of contents to mark those blocks as available to be overwritten, so simply using your computer right now risks those blocks being overwritten permanently. If it's critical data, you should turn off the computer before the file sectors gets overwritten. Good luck!

Some restore utility: http://www.ubuntugeek.com/recover-deleted-files-with-foremostscalpel-in-ubuntu.html

Forum where this was previously answered: http://webcache.googleusercontent.com/search?q=cache:m4hiPw-_GekJ:ubuntuforums.org/archive/index.php/t-1134955.html+&cd=1&hl=en&ct=clnk&gl=us

SVN undo delete before commit

You could remove the folder and update the parent directory before committing:

rm -r some_dir

svn update some_dir_parent

Can I delete a git commit but keep the changes?

I think you are looking for this

git reset --soft HEAD~1

It undoes the most recent commit whilst keeping the changes made in that commit to staging.

How to undo a git pull?

Reset the master branch:

git reset --hard origin/master

Undo working copy modifications of one file in Git?

If your file is already staged (happens when you do a git add etc after the file is edited) to unstage your changes.

Use

git reset HEAD <file>

Then

git checkout <file>

If not already staged, just use

git checkout <file>

How to undo "git commit --amend" done instead of "git commit"

  1. Checkout to temporary branch with last commit

    git branch temp HEAD@{1}

  2. Reset last commit

    git reset temp

  3. Now, you'll have all files your commit as well as previous commit. Check status of all the files.

    git status

  4. Reset your commit files from git stage.

    git reset myfile1.js (so on)

  5. Reattach this commit

    git commit -C HEAD@{1}

  6. Add and commit your files to new commit.

How to uncommit my last commit in Git

To keep the changes from the commit you want to undo

git reset --soft HEAD^

To destroy the changes from the commit you want to undo

git reset --hard HEAD^

You can also say

git reset --soft HEAD~2

to go back 2 commits.

Edit: As charsi mentioned, if you are on Windows you will need to put HEAD or commit hash in quotes.

git reset --soft "HEAD^"
git reset --soft "asdf"

Undoing a git rebase

It annoys me to no end that none of these answers is fully automatic, despite the fact that it should be automatable (at least mostly). I created a set of aliases to try to remedy this:

# Useful commands
#################

# Undo the last rebase
undo-rebase = "! f() { : git reset ; PREV_COMMIT=`git x-rev-before-rebase` && git reset --merge \"$PREV_COMMIT\" \"$@\";}; f"

# See what changed since the last rebase
rdiff = "!f() { : git diff ; git diff `git x-rev-before-rebase` "$@";}; f"

# Helpers
########
# Get the revision before the last rebase started
x-rev-before-rebase = !git reflog --skip=1 -1 \"`git x-start-of-rebase`\" --format=\"%gD\"

# Get the revision that started the rebase
x-start-of-rebase = reflog --grep-reflog '^rebase (start)' -1 --format="%gD"

You should be able to tweak this to allow going back an arbitrary number of rebases pretty easily (juggling the args is the trickiest part), which can be useful if you do a number of rebases in quick succession and mess something up along the way.

Caveats

It will get confused if any commit messages begin with "rebase (start)" (please don't do this). You could make the regex more resilient to improve the situation by matching something like this for your regex:

--grep-reflog "^rebase (start): checkout " 

WARNING: not tested (regex may need adjustments)

The reason I haven't done this is because I'm not 100% that a rebase always begins with a checkout. Can anyone confirm this?

[If you're curious about the null (:) commands at the beginning of the function, that's a way of setting up bash completions for the aliases]

Reset local repository branch to be just like remote repository HEAD

Have you forgotten to create a feature-branch and have committed directly on master by mistake?

You can create the feature branch now and set master back without affecting the worktree (local filesystem) to avoid triggering builds, tests and trouble with file-locks:

git checkout -b feature-branch
git branch -f master origin/master

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

This is the main difference between use git reset --hard and git reset --soft:

--soft

Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since are discarded.

Undo a Git merge that hasn't been pushed yet

It is strange that the simplest command was missing. Most answers work, but undoing the merge you just did, this is the easy and safe way:

git reset --merge ORIG_HEAD

The ref ORIG_HEAD will point to the original commit from before the merge.

(The --merge option has nothing to do with the merge. It's just like git reset --hard ORIG_HEAD, but safer since it doesn't touch uncommitted changes.)

git undo all uncommitted or unsaved changes

I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:

1) just need to reset the workspace file status

enter image description here 2) select all unstage files (command +a), right click and select remove

enter image description here

It's that simple :D

How to go back (ctrl+z) in vi/vim

Just in normal mode press:

  • u - undo,
  • Ctrl + r - redo changes which were undone (undo the undos).

Undo and Redo

How to make in CSS an overlay over an image?

A bit late for this, but this thread comes up in Google as a top result when searching for an overlay method.

You could simply use a background-blend-mode

.foo {
    background-image: url(images/image1.png), url(images/image2.png);
    background-color: violet;
    background-blend-mode: screen multiply;
}

What this does is it takes the second image, and it blends it with the background colour by using the multiply blend mode, and then it blends the first image with the second image and the background colour by using the screen blend mode. There are 16 different blend modes that you could use to achieve any overlay.

multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.

Adding background image to div using CSS

To use an image for body background in CSS

body {
  background-image: url("image.jpg");
}

Formatting DataBinder.Eval data

After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.

The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.

So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:

default.aspx

<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>

default.aspx.cs code:

public partial class _Default : System.Web.UI.Page
{

    protected string GetDateInHomepageFormat(DateTime d)
    {

        string retValue = "";

        // Do all processing required and return value

        return retValue;
    }
}

Hope this helps others as well.

How can we dynamically allocate and grow an array

You have to manually create a new bigger array and copy over the items.

this may help

How to do a SOAP wsdl web services call from the command line

For Windows:

Save the following as MSFT.vbs:

set SOAPClient = createobject("MSSOAP.SOAPClient")
SOAPClient.mssoapinit "https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc?wsdl"
WScript.Echo "MSFT = " & SOAPClient.GetQuote("MSFT")

Then from a command prompt, run:

C:\>MSFT.vbs

Reference: http://blogs.msdn.com/b/bgroth/archive/2004/10/21/246155.aspx

Efficient way to add spaces between characters in a string

s = "BINGO"
print(" ".join(s))

Should do it.

Can I set a TTL for @Cacheable

Spring 3.1 and Guava 1.13.1:

@EnableCaching
@Configuration
public class CacheConfiguration implements CachingConfigurer {

    @Override
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {

            @Override
            protected Cache createConcurrentMapCache(final String name) {
                return new ConcurrentMapCache(name,
                    CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
            }
        };

        return cacheManager;
    }

    @Override
    public KeyGenerator keyGenerator() {
        return new DefaultKeyGenerator();
    }

}

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

How can I reset or revert a file to a specific revision?

This is a very simple step. Checkout file to the commit id we want, here one commit id before, and then just git commit amend and we are done.

# git checkout <previous commit_id> <file_name>
# git commit --amend

This is very handy. If we want to bring any file to any prior commit id at the top of commit, we can easily do.

How to check if object has been disposed in C#

If you're not sure whether the object has been disposed or not, you should call the Dispose method itself rather than methods such as Close. While the framework doesn't guarantee that the Dispose method must run without exceptions even if the object had previously been disposed, it's a common pattern and to my knowledge implemented on all disposable objects in the framework.

The typical pattern for Dispose, as per Microsoft:

public void Dispose() 
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);      
}

protected virtual void Dispose(bool disposing)
{
    // If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
    {
        if (disposing) {
            if (_resource != null)
                _resource.Dispose();
                Console.WriteLine("Object disposed.");
        }

        // Indicate that the instance has been disposed.
        _resource = null;
        _disposed = true;   
    }
}

Notice the check on _disposed. If you were to call a Dispose method implementing this pattern, you could call Dispose as many times as you wanted without hitting exceptions.

Exit a while loop in VBS/VBA

While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.

check = 0 

Do while not rs.EOF 
   if rs("reg_code") = rcode then 
      check = 1 
      Response.Write ("Found") 
      Exit do
   else 
      rs.MoveNext 
    end if 
Loop 

if check = 0 then 
   Response.Write "Not Found" 
end if}

How to set a radio button in Android

If you want to do it in code, you can call the check member of RadioGroup:

radioGroup.check(R.id.radioButtonId);

This will check the button you specify and uncheck the others.

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

If you use XAMPP Path ( $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; ) C:\xampp\phpmyadmin\config.inc.php (Probably XAMPP1.8 at Line Number 34)

Another Solution: I face same type problem "#1142 - SELECT command denied to user ''@'localhost' for table 'pma_recent'"

  1. open phpmyadmin==>setting==>Navigation frame==> Recently used tables==>0(set the value 0) ==> Save

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

How do I instantiate a JAXBElement<String> object?

When you imported the WSDL, you should have an ObjectFactory class which should have bunch of methods for creating various input parameters.

ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);

Why is volatile needed in C?

Volatile is also useful, when you want to force the compiler not to optimize a specific code sequence (e.g. for writing a micro-benchmark).

How to load a resource bundle from a file resource in Java?

ResourceBundle rb = ResourceBundle.getBundle("service"); //service.properties
System.out.println(rb.getString("server.dns")); //server.dns=http://....

How to update gradle in android studio?

On Mac, open terminal and run the following commands as per instructions:

$ curl -s https://get.sdkman.io | bash

then

$ sdk install gradle 3.0

Once the installation is complete, the terminal would ask whether to set it as a default version so type y and make it the default version.

Now open Android Studio -> Terminal and run the following command

Gradle --version

Want to upgrade project from Angular v5 to Angular v6

Just use the official upgrade guide which will tell you what you need to do for your own particular needs:

Upgrade angular

https://update.angular.io/

Angular2 get clicked element id

When your HTMLElement doesn't have an id, name or class to call,

then use

<input type="text" (click)="selectedInput($event)">

selectedInput(event: MouseEvent) {
   log(event.srcElement) // HTMInputLElement
}

Get json value from response

var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301

results is now an object.

Accessing items in an collections.OrderedDict by index

If you have pandas installed, you can convert the ordered dict to a pandas Series. This will allow random access to the dictionary elements.

>>> import collections
>>> import pandas as pd
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'

>>> s = pd.Series(d)

>>> s['bar']
spam
>>> s.iloc[1]
spam
>>> s.index[1]
bar

How can I remove Nan from list Python/NumPy

use numpy fancy indexing:

In [29]: countries=np.asarray(countries)

In [30]: countries[countries!='nan']
Out[30]: 
array(['USA', 'UK', 'France'], 
      dtype='|S6')

jQuery if statement, syntax

jQuery is just a library which enhances the capabilities of the DOM within a web browser; the underlying language is JavaScript, which has, as you might hope to expect from a programming language, the ability to perform conditional logic, i.e.

if( condition ) {
    // do something
}

Testing two conditions is straightforward, too:

if( A && B ) {
    // do something
}

Dear God, I hope this isn't a troll...

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

How do I allow HTTPS for Apache on localhost?

Another simple method is using Python Server in Ubuntu.

  1. Generate server.xml with the following command in terminal:

    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes

    Note: Assuming you have openssl installed.

  2. Save below code in a file named simple-https-server.py in any directory you want to run the server.

    import BaseHTTPServer, SimpleHTTPServer
    import ssl
    
    httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
    httpd.serve_forever()
    
  3. Run the server from terminal:

    python simple-https-server.py

  4. Visit the page at:

    https://localhost:4443

Extra notes::

  1. You can change the port in simple-https-server.py file in line

    httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)

  2. You can change localhost to your IP in the same line above:

    httpd = BaseHTTPServer.HTTPServer(('10.7.1.3', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)

    and access the page on any device your network connected. This is very handy in cases like "you have to test HTML5 GeoLocation API in a mobile, and Chrome restricts the API in secure connections only".

Gist: https://gist.github.com/dergachev/7028596

http://www.piware.de/2011/01/creating-an-https-server-in-python/

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

How to create cross-domain request?

In fact, there is nothing to do in Angular2 regarding cross domain requests. CORS is something natively supported by browsers. This link could help you to understand how it works:

To be short, in the case of cross domain request, the browser automatically adds an Origin header in the request. There are two cases:

  • Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
  • Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

So in fact most of work must be done on the server side to return the CORS headers. The main one is the Access-Control-Allow-Origin one.

200 OK HTTP/1.1
(...)
Access-Control-Allow-Origin: *

To debug such issues, you can use developer tools within browsers (Network tab).

Regarding Angular2, simply use the Http object like any other requests (same domain for example):

return this.http.get('https://angular2.apispark.net/v1/companies/')
           .map(res => res.json()).subscribe(
  ...
);

What is private bytes, virtual bytes, working set?

There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.

Long story short:

if I call

p=malloc(1000);
free(p);

then the Private Bytes reflect only the allocation, not the deallocation.

if I call

p=malloc(>512k);
free(p);

then the Private Bytes correctly reflect the allocation and the deallocation.

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

Angular-cli from css to scss

Open angular.json file

1.change from

"schematics": {}

to

"schematics": {
           "@schematics/angular:component": {
                   "styleext": "scss"       
             }  
  }
  1. change from (at two places)

"src/styles.css"

to

"src/styles.scss"

then check and rename all .css files and update component.ts files styleUrls from .css to .scss

"The semaphore timeout period has expired" error for USB connection

Too many big files all in one go. Windows barfs. Essentially the copying took too long because you asked too much of the computer and the file locking was locked too long and set a flag off, the flag is a semaphore error.

The computer stuffed itself and choked on it. I saw the RAM memory here get progressively filled with a Cache in RAM. Then when filled the subsystem ground to a halt with a semaphore error.

I have a workaround; copy or transfer fewer files not one humongous block. Break it down into sets of blocks and send across the files one at a time, maybe a few at a time, but not never the lot.

References:

https://appuals.com/how-to-fix-the-semaphore-timeout-period-has-expired-0x80070079/

https://www-01.ibm.com/support/docview.wss?uid=swg21094630

How can I determine if a variable is 'undefined' or 'null'?

You can check if the value is undefined or null by simply using typeof:

if(typeof value == 'undefined'){

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

How to order events bound with jQuery

If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.

$('#mydiv').click(function(e) {
    // maniplate #mydiv ...
    $('#mydiv').trigger('mydiv-manipulated');
});

$('#mydiv').bind('mydiv-manipulated', function(e) {
    // do more stuff now that #mydiv has been manipulated
    return;
});

Something like that at least.

PHP isset() with multiple parameters

Use the php's OR (||) logical operator for php isset() with multiple operator e.g

if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {

}

Understanding The Modulus Operator %

lets put it in this way:
actually Modulus operator does the same division but it does not care about the answer , it DOES CARE ABOUT reminder for example if you divide 7 to 5 ,
so , lets me take you through a simple example:
think 5 is a block, then for example we going to have 3 blocks in 15 (WITH Nothing Left) , but when that loginc comes to this kinda numbers {1,3,5,7,9,11,...} , here is where the Modulus comes out , so take that logic that i said before and apply it for 7 , so the answer gonna be that we have 1 block of 5 in 7 => with 2 reminds in our hand! that is the modulus!!!
but you were asking about 5 % 7 , right ?
so take the logic that i said , how many 7 blocks do we have in 5 ???? 0
so the modulus returns 0...
that's it ...

Return single column from a multi-dimensional array

very simple go for this

$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma 

How to run a command as a specific user in an init script?

Adding this answer as I had to lookup multiple places to achieve my use case. I had a script that runs on startup. This script runs process as a specific (passwordless) user and is running on multiple linux flavors. Here are options on different flavors: (I have taken java as target process for example)

1. RHEL / CentOS 6:

source /etc/rc.d/init.d/functions
daemon --user=myUser $JAVA_HOME/bin/java

2. RHEL 7 / SUSE12 / other linux flavors where systemd is used:

In your systemd unit file add:

User=myUser

3. Suse 11:

/sbin/startproc -u myUser $JAVA_HOME/bin/java

Convert JSONObject to Map

This is what worked for me:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonobj.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            Object value = jsonobj.get(key);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }   
            map.put(key, value);
        }   return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }
            else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }   return list;
}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java

CSS Circular Cropping of Rectangle Image

The accepted answer probably works for some situations, but it depends on the ratio of the rectangle and any predetermined styles.

I use this method because it's more compatible than solutions only using object-fit:

_x000D_
_x000D_
.image-cropper {
   width: 150px;
   height: 150px;
   position: relative;
   overflow: hidden;
   border-radius: 50%;
   border:2px solid #f00;
}

/* Common img styles in web dev environments */
img {
   height: auto;
   max-width: 100%;
}

/* Center image inside of parent */
img.center {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

/* For horizontal rectangles */
img.horizontal {
   height: 100%;
   width: auto;
   max-width: 9999px; /* max-content fall back */
   max-width: max-content;
}
_x000D_
<div class="image-cropper">
  <img src="https://via.placeholder.com/300x600" class="center" />
</div>

<div class="image-cropper">
  <img src="https://via.placeholder.com/600x300" class="horizontal center" />
</div>
_x000D_
_x000D_
_x000D_

If you run the snippet you can see, for horizontal rectangles we add another class .horizontal.

We override max-width to allow the img to go larger than 100% of the width. This preserves the aspect ratio, preventing the image from stretching.

However, the image will not be centered and that's where the .centered class comes in. It uses a great centering trick to absolute position the image in the center both vertically and horizontally.

More information on the centering at CSS Tricks

More than likely you won't always know what ratio the image will be, so this is why I'd suggest using javascript to target the img and add the .horizontal class if needed.

Here is a stack overflow answer that would work

Java Spring - How to use classpath to specify a file location?

Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean

<bean class="test.Test1">
        <property name="path" value="classpath:/test/test1.xml" />
    </bean>

and you get it in your bean as Resource:

public void setPath(Resource path) throws IOException {
    File file = path.getFile();
    System.out.println(file);
    }

output

D:\workspace1\spring\target\test-classes\test\test1.xml

Now you can use it in new FileReader(file)

How can I check for existence of element in std::vector, in one line?

int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
  //elem exists in the vector
} 

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

This error can occur if you are installing a package with a different bitness than your Python version. To see whether your Python installation is 32- or 64-bit, see here.

Some superpacks (e.g. for Scipy) available on SourceForge or python.org are for 32-bit systems and some are for 64-bit systems. See this answer. In Windows, uninstalling the 32-bit and installing the 64-bit version (or vice versa if your installation is 32-bit) can solve the problem.

Python script header

Yes, there is - python may not be in /usr/bin, but for example in /usr/local/bin (BSD).

When using virtualenv, it may even be something like ~/projects/env/bin/python

How to call a method after a delay in Android

For a Simple line Handle Post delay, you can do as following :

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do someting
    }
}, 3000);

I hope this helps

Get encoding of a file in Windows

If you have "git" or "Cygwin" on your Windows Machine, then go to the folder where your file is present and execute the command:

file *

This will give you the encoding details of all the files in that folder.

How to get page content using cURL?

Try This:

$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

Ternary operator in PowerShell

I've recently improved (open PullRequest) the ternary conditional and null-coalescing operators in the PoweShell lib 'Pscx'
Pls have a look for my solution.


My github topic branch: UtilityModule_Invoke-Operators

Functions:

Invoke-Ternary
Invoke-TernaryAsPipe
Invoke-NullCoalescing
NullCoalescingAsPipe

Aliases

Set-Alias :?:   Pscx\Invoke-Ternary                     -Description "PSCX alias"
Set-Alias ?:    Pscx\Invoke-TernaryAsPipe               -Description "PSCX alias"
Set-Alias :??   Pscx\Invoke-NullCoalescing              -Description "PSCX alias"
Set-Alias ??    Pscx\Invoke-NullCoalescingAsPipe        -Description "PSCX alias"

Usage

<condition_expression> |?: <true_expression> <false_expression>

<variable_expression> |?? <alternate_expression>

As expression you can pass:
$null, a literal, a variable, an 'external' expression ($b -eq 4) or a scriptblock {$b -eq 4}

If a variable in the variable expression is $null or not existing, the alternate expression is evaluated as output.

How to recover MySQL database from .myd, .myi, .frm files

Simple! Create a dummy database (say abc)

Copy all these .myd, .myi, .frm files to mysql\data\abc wherein mysql\data\ is the place where .myd, .myi, .frm for all databases are stored.

Then go to phpMyadmin, go to db abc and you find your database.

jQuery - find table row containing table cell containing specific text

$(function(){
    var search = 'foo';
    $("table tr td").filter(function() {
        return $(this).text() == search;
    }).parent('tr').css('color','red');
});

Will turn the text red for rows which have a cell whose text is 'foo'.

How to set the LDFLAGS in CMakeLists.txt?

Look at:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Create a jTDS connection string

jdbc:jtds:sqlserver://x.x.x.x/database replacing x.x.x.x with the IP or hostname of your SQL Server machine.

jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS

or

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS

If you are wanting to set the username and password in the connection string too instead of against a connection object separately:

jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS;user=foo;password=bar

(Updated my incorrect information and add reference to the instance syntax)

Collections.sort with multiple fields

If the StudentNumber is numeric it will not be sorted numeric but alphanumeric. Do not expect

"2" < "11"

it will be:

"11" < "2"

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0
 ...
#endif

Double precision - decimal places

A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.

This is odd, so I'll show an extreme example. If we make a super simple floating point value that holds only 3 binary digits of accuracy, and no mantissa or sign (so range is 0-0.875), our options are:

binary - decimal
000    - 0.000
001    - 0.125
010    - 0.250
011    - 0.375
100    - 0.500
101    - 0.625
110    - 0.750
111    - 0.875

But if you do the numbers, this format is only accurate to 0.903089987 decimal digits. Not even 1 digit is accurate. As is easy to see, since there's no value that begins with 0.4?? nor 0.9??, and yet to display the full accuracy, we require 3 decimal digits.

tl;dr: The debugger shows you the value of the floating point variable to some arbitrary precision (19 digits in your case), which doesn't necessarily correlate with the accuracy of the floating point format (17 digits in your case).

Cannot find pkg-config error

for me, (OSX) the problem was solved doing this:

brew install pkg-config

How can I make Bootstrap columns all the same height?

So yes, Bootstrap 4 does make all the cols in a row equal height, however if you are creating a border around the content inside the row you may find that it appears like the cols are not equal heights!

When I applied height: 100% to the element inside the col I found that I lost my margin.

My solution is to use padding on the col's div (instead of a margin on the inner element). Like so:

<div class="container">
    <div class="row">
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
        <div class="col-lg-4 col-md-6 col-12 py-4">
            <div class="h-100 border round">
                        ...
            </div>
        </div>
    </div>
</div>

The above code example uses Bootstrap 4.1 to create a set of nine boxes with a border

"ImportError: no module named 'requests'" after installing with pip

Run in command prompt.

pip list

Check what version you have installed on your system if you have an old version.

Try to uninstall the package...

pip uninstall requests

Try after to install it:

pip install requests

You can also test if pip does not do the job.

easy_install requests

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

Two color borders

Simply write

style="border:medium double;"

for the html tag

Why are my PHP files showing as plain text?

You need to configure Apache (the webserver) to process PHP scripts as PHP. Check Apache's configuration. You need to load the module (the path may differ on your system):

LoadModule php5_module "c:/php/php5apache.dll"

And you also need to tell Apache what to process with PHP:

AddType application/x-httpd-php .php

See the documentation for more details.

Rails how to run rake task

You can run Rake tasks from your shell by running:

rake task_name

To run from from Ruby (e.g., in the Rails console or another Rake task):

Rake::Task['task_name'].invoke

To run multiple tasks in the same namespace with a single task, create the following new task in your namespace:

task :runall => [:iqmedier, :euroads, :mikkelsen, :orville] do
  # This will run after all those tasks have run
end

Escape dot in a regex range

Because the dot is inside character class (square brackets []).

Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):

Any character except ^-]\ add that character to the possible matches for the character class.

Is SMTP based on TCP or UDP?

In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.

As defined in RFC 821, RFC 2821, and RFC 5321:

SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.

In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.

In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.


The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.

Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.

What is [Serializable] and when should I use it?

Some practical uses for the [Serializable] attribute:

  • Saving object state using binary serialisation; you can very easily 'save' entire object instances in your application to a file or network stream and then recreate them by deserialising - check out the BinaryFormatter class in System.Runtime.Serialization.Formatters.Binary
  • Writing classes whose object instances can be stored on the clipboard using Clipboard.SetData() - nonserialisable classes cannot be placed on the clipboard.
  • Writing classes which are compatible with .NET Remoting; generally, any class instance you pass between application domains (except those which extend from MarshalByRefObject) must be serialisable.

These are the most common usage cases that I have come across.

What is the difference between angular-route and angular-ui-router?

ngRoute is a module built by the Angular team that provides basic client-side routing functionality. This module provides a fairly powerful base for routing, and can be built upon pretty easily to give solid routing functionality, as exemplified in this blog post (be sure to read the comment trail between Ward Bell and Ben Nadel, the author - they are a couple of Angular pros)

ui-router shifts the focus from url-centric routes to application "states", which may or may not be reflected in the url.

The primary features added by ui-router are nested states and named views.

Nested states allow you to separate controller logic for the various pieces of the application. A very simple example of this would be an app with primary navigation across the top, a secondary navigation list along the left, and content on the right. Without nested states, a single controller would typically have to handle the display logic for the secondary navigation as well as the content. Nested routing allows you to separate these concerns.

Named views are another additional feature of ui-router. With ngRoute, you can only have a single ngView directive on a page, whereas with named views in ui-router you can specify multiple ui-view directives, and then each state is able to affect the template and controller of the names views. A super simple example of this would be to have the main content of your app be the primary view, and then to also have a footer bar that would be a separate ui-view. In this scenario, the footer's controller no longer has to listen for state/route changes.

A good comparison of ngRoute and ui-router can be found on this podcast episode.

Just to make things more confusing, keep an eye on the new "official" routing module that the Angular team is expecting to release for versions 1.5 and 2.0 of Angular. This will be replacing the ngRoute module. Here is the current documentation for the new Router module - it is fairly sparse as of this posting since the implementation has not yet been finalized. Watch here for more news on when this module will actually be released.

When to use margin vs padding in CSS

It's good to know the differences between margin and padding. Here are some differences:

  • Margin is outer space of an element, while padding is inner space of an element.

  • Margin is the space outside the border of an element, while padding is the space inside the border of it.

  • Margin accepts the value of auto: margin: auto, but you can't set padding to auto.

  • Margin can be set to any number, but padding must be non-negative.

  • When you style an element, padding will also be affected (e.g. background color), but not margin.

List vs tuple, when to use each?

A minor but notable advantage of a list over a tuple is that lists tend to be slightly more portable. Standard tools are less likely to support tuples. JSON, for example, does not have a tuple type. YAML does, but its syntax is ugly compared to its list syntax, which is quite nice.

In those cases, you may wish to use a tuple internally then convert to list as part of an export process. Alternately, you might want to use lists everywhere for consistency.

Linq to Entities join vs groupjoin

Let's suppose you have two different classes:

public class Person
{
    public string Name, Email;
    
    public Person(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
class Data
{
    public string Mail, SlackId;
    
    public Data(string mail, string slackId)
    {
        Mail = mail;
        SlackId = slackId;
    }
}

Now, let's Prepare data to work with:

var people = new Person[]
    {
        new Person("Sudi", "[email protected]"),
        new Person("Simba", "[email protected]"),
        new Person("Sarah", string.Empty)
    };
    
    var records = new Data[]
    {
        new Data("[email protected]", "Sudi_Try"),
        new Data("[email protected]", "Sudi@Test"),
        new Data("[email protected]", "SimbaLion")
    };

You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.

Let's now construct the query to join Person with Data:

var query = people.Join(records,
        x => x.Email,
        y => y.Mail,
        (person, record) => new { Name = person.Name, SlackId = record.SlackId});
    Console.WriteLine(query);

After constructing the query, you could also iterate over it with a foreach like so:

foreach (var item in query)
    {
        Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
    }

Let's also output the result for GroupJoin:

Console.WriteLine(
    
        people.GroupJoin(
            records,
            x => x.Email,
            y => y.Mail,
            (person, recs) => new {
                Name = person.Name,
                SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
            }
        ));

You will notice that the GroupJoin will put all SlackIds in a single group.

How to concatenate strings in windows batch file for loop?

In batch you could do it like this:

@echo off

setlocal EnableDelayedExpansion

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do (
  set "var=%%sxyz"
  svn co "!var!"
)

If you don't need the variable !var! elsewhere in the loop, you could simplify that to

@echo off

setlocal

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do svn co "%%sxyz"

However, like C.B. I'd prefer PowerShell if at all possible:

$string_list = 'str1', 'str2', 'str3', ... 'str10'

$string_list | ForEach-Object {
  $var = "${_}xyz"   # alternatively: $var = $_ + 'xyz'
  svn co $var
}

Again, this could be simplified if you don't need $var elsewhere in the loop:

$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

Template/HTML File (component.ts)

<select>
 <option *ngFor="let v of values" [value]="v" (ngModelChange)="onChange($event)">  
    {{v.name}}
  </option>
</select>

Typescript File (component.ts)

values = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

onChange(cityEvent){
    console.log(cityEvent); // It will display the select city data
}

(ngModelChange) is the @Output of the ngModel directive. It fires when the model changes. You cannot use this event without the ngModel directive

Populate unique values into a VBA array from Excel

Profiting from the MS Excel 365 function UNIQUE()

In order to enrich the valid solutions above:

Sub ExampleCall()
Dim rng As Range: Set rng = Sheet1.Range("A2:A11")   ' << change to your sheet's Code(Name)
Dim a: a = rng
a = getUniques(a)
arrInfo a
End Sub
Function getUniques(a, Optional ZeroBased As Boolean = True)
Dim tmp: tmp = Application.Transpose(WorksheetFunction.Unique(a))
If ZeroBased Then ReDim Preserve tmp(0 To UBound(tmp) - 1)
getUniques = tmp
End Function

Understanding colors on Android (six characters)

On Android the color can be declared in the following format

#AARRGGBB

AA - is the bit that’s of most interest to us, it stands for alpha channel

RR GG BB - red, green & blue channels respectively

Now in order to add transparency to our color we need to prepend it with hexadecimal value representing the alpha (transparency).

For example if you want to set 80% transparency value to black color (#000000) you need to prepend it with CC, as a result we end up with the following color resource #CC000000.

You can read about it in more detail on my blog https://androidexplained.github.io/android/ui/2020/10/12/hex-color-code-transparency.html

Create an empty data.frame

Just declare

table = data.frame()

when you try to rbind the first line it will create the columns

How to change color and font on ListView

If you just need to change some parameters of the View and the default behavior of ArrayAdapter its OK for you:

 import android.content.Context;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;

 public class CustomArrayAdapter<T> extends ArrayAdapter<T> {

    public CustomArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

            // Here all your customization on the View
            view.setBackgroundColor(.......);
            ...

        return view;
    }


 }

Form Submission without page refresh

<script type="text/javascript">
    var frm = $('#myform');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok');
            }
        });

        ev.preventDefault();
    });
</script>

<form id="myform" action="/your_url" method="post">
    ...
</form>

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

How do I check for equality using Spark Dataframe without SQL Query?

In Spark 2.4

To compare with one value:

df.filter(lower(trim($"col_name")) === "<value>").show()

To compare with collection of value:

df.filter($"col_name".isInCollection(new HashSet<>(Arrays.asList("value1", "value2")))).show()

Increasing the JVM maximum heap size for memory intensive applications

When you are using JVM in 32-bit mode, the maximum heap size that can be allocated is 1280 MB. So, if you want to go beyond that, you need to invoke JVM in 64-mode.

You can use following:

$ java -d64 -Xms512m -Xmx4g HelloWorld

where,

  • -d64: Will enable 64-bit JVM
  • -Xms512m: Will set initial heap size as 512 MB
  • -Xmx4g: Will set maximum heap size as 4 GB

You can tune in -Xms and -Xmx as per you requirements (YMMV)

A very good resource on JVM performance tuning, which might want to look into: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html

What's the best way to generate a UML diagram from Python source code?

Epydoc is a tool to generate API documentation from Python source code. It also generates UML class diagrams, using Graphviz in fancy ways. Here is an example of diagram generated from the source code of Epydoc itself.

Because Epydoc performs both object introspection and source parsing it can gather more informations respect to static code analysers such as Doxygen: it can inspect a fair amount of dynamically generated classes and functions, but can also use comments or unassigned strings as a documentation source, e.g. for variables and class public attributes.

How can I reuse a navigation bar on multiple pages?

A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml extension. For instance this would be your index.shtml file:

<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>

Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).

SQL Call Stored Procedure for each Row without using a cursor

I usually do it this way when it's a quite a few rows:

  1. Select all sproc parameters in a dataset with SQL Management Studio
  2. Right-click -> Copy
  3. Paste in to excel
  4. Create single-row sql statements with a formula like '="EXEC schema.mysproc @param=" & A2' in a new excel column. (Where A2 is your excel column containing the parameter)
  5. Copy the list of excel statements into a new query in SQL Management Studio and execute.
  6. Done.

(On larger datasets i'd use one of the solutions mentioned above though).

Prevent direct access to a php include file

The easiest way is to set some variable in the file that calls include, such as

$including = true;

Then in the file that's being included, check for the variable

if (!$including) exit("direct access not permitted");

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

If you are using docker service and you have switched to other network. You need to restart docker service.

service docker restart

This solved my problem in docker.

Search for exact match of string in excel row using VBA Macro

This is not another code as you have already helped yourself; but for you to take a look at the performance when using Excel functions in VBA.

PS: **On a latter note, if you wish to do pattern matching then you may consider ScriptingObject **Regex.

ORA-28000: the account is locked error getting frequently

Check the PASSWORD_LOCK_TIME parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock command.

Trying Gradle build - "Task 'build' not found in root project"

run

gradle clean 

then try

gradle build 

it worked for me

How to convert a negative number to positive?

If you are working with numpy you can use

import numpy as np
np.abs(-1.23)
>> 1.23

It will provide absolute values.

Is there way to use two PHP versions in XAMPP?

Use this php switcher

You can control php version to any your project you want via vhost config.

How many threads is too many?

In most cases you should allow the thread pool to handle this. If you post some code or give more details it might be easier to see if there is some reason the default behavior of the thread pool would not be best.

You can find more information on how this should work here: http://en.wikipedia.org/wiki/Thread_pool_pattern

How to check if directory exists in %PATH%?

-contains worked for me

$pathToCheck = "c:\some path\to\a\file.txt"

$env:Path - split ';' -contains $pathToCheck

To add the path when it does not exist yet I use

$pathToCheck = "c:\some path\to\a\file.txt"

if(!($env:Path -split ';' -contains $vboxPath)) {
  $documentsDir = [Environment]::GetFolderPath("MyDocuments")
  $profileFilePath = Join-Path $documentsDir "WindowsPowerShell/profile.ps1"
  Out-File -FilePath $profileFilePath -Append -Force -Encoding ascii -InputObject "`$env:Path += `";$pathToCheck`""
  Invoke-Expression -command $profileFilePath
}

How can I sanitize user input with PHP?

No. You can't generically filter data without any context of what it's for. Sometimes you'd want to take a SQL query as input and sometimes you'd want to take HTML as input.

You need to filter input on a whitelist -- ensure that the data matches some specification of what you expect. Then you need to escape it before you use it, depending on the context in which you are using it.

The process of escaping data for SQL - to prevent SQL injection - is very different from the process of escaping data for (X)HTML, to prevent XSS.

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Another simple solution (not very elegant, but not too ugly also) is to place a inner div / span then get his height ($(this).find('span).height()).

Here is an example of using this strategy:

_x000D_
_x000D_
$(".more").click(function(){_x000D_
if($(this).parent().find('.showMore').length) {_x000D_
$(this).parent().find('.showMore').removeClass('showMore').css('max-height','90px');_x000D_
$(this).parent().find('.more').removeClass('less').text('More');_x000D_
} else {_x000D_
$(this).parent().find('.text').addClass('showMore').css('max-height',$(this).parent().find('span').height());_x000D_
$(this).parent().find('.more').addClass('less').text('Less');_x000D_
}_x000D_
});
_x000D_
* {transition: all 0.5s;}_x000D_
.text {position:relative;width:400px;max-height:90px;overflow:hidden;}_x000D_
.showMore {}_x000D_
.text::after {_x000D_
  content: "";_x000D_
    position: absolute; bottom: 0; left: 0;_x000D_
        box-shadow: inset 0 -26px 22px -17px #fff;_x000D_
    height: 39px;_x000D_
  z-index:99999;_x000D_
  width:100%;_x000D_
  opacity:1;_x000D_
}_x000D_
.showMore::after {opacity:0;}_x000D_
.more {border-top:1px solid gray;width:400px;color:blue;cursor:pointer;}_x000D_
.more.less {border-color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="text">_x000D_
<span>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</span></div>_x000D_
<div class="more">More</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(This specific example is using this trick to animate the max-height and avoiding animation delay when collapsing (when using high number for the max-height property).

How to Use UTF-8 Collation in SQL Server database?

No! It's not a joke.

Take a look here: http://msdn.microsoft.com/en-us/library/ms186939.aspx

Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set.

And also here: http://en.wikipedia.org/wiki/UTF-16

The older UCS-2 (2-byte Universal Character Set) is a similar character encoding that was superseded by UTF-16 in version 2.0 of the Unicode standard in July 1996.

Anaconda version with Python 3.5

command install:

  • python3.5: conda install python=3.5
  • python3.6: conda install python=3.6

download the most recent Anaconda installer:

  • python3.5: Anaconda 4.2.0
  • python3.6: Anaconda 5.2.0

reference from anaconda doc:

PHP PDO with foreach and fetch

foreach over a statement is just a syntax sugar for the regular one-way fetch() loop. If you want to loop over your data more than once, select it as a regular array first

$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO

How do I set a value in CKEditor with Javascript?

<textarea id="editor1" name="editor1">This is sample text</textarea>

<div id="trackingDiv" ></div>

<script type="text/javascript">
    CKEDITOR.replace( 'editor1' );

</script>

Let try this..

Update :

To set data :

Create instance First::

var editor = CKEDITOR.instances['editor1'];

Then,

editor.setData('your data');

or

editor.insertHtml('your html data');

or

editor.insertText('your text data');  

And Retrieve data from your editor::

editor.getData();

If change the particular para HTML data in CKEditor.

var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');

These are the possible ways that I know in CKEditor

How to add meta tag in JavaScript

$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');

or

var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);

Though I'm not certain it will have an affect as it will be generated after the page is loaded

If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx

This may allow other meta tags, if you're lucky

Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx

Convert HTML + CSS to PDF

Fine rendering doesn't mean anything. Does it validate?

All browsers do the most they can to just show something on the screen, no matter how bad the input. And of course they do not do the same thing. If you want the same rendering as FireFox, you could use its rendering engine. There are pdf generators for it. It is an awful lot of work, though.

How to get JSON objects value if its name contains dots?

Just to make use of updated solution try using lodash utility https://lodash.com/docs#get

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

Just to put it out there, i had the same problems. On my local homestead it would work as expected but after pushing it to the development server i got the session timeout message as well. Figuring its a environment issue i changed from apache to nginx and that miraculously made the problem go away.

Process list on Linux via Python

I would use the subprocess module to execute the command ps with appropriate options. By adding options you can modify which processes you see. Lot's of examples on subprocess on SO. This question answers how to parse the output of ps for example:)

You can, as one of the example answers showed also use the PSI module to access system information (such as the process table in this example).

Write output to a text file in PowerShell

Another way this could be accomplished is by using the Start-Transcript and Stop-Transcript commands, respectively before and after command execution. This would capture the entire session including commands.

Start-Transcript

Stop-Transcript

For this particular case Out-File is probably your best bet though.

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

Implement Validation for WPF TextBoxes

There a 3 ways to implement validation:

  1. Validation Rule
  2. Implementation of INotifyDataErrorInfo
  3. Implementation of IDataErrorInfo

Validation rule example:

public class NumericValidationRule : ValidationRule
{
    public Type ValidationType { get; set; }
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string strValue = Convert.ToString(value);

        if (string.IsNullOrEmpty(strValue))
            return new ValidationResult(false, $"Value cannot be coverted to string.");
        bool canConvert = false;
        switch (ValidationType.Name)
        {

            case "Boolean":
                bool boolVal = false;
                canConvert = bool.TryParse(strValue, out boolVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of boolean");
            case "Int32":
                int intVal = 0;
                canConvert = int.TryParse(strValue, out intVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int32");
            case "Double":
                double doubleVal = 0;
                canConvert = double.TryParse(strValue, out doubleVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Double");
            case "Int64":
                long longVal = 0;
                canConvert = long.TryParse(strValue, out longVal);
                return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int64");
            default:
                throw new InvalidCastException($"{ValidationType.Name} is not supported");
        }
    }
}

XAML:

Very important: don't forget to set ValidatesOnTargetUpdated="True" it won't work without this definition.

 <TextBox x:Name="Int32Holder"
         IsReadOnly="{Binding IsChecked,ElementName=CheckBoxEditModeController,Converter={converters:BooleanInvertConverter}}"
         Style="{StaticResource ValidationAwareTextBoxStyle}"
         VerticalAlignment="Center">
    <!--Text="{Binding Converter={cnv:TypeConverter}, ConverterParameter='Int32', Path=ValueToEdit.Value, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"-->
    <TextBox.Text>
        <Binding Path="Name"
                 Mode="TwoWay"
                 UpdateSourceTrigger="PropertyChanged"
                 Converter="{cnv:TypeConverter}"
                 ConverterParameter="Int32"
                 ValidatesOnNotifyDataErrors="True"
                 ValidatesOnDataErrors="True"
                 NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <validationRules:NumericValidationRule ValidationType="{x:Type system:Int32}"
                                                       ValidatesOnTargetUpdated="True" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
    <!--NumericValidationRule-->
</TextBox>

INotifyDataErrorInfo example:

public abstract class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
{

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        ValidateAsync();
    }
    #endregion


    public virtual void OnLoaded()
    {
    }

    #region INotifyDataErrorInfo
    private ConcurrentDictionary<string, List<string>> _errors = new ConcurrentDictionary<string, List<string>>();

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public void OnErrorsChanged(string propertyName)
    {
        var handler = ErrorsChanged;
        if (handler != null)
            handler(this, new DataErrorsChangedEventArgs(propertyName));
    }

    public IEnumerable GetErrors(string propertyName)
    {
        List<string> errorsForName;
        _errors.TryGetValue(propertyName, out errorsForName);
        return errorsForName;
    }

    public bool HasErrors
    {
        get { return _errors.Any(kv => kv.Value != null && kv.Value.Count > 0); }
    }

    public Task ValidateAsync()
    {
        return Task.Run(() => Validate());
    }

    private object _lock = new object();
    public void Validate()
    {
        lock (_lock)
        {
            var validationContext = new ValidationContext(this, null, null);
            var validationResults = new List<ValidationResult>();
            Validator.TryValidateObject(this, validationContext, validationResults, true);

            foreach (var kv in _errors.ToList())
            {
                if (validationResults.All(r => r.MemberNames.All(m => m != kv.Key)))
                {
                    List<string> outLi;
                    _errors.TryRemove(kv.Key, out outLi);
                    OnErrorsChanged(kv.Key);
                }
            }

            var q = from r in validationResults
                    from m in r.MemberNames
                    group r by m into g
                    select g;

            foreach (var prop in q)
            {
                var messages = prop.Select(r => r.ErrorMessage).ToList();

                if (_errors.ContainsKey(prop.Key))
                {
                    List<string> outLi;
                    _errors.TryRemove(prop.Key, out outLi);
                }
                _errors.TryAdd(prop.Key, messages);
                OnErrorsChanged(prop.Key);
            }
        }
    }
    #endregion

}

View Model Implementation:

public class MainFeedViewModel : BaseViewModel//, IDataErrorInfo
{
    private ObservableCollection<FeedItemViewModel> _feedItems;
    [XmlIgnore]
    public ObservableCollection<FeedItemViewModel> FeedItems
    {
        get
        {
            return _feedItems;
        }
        set
        {
            _feedItems = value;
            OnPropertyChanged("FeedItems");
        }
    }
    [XmlIgnore]
    public ObservableCollection<FeedItemViewModel> FilteredFeedItems
    {
        get
        {
            if (SearchText == null) return _feedItems;

            return new ObservableCollection<FeedItemViewModel>(_feedItems.Where(x => x.Title.ToUpper().Contains(SearchText.ToUpper())));
        }
    }

    private string _title;
    [Required]
    [StringLength(20)]
    //[CustomNameValidationRegularExpression(5, 20)]
    [CustomNameValidationAttribute(3, 20)]
    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            OnPropertyChanged("Title");
        }
    }
    private string _url;
    [Required]
    [StringLength(200)]
    [Url]
    //[CustomValidation(typeof(MainFeedViewModel), "UrlValidation")]
    /// <summary>
    /// Validation of URL should be with custom method like the one that implemented below, or with 
    /// </summary>
    public string Url
    {
        get { return _url; }
        set
        {
            _url = value;
            OnPropertyChanged("Url");
        }
    }

    public MainFeedViewModel(string url, string title)
    {
        Title = title;
        Url = url;
    }
    /// <summary>
    /// 
    /// </summary>
    public MainFeedViewModel()
    {

    }
    public MainFeedViewModel(ObservableCollection<FeedItemViewModel> feeds)
    {
        _feedItems = feeds;
    }


    private string _searchText;
    [XmlIgnore]
    public string SearchText
    {
        get { return _searchText; }
        set
        {
            _searchText = value;

            OnPropertyChanged("SearchText");
            OnPropertyChanged("FilteredFeedItems");
        }
    }

    #region Data validation local
    /// <summary>
    /// Custom URL validation method
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public static ValidationResult UrlValidation(object obj, ValidationContext context)
    {
        var vm = (MainFeedViewModel)context.ObjectInstance;
        if (!Uri.IsWellFormedUriString(vm.Url, UriKind.Absolute))
        {
            return new ValidationResult("URL should be in valid format", new List<string> { "Url" });
        }
        return ValidationResult.Success;
    }

    #endregion
}

XAML:

<UserControl x:Class="RssReaderTool.Views.AddNewFeedDialogView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300"
             d:DesignWidth="300">
    <FrameworkElement.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate x:Name="TextErrorTemplate">
                        <DockPanel LastChildFill="True">
                            <AdornedElementPlaceholder>
                                <Border BorderBrush="Red"
                                        BorderThickness="2" />
                            </AdornedElementPlaceholder>
                            <TextBlock FontSize="20"
                                       Foreground="Red">*?*</TextBlock>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError"
                         Value="True">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource=
            {x:Static RelativeSource.Self},
            Path=(Validation.Errors)[0].ErrorContent}"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
        <!--<Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError"
                         Value="true">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)[0].ErrorContent}" />
                </Trigger>
            </Style.Triggers>
        </Style>-->
    </FrameworkElement.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="5" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="5" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock Text="Feed Name"
                   ToolTip="Display" />
        <TextBox Text="{Binding MainFeedViewModel.Title,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
                 Grid.Column="2" />

        <TextBlock Text="Feed Url"
                   Grid.Row="2" />
        <TextBox Text="{Binding MainFeedViewModel.Url,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
                 Grid.Column="2"
                 Grid.Row="2" />
    </Grid>
</UserControl>

IDataErrorInfo:

View Model:

public class OperationViewModel : ViewModelBase, IDataErrorInfo
{
    private const int ConstCodeMinValue = 1;
    private readonly IEventAggregator _eventAggregator;
    private OperationInfoDefinition _operation;
    private readonly IEntityFilterer _contextFilterer;
    private OperationDescriptionViewModel _description;

    public long Code
    {
        get { return _operation.Code; }
        set
        {
            if (SetProperty(value, _operation.Code, o => _operation.Code = o))
            {
                UpdateDescription();
            }
        }
    }

    public string Description
    {
        get { return _operation.Description; }
        set
        {
            if (SetProperty(value, _operation.Description, o => _operation.Description = o))
            {
                UpdateDescription();
            }
        }
    }

    public string FriendlyName
    {
        get { return _operation.FriendlyName; }
        set
        {
            if (SetProperty(value, _operation.FriendlyName, o => _operation.FriendlyName = o))
            {
                UpdateDescription();
            }
        }
    }

    public int Timeout
    {
        get { return _operation.Timeout; }
        set
        {
            if (SetProperty(value, _operation.Timeout, o => _operation.Timeout = o))
            {
                UpdateDescription();
            }
        }
    }

    public string Category
    {
        get { return _operation.Category; }
        set
        {
            if (SetProperty(value, _operation.Category, o => _operation.Category = o))
            {
                UpdateDescription();
            }
        }
    }

    public bool IsManual
    {
        get { return _operation.IsManual; }
        set
        {
            if (SetProperty(value, _operation.IsManual, o => _operation.IsManual = o))
            {
                UpdateDescription();
            }
        }
    }


    void UpdateDescription()
    {
        //some code
    }




    #region Validation




    #region IDataErrorInfo

    public ValidationResult Validate()
    {
        return ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);
    }

    public string this[string columnName]
    {
        get
        {
            var validation = ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);

            return validation.IsValid ? null : validation.ErrorContent.ToString();
        }
    }

    public string Error
    {
        get
        {
            var result = Validate();
            return result.IsValid ? null : result.ErrorContent.ToString();
        }
    }
    #endregion

    #endregion
}

XAML:

<controls:NewDefinitionControl x:Class="DiagnosticsDashboard.EntityData.Operations.Views.NewOperationView"
                               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                               xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                               xmlns:views="clr-namespace:DiagnosticsDashboard.EntityData.Operations.Views"
                               xmlns:controls="clr-namespace:DiagnosticsDashboard.Core.Controls;assembly=DiagnosticsDashboard.Core"
                               xmlns:c="clr-namespace:DiagnosticsDashboard.Core.Validation;assembly=DiagnosticsDashboard.Core"
                               mc:Ignorable="d">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="40" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Label Grid.Column="0"
               Grid.Row="0"
               Margin="5">Code:</Label>
        <Label Grid.Column="0"
               Grid.Row="1"
               Margin="5">Description:</Label>
        <Label Grid.Column="0"
               Grid.Row="2"
               Margin="5">Category:</Label>
        <Label Grid.Column="0"
               Grid.Row="3"
               Margin="5">Friendly Name:</Label>
        <Label Grid.Column="0"
               Grid.Row="4"
               Margin="5">Timeout:</Label>
        <Label Grid.Column="0"
               Grid.Row="5"
               Margin="5">Is Manual:</Label>
        <TextBox Grid.Column="1"
                 Text="{Binding Code,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
                 Grid.Row="0"
                 Margin="5"/>
        <TextBox Grid.Column="1"
                 Grid.Row="1"
                 Margin="5"
                 Text="{Binding Description}" />
        <TextBox Grid.Column="1"
                 Grid.Row="2"
                 Margin="5"
                 Text="{Binding Category}" />
        <TextBox Grid.Column="1"
                 Grid.Row="3"
                 Margin="5"
                 Text="{Binding FriendlyName}" />
        <TextBox Grid.Column="1"
                 Grid.Row="4"
                 Margin="5"
                 Text="{Binding Timeout}" />
        <CheckBox Grid.Column="1"
                  Grid.Row="5"
                  Margin="5"
                  IsChecked="{Binding IsManual}"
                  VerticalAlignment="Center" />


    </Grid>
</controls:NewDefinitionControl>

Avoid synchronized(this) in Java?

This is really just supplementary to the other answers, but if your main objection to using private objects for locking is that it clutters your class with fields that are not related to the business logic then Project Lombok has @Synchronized to generate the boilerplate at compile-time:

@Synchronized
public int foo() {
    return 0;
}

compiles to

private final Object $lock = new Object[0];

public int foo() {
    synchronized($lock) {
        return 0;
    }
}

How do I tell CMake to link in a static library in the source directory?

CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}, doing the following should succeed:

add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)

can't access mysql from command line mac

I've tried all the solutions from the answers but couldn't get mysql command to work from the terminal, always getting the message

bash: command not found

The solution is to change the .bash_profile, and add the mysql path to .bash_profile

To do so follow these steps: 1. Open a new Terminal window or make sure you are in the home directory 2. Open .bash_profile using

nano .bash_profile

3. Add the following command to add the mysql path

PATH="/usr/local/mysql/bin:${PATH}"
export PATH

4. Press Ctrl+X, then press y and press enter.

The following is how my .bash_profile looks like enter image description here

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

You need to fix your include_path system variable to point to the correct location.

To fix it edit the php.ini file. In that file you will find a line that says, "include_path = ...". (You can find out what the location of php.ini by running phpinfo() on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR" to read "C:\xampplite\php\pear". Make sure to leave the semi-colons before and/or after the line in place.

Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.

How to right-align and justify-align in Markdown?

If you want to right-align in a form, you can try:

| Option | Description |
| ------:| -----------:|
| data   | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext    | extension to be used for dest files. |

https://learn.getgrav.org/content/markdown#right-aligned-text

asp.net: How can I remove an item from a dropdownlist?

You can use this:

myDropDown.Items.Remove(myDropDown.Items.FindByValue("TextToFind"));

How to cast Object to its actual type?

If multiple types are possible, the method itself does not know the type to cast, but the caller does, you might use something like this:

void TheObliviousHelperMethod<T>(object obj) {
    (T)obj.ThatClassMethodYouWantedToInvoke();
}

// Meanwhile, where the method is called:
TheObliviousHelperMethod<ActualType>(obj);

Restrictions on the type could be added using the where keyword after the parentheses.

How to attach a file using mail command on Linux?

On Linux I would suggest,

# FILE_TO_BE_ATTACHED=abc.gz

uuencode abc.gz abc.gz > abc.gz.enc # This is optional, but good to have
                                    # to prevent binary file corruption.
                                    # also it make sure to get original 
                                    # file on other system, w/o worry of endianness

# Sending Mail, multiple attachments, and multiple receivers.
echo "Body Part of Mail" | mailx -s "Subject Line" -a attachment1 -a abc.gz.enc "[email protected] [email protected]"

Upon receiving mail attachment, if you have used uuencode, you would need uudecode

uudecode abc.gz.enc

# This will generate file as original with name as same as the 2nd argument for uuencode.

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Is it possible the root password is not what you think it is? Have you checked the file /root/.mysql_secret for the password? That is the default location for the automated root password that is generated from starting from version 5.7.

cat /root/.mysql_secret

Parser Error when deploy ASP.NET application

I am too late but let me explain how I solved this problem.

This problem is basically because of improper folders/solution structure.

this issue may occur because 1. If you have copied project from other location and trying to run the project.

so to resolve this go to original location and crosscheck the folders and files again.

this works for me.

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

What's the best way to cancel event propagation between nested ng-click calls?

You can register another directive on top of ng-click which amends the default behaviour of ng-click and stops the event propagation. This way you wouldn't have to add $event.stopPropagation by hand.

app.directive('ngClick', function() {
    return {
        restrict: 'A',
        compile: function($element, attr) {
            return function(scope, element, attr) {
                element.on('click', function(event) {
                    event.stopPropagation();
                });
            };
        }
    }
});

What are good examples of genetic algorithms/genetic programming solutions?

At work I had the following problem: given M tasks and N DSPs, what was the best way to assign tasks to DSPs? "Best" was defined as "minimizing the load of the most loaded DSP". There were different types of tasks, and various task types had various performance ramifications depending on where they were assigned, so I encoded the set of job-to-DSP assignments as a "DNA string" and then used a genetic algorithm to "breed" the best assignment string I could.

It worked fairly well (much better than my previous method, which was to evaluate every possible combination... on non-trivial problem sizes, it would have taken years to complete!), the only problem was that there was no way to tell if the optimal solution had been reached or not. You could only decide if the current "best effort" was good enough, or let it run longer to see if it could do better.

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

Programmatically create a UIView with color gradient

What you are looking for is CAGradientLayer. Every UIView has a layer - into that layer you can add sublayers, just as you can add subviews. One specific type is the CAGradientLayer, where you give it an array of colors to gradiate between.

One example is this simple wrapper for a gradient view:

http://oleb.net/blog/2010/04/obgradientview-a-simple-uiview-wrapper-for-cagradientlayer/

Note that you need to include the QuartZCore framework in order to access all of the layer parts of a UIView.

Unable to connect PostgreSQL to remote database using pgAdmin

For redhat linux

sudo vi /var/lib/pgsql9/data/postgresql.conf 

pgsql9 is the folder for the postgres version installed, might be different for others

changed listen_addresses = '*' from listen_addresses = ‘localhost’ and then

sudo /etc/init.d/postgresql stop
sudo /etc/init.d/postgresql start

Setting the Vim background colors

Try adding

set background=dark

to your .gvimrc too. This work well for me.

How to access component methods from “outside” in ReactJS?

You could also do it like this, not sure if it's a good plan :D

class Parent extends Component {
  handleClick() {
    if (this._getAlert !== null) {
      this._getAlert()
    }
  }

  render() {
    return (
      <div>
        <Child>
        {(getAlert, childScope) => (
          <span> {!this._getAlert ? this._getAlert = getAlert.bind(childScope) : null}</span>
        )}
        </Child>
        <button onClick={() => this.handleClick()}> Click me</button>
      </div>
      );
    }
  }

class Child extends Component {
  constructor() {
    super();
    this.state = { count: 0 }
  }

  getAlert() {
    alert(`Child function called state: ${this.state.count}`);
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return this.props.children(this.getAlert, this)
  }
}

MySQL Sum() multiple columns

//Mysql sum of multiple rows Hi Here is the simple way to do sum of columns

SELECT sum(IF(day_1 = 1,1,0)+IF(day_3 = 1,1,0)++IF(day_4 = 1,1,0)) from attendence WHERE class_period_id='1' and student_id='1'

Convert python datetime to epoch with strftime

In Python 3.7

Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat(). Specifically, this function supports strings in the format(s) YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where * can match any single character.

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

How do I auto size a UIScrollView to fit its content

it depends on the content really : content.frame.height might give you what you want ? Depends if content is a single thing, or a collection of things.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Just one sentence to say Instruct Internet Explorer to use its latest rendering engine

<meta http-equiv="x-ua-compatible" content="ie=edge">

The ResourceConfig instance does not contain any root resource classes

Your resource package should contain at least one pojo which is either annotated with @Path or have at least one method annotated with @Path or a request method designator, such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a request method designator. This resolved my issue...

Stretch and scale a CSS image in the background - with CSS only

You can add this class into your CSS file.

.stretch {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

It works in:

  • Safari 3 or later
  • Chrome Whatever or later
  • Internet Explorer 9 or later
  • Opera 10 or later (Opera 9.5 supported background-size, but not the keywords)
  • Firefox 3.6 or later (Firefox 4 supports non-vendor prefixed version)

application/x-www-form-urlencoded or multipart/form-data?

Just a little hint from my side for uploading HTML5 canvas image data:

I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.

Once I set the contentType option of my jQuery ajax call to application/x-www-form-urlencoded everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.


Maybe that helps someone!

Using "like" wildcard in prepared statement

We can use the CONCAT SQL function.

PreparedStatement pstmt = con.prepareStatement(
      "SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();

This works perfectly for my case.

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

I got similar message when running command line mvn (version 3.3.3) on Linux with Java 8. By opening maven script /$MAVEN-HOME/bin/mvn, found the following line

MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"

Where $MAVEN_PROJECTBASEDIR by default is your home directory. So two places you can take a look, first is file $MAVEN_PROJECTBASEDIR/.mvn/jvm.config if it exists. Secondly look at files possibly set up the environment variable MAVEN_OPTS. Candidate files are .bashrc, .bash_profile, .profile and those files included by them such as /etc/profile, /etc/bash.bashrc

I located

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256m"

in .bashrc in my system, change it to

export MAVEN_OPTS="-Xmx512m"

issue resolved

RegEx for matching "A-Z, a-z, 0-9, _" and "."

regex: /^[a-zA-Z0-9_.]$/i

This works

Among $_REQUEST, $_GET and $_POST which one is the fastest?

I would use the second method as it is more explicit. Otherwise you don't know where the variables are coming from.

Why do you need to check both GET and POST anyway? Surely using one or the other only makes more sense.

Send inline image in email

Some minimal c# code to embed an image, can be:

MailMessage mailWithImg = GetMailWithImg();
MySMTPClient.Send(mailWithImg); //* Set up your SMTPClient before!

private MailMessage GetMailWithImg() {
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.AlternateViews.Add(GetEmbeddedImage("c:/image.png"));
    mail.From = new MailAddress("yourAddress@yourDomain");
    mail.To.Add("recipient@hisDomain");
    mail.Subject = "yourSubject";
    return mail;
}

private AlternateView GetEmbeddedImage(String filePath) {
    LinkedResource res = new LinkedResource(filePath);
    res.ContentId = Guid.NewGuid().ToString();
    string htmlBody = @"<img src='cid:" + res.ContentId + @"'/>";
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(res);
    return alternateView;
}

Returning first x items from array

You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

How to create file execute mode permissions in Git on Windows?

Indeed, it would be nice if git-add had a --mode flag

git 2.9.x/2.10 (Q3 2016) actually will allow that (thanks to Edward Thomson):

git add --chmod=+x -- afile
git commit -m"Executable!"

That makes the all process quicker, and works even if core.filemode is set to false.

See commit 4e55ed3 (31 May 2016) by Edward Thomson (ethomson).
Helped-by: Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit c8b080a, 06 Jul 2016)

add: add --chmod=+x / --chmod=-x options

The executable bit will not be detected (and therefore will not be set) for paths in a repository with core.filemode set to false, though the users may still wish to add files as executable for compatibility with other users who do have core.filemode functionality.
For example, Windows users adding shell scripts may wish to add them as executable for compatibility with users on non-Windows.

Although this can be done with a plumbing command (git update-index --add --chmod=+x foo), teaching the git-add command allows users to set a file executable with a command that they're already familiar with.

Entity Framework and Connection Pooling

  1. Connection pooling is handled as in any other ADO.NET application. Entity connection still uses traditional database connection with traditional connection string. I believe you can turn off connnection pooling in connection string if you don't want to use it. (read more about SQL Server Connection Pooling (ADO.NET))
  2. Never ever use global context. ObjectContext internally implements several patterns including Identity Map and Unit of Work. Impact of using global context is different per application type.
  3. For web applications use single context per request. For web services use single context per call. In WinForms or WPF application use single context per form or per presenter. There can be some special requirements which will not allow to use this approach but in most situation this is enough.

If you want to know what impact has single object context for WPF / WinForm application check this article. It is about NHibernate Session but the idea is same.

Edit:

When you use EF it by default loads each entity only once per context. The first query creates entity instace and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.

Any changes made to the entity are not persisted until you call SaveChanges on the context. You can do changes in multiple entities and store them at once. This is called Unit of Work pattern. You can't selectively say which modified attached entity you want to save.

Combine these two patterns and you will see some interesting effects. You have only one instance of entity for the whole application. Any changes to the entity affect the whole application even if changes are not yet persisted (commited). In the most times this is not what you want. Suppose that you have an edit form in WPF application. You are working with the entity and you decice to cancel complex editation (changing values, adding related entities, removing other related entities, etc.). But the entity is already modified in shared context. What will you do? Hint: I don't know about any CancelChanges or UndoChanges on ObjectContext.

I think we don't have to discuss server scenario. Simply sharing single entity among multiple HTTP requests or Web service calls makes your application useless. Any request can just trigger SaveChanges and save partial data from another request because you are sharing single unit of work among all of them. This will also have another problem - context and any manipulation with entities in the context or a database connection used by the context is not thread safe.

Even for a readonly application a global context is not a good choice because you probably want fresh data each time you query the application.

When should I use nil and NULL in Objective-C?

There is a difference in some contexts.

Literally, Null is a character: ASCII 0.

Nil is equivalent to blank, no value.

Depending on the programming context, this can be a big difference.

Vertical Alignment of text in a table cell

CSS {vertical-align: top;} or html Attribute {valign="top"}

_x000D_
_x000D_
.table td, 
.table th {
    border: 1px solid #161b21;
    text-align: left;
    padding: 8px;
    width: 250px;
    height: 100px;
    
    /* style for table */
}

.table-body-text {
  vertical-align: top;
}
_x000D_
<table class="table">
    <tr>
      <th valign="top">Title 1</th>
      <th valign="top">Title 2</th>
    </tr>
    <tr>
      <td class="table-body-text">text</td>
      <td class="table-body-text">text</td>
    </tr>
   </table>
_x000D_
_x000D_
_x000D_

For table vertical-align we have 2 options.

  1. is to use css {vertical-align: top;}
  1. another way is to user attribute "valign" and the property should be "top" {valign="top"}

Get yesterday's date in bash on Linux, DST-safe

I think this should work, irrespective of how often and when you run it ...

date -d "yesterday 13:00" '+%Y-%m-%d'

How do I read from parameters.yml in a controller in symfony2?

I send you an example with swiftmailer:

parameters.yml

recipients: [email1, email2, email3]

services:

your_service_name:
        class: your_namespace
        arguments: ["%recipients%"]

the class of the service:

protected $recipients;

public function __construct($recipients)
{
    $this->recipients = $recipients;
}

What version of Java is running in Eclipse?

There are various options are available to test which java version is using your eclipse. The best way is to find first java installed in your machine.

run java -version command on terminal

then to check whether your eclipse pointing to the right version or not.

For that go to

Eclipse >> Preferences >>Java >>Installed JREs

CMake unable to determine linker language with C++

In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.

How to end a session in ExpressJS

Express 4.x Updated Answer

Session handling is no longer built into Express. This answer refers to the standard session module: https://github.com/expressjs/session

To clear the session data, simply use:

req.session.destroy();

The documentation is a bit useless on this. It says:

Destroys the session, removing req.session, will be re-generated next request. req.session.destroy(function(err) { // cannot access session here })

This does not mean that the current session will be re-loaded on the next request. It means that a clean empty session will be created in your session store on next request. (Presumably the session ID isn't changing, but I have not tested that.)

Add key value pair to all objects in array

_.forEach(arrOfObj,(arrVal,arrIn) => {
             arrVal.isAcitve = true;
            }

How do I get bit-by-bit data from an integer value in C?

As requested, I decided to extend my comment on forefinger's answer to a full-fledged answer. Although his answer is correct, it is needlessly complex. Furthermore all current answers use signed ints to represent the values. This is dangerous, as right-shifting of negative values is implementation-defined (i.e. not portable) and left-shifting can lead to undefined behavior (see this question).

By right-shifting the desired bit into the least significant bit position, masking can be done with 1. No need to compute a new mask value for each bit.

(n >> k) & 1

As a complete program, computing (and subsequently printing) an array of single bit values:

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

int main(int argc, char** argv)
{
    unsigned
        input = 0b0111u,
        n_bits = 4u,
        *bits = (unsigned*)malloc(sizeof(unsigned) * n_bits),
        bit = 0;

    for(bit = 0; bit < n_bits; ++bit)
        bits[bit] = (input >> bit) & 1;

    for(bit = n_bits; bit--;)
        printf("%u", bits[bit]);
    printf("\n");

    free(bits);
}

Assuming that you want to calculate all bits as in this case, and not a specific one, the loop can be further changed to

for(bit = 0; bit < n_bits; ++bit, input >>= 1)
    bits[bit] = input & 1;

This modifies input in place and thereby allows the use of a constant width, single-bit shift, which may be more efficient on some architectures.

Passing an array using an HTML form hidden element

There are mainly two possible ways to achieve this:

  1. Serialize the data in some way:

    $postvalue = serialize($array); // Client side
    
    $array = unserialize($_POST['result']; // Server side
    

And then you can unserialize the posted values with unserialize($postvalue). Further information on this is here in the PHP manuals.

Alternativeley you can use the json_encode() and json_decode() functions to get a JSON formatted serialized string. You could even shrink the transmitted data with gzcompress() (note that this is performance intensive) and secure the transmitted data with base64_encode() (to make your data survive in non-8 bit clean transport layers) This could look like this:

    $postvalue = base64_encode(json_encode($array)); // Client side

    $array = json_decode(base64_decode($_POST['result'])); // Server side

A not recommended way to serialize your data (but very cheap in performance) is to simply use implode() on your array to get a string with all values separated by some specified character. On the server side you can retrieve the array with explode() then. But note that you shouldn't use a character for separation that occurs in the array values (or then escape it) and that you cannot transmit the array keys with this method.

  1. Use the properties of special named input elements:

    $postvalue = "";
    foreach ($array as $v) {
      $postvalue .= '<input type="hidden" name="result[]" value="' .$v. '" />';
    }
    

    Like this you get your entire array in the $_POST['result'] variable if the form is sent. Note that this doesn't transmit array keys. However you can achieve this by using result[$key] as name of each field.

Everyone of these methods got their own advantages and disadvantages. What you use is mainly depending on how large your array will be, since you should try to send a minimal amount of data with all of this methods.

Another way to achieve the same is to store the array in a server side session instead of transmitting it client side. Like this you can access the array over the $_SESSION variable and don't have to transmit anything over the form. For this have a look at a basic usage example of sessions on php.net.

Android custom Row Item for ListView

Use a custom Listview.

You can also customize how row looks by having a custom background. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" 
 android:background="#0095FF"> //background color

<ListView android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="0dip"
 android:focusableInTouchMode="false"
 android:listSelector="@android:color/transparent"
 android:layout_weight="2"
 android:headerDividersEnabled="false"
 android:footerDividersEnabled="false"
 android:dividerHeight="8dp" 
 android:divider="#000000" 
 android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>  

MainActivity

Define populateString() in MainActivity

 public class MainActivity extends Activity {

   String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
            data_array = populateString(); 
    ListView ll = (ListView) findViewById(R.id.list);
    CustomAdapter cus = new CustomAdapter();
    ll.setAdapter(cus);
}

class CustomAdapter extends BaseAdapter
{
    LayoutInflater mInflater;


    public CustomAdapter()
    {
        mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data_array.length;//listview item count. 
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position; 
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder vh;
        vh= new ViewHolder();

        if(convertView==null )
         {
            convertView=mInflater.inflate(R.layout.row, parent,false);
                    //inflate custom layour
            vh.tv2= (TextView)convertView.findViewById(R.id.textView2);

         }
        else
        {
         convertView.setTag(vh);
        }
               //vh.tv2.setText("Position = "+position);
            vh.tv2.setText(data_array[position]);   
                           //set text of second textview based on position

        return convertView;
    }

 class ViewHolder
 {
    TextView tv1,tv2;
 }

   }  
}

row.xml. Custom layout for each row.

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Header" />

 <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="TextView" />

 </LinearLayout>

Inflate a custom layout. Use a view holder for smooth scrolling and performance.

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview performance by android developers.

enter image description here

Selenium IDE - Command to wait for 5 seconds

This will delay things for 5 seconds:

Command: pause
Target: 5000
Value:

This will delay things for 3 seconds:

Command: pause
Target: 3000
Value:

Documentation:

http://release.seleniumhq.org/selenium-core/1.0/reference.html#pause

enter image description here enter image description here

Is there an alternative to string.Replace that is case-insensitive?

Inspired by cfeduke's answer, I made this function which uses IndexOf to find the old value in the string and then replaces it with the new value. I used this in an SSIS script processing millions of rows, and the regex-method was way slower than this.

public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)
{
    int prevPos = 0;
    string retval = str;
    // find the first occurence of oldValue
    int pos = retval.IndexOf(oldValue, StringComparison.InvariantCultureIgnoreCase);

    while (pos > -1)
    {
        // remove oldValue from the string
        retval = retval.Remove(pos, oldValue.Length);

        // insert newValue in it's place
        retval = retval.Insert(pos, newValue);

        // check if oldValue is found further down
        prevPos = pos + newValue.Length;
        pos = retval.IndexOf(oldValue, prevPos, StringComparison.InvariantCultureIgnoreCase);
    }

    return retval;
}

How can I convert a Unix timestamp to DateTime and vice versa?

The latest version of .NET (v4.6) has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.

  • Unix time in seconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
  • DateTimeOffset to Unix time in seconds:

long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
  • Unix time in milliseconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
  • DateTimeOffset to Unix time in milliseconds:

long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();

Note: These methods convert to and from a UTC DateTimeOffset. To get a DateTime representation simply use the DateTimeOffset.UtcDateTime or DateTimeOffset.LocalDateTime properties:

DateTime dateTime = dateTimeOffset.UtcDateTime;

How to expand a list to function arguments in Python

Try the following:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.

How to run a jar file in a linux commandline

Under linux there's a package called binfmt-support that allows you to run directly your jar without typing java -jar:

sudo apt-get install binfmt-support
chmod u+x my-jar.jar
./my-jar.jar # there you go!

Video format or MIME type is not supported

Firefox does not support the MPEG H.264 (mp4) format at this time, due to a philosophical disagreement with the closed-source nature of the format.

To play videos in all browsers without using plugins, you will need to host multiple copies of each video, in different formats. You will also need to use an alternate form of the video tag, as seen in the JSFiddle from @TimHayes above, reproduced below. Mozilla claims that only mp4 and WebM are necessary to ensure complete coverage of all major browsers, but you may wish to consult the Video Formats and Browser Support heading on W3C's HTML5 Video page to see which browser supports what formats.

Additionally, it's worth checking out the HTML5 Video page on Wikipedia for a basic comparison of the major file formats.

Below is the appropriate video tag (you will need to re-encode your video in WebM or OGG formats as well as your existing mp4):

<video id="video" controls='controls'>
  <source src="videos/clip.mp4" type="video/mp4"/>
  <source src="videos/clip.webm" type="video/webm"/>
  <source src="videos/clip.ogv" type="video/ogg"/>
  Your browser doesn't seem to support the video tag.
</video>

Updated Nov. 8, 2013

Network infrastructure giant Cisco has announced plans to open-source an implementation of the H.264 codec, removing the licensing fees that have so far proved a barrier to use by Mozilla. Without getting too deep into the politics of it (see following link for that) this will allow Firefox to support H.264 starting in "early 2014". However, as noted in that link, this still comes with a caveat. The H.264 codec is merely for video, and in the MPEG-4 container it is most commonly paired with the closed-source AAC audio codec. Because of this, playback of H.264 video will work, but audio will depend on whether the end-user has the AAC codec already present on their machine.

The long and short of this is that progress is being made, but you still can't avoid using multiple encodings without using a plugin.

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

Check following things in your project:

  • Make sure any XML file doesn't have blank space at starting of the file.

  • Make sure that any drawable file doesn't have any issue like capital letters or any special symbols in name.

  • If your aapt2.exe is missing continuously then please scan your full PC, May be there is a virus which is removing adb.exp or aapt2.exe

Hope you will get solution.

jQuery removeClass wildcard

The removeClass function takes a function argument since jQuery 1.4.

$("#hello").removeClass (function (index, className) {
    return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});

Live example: http://jsfiddle.net/xa9xS/1409/

How to upload (FTP) files to server in a bash script?

if you want to use it inside a 'for' to copy the last generated files for a every-day bacakup...

j=0  
var="`find /backup/path/ -name 'something*' -type f -mtime -1`"  
#we have in $var some files with last day change date

for i in $var  
  do  
  j=$(( $j + 1 ))  
  dirname="`dirname $i`"  
  filename="`basename $i`"  
  /usr/bin/ftp -in >> /tmp/ftp.good 2>> /tmp/ftp.bad << EOF  
    open 123.456.789.012  
    user user_name passwd  
    bin  
    lcd $dirname  
    put $filename  
    quit  
  EOF      #end of ftp  
done       #end of for iteration

Cannot access a disposed object - How to fix?

It looks like a threading issue.
Hypothesis: Maybe you have the main thread and a timer thread accessing this control. The main thread shuts down - calling Control.Dispose() to indicate that I'm done with this Control and I shall make no more calls to this. However, the timer thread is still active - a context switch to that thread, where it may call methods on the same control. Now the control says I'm Disposed (already given up my resources) and I shall not work anymore. ObjectDisposed exception.

How to solve this: In the timer thread, before calling methods/properties on the control, do a check with

if ControlObject.IsDisposed then return; // or do whatever - but don't call control methods

OR stop the timer thread BEFORE disposing the object.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

The count method of NSArray returns an NSUInteger, and on the 64-bit OS X platform

  • NSUInteger is defined as unsigned long, and
  • unsigned long is a 64-bit unsigned integer.
  • int is a 32-bit integer.

So int is a "smaller" datatype than NSUInteger, therefore the compiler warning.

See also NSUInteger in the "Foundation Data Types Reference":

When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.

To fix that compiler warning, you can either declare the local count variable as

NSUInteger count;

or (if you are sure that your array will never contain more than 2^31-1 elements!), add an explicit cast:

int count = (int)[myColors count];

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

Is it possible to send an array with the Postman Chrome extension?

{
    "data" : [  
        {
            "key1" : "value1",
            "key2" : "value2"   
        },
        {
            "key01" : "value01",
            "key02" : "value02"             
        },
        {
            "key10" : "value10",
            "key20" : "value20"   
        }
    ]
}

You can pass like this. Hope this will help someone.

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

_x000D_
_x000D_
function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  _x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
            sliders[y].oninput();_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
}
_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
}_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
_x000D_
_x000D_

What are libtool's .la file for?

It is a textual file that includes a description of the library.

It allows libtool to create platform-independent names.

For example, libfoo goes to:

Under Linux:

/lib/libfoo.so       # Symlink to shared object
/lib/libfoo.so.1     # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library

Under Cygwin:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # libtool library
/bin/cygfoo_1.dll    # DLL

Under Windows MinGW:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library
/bin/foo_1.dll       # DLL

So libfoo.la is the only file that is preserved between platforms by libtool allowing to understand what happens with:

  • Library dependencies
  • Actual file names
  • Library version and revision

Without depending on a specific platform implementation of libraries.

How to check if a string array contains one string in JavaScript?

Create this function prototype:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   }
   return false;
}

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}

How to validate Google reCAPTCHA v3 on server side?

Private key safety

While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.

For a little bit more detail: https://stackoverflow.com/a/323286/1680919

Verification via POST

function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '[YOUR SECRET KEY]',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];
                 
        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];
    
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}

Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).

Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }

How to correctly dismiss a DialogFragment?

Adding to the other answers, when having a DialogFragment that is full screen calling dismiss() won't pop the DialogFragment from the fragment backstack. A workaround is to call onBackPressed() on the parent activity.

Something like this:

CustomDialogFragment.kt

closeButton.onClick {
    requireActivity().onBackPressed()
}

Dynamically creating keys in a JavaScript associative array

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

This is ok, but it iterates through every property of the array object.

If you want to only iterate through the properties myArray.one, myArray.two... you try like this:

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

Now you can access both by myArray["one"] and iterate only through these properties.

How would you implement an LRU cache in Java?

Here's my own implementation to this problem

simplelrucache provides threadsafe, very simple, non-distributed LRU caching with TTL support. It provides two implementations:

  • Concurrent based on ConcurrentLinkedHashMap
  • Synchronized based on LinkedHashMap

You can find it here: http://code.google.com/p/simplelrucache/

How to get relative path of a file in visual studio?

In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.

Now to get the file path using relative path just type:

string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";

Hope that helped.

How to perform a for loop on each character in a string in Bash?

Another approach, if you don't care about whitespace being ignored:

for char in $(sed -E s/'(.)'/'\1 '/g <<<"$your_string"); do
    # Handle $char here
done

Loading all images using imread from a given folder

Why not just try loading all the files in the folder? If OpenCV can't open it, oh well. Move on to the next. cv2.imread() returns None if the image can't be opened. Kind of weird that it doesn't raise an exception.

import cv2
import os

def load_images_from_folder(folder):
    images = []
    for filename in os.listdir(folder):
        img = cv2.imread(os.path.join(folder,filename))
        if img is not None:
            images.append(img)
    return images

How to create a DB for MongoDB container on start up?

My answer is based on the one provided by @x-yuri; but my scenario it's a little bit different. I wanted an image containing the script, not bind without needing to bind-mount it.

mongo-init.sh -- don't know whether or not is need but but I ran chmod +x mongo-init.sh also:

#!/bin/bash
# https://stackoverflow.com/a/53522699
# https://stackoverflow.com/a/37811764
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
  var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
  var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
  var user = '$MONGO_INITDB_USERNAME';
  var passwd = '$MONGO_INITDB_PASSWORD';

  var admin = db.getSiblingDB('admin');

  admin.auth(rootUser, rootPassword);
  db.createUser({
    user: user,
    pwd: passwd,
    roles: [
      {
        role: "root",
        db: "admin"
      }
    ]
  });
EOF

Dockerfile:

FROM mongo:3.6

COPY mongo-init.sh /docker-entrypoint-initdb.d/mongo-init.sh

CMD [ "/docker-entrypoint-initdb.d/mongo-init.sh" ]

docker-compose.yml:

version: '3'

services:
    mongodb:
        build: .
        container_name: mongodb-test
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=example
            - MONGO_INITDB_USERNAME=myproject
            - MONGO_INITDB_PASSWORD=myproject
            - MONGO_INITDB_DATABASE=myproject

    myproject:
        image: myuser/myimage
        restart: on-failure
        container_name: myproject
        environment:
            - DB_URI=mongodb
            - DB_HOST=mongodb-test
            - DB_NAME=myproject
            - DB_USERNAME=myproject
            - DB_PASSWORD=myproject
            - DB_OPTIONS=
            - DB_PORT=27017            
        ports:
            - "80:80"

After that, I went ahead and publish this Dockefile as an image to use in other projects.

note: without adding the CMD it mongo throws: unbound variable error

How can I remove the last character of a string in python?

To remove the last character, just use a slice: my_file_path[:-1]. If you only want to remove a specific set of characters, use my_file_path.rstrip('/'). If you see the string as a file path, the operation is os.path.dirname. If the path is in fact a filename, I rather wonder where the extra slash came from in the first place.

Launch Android application without main Activity and start Service on launching application

You said you didn't want to use a translucent Activity, but that seems to be the best way to do this:

  1. In your Manifest, set the Activity theme to Theme.Translucent.NoTitleBar.
  2. Don't bother with a layout for your Activity, and don't call setContentView().
  3. In your Activity's onCreate(), start your Service with startService().
  4. Exit the Activity with finish() once you've started the Service.

In other words, your Activity doesn't have to be visible; it can simply make sure your Service is running and then exit, which sounds like what you want.

I would highly recommend showing at least a Toast notification indicating to the user that you are launching the Service, or that it is already running. It is very bad user experience to have a launcher icon that appears to do nothing when you press it.

Hash Table/Associative Array in VBA

Here we go... just copy the code to a module, it's ready to use

Private Type hashtable
    key As Variant
    value As Variant
End Type

Private GetErrMsg As String

Private Function CreateHashTable(htable() As hashtable) As Boolean
    GetErrMsg = ""
    On Error GoTo CreateErr
        ReDim htable(0)
        CreateHashTable = True
    Exit Function

CreateErr:
    CreateHashTable = False
    GetErrMsg = Err.Description
End Function

Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
    GetErrMsg = ""
    On Error GoTo AddErr
        Dim idx As Long
        idx = UBound(htable) + 1

        Dim htVal As hashtable
        htVal.key = key
        htVal.value = value

        Dim i As Long
        For i = 1 To UBound(htable)
            If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
        Next i

        ReDim Preserve htable(idx)

        htable(idx) = htVal
        AddValue = idx
    Exit Function

AddErr:
    AddValue = 0
    GetErrMsg = Err.Description
End Function

Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
    GetErrMsg = ""
    On Error GoTo RemoveErr

        Dim i As Long, idx As Long
        Dim htTemp() As hashtable
        idx = 0

        For i = 1 To UBound(htable)
            If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
                ReDim Preserve htTemp(idx)
                AddValue htTemp, htable(i).key, htable(i).value
                idx = idx + 1
            End If
        Next i

        If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"

        htable = htTemp
        RemoveValue = True
    Exit Function

RemoveErr:
    RemoveValue = False
    GetErrMsg = Err.Description
End Function

Private Function GetValue(htable() As hashtable, key As Variant) As Variant
    GetErrMsg = ""
    On Error GoTo GetValueErr
        Dim found As Boolean
        found = False

        For i = 1 To UBound(htable)
            If htable(i).key = key And IsEmpty(htable(i).key) = False Then
                GetValue = htable(i).value
                Exit Function
            End If
        Next i
        Err.Raise 9997, , "Key [" & CStr(key) & "] not found"

    Exit Function

GetValueErr:
    GetValue = ""
    GetErrMsg = Err.Description
End Function

Private Function GetValueCount(htable() As hashtable) As Long
    GetErrMsg = ""
    On Error GoTo GetValueCountErr
        GetValueCount = UBound(htable)
    Exit Function

GetValueCountErr:
    GetValueCount = 0
    GetErrMsg = Err.Description
End Function

To use in your VB(A) App:

Public Sub Test()
    Dim hashtbl() As hashtable
    Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
    Debug.Print ""
    Debug.Print "ID Test   Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test   Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
    Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
    Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
    Debug.Print ""
    Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
    Debug.Print ""
    Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
    Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
    Debug.Print ""
    Debug.Print "Hashtable Content:"

    For i = 1 To UBound(hashtbl)
        Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
    Next i

    Debug.Print ""
    Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub

How to process SIGTERM signal gracefully?

The simplest solution I have found, taking inspiration by responses above is

class SignalHandler:

    def __init__(self):

        # register signal handlers
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)

        self.logger = Logger(level=ERROR)

    def exit_gracefully(self, signum, frame):
        self.logger.info('captured signal %d' % signum)
        traceback.print_stack(frame)

        ###### do your resources clean up here! ####

        raise(SystemExit)

did you specify the right host or port? error on Kubernetes

Reinitialising gcloud with proper account and project worked for me.

gcloud init

After this retrying the below command was successful and kubeconfig entry was generated.

gcloud container clusters get-credentials "cluster_name"

check the cluster info with

kubectl cluster-info

CryptographicException 'Keyset does not exist', but only through WCF

I just reinstalled my certificate in local machine and then it is working fine

Calculate the execution time of a method

 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

Exclude all transitive dependencies of a single dependency

Currently, there's no way to exclude more than one transitive dependency at a time, but there is a feature request for this on the Maven JIRA site:

https://issues.apache.org/jira/browse/MNG-2315

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

You have to put the path to the file. For example:

require_once('../web/a.php');

You cannot get the file to require it from internet (with http protocol) it's restricted. The files must be on the same server. With Possibility to see each others (rights)

Dir-1 -
         > Folder-1 -> a.php
Dir-2 -
         > Folder-2 -> b.php

To include a.php inside b.php => require_once('../../Dir-1/Folder-1/a.php');
To include b.php inside a.php => require_once('../../Dir-2/Folder-2/b.php');

What are the rules for casting pointers in C?

You have a pointer to a char. So as your system knows, on that memory address there is a char value on sizeof(char) space. When you cast it up to int*, you will work with data of sizeof(int), so you will print your char and some memory-garbage after it as an integer.

Install psycopg2 on Ubuntu

This works for me in Ubuntu 12.04 and 15.10

if pip not installed:

sudo apt-get install python-pip

and then:

sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2

require_once :failed to open stream: no such file or directory

You will need to link to the file relative to the file that includes eventManager.php (Page A)

Change your code from
require_once('../includes/dbconn.inc');

To
require_once('../mysite/php/includes/dbconn.inc');

node.js: cannot find module 'request'

I have met the same problem as I install it globally, then I try to install it locally, and it work.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory

I gues there are too many keys in the counter dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.

To save it, don't create a giant object, e.g. the counter.

1.StackOverflow

a program that create too many local variables.

Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
...   f.write('\tx%d = %d\n' % (x, x))
... 
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed

2.OutOfMemory

a program that creats a giant dict includes too many keys.

>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
...   f.write('counter[%d] = %d\n' % (x, x))
... 
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed

References

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

warning: LF will be replaced by CRLF.

Depending on the editor you are using, a text file with LF wouldn't necessary be saved with CRLF: recent editors can preserve eol style. But that git config setting insists on changing those...

Simply make sure that (as I recommend here):

git config --global core.autocrlf false

That way, you avoid any automatic transformation, and can still specify them through a .gitattributes file and core.eol directives.


windows git "LF will be replaced by CRLF"
Is this warning tail backward?

No: you are on Windows, and the git config help page does mention

Use this setting if you want to have CRLF line endings in your working directory even though the repository does not have normalized line endings.

As described in "git replacing LF with CRLF", it should only occur on checkout (not commit), with core.autocrlf=true.

       repo
    /        \ 
crlf->lf    lf->crlf 
 /              \    

As mentioned in XiaoPeng's answer, that warning is the same as:

warning: (If you check it out/or clone to another folder with your current core.autocrlf configuration,) LF will be replaced by CRLF
The file will have its original line endings in your (current) working directory.

As mentioned in git-for-windows/git issue 1242:

I still feel this message is confusing, the message could be extended to include a better explanation of the issue, for example: "LF will be replaced by CRLF in file.json after removing the file and checking it out again".

Note: Git 2.19 (Sept 2018), when using core.autocrlf, the bogus "LF will be replaced by CRLF" warning is now suppressed.


As quaylar rightly comments, if there is a conversion on commit, it is to LF only.

That specific warning "LF will be replaced by CRLF" comes from convert.c#check_safe_crlf():

if (checksafe == SAFE_CRLF_WARN)
  warning("LF will be replaced by CRLF in %s.
           The file will have its original line endings 
           in your working directory.", path);
else /* i.e. SAFE_CRLF_FAIL */
  die("LF would be replaced by CRLF in %s", path);

It is called by convert.c#crlf_to_git(), itself called by convert.c#convert_to_git(), itself called by convert.c#renormalize_buffer().

And that last renormalize_buffer() is only called by merge-recursive.c#blob_unchanged().

So I suspect this conversion happens on a git commit only if said commit is part of a merge process.


Note: with Git 2.17 (Q2 2018), a code cleanup adds some explanation.

See commit 8462ff4 (13 Jan 2018) by Torsten Bögershausen (tboegi).
(Merged by Junio C Hamano -- gitster -- in commit 9bc89b1, 13 Feb 2018)

convert_to_git(): safe_crlf/checksafe becomes int conv_flags

When calling convert_to_git(), the checksafe parameter defined what should happen if the EOL conversion (CRLF --> LF --> CRLF) does not roundtrip cleanly.
In addition, it also defined if line endings should be renormalized (CRLF --> LF) or kept as they are.

checksafe was an safe_crlf enum with these values:

SAFE_CRLF_FALSE:       do nothing in case of EOL roundtrip errors
SAFE_CRLF_FAIL:        die in case of EOL roundtrip errors
SAFE_CRLF_WARN:        print a warning in case of EOL roundtrip errors
SAFE_CRLF_RENORMALIZE: change CRLF to LF
SAFE_CRLF_KEEP_CRLF:   keep all line endings as they are

Note that a regression introduced in 8462ff4 ("convert_to_git(): safe_crlf/checksafe becomes int conv_flags", 2018-01-13, Git 2.17.0) back in Git 2.17 cycle caused autocrlf rewrites to produce a warning message despite setting safecrlf=false.

See commit 6cb0912 (04 Jun 2018) by Anthony Sottile (asottile).
(Merged by Junio C Hamano -- gitster -- in commit 8063ff9, 28 Jun 2018)

How do I set up cron to run a file just once at a specific time?

at is the correct way.

If you don't have the at command in the machine and you also don't have install privilegies on it, you can put something like this on cron (maybe with the crontab command):

* * * 5 * /path/to/comand_to_execute; /usr/bin/crontab -l | /usr/bin/grep -iv command_to_execute | /usr/bin/crontab - 

it will execute your command one time and remove it from cron after that.