Programs & Examples On #Dbvisualizer

DBVisualizer is a popular database tool by DbVis Software AB. Written in Java, it runs on Windows, Mac OS X, and Unix/Linux, and will connect to any JDBC enabled database server.

What is the best free SQL GUI for Linux for various DBMS systems

I use SQLite Database Browser for SQLite3 currently and it's pretty useful. Works across Windows/OS X/Linux and is lightweight and fast. Slightly unstable with executing SQL on the DB if it's incorrectly formatted.

Edit: I have recently discovered SQLite Manager, a plugin for Firefox. Obviously you need to run Firefox, but you can close all windows and just run it "standalone". It's very feature complete, amazingly stable and it remembers your databases! It has tonnes of features so I've moved away from SQLite Database Browser as the instability and lack of features is too much to bear.

compare differences between two tables in mysql

Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....

Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"

SELECT ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

So you need to add the extra "where in" clause:

WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)


Also:

For ease of reading if you want to indicate the table names you can use the following:

SELECT tbl, ID, col
FROM
(
    SELECT
    tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
    UNION ALL
    SELECT
    tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
 ORDER BY ID

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Read all worksheets in an Excel workbook into an R list with data.frames

Since this is the number one hit to the question: Read multi sheet excel to list:

here is the openxlsx solution:

filename <-"myFilePath"

sheets <- openxlsx::getSheetNames(filename)
SheetList <- lapply(sheets,openxlsx::read.xlsx,xlsxFile=filename)
names(SheetList) <- sheets

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

Faced exactly the same issue while upgrading my application from java 6 to java 8 on tomcat 7.0.19. After upgrading the tomcat to 7.0.59, this issue is resolved.

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

I had a run in with the same problem. My application was also a Silverlight application and the service was being called from a class library with a custom UserControl that was being used in it.

The solution is simple. Copy the endpoint definitions from the config file (e.g. ServiceReferences.ClientConfig) of the class library to the config file of the silverlight application. I know you'd expect it to work without having to do this, but apparently someone in Redmond had a vacation that day.

One line if/else condition in linux shell scripting

It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".

maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi

Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Unable to copy ~/.ssh/id_rsa.pub

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub didn't work for me (ubuntu 14.04), but you can use :

cat ~/.ssh/id_rsa.pub

to get your public key

How to have click event ONLY fire on parent DIV, not children?

If the e.target is the same element as this, you've not clicked on a descendant.

_x000D_
_x000D_
$('.foobar').on('click', function(e) {_x000D_
  if (e.target !== this)_x000D_
    return;_x000D_
  _x000D_
  alert( 'clicked the foobar' );_x000D_
});
_x000D_
.foobar {_x000D_
  padding: 20px; background: yellow;_x000D_
}_x000D_
span {_x000D_
  background: blue; color: white; padding: 8px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class='foobar'> .foobar (alert) _x000D_
  <span>child (no alert)</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JQuery ajax call default timeout value

There doesn't seem to be a standardized default value. I have the feeling the default is 0, and the timeout event left totally dependent on browser and network settings.

For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

Stop form from submitting , Using Jquery

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

I want it to be allowed HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

Viewing full output of PS command

Evidence for truncation mentioned by others, (a personal example)

foo=$(ps -p 689 -o command); echo "$foo"

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtime/kernel-5732db1a-d484-4a58-9d67-de6ef5ac721b.json

That ^^ captures that long output in a variable As opposed to

ps -p 689 -o command

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtim

Since I was trying this from a Docker jupyter notebook, I needed to run this with the bang of course ..

!foo=$(ps -p 689 -o command); echo "$foo"

Surprisingly jupyter notebooks let you execute even that! But glad to help find the offending notebook taking up all my memory =D

Install Application programmatically on Android

Just an extension, if anyone need a library then this might help. Thanks to Raghav

"Error: Main method not found in class MyClass, please define the main method as..."

Generally, it means the program you are trying to run does not have a "main" method. If you are going to execute a Java program, the class being executed must have a main method:

For example, in the file Foo.java

public class Foo {
    public static void main(final String args[]) {
        System.out.println("hello");
    }
}

This program should compile and run no problem - if main was called something else, or was not static, it would generate the error you experienced.

Every executable program, regardless of language, needs an entry point, to tell the interpreter, operating system or machine where to start execution. In Java's case, this is the static method main, which is passed the parameter args[] containing the command line arguments. This method is equivalent to int main(int argc, char** argv) in C language.

How to return a value from __init__ in Python?

Well, if you don't care about the object instance anymore ... you can just replace it!

class MuaHaHa():
def __init__(self, ret):
    self=ret

print MuaHaHa('foo')=='foo'

Change the project theme in Android Studio?

In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click on android:theme = "@style/AppTheme" in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

At parent= in styles.xml you can browse all available styles by using auto-complete inside the "". E.g. try parent="Theme." with your cursor right after the . and then pressing Ctrl + Space.

You can also preview themes in the preview window in Android Studio.

enter image description here

Laravel back button

One of the below solve your problem

URL::previous() 
URL::back()

other

URL::current()

How to add a where clause in a MySQL Insert statement?

I think you are looking for UPDATE and not insert?

UPDATE `users`
SET `username` = 'Jack', `password` = '123'
WHERE `id` = 1

Composer: Command Not Found

I am using CentOS and had same problem.

I changed /usr/local/bin/composer to /usr/bin/composer and it worked.

Run below command :

curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/bin/composer

Verify Composer is installed or not

composer --version

Add space between HTML elements only using CSS

Or, instead of setting margin and than overriding it, you can just set it properly right away with the following combo:

span:not(:first-of-type) {
    margin-left:  5px;
}

span:not(:last-of-type) {
    margin-right: 5px;
}

Check existence of directory and create if doesn't exist

To find out if a path is a valid directory try:

file.info(cacheDir)[1,"isdir"]

file.info does not care about a slash on the end.

file.exists on Windows will fail for a directory if it ends in a slash, and succeeds without it. So this cannot be used to determine if a path is a directory.

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache/")
[1] FALSE

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache")
[1] TRUE

file.info(cacheDir)["isdir"]

How to find the sum of an array of numbers

This is much easier

function sumArray(arr) {
    var total = 0;
    arr.forEach(function(element){
        total += element;
    })
    return total;
}

var sum = sumArray([1,2,3,4])

console.log(sum)

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

Database Diagram Support Objects cannot be Installed ... no valid owner

An easier way to solve this issues would be to right click the name of your database, choose "New Query", type " exec sp_changedbowner 'sa' " and execute the query. Then you'll be good to go.

What command means "do nothing" in a conditional in Bash?

Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.

I try to give a general rule by using the OPs example

do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"

we have to avoid a branch where $a gets more than 10, so $a < 10 as a general condition can be applied to every other, following condition.

In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.

So the OPs example with the rule applied may be restructured as:

if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
    echo "1"
elif [ "$a" -lt 10 ]
then
    echo "2"
fi

Just a variation of the above, enclosing everything in the $a < 10 condition:

if [ "$a" -lt 10 ]
then
    if [ "$a" -le 5 ]
    then
        echo "1"
    else
        echo "2"
    fi
fi

(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)

How to format a string as a telephone number in C#

As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:

string.Format("({0}) {1}-{2}",
     phoneNumber.Substring(0, 3),
     phoneNumber.Substring(3, 3),
     phoneNumber.Substring(6));

This assumes the data has been entered correctly, which you could use regular expressions to validate.

TypeError: 'dict_keys' object does not support indexing

In Python 2 dict.keys() return a list, whereas in Python 3 it returns a generator.

You could only iterate over it's values else you may have to explicitly convert it to a list i.e. pass it to a list function.

Is there a C++ gdb GUI for Linux?

There's one IDE that is missing in this list and which is very efficient (I've used it in many C/C++ projects without any issues): Netbeans.

Remove all constraints affecting a UIView

The only solution I have found so far is to remove the view from its superview:

[view removeFromSuperview]

This looks like it removes all constraints affecting its layout and is ready to be added to a superview and have new constraints attached. However, it will incorrectly remove any subviews from the hierarchy as well, and get rid of [C7] incorrectly.

TensorFlow: "Attempting to use uninitialized value" in variable initialization

It's not 100% clear from the code example, but if the list initial_parameters_of_hypothesis_function is a list of tf.Variable objects, then the line session.run(init) will fail because TensorFlow isn't (yet) smart enough to figure out the dependencies in variable initialization. To work around this, you should change the loop that creates parameters to use initial_parameters_of_hypothesis_function[i].initialized_value(), which adds the necessary dependency:

parameters = []
for i in range(0, number_of_attributes, 1):
    parameters.append(tf.Variable(
        initial_parameters_of_hypothesis_function[i].initialized_value()))

MySQL TEXT vs BLOB vs CLOB

It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.

http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html

Data Type   Date Type   Storage Required
(CLOB)      (BLOB)

TINYTEXT    TINYBLOB    L + 1 bytes, where L < 2**8  (255)
TEXT        BLOB        L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT  MEDIUMBLOB  L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT    LONGBLOB    L + 4 bytes, where L < 2**32 (4 GB)

where L stands for the byte length of a string

How to clear the logs properly for a Docker container?

As a root user, try to run the following:

>  /var/lib/docker/containers/*/*-json.log

or

cat /dev/null > /var/lib/docker/containers/*/*-json.log

or

echo "" > /var/lib/docker/containers/*/*-json.log

Android - styling seek bar

Android seekbar custom material style, for other seekbar customizations http://www.zoftino.com/android-seekbar-and-custom-seekbar-examples

<style name="MySeekBar" parent="Widget.AppCompat.SeekBar">
    <item name="android:progressBackgroundTint">#f4511e</item>
    <item name="android:progressTint">#388e3c</item>
    <item name="android:colorControlActivated">#c51162</item>
</style>

seekbar custom material style

How to export a MySQL database to JSON?

Using MySQL Shell you can out put directly to JSON using only terminal

echo "Your SQL query" | mysqlsh --sql --result-format=json --uri=[username]@localhost/[schema_name]

Get the client IP address using PHP

In PHP 5.3 or greater, you can get it like this:

$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');

How to add a ScrollBar to a Stackpanel

If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.

So try something like this:

   <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <StackPanel Width="311">
              <TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
              <TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
        </StackPanel>
    </Grid>

You could even make this work with a ScrollViewer

Purpose of ESI & EDI registers?

There are a few operations you can only do with DI/SI (or their extended counterparts, if you didn't learn ASM in 1985). Among these are

REP STOSB
REP MOVSB
REP SCASB

Which are, respectively, operations for repeated (= mass) storing, loading and scanning. What you do is you set up SI and/or DI to point at one or both operands, perhaps put a count in CX and then let 'er rip. These are operations that work on a bunch of bytes at a time, and they kind of put the CPU in automatic. Because you're not explicitly coding loops, they do their thing more efficiently (usually) than a hand-coded loop.

Just in case you're wondering: Depending on how you set the operation up, repeated storing can be something simple like punching the value 0 into a large contiguous block of memory; MOVSB is used, I think, to copy data from one buffer (well, any bunch of bytes) to another; and SCASB is used to look for a byte that matches some search criterion (I'm not sure if it's only searching on equality, or what – you can look it up :) )

That's most of what those regs are for.

What is Common Gateway Interface (CGI)?

CGI is an interface which tells the webserver how to pass data to and from an application. More specifically, it describes how request information is passed in environment variables (such as request type, remote IP address), how the request body is passed in via standard input, and how the response is passed out via standard output. You can refer to the CGI specification for details.

To use your image:

user (client) request for page ---> webserver ---[CGI]----> Server side Program ---> MySQL Server.

Most if not all, webservers can be configured to execute a program as a 'CGI'. This means that the webserver, upon receiving a request, will forward the data to a specific program, setting some environment variables and marshalling the parameters via standard input and standard output so the program can know where and what to look for.

The main benefit is that you can run ANY executable code from the web, given that both the webserver and the program know how CGI works. That's why you could write web programs in C or Bash with a regular CGI-enabled webserver. That, and that most programming environments can easily use standard input, standard output and environment variables.

In your case you most likely used another, specific for PHP, means of communication between your scripts and the webserver, this, as you well mention in your question, is an embedded interpreter called mod_php.

So, answering your questions:

What exactly is CGI?

See above.

Whats the big deal with /cgi-bin/*.cgi? Whats up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.

That's the traditional place for cgi programs, many webservers come with this directory pre configured to execute all binaries there as CGI programs. The .cgi extension denotes an executable that is expected to work through the CGI.

Why does Perl always comes in the way. CGI & Perl (language). I also don't know whats up with these two. Almost all the time I keep hearing these two in combination "CGI & Perl". This book is another great example CGI Programming with Perl Why not "CGI Programming with PHP/JSP/ASP". I never saw such things.

Because Perl is ancient (older than PHP, JSP and ASP which all came to being when CGI was already old, Perl existed when CGI was new) and became fairly famous for being a very good language to serve dynamic webpages via the CGI. Nowadays there are other alternatives to run Perl in a webserver, mainly mod_perl.

CGI Programming in C this confuses me a lot. in C?? Seriously?? I don't know what to say. I"m just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB & MySQL) using socket programming? I'm lost!!

You compile the executable once, the webserver executes the program and passes the data in the request to the program and outputs the received response. CGI specifies that one program instance will be launched per each request. This is why CGI is inefficient and kind of obsolete nowadays.

They say that CGI is deprecated. Its no more in use. Is it so? What is its latest update?

CGI is still used when performance is not paramount and a simple means of executing code is required. It is inefficient for the previously stated reasons and there are more modern means of executing any program in a web enviroment. Currently the most famous is FastCGI.

Multiple "order by" in LINQ

I have created some extension methods (below) so you don't have to worry if an IQueryable is already ordered or not. If you want to order by multiple properties just do it as follows:

// We do not have to care if the queryable is already sorted or not. 
// The order of the Smart* calls defines the order priority
queryable.SmartOrderBy(i => i.Property1).SmartOrderByDescending(i => i.Property2);

This is especially helpful if you create the ordering dynamically, f.e. from a list of properties to sort.

public static class IQueryableExtension
{
    public static bool IsOrdered<T>(this IQueryable<T> queryable) {
        if(queryable == null) {
            throw new ArgumentNullException("queryable");
        }

        return queryable.Expression.Type == typeof(IOrderedQueryable<T>);
    }

    public static IQueryable<T> SmartOrderBy<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenBy(keySelector);
        } else {
            return queryable.OrderBy(keySelector);
        }
    }

    public static IQueryable<T> SmartOrderByDescending<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenByDescending(keySelector);
        } else {
            return queryable.OrderByDescending(keySelector);
        }
    }
}

How to delete duplicate rows in SQL Server?

-- this query will keep only one instance of a duplicate record.
;WITH cte
     AS (SELECT ROW_NUMBER() OVER (PARTITION BY col1, col2, col3-- based on what? --can be multiple columns
                                       ORDER BY ( SELECT 0)) RN
         FROM   Mytable)



delete  FROM cte
WHERE  RN > 1

How to correctly implement custom iterators and const_iterators?

I'm going to show you how you can easily define iterators for your custom containers, but just in case I have created a c++11 library that allows you to easily create custom iterators with custom behavior for any type of container, contiguous or non-contiguous.

You can find it on Github

Here are the simple steps to creating and using custom iterators:

  1. Create your "custom iterator" class.
  2. Define typedefs in your "custom container" class.
    • e.g. typedef blRawIterator< Type > iterator;
    • e.g. typedef blRawIterator< const Type > const_iterator;
  3. Define "begin" and "end" functions
    • e.g. iterator begin(){return iterator(&m_data[0]);};
    • e.g. const_iterator cbegin()const{return const_iterator(&m_data[0]);};
  4. We're Done!!!

Finally, onto defining our custom iterator classes:

NOTE: When defining custom iterators, we derive from the standard iterator categories to let STL algorithms know the type of iterator we've made.

In this example, I define a random access iterator and a reverse random access iterator:

  1. //-------------------------------------------------------------------
    // Raw iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawIterator
    {
    public:
    
        using iterator_category = std::random_access_iterator_tag;
        using value_type = blDataType;
        using difference_type = std::ptrdiff_t;
        using pointer = blDataType*;
        using reference = blDataType&;
    
    public:
    
        blRawIterator(blDataType* ptr = nullptr){m_ptr = ptr;}
        blRawIterator(const blRawIterator<blDataType>& rawIterator) = default;
        ~blRawIterator(){}
    
        blRawIterator<blDataType>&                  operator=(const blRawIterator<blDataType>& rawIterator) = default;
        blRawIterator<blDataType>&                  operator=(blDataType* ptr){m_ptr = ptr;return (*this);}
    
        operator                                    bool()const
        {
            if(m_ptr)
                return true;
            else
                return false;
        }
    
        bool                                        operator==(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr == rawIterator.getConstPtr());}
        bool                                        operator!=(const blRawIterator<blDataType>& rawIterator)const{return (m_ptr != rawIterator.getConstPtr());}
    
        blRawIterator<blDataType>&                  operator+=(const difference_type& movement){m_ptr += movement;return (*this);}
        blRawIterator<blDataType>&                  operator-=(const difference_type& movement){m_ptr -= movement;return (*this);}
        blRawIterator<blDataType>&                  operator++(){++m_ptr;return (*this);}
        blRawIterator<blDataType>&                  operator--(){--m_ptr;return (*this);}
        blRawIterator<blDataType>                   operator++(int){auto temp(*this);++m_ptr;return temp;}
        blRawIterator<blDataType>                   operator--(int){auto temp(*this);--m_ptr;return temp;}
        blRawIterator<blDataType>                   operator+(const difference_type& movement){auto oldPtr = m_ptr;m_ptr+=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
        blRawIterator<blDataType>                   operator-(const difference_type& movement){auto oldPtr = m_ptr;m_ptr-=movement;auto temp(*this);m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawIterator<blDataType>& rawIterator){return std::distance(rawIterator.getPtr(),this->getPtr());}
    
        blDataType&                                 operator*(){return *m_ptr;}
        const blDataType&                           operator*()const{return *m_ptr;}
        blDataType*                                 operator->(){return m_ptr;}
    
        blDataType*                                 getPtr()const{return m_ptr;}
        const blDataType*                           getConstPtr()const{return m_ptr;}
    
    protected:
    
        blDataType*                                 m_ptr;
    };
    //-------------------------------------------------------------------
    
  2. //-------------------------------------------------------------------
    // Raw reverse iterator with random access
    //-------------------------------------------------------------------
    template<typename blDataType>
    class blRawReverseIterator : public blRawIterator<blDataType>
    {
    public:
    
        blRawReverseIterator(blDataType* ptr = nullptr):blRawIterator<blDataType>(ptr){}
        blRawReverseIterator(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();}
        blRawReverseIterator(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        ~blRawReverseIterator(){}
    
        blRawReverseIterator<blDataType>&           operator=(const blRawReverseIterator<blDataType>& rawReverseIterator) = default;
        blRawReverseIterator<blDataType>&           operator=(const blRawIterator<blDataType>& rawIterator){this->m_ptr = rawIterator.getPtr();return (*this);}
        blRawReverseIterator<blDataType>&           operator=(blDataType* ptr){this->setPtr(ptr);return (*this);}
    
        blRawReverseIterator<blDataType>&           operator+=(const difference_type& movement){this->m_ptr -= movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator-=(const difference_type& movement){this->m_ptr += movement;return (*this);}
        blRawReverseIterator<blDataType>&           operator++(){--this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>&           operator--(){++this->m_ptr;return (*this);}
        blRawReverseIterator<blDataType>            operator++(int){auto temp(*this);--this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator--(int){auto temp(*this);++this->m_ptr;return temp;}
        blRawReverseIterator<blDataType>            operator+(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr-=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
        blRawReverseIterator<blDataType>            operator-(const int& movement){auto oldPtr = this->m_ptr;this->m_ptr+=movement;auto temp(*this);this->m_ptr = oldPtr;return temp;}
    
        difference_type                             operator-(const blRawReverseIterator<blDataType>& rawReverseIterator){return std::distance(this->getPtr(),rawReverseIterator.getPtr());}
    
        blRawIterator<blDataType>                   base(){blRawIterator<blDataType> forwardIterator(this->m_ptr); ++forwardIterator; return forwardIterator;}
    };
    //-------------------------------------------------------------------
    

Now somewhere in your custom container class:

template<typename blDataType>
class blCustomContainer
{
public: // The typedefs

    typedef blRawIterator<blDataType>              iterator;
    typedef blRawIterator<const blDataType>        const_iterator;

    typedef blRawReverseIterator<blDataType>       reverse_iterator;
    typedef blRawReverseIterator<const blDataType> const_reverse_iterator;

                            .
                            .
                            .

public:  // The begin/end functions

    iterator                                       begin(){return iterator(&m_data[0]);}
    iterator                                       end(){return iterator(&m_data[m_size]);}

    const_iterator                                 cbegin(){return const_iterator(&m_data[0]);}
    const_iterator                                 cend(){return const_iterator(&m_data[m_size]);}

    reverse_iterator                               rbegin(){return reverse_iterator(&m_data[m_size - 1]);}
    reverse_iterator                               rend(){return reverse_iterator(&m_data[-1]);}

    const_reverse_iterator                         crbegin(){return const_reverse_iterator(&m_data[m_size - 1]);}
    const_reverse_iterator                         crend(){return const_reverse_iterator(&m_data[-1]);}

                            .
                            .
                            .
    // This is the pointer to the
    // beginning of the data
    // This allows the container
    // to either "view" data owned
    // by other containers or to
    // own its own data
    // You would implement a "create"
    // method for owning the data
    // and a "wrap" method for viewing
    // data owned by other containers

    blDataType*                                    m_data;
};

How do I list all tables in all databases in SQL Server in a single result set?

I posted an answer a while back here that you could use here. The outline is:

  • Create a temp table
  • Call sp_msForEachDb
  • The query run against each DB stores the data in the temp table
  • When done, query the temp table

Math operations from string

A simple way but dangerous way to do this would be to use eval(). eval() executes the string passed to it as code. The dangerous thing about this is that if this string is gained from user input, they could maliciously execute code that could break the computer. I would get the input, check it with a regex, and then execute it if you determine if it's OK. If it's only going to be in the format "number operation number", then you could use a simple regex:

import re
s = raw_input('What is your math problem? ')
if re.findall('\d+? *?\+ *?\d+?', s):
  print eval(s)
else:
  print "Try entering a math problem"

Otherwise, you would have to come up with something a bit stricter than this. You could also do it conversely, using a regex to find if certain things are not in it, such as numbers and operations. Also you could check to see if the input contains certain commands.

Calculate number of hours between 2 dates in PHP

First, you should create an interval object from a range of dates. By the wording used in this sentence alone, one can easily identify basic abstractions needed. There is an interval as a concept, and a couple of more ways to implement it, include the one already mentioned -- from a range of dates. Thus, an interval looks like that:

$interval =
    new FromRange(
        new FromISO8601('2017-02-14T14:27:39+00:00'),
        new FromISO8601('2017-03-14T14:27:39+00:00')
    );

FromISO8601 has the same semantics: it's a datetime object created from iso8601-formatted string, hence the name.

When you have an interval, you can format it however you like. If you need a number of full hours, you can have

(new TotalFullHours($interval))->value();

If you want a ceiled total hours, here you go:

(new TotalCeiledHours($interval))->value();

For more about this approach and some examples, check out this entry.

How to start an application using android ADB tools?

Also, I want to mention one more thing.

When you start an application from adb shell am, it automatically adds FLAG_ACTIVITY_NEW_TASK flag which makes behavior change. See the code.

For example, if you launch Play Store activity from adb shell am, pressing 'Back' button(hardware back button) wouldn't take you your app, instead it would take you previous Play Store activity if there was some(If there was not Play store task, then it would take you your app). FLAG_ACTIVITY_NEW_TASK documentation says :

if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in

This caused me to spend a few hours to find out what went wrong.

So, keep in mind that adb shell am add FLAG_ACTIVITY_NEW_TASK flag.

A html space is showing as %2520 instead of %20

A bit of explaining as to what that %2520 is :

The common space character is encoded as %20 as you noted yourself. The % character is encoded as %25.

The way you get %2520 is when your url already has a %20 in it, and gets urlencoded again, which transforms the %20 to %2520.

Are you (or any framework you might be using) double encoding characters?

Edit: Expanding a bit on this, especially for LOCAL links. Assuming you want to link to the resource C:\my path\my file.html:

  • if you provide a local file path only, the browser is expected to encode and protect all characters given (in the above, you should give it with spaces as shown, since % is a valid filename character and as such it will be encoded) when converting to a proper URL (see next point).
  • if you provide a URL with the file:// protocol, you are basically stating that you have taken all precautions and encoded what needs encoding, the rest should be treated as special characters. In the above example, you should thus provide file:///c:/my%20path/my%20file.html. Aside from fixing slashes, clients should not encode characters here.

NOTES:

  • Slash direction - forward slashes / are used in URLs, reverse slashes \ in Windows paths, but most clients will work with both by converting them to the proper forward slash.
  • In addition, there are 3 slashes after the protocol name, since you are silently referring to the current machine instead of a remote host ( the full unabbreviated path would be file://localhost/c:/my%20path/my%file.html ), but again most clients will work without the host part (ie two slashes only) by assuming you mean the local machine and adding the third slash.

'Conda' is not recognized as internal or external command

In addition to adding C:\Users\yourusername\Anaconda3 and C:\Users\yourusername\Anaconda3\Scripts, as recommended by Raja (above), also add C:\Users\yourusername\Anaconda3\Library\bin to your path variable. This will prevent an SSL error that is bound to happen if you're performing this on a fresh install of Anaconda.

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.

How do you input command line arguments in IntelliJ IDEA?

In IntelliJ, if you want to pass args parameters to the main method.

go to-> edit configurations

program arguments: 5 10 25

you need to pass the arguments through space separated and click apply and save.

now run the program if you print

System.out.println(args[0]); System.out.println(args[1]); System.out.println(args[2]); Out put is 5 10 25

Java synchronized block vs. Collections.synchronizedMap

If you are using JDK 6 then you might want to check out ConcurrentHashMap

Note the putIfAbsent method in that class.

Change label text using JavaScript

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>

jQuery UI Color Picker

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

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

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

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

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

Passing parameters to a JDBC PreparedStatement

Do something like this, which also prevents SQL injection attacks

statement = con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();

updating table rows in postgres using subquery

Postgres allows:

UPDATE dummy
SET customer=subquery.customer,
    address=subquery.address,
    partn=subquery.partn
FROM (SELECT address_id, customer, address, partn
      FROM  /* big hairy SQL */ ...) AS subquery
