Programs & Examples On #Recover

where does MySQL store database files?

WAMP stores the db data under WAMP\bin\mysql\mysql(version)\data. Where the WAMP folder itself is depends on where you installed it to (on xp, I believe it is directly in the main drive, for example c:\WAMP\...

If you deleted that folder, or if the uninstall deleted that folder, if you did not do a DB backup before the uninstall, you may be out of luck.

If you did do a backup though phpmyadmin, then login, and click the import tab, and browse to the backup file.

How to recover closed output window in netbeans?

In NetBeans 7.4, Under Window menu, click on "Reset Window". Then NetBeans will disappear and reappear. At last, after it reappears, click on "Output" under Window menu.

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

Forward X11 failed: Network error: Connection refused

X display location : localhost:0 Worked for me :)

Difference between size and length methods?

size() is a method specified in java.util.Collection, which is then inherited by every data structure in the standard library. length is a field on any array (arrays are objects, you just don't see the class normally), and length() is a method on java.lang.String, which is just a thin wrapper on a char[] anyway.

Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

One option seems to be using CSS to style the textarea

.multi-line { height:5em; width:5em; }

See this entry on SO or this one.

Amurra's accepted answer seems to imply this class is added automatically when using EditorFor but you'd have to verify this.

EDIT: Confirmed, it does. So yes, if you want to use EditorFor, using this CSS style does what you're looking for.

<textarea class="text-box multi-line" id="StoreSearchCriteria_Location" name="StoreSearchCriteria.Location">

JAXB Exception: Class not known to this context

I had the same problem with spring boot. It resolved when i set package to marshaller.

@Bean
public Jaxb2Marshaller marshaller() throws Exception
{
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setPackagesToScan("com.octory.ws.dto");
    return marshaller;
}

@Bean
public WebServiceTemplate webServiceTemplate(final Jaxb2Marshaller marshaller)   
{
    WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
    webServiceTemplate.setMarshaller(marshaller);
    webServiceTemplate.setUnmarshaller(marshaller);
    return webServiceTemplate;
}

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.

If you're experiencing a different behaviour, it's time to change for another DBMS.

How to copy a file to a remote server in Python using SCP or SSH?

There are a couple of different ways to approach the problem:

  1. Wrap command-line programs
  2. use a Python library that provides SSH capabilities (eg - Paramiko or Twisted Conch)

Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.

NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.

I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.

If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Need to Update

Android SDK : SDK Tools -> Support Repository -> Google Repository

After updating the Android SDK need to sync gradle build in Android studio.

How do I get today's date in C# in mm/dd/yyyy format?

string today = DateTime.Today.ToString("M/d");

Hibernate: "Field 'id' doesn't have a default value"

In addition to what is mentioned above, do not forget while creating sql table to make the AUTO INCREMENT as in this example

CREATE TABLE MY_SQL_TABLE (

  USER_ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
  FNAME VARCHAR(50) NOT NULL,
  LNAME VARCHAR(20) NOT NULL,
  EMAIL VARCHAR(50) NOT NULL
);

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

My solution is a mix of several answers here.

I checked the build server, and Windows7/NET4.0 SDK was already installed, so I did find the path:

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets`

However, on this line:

<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets" />

$(MSBuildExtensionsPath) expands to C:\Program Files\MSBuild which does not have the path.

Therefore what I did was to create a symlink, using this command:

mklink /J "C:\Program Files\MSBuild\Microsoft\VisualStudio" "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio"

This way the $(MSBuildExtensionsPath) expands to a valid path, and no changes are needed in the app itself, only in the build server (perhaps one could create the symlink every build, to make sure this step is not lost and is "documented").

How do I make a MySQL database run completely in memory?

It is also possible to place the MySQL data directory in a tmpfs in thus speeding up the database write and read calls. It might not be the most efficient way to do this but sometimes you can't just change the storage engine.

Here is my fstab entry for my MySQL data directory

none            /opt/mysql/server-5.6/data  tmpfs   defaults,size=1000M,uid=999,gid=1000,mode=0700          0       0

You may also want to take a look at the innodb_flush_log_at_trx_commit=2 setting. Maybe this will speedup your MySQL sufficently.

innodb_flush_log_at_trx_commit changes the mysql disk flush behaviour. When set to 2 it will only flush the buffer every second. By default each insert will cause a flush and thus cause more IO load.

Is the Javascript date object always one day off?

The following worked for me -

    var doo = new Date("2011-09-24").format("m/d/yyyy");

CSS hide scroll bar, but have element scrollable

You can hide it :

html {
  overflow:   scroll;
}
::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* make scrollbar transparent */
}

For further information, see : Hide scroll bar, but while still being able to scroll

how to access the command line for xampp on windows

In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)

enter image description here

After pressing the button, you will see the command prompt window.

enter image description here

From this window you can navigate through the different folders and start the different services available.

What does localhost:8080 mean?

http://localhost:8080/web: localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat. 8080 ( port ) is the address of the port on which the host server is listening for requests.

http://localhost/web: localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat. host server listening to default port 80.

How does java do modulus calculations with negative numbers?

Are you sure you are working in Java? 'cause Java gives -13 % 64 = -13 as expected. The sign of dividend!

Call static method with reflection

I prefer simplicity...

private void _InvokeNamespaceClassesStaticMethod(string namespaceName, string methodName, params object[] parameters) {
    foreach(var _a in AppDomain.CurrentDomain.GetAssemblies()) {
        foreach(var _t in _a.GetTypes()) {
            try {
                if((_t.Namespace == namespaceName) && _t.IsClass) _t.GetMethod(methodName, (BindingFlags.Static | BindingFlags.Public))?.Invoke(null, parameters);
            } catch { }
        }
    }
}

Usage...

    _InvokeNamespaceClassesStaticMethod("mySolution.Macros", "Run");

But in case you're looking for something a little more robust, including the handling of exceptions...

private InvokeNamespaceClassStaticMethodResult[] _InvokeNamespaceClassStaticMethod(string namespaceName, string methodName, bool throwExceptions, params object[] parameters) {
    var results = new List<InvokeNamespaceClassStaticMethodResult>();
    foreach(var _a in AppDomain.CurrentDomain.GetAssemblies()) {
        foreach(var _t in _a.GetTypes()) {
            if((_t.Namespace == namespaceName) && _t.IsClass) {
                var method_t = _t.GetMethod(methodName, parameters.Select(_ => _.GetType()).ToArray());
                if((method_t != null) && method_t.IsPublic && method_t.IsStatic) {
                    var details_t = new InvokeNamespaceClassStaticMethodResult();
                    details_t.Namespace = _t.Namespace;
                    details_t.Class = _t.Name;
                    details_t.Method = method_t.Name;
                    try {
                        if(method_t.ReturnType == typeof(void)) {
                            method_t.Invoke(null, parameters);
                            details_t.Void = true;
                        } else {
                            details_t.Return = method_t.Invoke(null, parameters);
                        }
                    } catch(Exception ex) {
                        if(throwExceptions) {
                            throw;
                        } else {
                            details_t.Exception = ex;
                        }
                    }
                    results.Add(details_t);
                }
            }
        }
    }
    return results.ToArray();
}

private class InvokeNamespaceClassStaticMethodResult {
    public string Namespace;
    public string Class;
    public string Method;
    public object Return;
    public bool Void;
    public Exception Exception;
}

Usage is pretty much the same...

_InvokeNamespaceClassesStaticMethod("mySolution.Macros", "Run", false);

How to generate a random integer number from within a range

As said before modulo isn't sufficient because it skews the distribution. Heres my code which masks off bits and uses them to ensure the distribution isn't skewed.

static uint32_t randomInRange(uint32_t a,uint32_t b) {
    uint32_t v;
    uint32_t range;
    uint32_t upper;
    uint32_t lower;
    uint32_t mask;

    if(a == b) {
        return a;
    }

    if(a > b) {
        upper = a;
        lower = b;
    } else {
        upper = b;
        lower = a; 
    }

    range = upper - lower;

    mask = 0;
    //XXX calculate range with log and mask? nah, too lazy :).
    while(1) {
        if(mask >= range) {
            break;
        }
        mask = (mask << 1) | 1;
    }


    while(1) {
        v = rand() & mask;
        if(v <= range) {
            return lower + v;
        }
    }

}

The following simple code lets you look at the distribution:

int main() {

    unsigned long long int i;


    unsigned int n = 10;
    unsigned int numbers[n];


    for (i = 0; i < n; i++) {
        numbers[i] = 0;
    }

    for (i = 0 ; i < 10000000 ; i++){
        uint32_t rand = random_in_range(0,n - 1);
        if(rand >= n){
            printf("bug: rand out of range %u\n",(unsigned int)rand);
            return 1;
        }
        numbers[rand] += 1;
    }

    for(i = 0; i < n; i++) {
        printf("%u: %u\n",i,numbers[i]);
    }

}

Subtract 1 day with PHP

A one-liner option is:

echo date_create('2011-04-24')->modify('-1 days')->format('Y-m-d');

Running it on Online PHP Editor.


mktime alternative

If you prefer to avoid using string methods, or going into calculations, or even creating additional variables, mktime supports subtraction and negative values in the following way:

// Today's date
echo date('Y-m-d'); // 2016-03-22

// Yesterday's date
echo date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-1, date("Y"))); // 2016-03-21

// 42 days ago
echo date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-42, date("Y"))); // 2016-02-09

//Using a previous date object
$date_object = new DateTime('2011-04-24');
echo date('Y-m-d',
  mktime(0, 0, 0,
     $date_object->format("m"),
     $date_object->format("d")-1,
     $date_object->format("Y")
    )
); // 2011-04-23

Online PHP Editor

How do you convert CString and std::string std::wstring to each other?

It is more effecient to convert CString to std::string using the conversion where the length is specified.

CString someStr("Hello how are you");
std::string std(somStr, someStr.GetLength());

In tight loop this makes a significant performance improvement.

sql how to cast a select query

If you're using SQL (which you didn't say):

select cast(column as varchar(200)) from table 

You can use it in any statement, for example:

select value where othervalue in( select cast(column as varchar(200)) from table)
from othertable

If you want to do a join query, the answer is here already in another post :)

"Cannot update paths and switch to branch at the same time"

You can use these commands: git remote update, git fetch, git checkout -b branch_nameA origin:branch_nameB

I think maybe it's because of your local branch can not track remote branch

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

Forwarding port 80 to 8080 using NGINX

you can do this very easy by using following in sudo vi /etc/nginx/sites-available/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _ your_domain;

    location /health {
            access_log off;
            return 200 "healthy\n";
    }

    location / {
            proxy_pass http://localhost:8080; 
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_cache_bypass $http_upgrade;
    }
  }

Listening for variable changes in JavaScript

No.

But, if it's really that important, you have 2 options (first is tested, second isn't):

First, use setters and getters, like so:

var myobj = {a : 1};

function create_gets_sets(obj) { // make this a framework/global function
    var proxy = {}
    for ( var i in obj ) {
        if (obj.hasOwnProperty(i)) {
            var k = i;
            proxy["set_"+i] = function (val) { this[k] = val; };
            proxy["get_"+i] = function ()    { return this[k]; };
        }
    }
    for (var i in proxy) {
        if (proxy.hasOwnProperty(i)) {
            obj[i] = proxy[i];
        }
    }
}

create_gets_sets(myobj);

then you can do something like:

function listen_to(obj, prop, handler) {
    var current_setter = obj["set_" + prop];
    var old_val = obj["get_" + prop]();
    obj["set_" + prop] = function(val) { current_setter.apply(obj, [old_val, val]); handler(val));
}

then set the listener like:

listen_to(myobj, "a", function(oldval, newval) {
    alert("old : " + oldval + " new : " + newval);
}

Second, you could put a watch on the value:

Given myobj above, with 'a' on it:

function watch(obj, prop, handler) { // make this a framework/global function
    var currval = obj[prop];
    function callback() {
        if (obj[prop] != currval) {
            var temp = currval;
            currval = obj[prop];
            handler(temp, currval);
        }
    }
    return callback;
}

var myhandler = function (oldval, newval) {
    //do something
};

var intervalH = setInterval(watch(myobj, "a", myhandler), 100);

myobj.set_a(2);

Is it possible to insert HTML content in XML document?

so long as your html content doesn't need to contain a CDATA element, you can contain the HTML in a CDATA element, otherwise you'll have to escape the XML entities.

<element><![CDATA[<p>your html here</p>]]></element>

VS

<element>&lt;p&gt;your html here&lt;/p&gt;</element>

How do I change the database name using MySQL?

InnoDB supports RENAME TABLE statement to move table from one database to another. To use it programmatically and rename database with large number of tables, I wrote a couple of procedures to get the job done. You can check it out here - SQL script @Gist

To use it simply call the renameDatabase procedure.

CALL renameDatabase('old_name', 'new_name');

Tested on MariaDB and should work ideally on all RDBMS using InnoDB transactional engine.

How can I rename a single column in a table at select?

select t1.Column as Price, t2.Column as Other_Price
from table1 as t1 INNER JOIN table2 as t2 
ON t1.Key = t2.Key 

like this ?

Java: Local variable mi defined in an enclosing scope must be final or effectively final

Yes this is happening because you are accessing mi variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi so that's why its telling you to set it to final.

Socket transport "ssl" in PHP not enabled

I am using XAMPP and came across the same error. I had done all those steps, added environmental variables path, copied the dll's every directory possible, to /php, /apache/bin, /system32, /syswow64, etc.. but still got this error.

Then after checking the apache error log, I noticed the issue with using brackets in path.

PHP: syntax error, unexpected '(' in C:\Program Files (other)\xampp\php\php.ini on line 707 0 server certificate does NOT include an ID which matches the server name

If you have installed the server in "Program Files (x86)" directory, the same error might occur due to the non-escaped brackets.

To fix this, open php.ini file and locate the line containing "include_path" and enclose the path with double quotes to fix this error.

include_path="C:\Program Files (other)\xampp\php\PEAR"

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

MySQL SELECT last few days?

You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:

created >= DATE_SUB(CURDATE(),INTERVAL 7 day)

Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:

created >= DATE_SUB(NOW(),INTERVAL 1 day)

Getting the minimum of two values in SQL

The solutions using CASE, IIF, and UDF are adequate, but impractical when extending the problem to the general case using more than 2 comparison values. The generalized solution in SQL Server 2008+ utilizes a strange application of the VALUES clause:

SELECT
PaidForPast=(SELECT MIN(x) FROM (VALUES (PaidThisMonth),(OwedPast)) AS value(x))

Credit due to this website: http://sqlblog.com/blogs/jamie_thomson/archive/2012/01/20/use-values-clause-to-get-the-maximum-value-from-some-columns-sql-server-t-sql.aspx

'module' object has no attribute 'DataFrame'

There may be two causes:

  1. It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.

  2. You have not install pandas (pip install pandas) in the python path.

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

Batch file script to zip files

This is the correct syntax for archiving individual; folders in a batch as individual zipped files...

for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\*"

How can I do a line break (line continuation) in Python?

What is the line? You can just have arguments on the next line without any problems:

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

Otherwise you can do something like this:

if (a == True and
    b == False):

or with explicit line break:

if a == True and \
   b == False:

Check the style guide for more information.

Using parentheses, your example can be written over multiple lines:

a = ('1' + '2' + '3' +
    '4' + '5')

The same effect can be obtained using explicit line break:

a = '1' + '2' + '3' + \
    '4' + '5'

Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.

Set CSS property in Javascript?

That's actually quite simple with vanilla JavaScript:

menu.style.width = "100px";

How can I disable mod_security in .htaccess file?

It is possible to do this, but most likely your host implemented mod_security for a reason. Be sure they approve of you disabling it for your own site.

That said, this should do it;

<IfModule mod_security.c>
  SecFilterEngine Off
  SecFilterScanPOST Off
</IfModule>

how to end ng serve or firebase serve

If you cannot see the "ng serve" command running, then you can do the following on Mac OSX (This should work on any Linux and Uni software as well).

ps -ef | grep "ng serve"

From this, find out the PID of the process and then kill it with the following command.

kill -9 <PID>

How to get the width of a react element

Here is a TypeScript version of @meseern's answer that avoids unnecessary assignments on re-render:

import React, { useState, useEffect } from 'react';

export function useContainerDimensions(myRef: React.RefObject<any>) {
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const getDimensions = () => ({
      width: (myRef && myRef.current.offsetWidth) || 0,
      height: (myRef && myRef.current.offsetHeight) || 0,
    });

    const handleResize = () => {
      setDimensions(getDimensions());
    };

    if (myRef.current) {
      setDimensions(getDimensions());
    }

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [myRef]);

  return dimensions;
}

Converting RGB to grayscale/intensity

Heres some code in c to convert rgb to grayscale. The real weighting used for rgb to grayscale conversion is 0.3R+0.6G+0.11B. these weights arent absolutely critical so you can play with them. I have made them 0.25R+ 0.5G+0.25B. It produces a slightly darker image.

NOTE: The following code assumes xRGB 32bit pixel format

unsigned int *pntrBWImage=(unsigned int*)..data pointer..;  //assumes 4*width*height bytes with 32 bits i.e. 4 bytes per pixel
unsigned int fourBytes;
        unsigned char r,g,b;
        for (int index=0;index<width*height;index++)
        {
            fourBytes=pntrBWImage[index];//caches 4 bytes at a time
            r=(fourBytes>>16);
            g=(fourBytes>>8);
            b=fourBytes;

            I_Out[index] = (r >>2)+ (g>>1) + (b>>2); //This runs in 0.00065s on my pc and produces slightly darker results
            //I_Out[index]=((unsigned int)(r+g+b))/3;     //This runs in 0.0011s on my pc and produces a pure average
        }

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Your Button2Click and Button3Click functions pass klad.xls and smimime.txt. These files most likely aren't actual executables indeed.

In order to open arbitrary files using the application associated with them, use ShellExecute

Composer: Command Not Found

Your composer.phar command lacks the flag for executable, or it is not inside the path.

The first problem can be fixed with chmod +x composer.phar, the second by calling it as ./composer.phar -v.

You have to prefix executables that are not in the path with an explicit reference to the current path in Unix, in order to avoid going into a directory that has an executable file with an innocent name that looks like a regular command, but is not. Just think of a cat in the current directory that does not list files, but deletes them.

The alternative, and better, fix for the second problem would be to put the composer.phar file into a location that is mentioned in the path

How to draw a filled triangle in android canvas?

private void drawArrows(Point[] point, Canvas canvas, Paint paint) {

    float [] points  = new float[8];             
    points[0] = point[0].x;      
    points[1] = point[0].y;      
    points[2] = point[1].x;      
    points[3] = point[1].y;         
    points[4] = point[2].x;      
    points[5] = point[2].y;              
    points[6] = point[0].x;      
    points[7] = point[0].y;

    canvas.drawVertices(VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
    Path path = new Path();
    path.moveTo(point[0].x , point[0].y);
    path.lineTo(point[1].x,point[1].y);
    path.lineTo(point[2].x,point[2].y);
    canvas.drawPath(path,paint);

}

Image is not showing in browser?

You need to import your image from the image folder. import name_of_image from '../imageFolder/name_of_image.jpg';

<img src={name_of_image} alt=''>

Please refer here. https://create-react-app.dev/docs/adding-images-fonts-and-files -

Mac OS X - EnvironmentError: mysql_config not found

Ok, well, first of all, let me check if I am on the same page as you:

  • You installed python
  • You did brew install mysql
  • You did export PATH=$PATH:/usr/local/mysql/bin
  • And finally, you did pip install MySQL-Python (or pip3 install mysqlclient if using python 3)

If you did all those steps in the same order, and you still got an error, read on to the end, if, however, you did not follow these exact steps try, following them from the very beginning.

So, you followed the steps, and you're still geting an error, well, there are a few things you could try:

  1. Try running which mysql_config from bash. It probably won't be found. That's why the build isn't finding it either. Try running locate mysql_config and see if anything comes back. The path to this binary needs to be either in your shell's $PATH environment variable, or it needs to be explicitly in the setup.py file for the module assuming it's looking in some specific place for that file.

  2. Instead of using MySQL-Python, try using 'mysql-connector-python', it can be installed using pip install mysql-connector-python. More information on this can be found here and here.

  3. Manually find the location of 'mysql/bin', 'mysql_config', and 'MySQL-Python', and add all these to the $PATH environment variable.

  4. If all above steps fail, then you could try installing 'mysql' using MacPorts, in which case the file 'mysql_config' would actually be called 'mysql_config5', and in this case, you would have to do this after installing: export PATH=$PATH:/opt/local/lib/mysql5/bin. You can find more details here.

Note1: I've seen some people saying that installing python-dev and libmysqlclient-dev also helped, however I do not know if these packages are available on Mac OS.

Note2: Also, make sure to try running the commands as root.

I got my answers from (besides my brain) these places (maybe you could have a look at them, to see if it would help): 1, 2, 3, 4.

I hoped I helped, and would be happy to know if any of this worked, or not. Good luck.

Android view pager with page indicator

you have to do following:

1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator 2- Import into the Eclipse.

After importing if you want to make following type of screen then follow below steps -

Screen Shot

change in

Sample circles Default

  package com.viewpagerindicator.sample;
  import android.os.Bundle;  
  import android.support.v4.view.ViewPager;
  import com.viewpagerindicator.CirclePageIndicator;

  public class SampleCirclesDefault extends BaseSampleActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_circles);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
  //  mPager.setAdapter(mAdapter);

    ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
    mPager.setAdapter(adapter);


    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
  }
}

ImageAdapter

 package com.viewpagerindicator.sample;

 import android.content.Context;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.widget.TextView;

 public class ImageAdapter extends PagerAdapter {
 private Context mContext;

 private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
        R.drawable.about3, R.drawable.about4, R.drawable.about5,
        R.drawable.about6, R.drawable.about7

 };

 public ImageAdapter(Context context) {
    mContext = context;
 }

 public int getCount() {
    return mImageIds.length;
 }

 public Object getItem(int position) {
    return position;
 }

 public long getItemId(int position) {
    return position;
 }

 @Override
 public Object instantiateItem(ViewGroup container, final int position) {

    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View convertView = inflater.inflate(R.layout.gallery_view, null);

    ImageView view_image = (ImageView) convertView
            .findViewById(R.id.view_image);
    TextView description = (TextView) convertView
            .findViewById(R.id.description);

    view_image.setImageResource(mImageIds[position]);
    view_image.setScaleType(ImageView.ScaleType.FIT_XY);

    description.setText("The natural habitat of the Niligiri tahr,Rajamala          Rajamala is 2695 Mts above sea level"
        + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
                    + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");

    ((ViewPager) container).addView(convertView, 0);

    return convertView;
 }

 @Override
 public boolean isViewFromObject(View view, Object object) {
    return view == ((View) object);
 }

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((ViewGroup) object);
 }
}

gallery_view.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:background="@drawable/about_bg"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/about_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:id="@+id/about_layout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".4"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/view_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="@drawable/about1">
     </ImageView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/about_layout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".6"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="18dp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearance" />


        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:fillViewport="false"
            android:orientation="vertical"
            android:scrollbars="none"
            android:layout_marginBottom="10dp"
            android:padding="10dp" >

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#000000"
                android:text="TextView" />

            </ScrollView>
    </LinearLayout>
 </LinearLayout>

How to correctly represent a whitespace character

You can always use Unicode character, for me personally this is the most clear solution:

var space = "\u0020"

What are the parameters for the number Pipe - Angular 2

The parameter has this syntax:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

So your example of '1.2-2' means:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

Convert java.util.Date to java.time.LocalDate

Date input = new Date();
LocalDateTime  conv=LocalDateTime.ofInstant(input.toInstant(), ZoneId.systemDefault());
LocalDate convDate=conv.toLocalDate();

The Date instance does contain time too along with the date while LocalDate doesn't. So you can firstly convert it into LocalDateTime using its method ofInstant() then if you want it without time then convert the instance into LocalDate.

Why isn't Python very good for functional programming?

Let me demonstrate with a piece of code taken from an answer to a "functional" Python question on SO

Python:

def grandKids(generation, kidsFunc, val):
  layer = [val]
  for i in xrange(generation):
    layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
  return layer

Haskell:

grandKids generation kidsFunc val =
  iterate (concatMap kidsFunc) [val] !! generation

The main difference here is that Haskell's standard library has useful functions for functional programming: in this case iterate, concat, and (!!)

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

How can I access "static" class variables within class methods in Python?

class Foo(object):    
    bar = 1

    def bah(object_reference):
        object_reference.var = Foo.bar
        return object_reference.var


f = Foo() 
print 'var=', f.bah()

How to style a JSON block in Github Wiki?

You can use some online websites to beautify JSON, such as: JSON Formatter, and then paste the beautified result to WIKI

How to get the onclick calling object?

http://docs.jquery.com/Events/jQuery.Event

Try with event.target

Contains the DOM element that issued the event. This can be the element that registered for the event or a child of it.

List an Array of Strings in alphabetical order

The first thing you tried seems to work fine. Here is an example program.
Press the "Start" button at the top of this page to run it to see the output yourself.

import java.util.Arrays;

public class Foo{
    public static void main(String[] args) {
        String [] stringArray = {"ab", "aB", "c", "0", "2", "1Ad", "a10"};
        orderedGuests(stringArray);
    }

    public static void orderedGuests(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }
}

Using Java 8 to convert a list of objects into a string obtained from the toString() method

StringListName = ObjectListName.stream().map( m -> m.toString() ).collect( Collectors.toList() );

What's the best way to parse command line arguments?

I extended Erco's approach to allow for required positional arguments and for optional arguments. These should precede the -d, -v etc. arguments.

Positional and optional arguments can be retrieved with PosArg(i) and OptArg(i, default) respectively. When an optional argument is found the start position of searching for options (e.g. -i) is moved 1 ahead to avoid causing an 'unexpected' fatal.

import os,sys


def HelpAndExit():
    print("<<your help output goes here>>")
    sys.exit(1)

def Fatal(msg):
    sys.stderr.write("%s: %s\n" % (os.path.basename(sys.argv[0]), msg))
    sys.exit(1)

def NextArg(i):
    '''Return the next command line argument (if there is one)'''
    if ((i+1) >= len(sys.argv)):
        Fatal("'%s' expected an argument" % sys.argv[i])
    return(1, sys.argv[i+1])

def PosArg(i):
    '''Return positional argument'''
    if i >= len(sys.argv):
        Fatal("'%s' expected an argument" % sys.argv[i])
    return sys.argv[i]

def OptArg(i, default):
    '''Return optional argument (if there is one)'''
    if i >= len(sys.argv):
        Fatal("'%s' expected an argument" % sys.argv[i])
    if sys.argv[i][:1] != '-':
        return True, sys.argv[i]
    else:
        return False, default


### MAIN
if __name__=='__main__':

    verbose = 0
    debug   = 0
    infile  = "infile"
    outfile = "outfile"
    options_start = 3

    # --- Parse two positional parameters ---
    n1 = int(PosArg(1))
    n2 = int(PosArg(2))

    # --- Parse an optional parameters ---
    present, a3 = OptArg(3,50)
    n3 = int(a3)
    options_start += int(present)

    # --- Parse rest of command line ---
    skip = 0
    for i in range(options_start, len(sys.argv)):
        if not skip:
            if   sys.argv[i][:2] == "-d": debug ^= 1
            elif sys.argv[i][:2] == "-v": verbose ^= 1
            elif sys.argv[i][:2] == "-i": (skip,infile)  = NextArg(i)
            elif sys.argv[i][:2] == "-o": (skip,outfile) = NextArg(i)
            elif sys.argv[i][:2] == "-h": HelpAndExit()
            elif sys.argv[i][:1] == "-":  Fatal("'%s' unknown argument" % sys.argv[i])
            else:                         Fatal("'%s' unexpected" % sys.argv[i])
        else: skip = 0

    print("Number 1 = %d" % n1)
    print("Number 2 = %d" % n2)
    print("Number 3 = %d" % n3)
    print("Debug    = %d" % debug)
    print("verbose  = %d" % verbose)
    print("infile   = %s" % infile)
    print("outfile  = %s" % outfile) 

Disable Buttons in jQuery Mobile

UPDATE:

Since this question still gets a lot of hits I'm also adding the current jQM Docs on how to disable the button:

Updated Examples:

enable enable a disabled form button

$('[type="submit"]').button('enable');  

disable disable a form button

$('[type="submit"]').button('disable'); 

refresh update the form button
If you manipulate a form button via JavaScript, you must call the refresh method on it to update the visual styling.

$('[type="submit"]').button('refresh');

Original Post Below:

Live Example: http://jsfiddle.net/XRjh2/2/

UPDATE:

Using @naugtur example below: http://jsfiddle.net/XRjh2/16/

UPDATE #2:

Link button example:

JS

var clicked = false;

$('#myButton').click(function() {
    if(clicked === false) {
        $(this).addClass('ui-disabled');
        clicked = true;
        alert('Button is now disabled');
    } 
});

$('#enableButton').click(function() {
    $('#myButton').removeClass('ui-disabled');
    clicked = false; 
});

HTML

<div data-role="page" id="home">
    <div data-role="content">

        <a href="#" data-role="button" id="myButton">Click button</a>
        <a href="#" data-role="button" id="enableButton">Enable button</a>

    </div>
</div>

NOTE: - http://jquerymobile.com/demos/1.0rc2/docs/buttons/buttons-types.html

Links styled like buttons have all the same visual options as true form-based buttons below, but there are a few important differences. Link-based buttons aren't part of the button plugin and only just use the underlying buttonMarkup plugin to generate the button styles so the form button methods (enable, disable, refresh) aren't supported. If you need to disable a link-based button (or any element), it's possible to apply the disabled class ui-disabled yourself with JavaScript to achieve the same effect.

remove attribute display:none; so the item will be visible

$('#lol').get(0).style.display=''

or..

$('#lol').css('display', '')

How to get the Google Map based on Latitude on Longitude?

this is the javascript to display google map by passing your longitude and latitude.

<script>
    function initialize() {
      var myLatlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }

    function loadScript() {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
      document.body.appendChild(script);
    }

    window.onload = loadScript;


</script>

How to detect if javascript files are loaded?

Change the loading order of your scripts so that function1 was defined before using it in ready callback.

Plus I always found it better to define ready callback as an anonymous method then named one.

What is the difference between Digest and Basic Authentication?

HTTP Basic Access Authentication

  • STEP 1 : the client makes a request for information, sending a username and password to the server in plain text
  • STEP 2 : the server responds with the desired information or an error

Basic Authentication uses base64 encoding(not encryption) for generating our cryptographic string which contains the information of username and password. HTTP Basic doesn’t need to be implemented over SSL, but if you don’t, it isn’t secure at all. So I’m not even going to entertain the idea of using it without.

Pros:

  • Its simple to implement, so your client developers will have less work to do and take less time to deliver, so developers could be more likely to want to use your API
  • Unlike Digest, you can store the passwords on the server in whatever encryption method you like, such as bcrypt, making the passwords more secure
  • Just one call to the server is needed to get the information, making the client slightly faster than more complex authentication methods might be

Cons:

  • SSL is slower to run than basic HTTP so this causes the clients to be slightly slower
  • If you don’t have control of the clients, and can’t force the server to use SSL, a developer might not use SSL, causing a security risk

In Summary – if you have control of the clients, or can ensure they use SSL, HTTP Basic is a good choice. The slowness of the SSL can be cancelled out by the speed of only making one request

Syntax of basic Authentication

Value = username:password
Encoded Value =  base64(Value)
Authorization Value = Basic <Encoded Value> 
//at last Authorization key/value map added to http header as follows
Authorization: <Authorization Value>

HTTP Digest Access Authentication
Digest Access Authentication uses the hashing(i.e digest means cut into small pieces) methodologies to generate the cryptographic result. HTTP Digest access authentication is a more complex form of authentication that works as follows:

  • STEP 1 : a client sends a request to a server
  • STEP 2 : the server responds with a special code (called a i.e. number used only once), another string representing the realm(a hash) and asks the client to authenticate
  • STEP 3 : the client responds with this nonce and an encrypted version of the username, password and realm (a hash)
  • STEP 4 : the server responds with the requested information if the client hash matches their own hash of the username, password and realm, or an error if not

Pros:

  • No usernames or passwords are sent to the server in plaintext, making a non-SSL connection more secure than an HTTP Basic request that isn’t sent over SSL. This means SSL isn’t required, which makes each call slightly faster

Cons:

  • For every call needed, the client must make 2, making the process slightly slower than HTTP Basic
  • HTTP Digest is vulnerable to a man-in-the-middle security attack which basically means it could be hacked
  • HTTP Digest prevents use of the strong password encryption, meaning the passwords stored on the server could be hacked

In Summary, HTTP Digest is inherently vulnerable to at least two attacks, whereas a server using strong encryption for passwords with HTTP Basic over SSL is less likely to share these vulnerabilities.

If you don’t have control over your clients however they could attempt to perform Basic authentication without SSL, which is much less secure than Digest.

RFC 2069 Digest Access Authentication Syntax

Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:Hash2)

RFC 2617 Digest Access Authentication Syntax

Hash1=MD5(username:realm:password)
Hash2=MD5(method:digestURI)
response=MD5(Hash1:nonce:nonceCount:cnonce:qop:Hash2)
//some additional parameters added 

source and example

In Postman looks as follows:

enter image description here

Note:

  • The Basic and Digest schemes are dedicated to the authentication using a username and a secret.
  • The Bearer scheme is dedicated to the authentication using a token.

how to replace an entire column on Pandas.DataFrame

For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.

Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4

columns_to_overwrite = ["column_1", "column_3"]

First delete the columns that you intend to replace...

original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)

... then re-insert the columns, but using the values that you intended to overwrite

original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]

About catching ANY exception

Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:

import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Logs the error appropriately. 

You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.

The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.

Storing Images in PostgreSQL

Try this. I've use the Large Object Binary (LOB) format for storing generated PDF documents, some of which were 10+ MB in size, in a database and it worked wonderfully.

How do I solve this "Cannot read property 'appendChild' of null" error?

Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.

Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
    if (container !== null) {
        container.appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
    if (container !== null) {
        container.appendChild(elem1);
    } else console.log("aaaaa");
}

Identify duplicate values in a list in Python

You can print duplicate and Unqiue using below logic using list.

def dup(x):
    duplicate = []
    unique = []
    for i in x:
        if i in unique:
            duplicate.append(i)
        else:
            unique.append(i)
    print("Duplicate values: ",duplicate)
    print("Unique Values: ",unique)

list1 = [1, 2, 1, 3, 2, 5]
dup(list1)

Remove CSS from a Div using JQuery

As a note, depending upon the property you may be able to set it to auto.

Having trouble setting working directory

This may help... use the following code and browse the folder you want to set as the working folder

setwd(choose.dir())

Remove menubar from Electron app

Most of the answers here are not valid for newer versions. With the version of 9.0 or upper, Menu.setApplicationMenu(null); should work. By the way, Menu exported from electron package: const {Menu} = require('electron');

Can you control how an SVG's stroke-width is drawn?

I found an easy way, which has a few restrictions, but worked for me:

  • define the shape in defs
  • define a clip path referencing the shape
  • use it and double the stroke with as the outside is clipped

Here a working example:

_x000D_
_x000D_
<svg width="240" height="240" viewBox="0 0 1024 1024">_x000D_
<defs>_x000D_
 <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>_x000D_
 <clipPath id="clip">_x000D_
  <use xlink:href="#ld"/>_x000D_
 </clipPath>_x000D_
</defs>_x000D_
<g>_x000D_
 <use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>_x000D_
</g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

What does \0 stand for?

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case.

The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0).

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

Python, print all floats to 2 decimal places in output

If you just want to convert the values to nice looking strings do the following:

twodecimals = ["%.2f" % v for v in vars]

Alternatively, you could also print out the units like you have in your question:

vars = [0, 1, 2, 3] # just some example values
units = ['kg', 'lb', 'gal', 'l']
delimiter = ', ' # or however you want the values separated

print delimiter.join(["%.2f %s" % (v,u) for v,u in zip(vars, units)])
Out[189]: '0.00 kg, 1.00 lb, 2.00 gal, 3.00 l'

The second way allows you to easily change the delimiter (tab, spaces, newlines, whatever) to suit your needs easily; the delimiter could also be a function argument instead of being hard-coded.

Edit: To use your 'name = value' syntax simply change the element-wise operation within the list comprehension:

print delimiter.join(["%s = %.2f" % (u,v) for v,u in zip(vars, units)])
Out[190]: 'kg = 0.00, lb = 1.00, gal = 2.00, l = 3.00'

Checkout one file from Subversion

You can do it in two steps:

  1. Checkout an empty SVN repository with meta information only:

    $ cd /tmp
    
    $ svn co --depth empty http://svn.your.company.ca/training/trunk/sql
    
  2. Run svn up to update specified file:

    $ svn up http://svn.your.company.ca/training/trunk/sql/showSID.sql
    

SqlServer: Login failed for user

Also make sure that account is not locked out in user properties "Status" tab

Write HTML to string

When I deal with this problem in other languages I go for a separation of code and HTML. Something like:

1.) Create a HTML template. use [varname] placeholders to mark replaced/inserted content.
2.) Fill your template variables from an array or structure/mapping/dictionary

Write( FillTemplate(myHTMLTemplate, myVariables) ) # pseudo-code

JSON array get length

At my Version the function to get the lenght or size was Count()

You're Welcome, hope it help someone.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

My problem is that I accidentally set the arguments for Main

static void Main(object value)

thanks to my refactoring tool. Took couple mins to figure out but should help someone along the way.

HTML5 Number Input - Always show 2 decimal places

import { Component, Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'replace'
})

export class ReplacePipe implements PipeTransform {
    transform(value: any): any {
        value = String(value).toString();
        var afterPoint = '';
        var plus = ',00';
        if (value.length >= 4) {
            if (value.indexOf('.') > 0) {
                afterPoint = value.substring(value.indexOf('.'), value.length);
                var te = afterPoint.substring(0, 3);
                if (te.length == 2) {
                    te = te + '0';
                }
            }
            if (value.indexOf('.') > 0) {
                if (value.indexOf('-') == 0) {
                    value = parseInt(value);
                    if (value == 0) {
                        value = '-' + value + te;
                        value = value.toString();
                    }
                    else {
                        value = value + te;
                        value = value.toString();
                    }
                }
                else {
                    value = parseInt(value);
                    value = value + te;
                    value = value.toString();
                }
            }
            else {
                value = value.toString() + plus;
            }
            var lastTwo = value.substring(value.length - 2);
            var otherNumbers = value.substring(0, value.length - 3);
            if (otherNumbers != '')
                lastTwo = ',' + lastTwo;
            let newValue = otherNumbers.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + lastTwo;
            parseFloat(newValue);
            return `${newValue}`;
        }
}
}

PHP - Get array value with a numeric index

$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

How to access first element of JSON object array?

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.

So either correct your source to:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };

and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

How to find all links / pages on a website

If this is a programming question, then I would suggest you write your own regular expression to parse all the retrieved contents. Target tags are IMG and A for standard HTML. For JAVA,

final String openingTags = "(<a [^>]*href=['\"]?|<img[^> ]* src=['\"]?)";

this along with Pattern and Matcher classes should detect the beginning of the tags. Add LINK tag if you also want CSS.

However, it is not as easy as you may have intially thought. Many web pages are not well-formed. Extracting all the links programmatically that human being can "recognize" is really difficult if you need to take into account all the irregular expressions.

Good luck!

Disabling user input for UITextfield in swift

If you want to do it while keeping the user interaction on. In my case I am using (or rather misusing) isFocused

self.myField.inputView = UIView()

This way it will focus but keyboard won't show up.

Examples for string find in Python

If you want to search for the last instance of a string in a text, you can run rfind.

Example:

   s="Hello"
   print s.rfind('l')

output: 3

*no import needed

Complete syntax:

stringEx.rfind(substr, beg=0, end=len(stringEx))

How to uninstall downloaded Xcode simulator?

Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.

I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.

So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.

Delete all the shutdown simulators:

xcrun simctl list | grep -w "Shutdown"  | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete  uuid

If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.

enter image description here

How to copy commits from one branch to another?

Or if You are little less on the evangelist's side You can do a little ugly way I'm using. In deploy_template there are commits I want to copy on my master as branch deploy

git branch deploy deploy_template
git checkout deploy
git rebase master

This will create new branch deploy (I use -f to overwrite existing deploy branch) on deploy_template, then rebase this new branch onto master, leaving deploy_template untouched.

Change Select List Option background colour on hover

I realise this is an older question, but I recently came across this need and came up with the following solution using jQuery and CSS:

jQuery('select[name*="lstDestinations"] option').hover(
        function() {
            jQuery(this).addClass('highlight');
        }, function() {
            jQuery(this).removeClass('highlight');
        }
    );

and the css:

.highlight {
    background-color:#333;
    cursor:pointer;
}

Perhaps this helps someone else.

How to use a wildcard in the classpath to add multiple jars?

From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

This should work in Java6, not sure about Java5

(If it seems it does not work as expected, try putting quotes. eg: "foo/*")

Stop an input field in a form from being submitted

Handle the form's submit in a function via onSubmit() and perform something like below to remove the form element: Use getElementById() of the DOM, then using [object].parentNode.removeChild([object])

suppose your field in question has an id attribute "my_removable_field" code:

var remEl = document.getElementById("my_removable_field");
if ( remEl.parentNode && remEl.parentNode.removeChild ) {
remEl.parentNode.removeChild(remEl);
}

This will get you exactly what you are looking for.

use jQuery to get values of selected checkboxes

$("#locationthemes").prop("checked")

How do I find the authoritative name-server for a domain name?

Unfortunately, most of these tools only return the NS record as provided by the actual name server itself. To be more accurate in determining which name servers are actually responsible for a domain, you'd have to either use "whois" and check the domains listed there OR use "dig [domain] NS @[root name server]" and run that recursively until you get the name server listings...

I wish there were a simple command line that you could run to get THAT result dependably and in a consistent format, not just the result that is given from the name server itself. The purpose of this for me is to be able to query about 330 domain names that I manage so I can determine exactly which name server each domain is pointing to (as per their registrar settings).

Anyone know of a command using "dig" or "host" or something else on *nix?

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

Programmatically create a UIView with color gradient

Simple swift view based on Yuchen's version

class GradientView: UIView {
    override class func layerClass() -> AnyClass { return CAGradientLayer.self }

    lazy var gradientLayer: CAGradientLayer = {
        return self.layer as! CAGradientLayer
    }()

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

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

}

Then you can use gradientLayer after initialization like this...

someView.gradientLayer.colors = [UIColor.whiteColor().CGColor, UIColor.blackColor().CGColor]

Internal Error 500 Apache, but nothing in the logs?

Add HttpProtocolOptions Unsafe to your apache config file and restart the apache server. It shows the error details.

java.lang.OutOfMemoryError: Java heap space in Maven

When I run maven test, java.lang.OutOfMemoryError happens. I google it for solutions and have tried to export MAVEN_OPTS=-Xmx1024m, but it did not work.

Setting the Xmx options using MAVEN_OPTS does work, it does configure the JVM used to start Maven. That being said, the maven-surefire-plugin forks a new JVM by default, and your MAVEN_OPTS are thus not passed.

To configure the sizing of the JVM used by the maven-surefire-plugin, you would either have to:

  • change the forkMode to never (which is be a not so good idea because Maven won't be isolated from the test) ~or~
  • use the argLine parameter (the right way):

In the later case, something like this:

<configuration>
  <argLine>-Xmx1024m</argLine>
</configuration>

But I have to say that I tend to agree with Stephen here, there is very likely something wrong with one of your test and I'm not sure that giving more memory is the right solution to "solve" (hide?) your problem.

References

Regular expression which matches a pattern, or is an empty string

\b matches a word boundary. I think you can use ^$ for empty string.

How to kill an application with all its activities?

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

    if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Mac OS apps cannot read bash environment variables. Look at this question Setting environment variables in OS X? to expose M2_HOME to all applications including IntelliJ. You do need to restart after doing this.

How to get a user's time zone?

edit/update:

Xcode 8 or later • Swift 3 or later

var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT  // -7200

if you need the abbreviation:

var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation   // "GMT-2"

if you need the timezone identifier:

var localTimeZoneIdentifier: String { return TimeZone.current.identifier }

localTimeZoneIdentifier // "America/Sao_Paulo"

To know all timezones abbreviations available:

var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations   // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]

To know all timezones names (identifiers) available:

var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers           // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]

There is a few other info you may need:

var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)

var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset)  // 3600 seconds (1 hour - daylight savings time)


var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition }    //  "Feb 18, 2017, 11:00 PM"
 print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition   // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"

var nextDaylightSavingTimeTransitionAfterNext: Date? {
    guard
        let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
        else { return nil }
    return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}

nextDaylightSavingTimeTransitionAfterNext  //   "Oct 15, 2017, 1:00 AM"

TimeZone - Apple Developer Swift Documentation

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I just had the same message with the following code (in IcedCoffeeScript):

f = (err,cb) ->
  cb null, true

await f defer err, res
console.log err if err  

This seemed to me like regular ICS code. I unfolded the await-defer construct to regular CoffeeScript:

f (err,res) ->
  console.log err if err

What really happend was that I tried to pass 1 callback function( with 2 parameters ) to function f expecting two parameters, effectively not setting cb inside f, which the compiler correctly reported as undefined is not a function.

The mistake happened because I blindly pasted callback-style boilerplate code. f doesn't need an err parameter passed into it, thus should simply be:

f = (cb) ->
  cb null, true
f (err,res) ->
  console.log err if err

In the general case, I'd recommend to double-check function signatures and invocations for matching arities. The call-stack in the error message should be able to provide helpful hints.

In your special case, I recommend looking for function definitions appearing twice in the merged file, with different signatures, or assignments to global variables holding functions.

How can I format date by locale in Java?

I agree with Laura and the SimpleDateFormat which is the best way to manage Dates in java. You can set the pattern and the locale. Plus you can have a look at this wikipedia article about Date in the world -there are not so many different ways to use it; typically USA / China / rest of the world -

Running a cron job on Linux every six hours

You need to use *

0 */6 * * * /path/to/mycommand

Also you can refer to https://crontab.guru/ which will help you in scheduling better...

How to change JDK version for an Eclipse project

In the preferences section under Java -> Installed JREs click the Add button and navigate to the 1.5 JDK home folder. Then check that one in the list and it will become the default for all projects:

enter image description here

mysql data directory location

As suggested, I edited this message to place a proper answer.

The 'physical' location of the mysql databases are under /usr/local/mysql

the mysql is a symlink to the current active mysql installation, in my case the exact folder is mysql-5.6.10-osx10.7-x86_64.

Inside that folder you'll see another data folder, inside it are RESTRICTED folders with your databases.

You can't actually see the size of your databases (that was my issue) from the Finder because the folder are protected, you can though see from the terminal with sudo du -sh /usr/local/mysql/data/{your-database-name} and like this you'll get a nice formatted output with the size.

In those folder you have different files with all the folders present in your database, so it's safer to check the db's folder to get a size.

That's it. Enjoy!

How to redirect output to a file and stdout

< command > |& tee filename # this will create a file "filename" with command status as a content, If a file already exists it will remove existed content and writes the command status.

< command > | tee >> filename # this will append status to the file but it doesn't print the command status on standard_output (screen).

I want to print something by using "echo" on screen and append that echoed data to a file

echo "hi there, Have to print this on screen and append to a file" 

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Converting a column within pandas dataframe from int to string

Warning: Both solutions given ( astype() and apply() ) do not preserve NULL values in either the nan or the None form.

import pandas as pd
import numpy as np

df = pd.DataFrame([None,'string',np.nan,42], index=[0,1,2,3], columns=['A'])

df1 = df['A'].astype(str)
df2 =  df['A'].apply(str)

print df.isnull()
print df1.isnull()
print df2.isnull()

I believe this is fixed by the implementation of to_string()

random.seed(): What does it do?

Seed() can be used for later use ---

Example:
>>> import numpy as np
>>> np.random.seed(12)
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
>>>
>>> np.random.seed(12) # When you use same seed as before you will get same random output as before
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>

How to get the last value of an ArrayList

The last item in the list is list.size() - 1. The collection is backed by an array and arrays start at index 0.

So element 1 in the list is at index 0 in the array

Element 2 in the list is at index 1 in the array

Element 3 in the list is at index 2 in the array

and so on..

Android: How to set password property in an edit text?

See this link text view android:password

This applies for EditText as well, as it is a known direct subclass of TextView.

How can I find whitespace in a String?

For checking if a string contains whitespace use a Matcher and call it's find method.

Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();

If you want to check if it only consists of whitespace then you can use String.matches:

boolean isWhitespace = s.matches("^\\s*$");

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

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

NumPy first and last element from array

How about this?

>>> import numpy
>>> test1 = numpy.array([1,23,4,6,7,8])
>>> forward = iter(test1)
>>> backward = reversed(test1)
>>> for a in range((len(test1)+1)//2):
...     print forward.next(), backward.next()
... 
1 8
23 7
4 6

The (len(test1)+1)//2 ensures that the middle element of odd length arrays is also returned:

>>> test1 = numpy.array([1,23,4,9,6,7,8]) # additional element '9' in the middle
>>> forward = iter(test1)                                                      
>>> backward = reversed(test1)
>>> for a in range((len(test1)+1)//2):
...     print forward.next(), backward.next()
1 8
23 7
4 6
9 9

Using just len(test1)//2 will drop the middle elemen of odd length arrays.

Select all child elements recursively in CSS

The rule is as following :

A B 

B as a descendant of A

A > B 

B as a child of A

So

div.dropdown *

and not

div.dropdown > *

Unsupported major.minor version 52.0 when rendering in Android Studio

Also, if issue appears while executing ./gradlew command, setting java home in gradle.properties file, solves this issue:

org.gradle.java.home=/usr/java/jdk1.8.0_45/

Pandas split DataFrame by column value

Using groupby you could split into two dataframes like

In [1047]: df1, df2 = [x for _, x in df.groupby(df['Sales'] < 30)]

In [1048]: df1
Out[1048]:
   A  Sales
2  7     30
3  6     40
4  1     50

In [1049]: df2
Out[1049]:
   A  Sales
0  3     10
1  4     20

Test process.env with Jest

The way I did it can be found in this Stack Overflow question.

It is important to use resetModules before each test and then dynamically import the module inside the test:

describe('environmental variables', () => {
  const OLD_ENV = process.env;

  beforeEach(() => {
    jest.resetModules() // Most important - it clears the cache
    process.env = { ...OLD_ENV }; // Make a copy
  });

  afterAll(() => {
    process.env = OLD_ENV; // Restore old environment
  });

  test('will receive process.env variables', () => {
    // Set the variables
    process.env.NODE_ENV = 'dev';
    process.env.PROXY_PREFIX = '/new-prefix/';
    process.env.API_URL = 'https://new-api.com/';
    process.env.APP_PORT = '7080';
    process.env.USE_PROXY = 'false';

    const testedModule = require('../../config/env').default

    // ... actual testing
  });
});

If you look for a way to load environment values before running the Jest look for the answer below. You should use setupFiles for that.

Convert date to datetime in Python

Today being 2016, I think the cleanest solution is provided by pandas Timestamp:

from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)

Timestamp is the pandas equivalent of datetime and is interchangable with it in most cases. Check:

from datetime import datetime
isinstance(pd.Timestamp(d), datetime)

But in case you really want a vanilla datetime, you can still do:

pd.Timestamp(d).to_datetime()

Timestamps are a lot more powerful than datetimes, amongst others when dealing with timezones. Actually, Timestamps are so powerful that it's a pity they are so poorly documented...

How to get a value from a Pandas DataFrame and not the index and object type

df[df.Letters=='C'].Letters.item()

This returns the first element in the Index/Series returned from that selection. In this case, the value is always the first element.

EDIT:

Or you can run a loc() and access the first element that way. This was shorter and is the way I have implemented it in the past.

IOError: [Errno 2] No such file or directory trying to open a file

Um...

with open(os.path.join(src_dir, f)) as fin:
    for line in fin:

Also, you never output to a new file.

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

When should I use Lazy<T>?

A great real-world example of where lazy loading comes in handy is with ORM's (Object Relation Mappers) such as Entity Framework and NHibernate.

Say you have an entity Customer which has properties for Name, PhoneNumber, and Orders. Name and PhoneNumber are regular strings but Orders is a navigation property that returns a list of every order the customer ever made.

You often might want to go through all your customer's and get their name and phone number to call them. This is a very quick and simple task, but imagine if each time you created a customer it automatically went and did a complex join to return thousands of orders. The worst part is that you aren't even going to use the orders so it is a complete waste of resources!

This is the perfect place for lazy loading because if the Order property is lazy it will not go fetch all the customer's order unless you actually need them. You can enumerate the Customer objects getting only their Name and Phone Number while the Order property is patiently sleeping, ready for when you need it.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I came to this solution and it did not worked for me! Because I was using 64bit I had to replace the registry:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

Instead of the one that everyone talks about:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]

Java: using switch statement with enum under subclass

Write someMethod() in this way:

public void someMethod() {

    SomeClass.AnotherClass.MyEnum enumExample = SomeClass.AnotherClass.MyEnum.VALUE_A;

    switch (enumExample) {
    case VALUE_A:
        break;
    }

}

In switch statement you must use the constant name only.

Setting Java heap space under Maven 2 on Windows

If you are running out of heap space during the surefire (or failsafe) JUnit testing run, changing MAVEN_OPTS may not help you. I kept trying different configurations in MAVEN_OPTS with no luck until I found this post that fixed the problem.

Basically the JUnits fork off into their own environment and ignore the settings in MAVEN_OPTS. You need to configure surefire in your pom to add more memory for the JUnits.

Hopefully this can save someone else some time!


Edit: Copying solution from Keith Chapman's blog just in case the link breaks some day:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <forkMode>pertest</forkMode> 
    <argLine>-Xms256m -Xmx512m</argLine>
    <testFailureIgnore>false</testFailureIgnore> 
    <skip>false</skip> 
    <includes> 
      <include>**/*IntegrationTestSuite.java</include>
    </includes>
  </configuration>
</plugin>

Update (5/31/2017): Thanks to @johnstosh for pointing this out - surefire has evolved a bit since I put this answer out there. Here is a link to their documentation and an updated code sample (arg line is still the important part for this question):

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <forkCount>3</forkCount>
        <reuseForks>true</reuseForks>
        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
        <systemPropertyVariables>
            <databaseSchema>MY_TEST_SCHEMA_${surefire.forkNumber}</databaseSchema>
        </systemPropertyVariables>
        <workingDirectory>FORK_DIRECTORY_${surefire.forkNumber}</workingDirectory>
    </configuration>
  </plugin>

Storing Python dictionaries

My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.

To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list or an object as root. So I considered that my JSON file always has a list of objects and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w):

def saveJson(url,sc): # This function writes the two values to the file
    newdata = {'url':url,'sc':sc}
    json_path = "db/file.json"

    old_list= []
    with open(json_path) as myfile:  # Read the contents first
        old_list = json.load(myfile)
    old_list.append(newdata)

    with open(json_path,"w") as myfile:  # Overwrite the whole content
        json.dump(old_list, myfile, sort_keys=True, indent=4)

    return "success"

The new JSON file will look something like this:

[
    {
        "sc": "a11",
        "url": "www.google.com"
    },
    {
        "sc": "a12",
        "url": "www.google.com"
    },
    {
        "sc": "a13",
        "url": "www.google.com"
    }
]

NOTE: It is essential to have a file named file.json with [] as initial data for this approach to work

PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.

Regular expression negative lookahead

A negative lookahead says, at this position, the following regex can not match.

Let's take a simplified example:

a(?!b(?!c))

a      Match: (?!b) succeeds
ac     Match: (?!b) succeeds
ab     No match: (?!b(?!c)) fails
abe    No match: (?!b(?!c)) fails
abc    Match: (?!b(?!c)) succeeds

The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

Why does the order in which libraries are linked sometimes cause errors in GCC?

A quick tip that tripped me up: if you're invoking the linker as "gcc" or "g++", then using "--start-group" and "--end-group" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.

You need to write them as "-Wl,--start-group" etc. to tell GCC to pass the argument through to the linker.

How do I decrease the size of my sql server log file?

This is one of the best suggestion in which is done using query. Good for those who has a lot of databases just like me. Can run it using a script.

https://medium.com/@bharatdwarkani/shrinking-sql-server-db-log-file-size-sql-server-db-maintenance-7ddb0c331668

USE DatabaseName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DatabaseName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DatabaseName_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DatabaseName
SET RECOVERY FULL;
GO

Please explain the exec() function and its family

When a process uses fork(), it creates a duplicate copy of itself and this duplicates becomes the child of the process. The fork() is implemented using clone() system call in linux which returns twice from kernel.

  • A non-zero value(Process ID of child) is returned to the parent.
  • A value of zero is returned to the child.
  • In case the child is not created successfully due to any issues like low memory, -1 is returned to the fork().

Let’s understand this with an example:

pid = fork(); 
// Both child and parent will now start execution from here.
if(pid < 0) {
    //child was not created successfully
    return 1;
}
else if(pid == 0) {
    // This is the child process
    // Child process code goes here
}
else {
    // Parent process code goes here
}
printf("This is code common to parent and child");

In the example, we have assumed that exec() is not used inside the child process.

But a parent and child differs in some of the PCB(process control block) attributes. These are:

  1. PID - Both child and parent have a different Process ID.
  2. Pending Signals - The child doesn’t inherit Parent’s pending signals. It will be empty for the child process when created.
  3. Memory Locks - The child doesn’t inherit its parent’s memory locks. Memory locks are locks which can be used to lock a memory area and then this memory area cannot be swapped to disk.
  4. Record Locks - The child doesn’t inherit its parent’s record locks. Record locks are associated with a file block or an entire file.
  5. Process resource utilisation and CPU time consumed is set to zero for the child.
  6. The child also doesn’t inherit timers from the parent.

But what about the child memory? Is a new address space created for a child?

The answers in no. After the fork(), both parent and child share the memory address space of parent. In linux, these address space are divided into multiple pages. Only when the child writes to one of the parent memory pages, a duplicate of that page is created for the child. This is also known as copy on write(Copy parent pages only when the child writes to it).

Let’s understand copy on write with an example.

int x = 2;
pid = fork();
if(pid == 0) {
    x = 10;
    // child is changing the value of x or writing to a page
    // One of the parent stack page will contain this local               variable. That page will be duplicated for child and it will store the value 10 in x in duplicated page.  
}
else {
    x = 4;
}

But why is copy on write necessary?

A typical process creation takes place through fork()-exec() combination. Let’s first understand what exec() does.

Exec() group of functions replaces the child’s address space with a new program. Once exec() is called within a child, a separate address space will be created for the child which is totally different from the parent’s one.

If there was no copy on write mechanism associated with fork(), duplicate pages would have created for the child and all the data would have been copied to child’s pages. Allocating new memory and copying data is a very expensive process(takes processor’s time and other system resources). We also know that in most cases, the child is going to call exec() and that would replace the child’s memory with a new program. So the first copy which we did would have been a waste if copy on write was not there.

pid = fork();
if(pid == 0) {
    execlp("/bin/ls","ls",NULL);
    printf("will this line be printed"); // Think about it
    // A new memory space will be created for the child and that   memory will contain the "/bin/ls" program(text section), it's stack, data section and heap section
else {
    wait(NULL);
    // parent is waiting for the child. Once child terminates, parent will get its exit status and can then continue
}
return 1; // Both child and parent will exit with status code 1.

Why does parent waits for a child process?

  1. The parent can assign a task to it’s child and wait till it completes it’s task. Then it can carry some other work.
  2. Once the child terminates, all the resources associated with child are freed except for the process control block. Now, the child is in zombie state. Using wait(), parent can inquire about the status of child and then ask the kernel to free the PCB. In case parent doesn’t uses wait, the child will remain in the zombie state.

Why is exec() system call necessary?

It’s not necessary to use exec() with fork(). If the code that the child will execute is within the program associated with parent, exec() is not needed.

But think of cases when the child has to run multiple programs. Let’s take the example of shell program. It supports multiple commands like find, mv, cp, date etc. Will be it right to include program code associated with these commands in one program or have child load these programs into the memory when required?

It all depends on your use case. You have a web server which given an input x that returns the 2^x to the clients. For each request, the web server creates a new child and asks it to compute. Will you write a separate program to calculate this and use exec()? Or you will just write computation code inside the parent program?

Usually, a process creation involves a combination of fork(), exec(), wait() and exit() calls.

Passing data between different controller action methods

I prefer to use this instead of TempData

public class Home1Controller : Controller 
{
    [HttpPost]
    public ActionResult CheckBox(string date)
    {
        return RedirectToAction("ActionName", "Home2", new { Date =date });
    }
}

and another controller Action is

public class Home2Controller : Controller 
{
    [HttpPost]
    Public ActionResult ActionName(string Date)
    {
       // do whatever with Date
       return View();
    }
}

it is too late but i hope to be helpful for any one in the future

MySQL SELECT AS combine two columns into one

You don't need to list ContactPhoneAreaCode1 and ContactPhoneNumber1

SELECT FirstName AS First_Name, 
LastName AS Last_Name, 
COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
FROM TABLE1

How to call a method in MainActivity from another class?

Use this code in sub Fragment of MainActivity to call the method on it.

((MainActivity) getActivity()).startChronometer();

How do I get an Excel range using row and column numbers in VSTO / C#?

Where the range is multiple cells:

Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,3]);

Where range is one cell:

Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.Cells[1, 1];

How to insert current_timestamp into Postgres via python

from datetime import datetime as dt

then use this in your code:

cur.execute('INSERT INTO my_table (dt_col) VALUES (%s)', (dt.now(),))

Count length of array and return 1 if it only contains one element

declare you array as:

$car = array("bmw")

EDIT

now with powershell syntax:)

$car = [array]"bmw"

How to do a JUnit assert on a message in a logger

Using Jmockit (1.21) I was able to write this simple test. The test makes sure a specific ERROR message is called just once.

@Test
public void testErrorMessage() {
    final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger( MyConfig.class );

    new Expectations(logger) {{
        //make sure this error is happens just once.
        logger.error( "Something went wrong..." );
        times = 1;
    }};

    new MyTestObject().runSomethingWrong( "aaa" ); //SUT that eventually cause the error in the log.    
}

Does Eclipse have line-wrap

In Version: 2019-12 (4.14.0) on MAC

Go to Windows -> Editor -> Toggle Word Wrap

Find index of a value in an array

Just posted my implementation of IndexWhere() extension method (with unit tests):

http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

Example usage:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

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

I got the commit ID from bitbucket and then did:

git checkout commitID .

Example:

git checkout 7991072 .

And it reverted it back up to that working copy of that commit.

warning: implicit declaration of function

If you have the correct headers defined & are using a non GlibC library (such as Musl C) gcc will also throw error: implicit declaration of function when GNU extensions such as malloc_trim are encountered.

The solution is to wrap the extension & the header:

#if defined (__GLIBC__)
  malloc_trim(0);
#endif

Omitting the second expression when using the if-else shorthand

Another option:

x === 2 ? doSomething() : void 0;

Command CompileSwift failed with a nonzero exit code in Xcode 10

Class re-declaration will be the problem. check duplicate class and build.

Working with time DURATION, not time of day

Let's say that you want to display the time elapsed between 5pm on Monday and 2:30pm the next day, Tuesday.

In cell A1 (for example), type in the date. In A2, the time. (If you type in 5 pm, including the space, it will display as 5:00 PM. If you want the day of the week to display as well, then in C3 (for example) enter the formula, =A1, then highlight the cell, go into the formatting dropdown menu, select Custom, and type in dddd.

Repeat all this in the row below.

Finally, say you want to display that duration in cell D2. Enter the formula, =(a2+b2)-(a1+b1). If you want this displayed as "22h 30m", select the cell, and in the formatting menu under Custom, type in h"h" m"m".

How to use sed to replace only the first occurrence in a file?

The following command removes the first occurrence of a string, within a file. It removes the empty line too. It is presented on an xml file, but it would work with any file.

Useful if you work with xml files and you want to remove a tag. In this example it removes the first occurrence of the "isTag" tag.

Command:

sed -e 0,/'<isTag>false<\/isTag>'/{s/'<isTag>false<\/isTag>'//}  -e 's/ *$//' -e  '/^$/d'  source.txt > output.txt

Source file (source.txt)

<xml>
    <testdata>
        <canUseUpdate>true</canUseUpdate>
        <isTag>false</isTag>
        <moduleLocations>
            <module>esa_jee6</module>
            <isTag>false</isTag>
        </moduleLocations>
        <node>
            <isTag>false</isTag>
        </node>
    </testdata>
</xml>

Result file (output.txt)

<xml>
    <testdata>
        <canUseUpdate>true</canUseUpdate>
        <moduleLocations>
            <module>esa_jee6</module>
            <isTag>false</isTag>
        </moduleLocations>
        <node>
            <isTag>false</isTag>
        </node>
    </testdata>
</xml>

ps: it didn't work for me on Solaris SunOS 5.10 (quite old), but it works on Linux 2.6, sed version 4.1.5

How do I make a Windows batch script completely silent?

To suppress output, use redirection to NUL.

There are two kinds of output that console commands use:

  • standard output, or stdout,

  • standard error, or stderr.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

or

COPY file1 file2 1>NUL

or

>NUL COPY file1 file2

or

1>NUL COPY file1 file2

suppresses all of COPY's standard output.

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

or

2>NUL DEL file

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

Java Minimum and Maximum values in Array

getMaxValue(array);
// get smallest number
getMinValue(array);

You are calling the methods but not using the returned values.

System.out.println(getMaxValue(array));
System.out.println(getMinValue(array)); 

How do you echo a 4-digit Unicode character in Bash?

Easy with a Python2/3 one-liner:

$ python -c 'print u"\u2620"'    # python2
$ python3 -c 'print(u"\u2620")'  # python3

Results in:

?

How do I get a computer's name and IP address using VB.NET?

Here is Example for this. In this example we can get IP address of our given host name.

   Dim strHostName As String = "jayeshsorathia.blogspot.com"
    'string strHostName = "www.microsoft.com";
    ' Get DNS entry of specified host name
    Dim addresses As IPAddress() = Dns.GetHostEntry(strHostName).AddressList

    ' The DNS entry may contains more than one IP addresses.
    ' Iterate them and display each along with the type of address (AddressFamily).
    For Each address As IPAddress In addresses
        Response.Write(String.Format("{0} = {1} ({2})", strHostName, address, address.AddressFamily))
        Response.Write("<br/><br/>")
    Next

How do I terminate a thread in C++11?

I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.

Define some global boolean:

std::atomic_bool stop_thread_1 = false;

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

if (stop_thread_1)
    return;

Then to stop the thread from another (main) thread:

stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)

Compare two files line by line and generate the difference in another file

Sometimes diff is the utility you need, but sometimes join is more appropriate. The files need to be pre-sorted or, if you are using a shell which supports process substitution such as bash, ksh or zsh, you can do the sort on the fly.

join -v 1 <(sort file1) <(sort file2)

What is the difference between mocking and spying when using Mockito?

If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:

  1. Using a mock you would have to set it up by invoking 7 callRealMethod and stub one method
  2. Using a spy you have to set it up by stubbing one method

The official documentation on doCallRealMethod recommends using a spy for partial mocks.

See also javadoc spy(Object) to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.

Project Links do not work on Wamp Server

Navigate to your www directory (if you are using wamp server) htdocs (if on XAMPP). Open your admin.php and search on project contents/ or just go directly to line number 339 and change the link, inserting 'local host to the link .

That should work ,,

How to get the current time in Google spreadsheet using script editor?

The Date object is used to work with dates and times.

Date objects are created with new Date().

var date= new Date();

 function myFunction() {
        var currentTime = new Date();
        Logger.log(currentTime);
    }

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

How to force Sequential Javascript Execution?

In your example, the first function does actually complete before the second function is started. setTimeout does not hold execution of the function until the timeout is reached, it will simply start a timer in the background and execute your alert statement after the specified time.

There is no native way of doing a "sleep" in JavaScript. You could write a loop that checks for the time, but that will put a lot of strain on the client. You could also do the Synchronous AJAX call, as emacsian described, but that will put extra load on your server. Your best bet is really to avoid this, which should be simple enough for most cases once you understand how setTimeout works.

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Here's a variation on this theme. I want to uninstall Cisco Amp, wait, and get the exit code. But the uninstall program starts a second program called "un_a" and exits. With this code, I can wait for un_a to finish and get the exit code of it, which is 3010 for "needs reboot". This is actually inside a .bat file.

If you've ever wanted to uninstall folding@home, it works in a similar way.

rem uninstall cisco amp, probably needs a reboot after

rem runs Un_A.exe and exits

rem start /wait isn't useful
"c:\program files\Cisco\AMP\6.2.19\uninstall.exe" /S

powershell while (! ($proc = get-process Un_A -ea 0)) { sleep 1 }; $handle = $proc.handle; 'waiting'; wait-process Un_A; exit $proc.exitcode

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

How to make grep only match if the entire line matches?

Works for me:

grep "\bsearch_word\b" text_file > output.txt  

\b indicates/sets boundaries.

Seems to work pretty fast

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

How do I set up a private Git repository on GitHub? Is it even possible?

Bitbucket - Their plans seem to be the best. They give you way more than GitHub do for free accounts - in fact, I'm still only using the free plan - no need to sign up to the paid ones; plus the interface is almost identical to GitHub.

A repository on Bitbucket can have up to five private users with unlimited public or private repositories - the only thing you seem to be paying for with the paid accounts are more users to access your private repositories.

Increasing the maximum number of TCP/IP connections in Linux

To improve upon the answer given by derobert,

You can determine what your OS connection limit is by catting nf_conntrack_max.

For example: cat /proc/sys/net/netfilter/nf_conntrack_max

You can use the following script to count the number of tcp connections to a given range of tcp ports. By default 1-65535.

This will confirm whether or not you are maxing out your OS connection limit.

Here's the script.

#!/bin/bash
OS=$(uname)

case "$OS" in
    'SunOS')
            AWK=/usr/bin/nawk
            ;;
    'Linux')
            AWK=/bin/awk
            ;;
    'AIX')
            AWK=/usr/bin/awk
            ;;
esac

netstat -an | $AWK -v start=1 -v end=65535 ' $NF ~ /TIME_WAIT|ESTABLISHED/ && $4 !~ /127\.0\.0\.1/ {
    if ($1 ~ /\./)
            {sip=$1}
    else {sip=$4}

    if ( sip ~ /:/ )
            {d=2}
    else {d=5}

    split( sip, a, /:|\./ )

    if ( a[d] >= start && a[d] <= end ) {
            ++connections;
            }
    }
    END {print connections}'

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

How can I remove text within parentheses with a regex?

s/\([^)]*\)//

So in Python, you'd do:

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

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

Django model "doesn't declare an explicit app_label"

If you have got all the config right, it might just be an import mess. keep an eye on how you are importing the offending model.

The following won't work from .models import Business. Use full import path instead: from myapp.models import Business

C++ deprecated conversion from string constant to 'char*'

As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:

void foo(char* str);
foo("hello");

However, if you want to keep your code warning-free as well then just make respective change in your code:

void foo(char* str);
foo((char *)"hello");

That is, simply cast the string constant to (char *).

Java: int[] array vs int array[]

No, there is no difference. But I prefer using int[] array as it is more readable.

How to trigger a click on a link using jQuery

Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:

$('#titleee a')[0].click();

Explanation: you trigger a click on the underlying html-element, not the jQuery-object.

You're welcome googlers :)

What does question mark and dot operator ?. mean in C# 6.0?

It's the null conditional operator. It basically means:

"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.

In other words, it's like this:

string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}

... except that a is only evaluated once.

Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:

FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null

JPA Hibernate One-to-One relationship

Try this

@Entity

@Table(name="tblperson")

public class Person {

public int id;

public OtherInfo otherInfo;
@Id //Here Id is autogenerated
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

@OneToOne(cascade = CascadeType.ALL,targetEntity=OtherInfo.class)
@JoinColumn(name="otherInfo_id") //there should be a column otherInfo_id in Person
public OtherInfo getOtherInfo() {
    return otherInfo;
}
public void setOtherInfo(OtherInfo otherInfo) {
    this.otherInfo= otherInfo;
}
rest of attributes ...
}


@Entity

@Table(name="tblotherInfo")

public class OtherInfo {

private int id;

private Person person;

@Id

@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}

  @OneToOne(mappedBy="OtherInfo",targetEntity=Person.class)   
public College getPerson() {
    return person;
}
public void setPerson(Person person) {
    this.person = person;
}    
 rest of attributes ...
}

Add class to an element in Angular 4

If you need that each div will have its own toggle and don't want clicks to affect other divs, do this:

Here's what I did to solve this...

<div [ngClass]="{'teaser': !teaser_1 }" (click)="teaser_1=!teaser_1">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_2 }" (click)="teaser_2=!teaser_2">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_3 }" (click)="teaser_3=!teaser_3">
...content...
</div>

it requires custom numbering which sucks, but it works.

How to put multiple statements in one line?

You could use the built-in exec statement, eg.:

exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello',  sam) \nexcept: pass")

Where \n is a newline and \t is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.

However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.

exec is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.

Get all rows from SQLite

This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:

Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;

private static final String MYDATABASE_TABLE = "anyTableName";

Then, wherever you are trying to retrieve all table rows;

SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);

List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
   fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
   while(cursor.moveToNext()){
      fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
   }
}
cursor.close();
db.close();

Honestly, there are many ways about doing this,

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

A primitive type cannot be null. So the solution is replace primitive type with primitive wrapper class in your tableName.java file. Such as:

@Column(nullable=true, name="client_os_id")
private Integer client_os_id;

public int getClient_os_id() {
    return client_os_id;
}

public void setClient_os_id(int clientOsId) {
    client_os_id = clientOsId;
}

reference http://en.wikipedia.org/wiki/Primitive_wrapper_class to find wrapper class of a primivite type.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

The webfonts link works now, in all browsers!

Simply add your themes to the font link separated by a pipe (|), like this

<link href="https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Outlined" rel="stylesheet">

Then reference the class, like this:

// class="material-icons" or class="material-icons-outlined"

<i class="material-icons">account_balance</i>
<i class="material-icons-outlined">account_balance</i>

This pattern will also work with Angular Material:

<mat-icon>account_balance</mat-icon>
<mat-icon class="material-icons-outlined">account_balance</mat-icon>

How to change default text file encoding in Eclipse?

For eclipse Mars:

Change Workspace Encoding:

Change workspace encoding

Check a file Encoding: Image check a file encoding

Specifying onClick event type with Typescript and React.Konva

React.MouseEvent works for me:

private onClick = (e: React.MouseEvent<HTMLInputElement>) => {
  let button = e.target as HTMLInputElement;
}

How do I get a YouTube video thumbnail from the YouTube API?

Each YouTube video has four generated images. They are predictably formatted as follows:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (i.e., one of 1.jpg, 2.jpg, 3.jpg) is:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

For the high quality version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a URL similar to the HQ:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

For the standard definition version of the thumbnail, use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

For the maximum resolution version of the thumbnail use a URL similar to this:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example URLs above.

Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.

Datatables on-the-fly resizing

might be late also like the other answer but I did this early this year and the solution I came up with is using css.

    $(window).bind('resize', function () {
        /*the line below was causing the page to keep loading.
        $('#tableData').dataTable().fnAdjustColumnSizing();
        Below is a workaround. The above should automatically work.*/
        $('#tableData').css('width', '100%');
    } );

How to get the Mongo database specified in connection string in C#

With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:

const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

Finaly I found another answer for this problem. and this is working for me. Just add below datas to the your webconfig file.

<configuration>
 <system.webServer>
  <security>
   <requestFiltering>
    <verbs allowUnlisted="true">
     <add verb="OPTIONS" allowed="false" />
    </verbs>
   </requestFiltering>
  </security>
 </system.webServer>
</configuration>

Form more information, you can visit this web site: http://www.iis.net/learn/manage/configuring-security/use-request-filtering

if you want to test your web site, is it working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/

How can I add the new "Floating Action Button" between two widgets/layouts

You can import the sample project of Google in Android Studio by clicking File > Import Sample...

Import sample

This Sample contains a FloatingActionButton View which inherits from FrameLayout.

Edit With the new Support Design Library you can implement it like in this example: https://github.com/chrisbanes/cheesesquare

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

How to automatically close cmd window after batch file execution?

You normally end a batch file with a line that just says exit. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines:

timeout 2 >nul
exit

But the exit command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed.

SOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\BgInfo, to run it from a batch file with the /popup switch and to close the DOS window while it still runs, use:

start "" "C:\BgInfo\BgInfo.exe" /popup
exit

Android map v2 zoom to show all the markers

this would help.. from google apis demos

private List<Marker> markerList = new ArrayList<>();
Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(geoLatLng)
                .title(title));
markerList.add(marker);
    // Pan to see all markers in view.
    // Cannot zoom to bounds until the map has a size.
    final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
    if (mapView!=null) {
        if (mapView.getViewTreeObserver().isAlive()) {
            mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @SuppressWarnings("deprecation") // We use the new method when supported
                @SuppressLint("NewApi") // We check which build version we are using.
                @Override
                public void onGlobalLayout() {
                    //Calculate the markers to get their position
                    LatLngBounds.Builder b = new LatLngBounds.Builder();
                    for (Marker m : markerList) {
                        b.include(m.getPosition());
                    }
                    // also include current location to include in the view
                    b.include(new LatLng(mLocation.getLatitude(),mLocation.getLongitude()));

                    LatLngBounds bounds = b.build();
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                        mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    } else {
                        mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
                }
            });
        }
    }

for clear info look at this url. https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

Insert images to XML file

I always convert the byte data to a Base64 encoding and then insert the image.

This is also the way that Word does it, for it's XML files (not that Word is a good example on how to work with XML :P).

When using SASS how can I import a file from a different directory?

Gulp will do the job for watching your sass files and also adding paths of other file with includePaths. example:

gulp.task('sass', function() {
  return gulp.src('scss/app.scss')
    .pipe($.sass({
      includePaths: sassPaths
    })
    .pipe(gulp.dest('css'));
});

Convert an int to ASCII character

Alternative way, But non-standard.

int i = 6;
char c[2];
char *str = NULL;
if (_itoa_s(i, c, 2, 10) == 0)
   str = c;

Or Using standard c++ stringstream

 std::ostringstream oss;
 oss << 6;