WHERE dummy.address_id=subquery.address_id;

This syntax is not standard SQL, but it is much more convenient for this type of query than standard SQL. I believe Oracle (at least) accepts something similar.

How can I get the current network interface throughput statistics on Linux/UNIX?

If you want just to get the value, you can use simple shell oneliner like this:

S=10; F=/sys/class/net/eth0/statistics/rx_bytes; X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))"; echo $BPS

It will show you the average "received bytes per second" for period of 10 seconds (you can change period by changing S=10 parameter, and you can measure transmitted BPS instead of received BPS by using tx_bytes instead of rx_bytes). Don't forget to change eth0 to network device you want to monitor.

Of course, you are not limited to displaying the average rate (as mentioned in other answers, there are other tools that will show you much nicer output), but this solution is easily scriptable to do other things.

For example, the following shell script (split into multiple lines for readability) will execute offlineimap process only when 5-minute average transmit speed drops below 10kBPS (presumably, when some other bandwidth-consuming process finishes):

#!/bin/sh
S=300; F=/sys/class/net/eth0/statistics/tx_bytes
BPS=999999
while [ $BPS -gt 10000 ]
do
  X=`cat $F`; sleep $S; Y=`cat $F`; BPS="$(((Y-X)/S))";
  echo BPS is currently $BPS
done
offlineimap

Note that /sys/class/... is Linux specific (which is ok as submitter did choose linux tag), and needs non-archaic kernel. Shell code itself is /bin/sh compatible (so not only bash, but dash and other /bin/sh implementations will work) and /bin/sh is something that is really always installed.

"Fade" borders in CSS

You could also use box-shadow property with higher value of blur and rgba() color to set opacity level. Sounds like a better choice in your case.

box-shadow: 0 30px 40px rgba(0,0,0,.1);

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

Here is the solution. I have fixed it. Here is the code

child: _status(data[index]["status"]),

Widget _status(status) {
  if (status == "3") {
    return Text('Process');
  } else if(status == "1") {
    return Text('Order');
  } else {
    return Text("Waiting");
  }
}

In C#, how to check if a TCP port is available?

If I'm not very much mistaken, you can use System.Network.whatever to check.

However, this will always incur a race condition.

The canonical way of checking is try to listen on that port. If you get an error that port wasn't open.

I think this is part of why bind() and listen() are two separate system calls.

Convert seconds into days, hours, minutes and seconds

function convert($seconds){
$string = "";

$days = intval(intval($seconds) / (3600*24));
$hours = (intval($seconds) / 3600) % 24;
$minutes = (intval($seconds) / 60) % 60;
$seconds = (intval($seconds)) % 60;

if($days> 0){
    $string .= "$days days ";
}
if($hours > 0){
    $string .= "$hours hours ";
}
if($minutes > 0){
    $string .= "$minutes minutes ";
}
if ($seconds > 0){
    $string .= "$seconds seconds";
}

return $string;
}

echo convert(3744000);

Seconds CountDown Timer

enter image description here .

Usage:

CountDownTimer timer = new CountDownTimer();


//set to 30 mins
timer.SetTime(30,0);     

timer.Start();

//update label text
timer.TimeChanged += () => Label1.Text = timer.TimeLeftMsStr; 

// show messageBox on timer = 00:00.000
timer.CountDownFinished += () => MessageBox.Show("Timer finished the work!"); 

//timer step. By default is 1 second
timer.StepMs = 77; // for nice milliseconds time switch

and don't forget to Dispose(); when timer is useless for you;

Source code:

using System;
using System.Diagnostics;
using System.Windows.Forms;

public class CountDownTimer : IDisposable
{
    public Stopwatch _stpWatch = new Stopwatch();

    public Action TimeChanged;
    public Action CountDownFinished;

    public bool IsRunnign => timer.Enabled;

    public int StepMs
    {
        get => timer.Interval;
        set => timer.Interval = value;
    }

    private Timer timer = new Timer();

    private TimeSpan _max = TimeSpan.FromMilliseconds(30000);

    public TimeSpan TimeLeft => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) > 0 ? TimeSpan.FromMilliseconds(_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) : TimeSpan.FromMilliseconds(0);

    private bool _mustStop => (_max.TotalMilliseconds - _stpWatch.ElapsedMilliseconds) < 0;

    public string TimeLeftStr => TimeLeft.ToString(@"\mm\:ss");

    public string TimeLeftMsStr => TimeLeft.ToString(@"mm\:ss\.fff");

    private void TimerTick(object sender, EventArgs e)
    {
        TimeChanged?.Invoke();

        if (_mustStop)
        {
            CountDownFinished?.Invoke();
            _stpWatch.Stop();
            timer.Enabled = false;
        }
    }

    public CountDownTimer(int min, int sec)
    {
        SetTime(min, sec);
        Init();
    }

    public CountDownTimer(TimeSpan ts)
    {
        SetTime(ts);
        Init();
    }

    public CountDownTimer()
    {
        Init();
    }

    private void Init()
    {
        StepMs = 1000;
        timer.Tick += new EventHandler(TimerTick);
    }

    public void SetTime(TimeSpan ts)
    {
        _max = ts;
        TimeChanged?.Invoke();
    }

    public void SetTime(int min, int sec = 0) => SetTime(TimeSpan.FromSeconds(min * 60 + sec));

    public void Start() {
        timer.Start();
        _stpWatch.Start();
    }

    public void Pause()
    {
        timer.Stop();
        _stpWatch.Stop();
    }

    public void Stop()
    {
        Reset();
        Pause();
    }

    public void Reset()
    {
        _stpWatch.Reset();
    }

    public void Restart()
    {
        _stpWatch.Reset();
        timer.Start();
    }

    public void Dispose() => timer.Dispose();
}

(updated 6.6.2020, because of problems with time calculation)

How to register ASP.NET 2.0 to web server(IIS7)?

Open Control Panel - Programs - Turn Windows Features on or off expand - Internet Information Services expand - World Wide Web Services expand - Application development Features check - ASP.Net

Its advisable you check other feature to avoid future problem that might not give direct error messages Please don't forget to mark this question as answered if it solves your problem for the purpose of others

HTML Canvas Full Screen

On document load set the

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

How do I pass options to the Selenium Chrome driver using Python?

Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :

desired_capabilities['chromeOptions'] = {
    "args": ["--disable-extensions"],
    "extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)

Draw radius around a point in Google map

I have just written a blog article that addresses exactly this, which you may find useful: http://seewah.blogspot.com/2009/10/circle-overlay-on-google-map.html

Basically, you need to create a GGroundOverlay with the correct GLatLngBounds. The tricky bit is in working out the southwest corner coordinate and the northeast corner coordinate of this imaginery square (the GLatLngBounds) bounding this circle, based on the desired radius. The math is quite complicated, but you can just refer to getDestLatLng function in the blog. The rest should be pretty straightforward.

How to SELECT a dropdown list item by value programmatically

If you know that the dropdownlist contains the value you're looking to select, use:

ddl.SelectedValue = "2";

If you're not sure if the value exists, use (or you'll get a null reference exception):

ListItem selectedListItem = ddl.Items.FindByValue("2");

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
}

Is it possible to install iOS 6 SDK on Xcode 5?

I downloaded XCode 4 and took iOS 6.1 SDK from it to the XCode 5 as described in other answers. Then I also installed iOS 6.1 Simulator (it was available in preferences). I also switched Base SDK to iOS 6.1 in project settings.

After all these manipulations the project with 6.1 base sdk runs in comp ability mode in iOS 7 Simulator.

Failed to resolve: com.android.support:appcompat-v7:26.0.0

you forgot to add add alpha1 in module area

compile 'com.android.support:appcompat-v7:26.0.0-alpha1'

use maven repository in project area that's it

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

CSV new-line character seen in unquoted field error

I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try

Python Error:

_csv.Error: new-line character seen in unquoted field

Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain CSV format or CSV (MS-DOS). Do not use CSV (Macintosh) as save-as type.

My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.

Lua - Current time in milliseconds

If you're using lua with nginx/openresty you could use ngx.now() which returns a float with millisecond precision

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

capture div into image using html2canvas

I ran into the same type of error you described, but mine was due to the dom not being completely ready to go. I tested with both jQuery pulling the div and also getElementById just to make sure there wasn't something strange with the jQuery selector. Below is an example that works in Chrome:

<html>
<head>
<style type="text/css">
div {
    height: 50px;
    width: 50px;
    background-color: #2C7CC3;
}
</style>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script language="javascript">
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
    html2canvas($("#testdiv"), {
        onrendered: function(canvas) {
            // canvas is the final rendered <canvas> element
            var myImage = canvas.toDataURL("image/png");
            window.open(myImage);
        }
    });
});
</script>
</head>
<body>
<div id="testdiv">
</div>
</body>
</html>

Don't understand why UnboundLocalError occurs (closure)

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword).

A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can't modify the binding in the enclosing environment.

In your case you are trying to treat counter as a local variable rather than a bound value. Note that this code, which binds the value of x assigned in the enclosing environment, works fine:

>>> x = 1

>>> def f():
>>>  return x

>>> f()
1

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

How to get element value in jQuery

<ul id="unOrderedList">
<li value="2">Whatever</li>
.
.



 $('#unOrderedList li').click(function(){
      var value = $(this).attr('value');
     alert(value); 
  });

Your looking for the attribute "value" inside the "li" tag

range() for floats

There will be of course some rounding errors, so this is not perfect, but this is what I use generally for applications, which don't require high precision. If you wanted to make this more accurate, you could add an extra argument to specify how to handle rounding errors. Perhaps passing a rounding function might make this extensible and allow the programmer to specify how to handle rounding errors.

arange = lambda start, stop, step: [i + step * i for i in range(int((stop - start) / step))]

If I write:

arange(0, 1, 0.1)

It will output:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

Function for 'does matrix contain value X?'

If you need to check whether the elements of one vector are in another, the best solution is ismember as mentioned in the other answers.

ismember([15 17],primes(20))

However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf

It gives a very practical example:

[tf, loc]=ismember(0.3, 0:0.1:1) % returns false 
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true

Though the default tolerance should normally be sufficient, it gives you more flexibility

ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true

How to Apply Gradient to background view of iOS Swift App

Xcode 11 • Swift 5.1


You can design your own Gradient View as follow:

@IBDesignable
public class Gradient: UIView {
    @IBInspectable var startColor:   UIColor = .black { didSet { updateColors() }}
    @IBInspectable var endColor:     UIColor = .white { didSet { updateColors() }}
    @IBInspectable var startLocation: Double =   0.05 { didSet { updateLocations() }}
    @IBInspectable var endLocation:   Double =   0.95 { didSet { updateLocations() }}
    @IBInspectable var horizontalMode:  Bool =  false { didSet { updatePoints() }}
    @IBInspectable var diagonalMode:    Bool =  false { didSet { updatePoints() }}

    override public class var layerClass: AnyClass { CAGradientLayer.self }

    var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }

    func updatePoints() {
        if horizontalMode {
            gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
        } else {
            gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
            gradientLayer.endPoint   = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
        }
    }
    func updateLocations() {
        gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
    }
    func updateColors() {
        gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
    }
    override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updatePoints()
        updateLocations()
        updateColors()
    }

}

enter image description here

How can I use threading in Python?

For me, the perfect example for threading is monitoring asynchronous events. Look at this code.

# thread_test.py
import threading
import time

class Monitor(threading.Thread):
    def __init__(self, mon):
        threading.Thread.__init__(self)
        self.mon = mon

    def run(self):
        while True:
            if self.mon[0] == 2:
                print "Mon = 2"
                self.mon[0] = 3;

You can play with this code by opening an IPython session and doing something like:

>>> from thread_test import Monitor
>>> a = [0]
>>> mon = Monitor(a)
>>> mon.start()
>>> a[0] = 2
Mon = 2
>>>a[0] = 2
Mon = 2

Wait a few minutes

>>> a[0] = 2
Mon = 2

Can we update primary key values of a table?

You can as long as

  • The value is unique
  • No existing foreign keys are violated

Running vbscript from batch file

You can use %~dp0 to get the path of the currently running batch file.

Edited to change directory to the VBS location before running

If you want the VBS to synchronously run in the same window, then

@echo off
pushd %~dp0
cscript necdaily.vbs

If you want the VBS to synchronously run in a new window, then

@echo off
pushd %~dp0
start /wait "" cmd /c cscript necdaily.vbs

If you want the VBS to asynchronously run in the same window, then

@echo off
pushd %~dp0
start /b "" cscript necdaily.vbs

If you want the VBS to asynchronously run in a new window, then

@echo off
pushd %~dp0
start "" cmd /c cscript necdaily.vbs

Clear text area

try this

 $("#vinanghinguyen_images_bbocde").attr("value", ""); 

SQL Delete Records within a specific Range

If you write it as the following in SQL server then there would be no danger of wiping the database table unless all of the values in that table happen to actually be between those values:

DELETE FROM [dbo].[TableName] WHERE [TableName].[IdField] BETWEEN 79 AND 296 

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

How to get the concrete class name as a string?

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'

How might I force a floating DIV to match the height of another floating DIV?

I recommend you wrap them both in an outer div with the desired background color.

C# Checking if button was clicked

button1, button2 and button3 have same even handler

private void button1_Click(Object sender, EventArgs e)
    {
        Button btnSender = (Button)sender;
        if (btnSender == button1 || btnSender == button2)
        {
            //some code here
        }
        else if (btnSender == button3)
            //some code here
    }

How to replace multiple white spaces with one white space

string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");

Split string to equal length substrings in Java

Here's a one-liner version which uses Java 8 IntStream to determine the indexes of the slice beginnings:

String x = "Thequickbrownfoxjumps";

String[] result = IntStream
                    .iterate(0, i -> i + 4)
                    .limit((int) Math.ceil(x.length() / 4.0))
                    .mapToObj(i ->
                        x.substring(i, Math.min(i + 4, x.length())
                    )
                    .toArray(String[]::new);

git replace local version with remote version

My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.

In that scenario you can just run the following command:

git checkout -- path/filename

React Native Responsive Font Size

You can use something like this.

var {height, width} = Dimensions.get('window'); var textFontSize = width * 0.03;

inputText: {
    color : TEXT_COLOR_PRIMARY,
    width: '80%',
    fontSize: textFontSize
}

Hope this helps without installing any third party libraries.

How to do 3 table JOIN in UPDATE query?

Below is the Update query which includes JOIN & WHERE both. Same way we can use multiple join/where clause, Hope it will help you :-

UPDATE opportunities_cstm oc JOIN opportunities o ON oc.id_c = o.id
 SET oc.forecast_stage_c = 'APX'
 WHERE o.deleted = 0
   AND o.sales_stage IN('ABC','PQR','XYZ')

Find duplicate entries in a column

Try this query.. It uses the Analytic function SUM:

SELECT * FROM
(  
 SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
 FROM table1 a 
 WHERE s_ind ='Y'   
)
WHERE cnt > 2

Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

This May be helpful:

//I personally prefer dynamic import (angular 8)
{ path: 'pages', loadChildren: () => import('./pages/pages.module').then(mod => mod.PageModule) }

In child routing it should look like: { path: 'about', component: AboutComponent },

Note that there is no pages in path of child routing and in routerLink or nsRouterLink it should look like routerLink="/pages/about"

I hope thi help someone out there.

Adding Multiple Values in ArrayList at a single index

create simple method to do that for you:

public void addMulti(String[] strings,List list){
    for (int i = 0; i < strings.length; i++) {
        list.add(strings[i]);
    }
}

Then you can create

String[] wrong ={"1","2","3","4","5","6"};

and add it with this method to your list.

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

How to do a recursive find/replace of a string with awk or sed?

I just needed this and was not happy with the speed of the available examples. So I came up with my own:

cd /var/www && ack-grep -l --print0 subdomainA.example.com | xargs -0 perl -i.bak -pe 's/subdomainA\.example\.com/subdomainB.example.com/g'

Ack-grep is very efficient on finding relevant files. This command replaced ~145 000 files with a breeze whereas others took so long I couldn't wait until they finish.

@Autowired - No qualifying bean of type found for dependency

Instead of @Autowire MailManager mailManager, you can mock the bean as given below:

import org.springframework.boot.test.mock.mockito.MockBean;

::
::

@MockBean MailManager mailManager;

Also, you can configure @MockBean MailManager mailManager; separately in the @SpringBootConfiguration class and initialize like below:

@Autowire MailManager mailManager

npm - how to show the latest version of a package

If you're looking for the current and the latest versions of all your installed packages, you can also use:

npm outdated

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

How to insert a picture into Excel at a specified cell position with VBA

If it's simply about inserting and resizing a picture, try the code below.

For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.

Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.

Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
    Dim Pic As Picture, Shp as Shape
    Set Pic = wsDestination.Pictures.Insert(FilePath)
    Pic.Name = "myPicture"
    'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
    Set Shp = wsDestination.Shapes("myPicture")
    With Shp
        .Height = 100
        .Width = 75
        .LockAspectRatio = msoTrue  'Put this later so that changing height doesn't change width and vice-versa)
        .Placement = 1
        .Top = 100
        .Left = 100
    End with
End Sub

Good luck!

Using Custom Domains With IIS Express

This method has been tested and worked with ASP.NET Core 3.1 and Visual Studio 2019.

.vs\PROJECTNAME\config\applicationhost.config

Change "*:44320:localhost" to "*:44320:*".

<bindings>
    <binding protocol="http" bindingInformation="*:5737:localhost" />
    <binding protocol="https" bindingInformation="*:44320:*" />
</bindings>

Both links work:

Now if you want the app to work with the custom domain, just add the following line to the host file:

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 customdomain

Now:

  • https://customdomain:44320

NOTE: If your app works without SSL, change the protocol="http" part.

How to perform a real time search and filter on a HTML table

Thank you @dfsq for the very helpful code!

I've made some adjustments and maybe some others like them too. I ensured that you can search for multiple words, without having a strict match.

Example rows:

  • Apples and Pears
  • Apples and Bananas
  • Apples and Oranges
  • ...

You could search for 'ap pe' and it would recognise the first row
You could search for 'banana apple' and it would recognise the second row

Demo: http://jsfiddle.net/JeroenSormani/xhpkfwgd/1/

var $rows = $('#table tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');

  $rows.hide().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    var matchesSearch = true;
    $(val).each(function(index, value) {
      matchesSearch = (!matchesSearch) ? false : ~text.indexOf(value);
    });
    return matchesSearch;
  }).show();
});

Read CSV with Scanner()

If you absolutely must use Scanner, then you must set its delimiter via its useDelimiter(...) method. Else it will default to using all white space as its delimiter. Better though as has already been stated -- use a CSV library since this is what they do best.

For example, this delimiter will split on commas with or without surrounding whitespace:

scanner.useDelimiter("\\s*,\\s*");

Please check out the java.util.Scanner API for more on this.

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

Type converting slices of interfaces

Try interface{} instead. To cast back as slice, try

func foo(bar interface{}) {
    s := bar.([]string)
    // ...
}

Laravel 5: Retrieve JSON array from $request

You need to change your Ajax call to

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    contentType: "json",
    processData: false,
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

change the dataType to contentType and add the processData option.

To retrieve the JSON payload from your controller, use:

dd(json_decode($request->getContent(), true));

instead of

dd($request->all());

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

How does Java resolve a relative path in new File()?

Relative paths can be best understood if you know how Java runs the program.

There is a concept of working directory when running programs in Java. Assuming you have a class, say, FileHelper that does the IO under /User/home/Desktop/projectRoot/src/topLevelPackage/.

Depending on the case where you invoke java to run the program, you will have different working directory. If you run your program from within and IDE, it will most probably be projectRoot.

  • In this case $ projectRoot/src : java topLevelPackage.FileHelper it will be src.

  • In this case $ projectRoot : java -cp src topLevelPackage.FileHelper it will be projectRoot.

  • In this case $ /User/home/Desktop : java -cp ./projectRoot/src topLevelPackage.FileHelper it will be Desktop.

(Assuming $ is your command prompt with standard Unix-like FileSystem. Similar correspondence/parallels with Windows system)

So, your relative path root (.) resolves to your working directory. Thus to be better sure of where to write files, it's said to consider below approach.

package topLevelPackage

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileHelper {

    // Not full implementation, just barebone stub for path
    public void createLocalFile() {

        // Explicitly get hold of working directory
        String workingDir = System.getProperty("user.dir");

        Path filePath = Paths.get(workingDir+File.separator+"sampleFile.txt");

        // In case we need specific path, traverse that path, rather using . or .. 
        Path pathToProjectRoot = Paths.get(System.getProperty("user.home"), "Desktop", "projectRoot");

        System.out.println(filePath);
        System.out.println(pathToProjectRoot);

    }
}

Hope this helps.

How do I make a LinearLayout scrollable?

you can make any layout scrollable. Just under <?xml version="1.0" encoding="utf-8"?> add these lines:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

and at the end add </ScrollView>

example of a non-scrollable activity:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:verticalScrollbarPosition="right"
    tools:context="p32929.demo.MainActivity">


    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="102dp"
        android:id="@+id/textView"
        android:textSize="30sp" />
</RelativeLayout>

After making it scrollable, it becomes like this:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:verticalScrollbarPosition="right"
        tools:context="p32929.demo.MainActivity">


        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="102dp"
            android:text="TextView"
            android:textSize="30sp" />
    </RelativeLayout>
</ScrollView>

Remove last item from array

splice(index,howmany) - This solution sounds good. But This howmany will work only for the positive array index. To remove last two items or three items use the index itself.

For example, splice(-2) to remove last two items. splice(-3) for removing last three items.

Get text of label with jquery

try document.getElementById('<%=Label1.ClientID%>').text or innerHTML OTHERWISE LOAD JQUERY SCRIPT AND put your code as it is....

How to Clone Objects

I use AutoMapper for this. It works like this:

Mapper.CreateMap(typeof(Person), typeof(Person));
Mapper.Map(a, b);

Now person a has all the properties of person b.

As an aside, AutoMapper works for differing objects as well. For more information, check it out at http://automapper.org

Update: I use this syntax now (simplistically - really the CreateMaps are in AutoMapper profiles):

Mapper.CreateMap<Person, Person>;
Mapper.Map(a, b);

Note that you don't have to do a CreateMap to map one object of the same type to another, but if you don't, AutoMapper will create a shallow copy, meaning to the lay man that if you change one object, the other changes also.

PHP refresh window? equivalent to F5 page reload?

Actually it is possible:

Header('Location: '.$_SERVER['PHP_SELF']);
Exit(); //optional

And it will reload the same page.

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

What exactly does a jar file contain?

A .jar file is akin to a .exe file. In essence, they are both executable zip files (different zip algorithms).

In a jar file, you will see folders and class files. Each class file is similar to your .o file, and is a compiled java archive.

If you wanted to see the code in a jar file, download a java decompiler (located here: http://java.decompiler.free.fr/?q=jdgui) and a .jar extractor (7zip works fine).

bootstrap multiselect get selected values

Shorter version:

$('#multiselect1').multiselect({
    ...
    onChange: function() {
        console.log($('#multiselect1').val());
    }
}); 

Excel: replace part of cell's string value

You have a character = STQ8QGpaM4CU6149665!7084880820, and you have a another column = 7084880820.

If you want to get only this in excel using the formula: STQ8QGpaM4CU6149665!, use this:

=REPLACE(H11,SEARCH(J11,H11),LEN(J11),"")

H11 is an old character and for starting number use search option then for no of character needs to replace use len option then replace to new character. I am replacing this to blank.

Absolute and Flexbox in React Native

Ok, solved my problem, if anyone is passing by here is the answer:

Just had to add left: 0, and top: 0, to the styles, and yes, I'm tired.

position: 'absolute',
left:     0,
top:      0,

SQL split values to multiple rows

I have take the reference from here with changed column name.

DELIMITER $$

CREATE FUNCTION strSplit(x VARCHAR(65000), delim VARCHAR(12), pos INTEGER) 
RETURNS VARCHAR(65000)
BEGIN
  DECLARE output VARCHAR(65000);
  SET output = REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos)
                 , LENGTH(SUBSTRING_INDEX(x, delim, pos - 1)) + 1)
                 , delim
                 , '');
  IF output = '' THEN SET output = null; END IF;
  RETURN output;
END $$


CREATE PROCEDURE BadTableToGoodTable()
BEGIN
  DECLARE i INTEGER;

  SET i = 1;
  REPEAT
    INSERT INTO GoodTable (id, name)
      SELECT id, strSplit(name, ',', i) FROM BadTable
      WHERE strSplit(name, ',', i) IS NOT NULL;
    SET i = i + 1;
    UNTIL ROW_COUNT() = 0
  END REPEAT;
END $$

DELIMITER ;

Add text at the end of each line

sed 's/.*/&:80/'  abcd.txt >abcde.txt

Python: Converting string into decimal number

A2 = [float(x.strip('"')) for x in A1] works, @Jake , but there are unnecessary 0s

AngularJS: How do I manually set input to $valid in controller?

The answers above didn't help me solve my problem. After a long search I bumped into this partial solution.

I've finally solved my problem with this code to set the input field manually to ng-invalid (to set to ng-valid set it to 'true'):

$scope.myForm.inputName.$setValidity('required', false);

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

If using the docker-compose file, Based on docker compose version 2.x We can set like as below, by overriding the default config.

ulimits:
  nproc: 65535
  nofile:
    soft: 26677
    hard: 46677

https://docs.docker.com/compose/compose-file/

Converting a generic list to a CSV string

As the code in the link given by @Frank Create a CSV File from a .NET Generic List there was a little issue of ending every line with a , I modified the code to get rid of it.Hope it helps someone.

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
    if (list == null || list.Count == 0) return;

    //get type from 0th member
    Type t = list[0].GetType();
    string newLine = Environment.NewLine;

    if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));

    if (!File.Exists(csvCompletePath)) File.Create(csvCompletePath);

    using (var sw = new StreamWriter(csvCompletePath))
    {
        //make a new instance of the class name we figured out to get its props
        object o = Activator.CreateInstance(t);
        //gets all properties
        PropertyInfo[] props = o.GetType().GetProperties();

        //foreach of the properties in class above, write out properties
        //this is the header row
        sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);

        //this acts as datarow
        foreach (T item in list)
        {
            //this acts as datacolumn
            var row = string.Join(",", props.Select(d => item.GetType()
                                                            .GetProperty(d.Name)
                                                            .GetValue(item, null)
                                                            .ToString())
                                                    .ToArray());
            sw.Write(row + newLine);

        }
    }
}

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

Failed to add the host to the list of know hosts

For anyone interested, this one worked for me in Ubuntu:

  1. Go to .ssh directory.

    $ cd ~/.ssh
    
  2. Remove the known_hosts file.

    $ rm known_hosts
    
  3. Re-push your Git changes.

IN-clause in HQL or Java Persistence Query Language

Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:

Entity.java:

@Entity
@NamedQueries({
    @NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
    @Column(name = "attribute")
    private String attribute;
}

Dao.java:

public class Dao {
    public List<Entity> findByAttributes(Set<String> attributes) {
        Query query = em.createNamedQuery("byAttributes");
        query.setParameter(1, attributes);

        List<Entity> entities = query.getResultList();
        return entities;
    }
}

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;

How do you do relative time in Rails?

You can use the arithmetic operators to do relative time.

Time.now - 2.days 

Will give you 2 days ago.

Should I use pt or px?

Here you've got a very detailed explanation of their differences

http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/

The jist of it (from source)

Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

How to get a resource id with a known resource name?

I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.

Here's the code:

/**
 * @author Lonkly
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param ? - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> ?) {

    Field field = null;
    int resId = 0;
    try {
        field = ?.getField(variableName);
        try {
            resId = field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resId;

}

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

You have to use the equal sign in the formula box

=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

How to connect to LocalDb

You can connect with MSSMS to LocalDB. Type only in SERVER NAME: (localdb)\v11.0 and leave it by Windows Authentication and it connects to your LocalDB server and shows you the databases in it.

Select a Column in SQL not in Group By

The direct answer is that you can't. You must select either an aggregate or something that you are grouping by.

So, you need an alternative approach.

1). Take you current query and join the base data back on it

SELECT
  cpe.*
FROM
  Filteredfmgcms_claimpaymentestimate cpe
INNER JOIN
  (yourQuery) AS lookup
    ON  lookup.MaxData           = cpe.createdOn
    AND lookup.fmgcms_cpeclaimid = cpe.fmgcms_cpeclaimid

2). Use a CTE to do it all in one go...

WITH
  sequenced_data AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARITION BY fmgcms_cpeclaimid ORDER BY CreatedOn DESC) AS sequence_id
  FROM
    Filteredfmgcms_claimpaymentestimate
  WHERE
    createdon < 'reportstartdate'
)
SELECT
  *
FROM
  sequenced_data
WHERE
  sequence_id = 1

NOTE: Using ROW_NUMBER() will ensure just one record per fmgcms_cpeclaimid. Even if multiple records are tied with the exact same createdon value. If you can have ties, and want all records with the same createdon value, use RANK() instead.

"Could not find bundler" error

I had the same problem .. something happened to my bash profile that wasn't setting up the RVM stuff correctly.

Make sure your bash profile has the following line:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"  # This loads RVM into a shell session.

Then I ran "source ~/.bash_profile" and that reloaded everything that was in my bash profile.

That seemed to fix it for me.

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

Java maximum memory on Windows XP

The Java heap size limits for Windows are:

  • maximum possible heap size on 32-bit Java: 1.8 GB
  • recommended heap size limit on 32-bit Java: 1.5 GB (or 1.8 GB with /3GB option)

This doesn't help you getting a bigger Java heap, but now you know you can't go beyond these values.

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

Format date to MM/dd/yyyy in JavaScript

Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.

_x000D_
_x000D_
var date = new Date('2010-10-11T00:00:00+05:30');_x000D_
    alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
_x000D_
_x000D_

JavaScript: What are .extend and .prototype used for?

This seems to be the clearest and simplest example to me, this just appends property or replaces existing.

function replaceProperties(copyTo, copyFrom)  {
  for (var property in copyFrom) 
    copyTo[property] =  copyFrom[property]
  return copyTo
}

Change button text from Xcode?

Swift 5 Use button.setTitle()

  1. If using storyboards, make a IBOutlet reference.

@IBOutlet weak var button: UIButton!

  1. Call setTitle on the button followed by the text and the state.

button.setTitle("Button text here", forState: .normal)

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

/* Warning: macro mod evaluates its arguments' side effects multiple times. */
#define mod(r,m) (((r) % (m)) + ((r)<0)?(m):0)

... or just get used to getting any representative for the equivalence class.

jQuery events .load(), .ready(), .unload()

Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.

How can I debug a .BAT script?

Make sure there are no 'echo off' statements in the scripts and call 'echo on' after calling each script to reset any you have missed.

The reason is that if echo is left on, then the command interpreter will output each command (after parameter processing) before executing it. Makes it look really bad for using in production, but very useful for debugging purposes as you can see where output has gone wrong.

Also, make sure you are checking the ErrorLevels set by the called batch scripts and programs. Remember that there are 2 different methods used in .bat files for this. If you called a program, the Error level is in %ERRORLEVEL%, while from batch files the error level is returned in the ErrorLevel variable and doesn't need %'s around it.

No @XmlRootElement generated by JAXB

This is mentioned at the bottom of the blog post already linked above but this works like a treat for me:

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement<MyClass>(new QName("uri","local"), MyClass.class, myClassInstance), System.out);

Inserting NOW() into Database with CodeIgniter's Active Record

you can load the date helper and use the codeigniter interal now() if you want to reference the users GMT time offset

it woulk look somewhat like this

$data = array(
'created_on' => date('Y-m-d H:i:s',now())
);

If you don't use the GTM master settings and let your users set their own offsets there is no advantage over using php's time() function.

Wordpress - Images not showing up in the Media Library

How did you upload those images; via FTP or through WP uploader? You have to upload images THROUGH WP uploader in order to show them in the image library.

Make page to tell browser not to cache/preserve input values

Another approach would be to reset the form using JavaScript right after the form in the HTML:

<form id="myForm">
  <input type="text" value="" name="myTextInput" />
</form>

<script type="text/javascript">
  document.getElementById("myForm").reset();
</script>

The calling thread cannot access this object because a different thread owns it

If you encounter this problem and UI Controls were created on a separate worker thread when working with BitmapSource or ImageSource in WPF, call Freeze() method first before passing the BitmapSource or ImageSource as a parameter to any method. Using Application.Current.Dispatcher.Invoke() does not work in such instances

Multiple selector chaining in jQuery?

You can combine multiple selectors with a comma:

$('#Create .myClass,#Edit .myClass').plugin({options here});

Or if you're going to have a bunch of them, you could add a class to all your form elements and then search within that class. This doesn't get you the supposed speed savings of restricting the search, but I honestly wouldn't worry too much about that if I were you. Browsers do a lot of fancy things to optimize common operations behind your back -- the simple class selector might be faster.

Comparing strings by their alphabetical order

Take a look at the String.compareTo method.

s1.compareTo(s2)

From the javadocs:

The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

filter out multiple criteria using excel vba

Alternative using VBA's Filter function

As an innovative alternative to @schlebe 's recent answer, I tried to use the Filter function integrated in VBA, which allows to filter out a given search string setting the third argument to False. All "negative" search strings (e.g. A, B, C) are defined in an array. I read the criteria in column A to a datafield array and basicly execute a subsequent filtering (A - C) to filter these items out.

Code

Sub FilterOut()
Dim ws  As Worksheet
Dim rng As Range, i As Integer, n As Long, v As Variant
' 1) define strings to be filtered out in array
  Dim a()                    ' declare as array
  a = Array("A", "B", "C")   ' << filter out values
' 2) define your sheetname and range (e.g. criteria in column A)
  Set ws = ThisWorkbook.Worksheets("FilterOut")
  n = ws.Range("A" & ws.Rows.Count).End(xlUp).row
  Set rng = ws.Range("A2:A" & n)
' 3) hide complete range rows temporarily
  rng.EntireRow.Hidden = True
' 4) set range to a variant 2-dim datafield array
  v = rng
' 5) code array items by appending row numbers
  For i = 1 To UBound(v): v(i, 1) = v(i, 1) & "#" & i + 1: Next i
' 6) transform to 1-dim array and FILTER OUT the first search string, e.g. "A"
  v = Filter(Application.Transpose(Application.Index(v, 0, 1)), a(0), False, False)
' 7) filter out each subsequent search string, i.e. "B" and "C"
  For i = 1 To UBound(a): v = Filter(v, a(i), False, False): Next i
' 8) get coded row numbers via split function and unhide valid rows
  For i = LBound(v) To UBound(v)
      ws.Range("A" & Split(v(i) & "#", "#")(1)).EntireRow.Hidden = False
  Next i
End Sub

What are Aggregates and PODs and how/why are they special?

What changes for C++11?

Aggregates

The standard definition of an aggregate has changed slightly, but it's still pretty much the same:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

Ok, what changed?

  1. Previously, an aggregate could have no user-declared constructors, but now it can't have user-provided constructors. Is there a difference? Yes, there is, because now you can declare constructors and default them:

    struct Aggregate {
        Aggregate() = default; // asks the compiler to generate the default implementation
    };
    

    This is still an aggregate because a constructor (or any special member function) that is defaulted on the first declaration is not user-provided.

  2. Now an aggregate cannot have any brace-or-equal-initializers for non-static data members. What does this mean? Well, this is just because with this new standard, we can initialize members directly in the class like this:

    struct NotAggregate {
        int x = 5; // valid in C++11
        std::vector<int> s{1,2,3}; // also valid
    };
    

    Using this feature makes the class no longer an aggregate because it's basically equivalent to providing your own default constructor.

So, what is an aggregate didn't change much at all. It's still the same basic idea, adapted to the new features.

What about PODs?

PODs went through a lot of changes. Lots of previous rules about PODs were relaxed in this new standard, and the way the definition is provided in the standard was radically changed.

The idea of a POD is to capture basically two distinct properties:

  1. It supports static initialization, and
  2. Compiling a POD in C++ gives you the same memory layout as a struct compiled in C.

Because of this, the definition has been split into two distinct concepts: trivial classes and standard-layout classes, because these are more useful than POD. The standard now rarely uses the term POD, preferring the more specific trivial and standard-layout concepts.

The new definition basically says that a POD is a class that is both trivial and has standard-layout, and this property must hold recursively for all non-static data members:

A POD struct is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.

Let's go over each of these two properties in detail separately.

Trivial classes

Trivial is the first property mentioned above: trivial classes support static initialization. If a class is trivially copyable (a superset of trivial classes), it is ok to copy its representation over the place with things like memcpy and expect the result to be the same.

The standard defines a trivial class as follows:

A trivially copyable class is a class that:

— has no non-trivial copy constructors (12.8),

— has no non-trivial move constructors (12.8),

— has no non-trivial copy assignment operators (13.5.3, 12.8),

— has no non-trivial move assignment operators (13.5.3, 12.8), and

— has a trivial destructor (12.4).

A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.

[ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

So, what are all those trivial and non-trivial things?

A copy/move constructor for class X is trivial if it is not user-provided and if

— class X has no virtual functions (10.3) and no virtual base classes (10.1), and

— the constructor selected to copy/move each direct base class subobject is trivial, and

— for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;

otherwise the copy/move constructor is non-trivial.

Basically this means that a copy or move constructor is trivial if it is not user-provided, the class has nothing virtual in it, and this property holds recursively for all the members of the class and for the base class.

The definition of a trivial copy/move assignment operator is very similar, simply replacing the word "constructor" with "assignment operator".

A trivial destructor also has a similar definition, with the added constraint that it can't be virtual.

And yet another similar rule exists for trivial default constructors, with the addition that a default constructor is not-trivial if the class has non-static data members with brace-or-equal-initializers, which we've seen above.

Here are some examples to clear everything up:

// empty classes are trivial
struct Trivial1 {};

// all special members are implicit
struct Trivial2 {
    int x;
};

struct Trivial3 : Trivial2 { // base class is trivial
    Trivial3() = default; // not a user-provided ctor
    int y;
};

struct Trivial4 {
public:
    int a;
private: // no restrictions on access modifiers
    int b;
};

struct Trivial5 {
    Trivial1 a;
    Trivial2 b;
    Trivial3 c;
    Trivial4 d;
};

struct Trivial6 {
    Trivial2 a[23];
};

struct Trivial7 {
    Trivial6 c;
    void f(); // it's okay to have non-virtual functions
};

struct Trivial8 {
     int x;
     static NonTrivial1 y; // no restrictions on static members
};

struct Trivial9 {
     Trivial9() = default; // not user-provided
      // a regular constructor is okay because we still have default ctor
     Trivial9(int x) : x(x) {};
     int x;
};

struct NonTrivial1 : Trivial3 {
    virtual void f(); // virtual members make non-trivial ctors
};

struct NonTrivial2 {
    NonTrivial2() : z(42) {} // user-provided ctor
    int z;
};

struct NonTrivial3 {
    NonTrivial3(); // user-provided ctor
    int w;
};
NonTrivial3::NonTrivial3() = default; // defaulted but not on first declaration
                                      // still counts as user-provided
struct NonTrivial5 {
    virtual ~NonTrivial5(); // virtual destructors are not trivial
};

Standard-layout

Standard-layout is the second property. The standard mentions that these are useful for communicating with other languages, and that's because a standard-layout class has the same memory layout of the equivalent C struct or union.

This is another property that must hold recursively for members and all base classes. And as usual, no virtual functions or virtual base classes are allowed. That would make the layout incompatible with C.

A relaxed rule here is that standard-layout classes must have all non-static data members with the same access control. Previously these had to be all public, but now you can make them private or protected, as long as they are all private or all protected.

When using inheritance, only one class in the whole inheritance tree can have non-static data members, and the first non-static data member cannot be of a base class type (this could break aliasing rules), otherwise, it's not a standard-layout class.

This is how the definition goes in the standard text:

A standard-layout class is a class that:

— has no non-static data members of type non-standard-layout class (or array of such types) or reference,

— has no virtual functions (10.3) and no virtual base classes (10.1),

— has the same access control (Clause 11) for all non-static data members,

— has no non-standard-layout base classes,

— either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

— has no base classes of the same type as the first non-static data member.

A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.

A standard-layout union is a standard-layout class defined with the class-key union.

[ Note: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in 9.2.—end note ]

And let's see a few examples.

// empty classes have standard-layout
struct StandardLayout1 {};

struct StandardLayout2 {
    int x;
};

struct StandardLayout3 {
private: // both are private, so it's ok
    int x;
    int y;
};

struct StandardLayout4 : StandardLayout1 {
    int x;
    int y;

    void f(); // perfectly fine to have non-virtual functions
};

struct StandardLayout5 : StandardLayout1 {
    int x;
    StandardLayout1 y; // can have members of base type if they're not the first
};

struct StandardLayout6 : StandardLayout1, StandardLayout5 {
    // can use multiple inheritance as long only
    // one class in the hierarchy has non-static data members
};

struct StandardLayout7 {
    int x;
    int y;
    StandardLayout7(int x, int y) : x(x), y(y) {} // user-provided ctors are ok
};

struct StandardLayout8 {
public:
    StandardLayout8(int x) : x(x) {} // user-provided ctors are ok
// ok to have non-static data members and other members with different access
private:
    int x;
};

struct StandardLayout9 {
    int x;
    static NonStandardLayout1 y; // no restrictions on static members
};

struct NonStandardLayout1 {
    virtual f(); // cannot have virtual functions
};

struct NonStandardLayout2 {
    NonStandardLayout1 X; // has non-standard-layout member
};

struct NonStandardLayout3 : StandardLayout1 {
    StandardLayout1 x; // first member cannot be of the same type as base
};

struct NonStandardLayout4 : StandardLayout3 {
    int z; // more than one class has non-static data members
};

struct NonStandardLayout5 : NonStandardLayout3 {}; // has a non-standard-layout base class

Conclusion

With these new rules a lot more types can be PODs now. And even if a type is not POD, we can take advantage of some of the POD properties separately (if it is only one of trivial or standard-layout).

The standard library has traits to test these properties in the header <type_traits>:

template <typename T>
struct std::is_pod;
template <typename T>
struct std::is_trivial;
template <typename T>
struct std::is_trivially_copyable;
template <typename T>
struct std::is_standard_layout;

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

You only need these CSS properties in .container class of Bootstrap and you can put inside him the normal grid system without someone content of the container will be out of him (without scroll-x in the viewport).

HTML:

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            Your content here!
            ...    
        </div>
    </div>
    ... more rows
</div>

CSS:

/* Bootstrap custom */
.container{
    padding-left: 0rem;
    padding-right: 0rem;
    overflow: hidden;
}

Python add item to the tuple

From tuple to list to tuple :

a = ('2',)
b = 'b'

l = list(a)
l.append(b)

tuple(l)

Or with a longer list of items to append

a = ('2',)
items = ['o', 'k', 'd', 'o']

l = list(a)

for x in items:
    l.append(x)

print tuple(l)

gives you

>>> 
('2', 'o', 'k', 'd', 'o')

The point here is: List is a mutable sequence type. So you can change a given list by adding or removing elements. Tuple is an immutable sequence type. You can't change a tuple. So you have to create a new one.

What are some alternatives to ReSharper?

CodeRush. Also, Scott Hanselman has a nice post comparing them, ReSharper vs. CodeRush.

A more up-to-date comparison is in Coderush vs Resharper by Jason Irwin.

Get data type of field in select statement in ORACLE

you can use the DBMS_SQL.DESCRIBE_COLUMNS2

    SET SERVEROUTPUT ON;
DECLARE
    STMT CLOB;
    CUR NUMBER;
    COLCNT NUMBER;
    IDX NUMBER;
    COLDESC DBMS_SQL.DESC_TAB2;
BEGIN
    CUR := DBMS_SQL.OPEN_CURSOR;
    STMT := 'SELECT  object_name , to_char(object_id), created FROM    DBA_OBJECTS where rownum<10';

    SYS.DBMS_SQL.PARSE(CUR, STMT, DBMS_SQL.NATIVE);
    DBMS_SQL.DESCRIBE_COLUMNS2(CUR, COLCNT, COLDESC);
    DBMS_OUTPUT.PUT_LINE('Statement: ' || STMT);
    FOR IDX IN 1 .. COLCNT
    LOOP
        CASE COLDESC(IDX).col_type
        WHEN 2 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': NUMBER');
        WHEN 12 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': DATE');
        WHEN 180 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': TIMESTAMP');
        WHEN 1 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': VARCHAR'||':'|| COLDESC(IDX).col_max_len);
        WHEN 9 THEN
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': VARCHAR2');
        -- Insert more cases if you need them
        ELSE
            DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': OTHERS (' || TO_CHAR(COLDESC(IDX).col_type) || ')');
        END CASE;
    END LOOP;
    SYS.DBMS_SQL.CLOSE_CURSOR(CUR);
EXCEPTION 
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE(SQLERRM(SQLCODE()) || ': ' || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
        SYS.DBMS_SQL.CLOSE_CURSOR(CUR);
END;
/


full example in the below url

https://www.ibm.com/support/knowledgecenter/sk/SSEPGG_9.7.0/com.ibm.db2.luw.sql.rtn.doc/doc/r0055146.html

Modifying the "Path to executable" of a windows service

It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services. Find the service you want to redirect, locate the ImagePath subkey and change that value.

Expand a div to fill the remaining width

Check this solution out

_x000D_
_x000D_
.container {_x000D_
  width: 100%;_x000D_
  height: 200px;_x000D_
  background-color: green;_x000D_
}_x000D_
.sidebar {_x000D_
  float: left;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background-color: yellow;_x000D_
}_x000D_
.content {_x000D_
  background-color: red;_x000D_
  height: 200px;_x000D_
  width: auto;_x000D_
  margin-left: 200px;_x000D_
}_x000D_
.item {_x000D_
  width: 25%;_x000D_
  background-color: blue;_x000D_
  float: left;_x000D_
  color: white;_x000D_
}_x000D_
.clearfix {_x000D_
  clear: both;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="clearfix"></div>_x000D_
  <div class="sidebar">width: 200px</div>_x000D_
_x000D_
  <div class="content">_x000D_
    <div class="item">25%</div>_x000D_
    <div class="item">25%</div>_x000D_
    <div class="item">25%</div>_x000D_
    <div class="item">25%</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I access a form in the controller?

Yes, you can access a form in the controller (as stated in the docs).

Except when your form is not defined in the controller scope and is defined in a child scope instead.

Basically, some angular directives, such as ng-if, ng-repeat or ng-include, will create an isolated child scope. So will any custom directives with a scope: {} property defined. Probably, your foundation components are also in your way.

I had the same problem when introducing a simple ng-if around the <form> tag.

See these for more info:

Note: I suggest you re-write your question. The answer to your question is yes but your problem is slightly different:

Can I access a form in a child scope from the controller?

To which the answer would simply be: no.

How to detect the character encoding of a text file?

If your file starts with the bytes 60, 118, 56, 46 and 49, then you have an ambiguous case. It could be UTF-8 (without BOM) or any of the single byte encodings like ASCII, ANSI, ISO-8859-1 etc.

How to communicate between Docker containers via "hostname"

That should be what --link is for, at least for the hostname part.
With docker 1.10, and PR 19242, that would be:

docker network create --net-alias=[]: Add network-scoped alias for the container

(see last section below)

That is what Updating the /etc/hosts file details

In addition to the environment variables, Docker adds a host entry for the source container to the /etc/hosts file.

For instance, launch an LDAP server:

docker run -t  --name openldap -d -p 389:389 larrycai/openldap

And define an image to test that LDAP server:

FROM ubuntu
RUN apt-get -y install ldap-utils
RUN touch /root/.bash_aliases
RUN echo "alias lds='ldapsearch -H ldap://internalopenldap -LL -b
ou=Users,dc=openstack,dc=org -D cn=admin,dc=openstack,dc=org -w
password'" > /root/.bash_aliases
ENTRYPOINT bash

You can expose the 'openldap' container as 'internalopenldap' within the test image with --link:

 docker run -it --rm --name ldp --link openldap:internalopenldap ldaptest

Then, if you type 'lds', that alias will work:

ldapsearch -H ldap://internalopenldap ...

That would return people. Meaning internalopenldap is correctly reached from the ldaptest image.


Of course, docker 1.7 will add libnetwork, which provides a native Go implementation for connecting containers. See the blog post.
It introduced a more complete architecture, with the Container Network Model (CNM)

https://blog.docker.com/media/2015/04/cnm-model.jpg

That will Update the Docker CLI with new “network” commands, and document how the “-net” flag is used to assign containers to networks.


docker 1.10 has a new section Network-scoped alias, now officially documented in network connect:

While links provide private name resolution that is localized within a container, the network-scoped alias provides a way for a container to be discovered by an alternate name by any other container within the scope of a particular network.
Unlike the link alias, which is defined by the consumer of a service, the network-scoped alias is defined by the container that is offering the service to the network.

Continuing with the above example, create another container in isolated_nw with a network alias.

$ docker run --net=isolated_nw -itd --name=container6 -alias app busybox
8ebe6767c1e0361f27433090060b33200aac054a68476c3be87ef4005eb1df17

--alias=[]         

Add network-scoped alias for the container

You can use --link option to link another container with a preferred alias

You can pause, restart, and stop containers that are connected to a network. Paused containers remain connected and can be revealed by a network inspect. When the container is stopped, it does not appear on the network until you restart it.

If specified, the container's IP address(es) is reapplied when a stopped container is restarted. If the IP address is no longer available, the container fails to start.

One way to guarantee that the IP address is available is to specify an --ip-range when creating the network, and choose the static IP address(es) from outside that range. This ensures that the IP address is not given to another container while this container is not on the network.

$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network

$ docker network connect --ip 172.20.128.2 multi-host-network container2
$ docker network connect --link container1:c1 multi-host-network container2

How to get the home directory in Python?

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')

jasmine: Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

It looks like the test is waiting for some callback that never comes. It's likely because the test is not executed with asynchronous behavior.

First, see if just using fakeAsync in your "it" scenario:

it('should do something', fakeAsync(() => {

You can also use flush() to wait for the microTask queue to finish or tick() to wait a specified amount of time.

Duplicate / Copy records in the same MySQL table

The way that I usually go about it is using a temporary table. It's probably not computationally efficient but it seems to work ok! Here i am duplicating record 99 in its entirety, creating record 100.

CREATE TEMPORARY TABLE tmp SELECT * FROM invoices WHERE id = 99;

UPDATE tmp SET id=100 WHERE id = 99;

INSERT INTO invoices SELECT * FROM tmp WHERE id = 100;

Hope that works ok for you!

copy all files and folders from one drive to another drive using DOS (command prompt)

Use robocopy. Robocopy is shipped by default on Windows Vista and newer, and is considered the replacement for xcopy. (xcopy has some significant limitations, including the fact that it can't handle paths longer than 256 characters, even if the filesystem can).

robocopy c:\ d:\ /e /zb /copyall /purge /dcopy:dat

Note that using /purge on the root directory of the volume will cause Robocopy to apply the requested operation on files inside the System Volume Information directory. Run robocopy /? for help. Also note that you probably want to open the command prompt as an administrator to be able to copy system files. To speed things up, use /b instead of /zb.

Lambda function in list comprehensions

The big difference is that the first example actually invokes the lambda f(x), while the second example doesn't.

Your first example is equivalent to [(lambda x: x*x)(x) for x in range(10)] while your second example is equivalent to [f for x in range(10)].

How does origin/HEAD get set?

It is your setting as the owner of your local repo. Change it like this:

git remote set-head origin some_branch

And origin/HEAD will point to your branch instead of master. This would then apply to your repo only and not for others. By default, it will point to master, unless something else has been configured on the remote repo.

Manual entry for remote set-head provides some good information on this.

Edit: to emphasize: without you telling it to, the only way it would "move" would be a case like renaming the master branch, which I don't think is considered "organic". So, I would say organically it does not move.

ThreadStart with parameters

I was having issue in the passed parameter. I passed integer from a for loop to the function and displayed it , but it always gave out different results. like (1,2,2,3) (1,2,3,3) (1,1,2,3) etc with ParametrizedThreadStart delegate.

this simple code worked as a charm

Thread thread = new Thread(Work);
thread.Start(Parameter);

private void Work(object param) 
{
 string Parameter = (string)param; 
}

Overwriting txt file in java

Add one more line after initializing file object

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

Easy way to make a confirmation dialog in Angular?

you can use window.confirm inside your function combined with if condition

 delete(whatever:any){
    if(window.confirm('Are sure you want to delete this item ?')){
    //put your delete method logic here
   }
}

when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.

Which terminal command to get just IP address and nothing else?

When looking up your external IP address on a NATed host, quite a few answers suggest using HTTP based methods like ifconfig.me eg:

$ curl ifconfig.me/ip

Over the years I have seen many of these sites come and go, I find this DNS based method more robust:

$ dig +short myip.opendns.com @resolver1.opendns.com

I have this handy alias in my ~/.bashrc:

alias wip='dig +short myip.opendns.com @resolver1.opendns.com'

jQuery textbox change event

The change event only fires after the input loses focus (and was changed).

Timeout jQuery effects

I just figured it out below:

$(".notice")
   .fadeIn( function() 
   {
      setTimeout( function()
      {
         $(".notice").fadeOut("fast");
      }, 2000);
   });

I will keep the post for other users!

Display two fields side by side in a Bootstrap Form

@KyleMit answer is one way to solve this, however we may chose to avoid the undivided input fields acheived by input-group class. A better way to do this is by using form-group and row classes on a parent div and use input elements with grid-system classes provided by bootstrap.

<div class="form-group row">
    <input class="form-control col-md-6" type="text">
    <input class="form-control col-md-6" type="text">
</div>

How to create a horizontal loading progress bar?

Just add a STYLE line and your progress becomes horizontal:

<ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progress"
        android:layout_centerHorizontal="true"      
        android:layout_centerVertical="true"      
        android:max="100" 
        android:progress="45"/>

How to create a jQuery function (a new jQuery method or plugin)?

$(function () {
    //declare function 
    $.fn.myfunction = function () {
        return true;
    };
});

$(document).ready(function () {
    //call function
    $("#my_div").myfunction();
});

Objective-C Static Class Level variables

As pgb said, there are no "class variables," only "instance variables." The objective-c way of doing class variables is a static global variable inside the .m file of the class. The "static" ensures that the variable can not be used outside of that file (i.e. it can't be extern).

How to create a timer using tkinter?

Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. If that function itself calls after you've set up an automatically recurring event.

Here is a working example:

# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import time

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

Bear in mind that after doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.

LINQ to read XML

A couple of plain old foreach loops provides a clean solution:

foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
    result.AppendLine(level1Element.Attribute("name").Value);

    foreach (XElement level2Element in level1Element.Elements("level2"))
    {
        result.AppendLine("  " + level2Element.Attribute("name").Value);
    }
}

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

TypeError: p.easing[this.easing] is not a function

For those who have a custom jQuery UI build (bower for ex.), add the effects core located in ..\jquery-ui\ui\effect.js.

How to discard uncommitted changes in SourceTree?

From sourcetree gui click on working directoy, right-click the file(s) that you want to discard, then click on Discard

Delete a database in phpMyAdmin

How to delete a database in phpMyAdmin?

From the Operations tab of the database, look for (and click) the text Drop the database (DROP).

Remove grid, background color, and top and right borders from ggplot2

Simplification from the above Andrew's answer leads to this key theme to generate the half border.

theme (panel.border = element_blank(),
       axis.line    = element_line(color='black'))

Appending a byte[] to the end of another byte[]

Using System.arraycopy(), something like the following should work:

// create a destination array that is the size of the two arrays
byte[] destination = new byte[ciphertext.length + mac.length];

// copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes)
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);

// copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes)
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length);

HTML Display Current date

var currentDate  = new Date(),
    currentDay   = currentDate.getDate() < 10 
                 ? '0' + currentDate.getDate() 
                 : currentDate.getDate(),
    currentMonth = currentDate.getMonth() < 9 
                 ? '0' + (currentDate.getMonth() + 1) 
                 : (currentDate.getMonth() + 1);

document.getElementById("date").innerHTML = currentDay + '/' + currentMonth + '/' +  currentDate.getFullYear();

You can read more about Date object

Numpy where function multiple conditions

Try:

np.intersect1d(np.where(dists >= r)[0],np.where(dists <= r + dr)[0])