Programs & Examples On #Corba

CORBA is an object-oriented middleware standard, defined by the OMG. It enables software components written in different languages to communicate with each other. Server components implement interfaces defined in IDL and register them with an Object Adapter, and clients can access those services using an ORB (Object Request Broker).

Address already in use: JVM_Bind

as the exception says there is already another server running on the same port. you can either kill that service or change glassfish to run on another poet

jQuery check if Cookie exists, if not create it

I think the bulletproof way is:

if (typeof $.cookie('token') === 'undefined'){
 //no cookie
} else {
 //have cookie
}

Checking the type of a null, empty or undefined var always returns 'undefined'

Edit: You can get there even easier:

if (!!$.cookie('token')) {
 // have cookie
} else {
 // no cookie
}

!! will turn the falsy values to false. Bear in mind that this will turn 0 to false!

How do I dump an object's fields to the console?

The to_yaml method seems to be useful sometimes:

$foo = {:name => "Clem", :age => 43}

puts $foo.to_yaml

returns

--- 
:age: 43
:name: Clem

(Does this depend on some YAML module being loaded? Or would that typically be available?)

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

Just type git init into your command line and press enter. Then run your command again, you probably were running git remote add origin [your-repository].

That should work, if it doesn't, just let me know.

How do you merge two Git repositories?

I merge projects slightly manually, which allows me to avoid needing to deal with merge conflicts.

first, copy in the files from the other project however you want them.

cp -R myotherproject newdirectory
git add newdirectory

next pull in the history

git fetch path_or_url_to_other_repo

tell git to merge in the history of last fetched thing

echo 'FETCH_HEAD' > .git/MERGE_HEAD

now commit however you normally would commit

git commit

Checking if element exists with Python Selenium

You can find elements by available methods and check response array length if the length of an array equal the 0 element not exist.

element_exist = False if len(driver.find_elements_by_css_selector('div.eiCW-')) > 0 else True

Java HashMap performance optimization / alternative

You could try to cache computed hash code to the key object.

Something like this:

public int hashCode() {
  if(this.hashCode == null) {
     this.hashCode = computeHashCode();
  }
  return this.hashCode;
}

private int computeHashCode() {
   int hash = 503;
   hash = hash * 5381 + (a[0] + a[1]);
   hash = hash * 5381 + (b[0] + b[1] + b[2]);
   return hash;
}

Of course you have to be careful not to change contents of the key after the hashCode has been calculated for the first time.

Edit: It seems that caching has code values is not worthwhile when you are adding each key only once to a map. In some other situation this could be useful.

What are the differences between ArrayList and Vector?

Vector is a broken class that is not threadsafe, despite it being "synchronized" and is only used by students and other inexperienced programmers.

ArrayList is the go-to List implementation used by professionals and experienced programmers.

Professionals wanting a threadsafe List implementation use a CopyOnWriteArrayList.

Why do table names in SQL Server start with "dbo"?

If you are using Sql Server Management Studio, you can create your own schema by browsing to Databases - Your Database - Security - Schemas.

To create one using a script is as easy as (for example):

CREATE SCHEMA [EnterSchemaNameHere] AUTHORIZATION [dbo]

You can use them to logically group your tables, for example by creating a schema for "Financial" information and another for "Personal" data. Your tables would then display as:

Financial.BankAccounts Financial.Transactions Personal.Address

Rather than using the default schema of dbo.

What is aria-label and how should I use it?

As a side answer it's worth to note that:

  • ARIA is commonly used to improve the accessibility for screen readers. (not only but mostly atm.)
  • Using ARIA does not necessarily make things better! Easily ARIA can lead to significantly worse accessibility if not implemented and tested properly. Don't use ARIA just to have some "cool things in the code" which you don't fully understand. Sadly too often ARIA implementations introduce more issues than solutions in terms of accessibility. This is rather common since sighted users and developers are less likely to put extra effort in extensive testing with screen readers while on the other hand ARIA specs and validators are currently far from perfect and even confusing in some cases. On top of that each browser and screen reader implement the ARIA support non-uniformly causing the major inconsistencies in the behavior. Often it's better idea to avoid ARIA completely when it's not clear exactly what it does, how it behaves and it won't be tested intensively with all screen readers and browsers (or at least the most common combinations). Disclaimer: My intention is not to disgrace ARIA but rather its bad ARIA implementations. In fact it's not so uncommon that HTML5 don't offer any other alternatives where implementing ARIA would bring significant benefits for the accessibility e.g. aria-hidden or aria-expanded. But only if implemented and tested properly!

How to add a Try/Catch to SQL Stored Procedure

Transact-SQL is a bit more tricky that C# or C++ try/catch blocks, because of the added complexity of transactions. A CATCH block has to check the xact_state() function and decide whether it can commit or has to rollback. I have covered the topic in my blog and I have an article that shows how to correctly handle transactions in with a try catch block, including possible nested transactions: Exception handling and nested transactions.

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(),
                 @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

Which Protocols are used for PING?

Ping can be used with a variety of protocols. The protocol value can be appletalk, clns, ip (the default), novell, apollo, vines, decnet, or xns. Some protocols require another Cisco router at the remote end to answer ping packets. ... (Cisco field manual: router configuration, By Dave Hucaby, Steve McQuerry. Page 64)

... For IP. ping uses ICMP type 8 requests and ICMP type 0 replies. The traceroute (by using UDP) command can be used to discover the routers along the path that packets are taking to a destination. ... (Page 63)

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.

SomeDate.Value.GetDateTimeFormats()[5]

GetDateTimeFormats

Rename multiple files in a folder, add a prefix (Windows)

The problem with the two Powershell answers here is that the prefix can end up being duplicated since the script will potentially run over the file both before and after it has been renamed, depending on the directory being resorted as the renaming process runs. To get around this, simply use the -Exclude option:

Get-ChildItem -Exclude "house chores-*" | rename-item -NewName { "house chores-" + $_.Name }

This will prevent the process from renaming any one file more than once.

Bash write to file without echo?

You can do this with "cat" and a here-document.

cat <<EOF > test.txt
some text
EOF

One reason for doing this would be to avoid any possibility of a password being visible in the output of ps. However, in bash and most modern shells, "echo" is a built-in command and it won't show up in ps output, so using something like this is safe (ignoring any issues with storing passwords in files, of course):

echo "$password" > test.txt

Provide an image for WhatsApp link sharing

Adding my 2 cents on this topic after loosing 4h.

I'm coding a vue app that's compiled with webpack. By default Webpack minifies the HTML, and does it like a butcher. It removes the double quotes from many attributes.

And Whatsapp hates that ! It just skips field not properly formated with quotes around attributes' values.

Turn off the minifaction of your index and things will be fine !

Here's how with Vue-CLI, add this on the vue.config.js file :

    module.exports = {
      chainWebpack: config => {
        config.plugin('html')
          .tap(args => {
            args[0].minify = false
            return args
          })
      }

from : https://github.com/vuejs/vue-cli/issues/4328#issuecomment-595682922

How to find a string inside a entire database?

Here is an easy and convenient cursor based solution

DECLARE
@search_string  VARCHAR(100),
@table_name     SYSNAME,
@table_id       INT,
@column_name    SYSNAME,
@sql_string     VARCHAR(2000)

SET @search_string = 'StringtoSearch'

DECLARE tables_cur CURSOR FOR SELECT name, object_id FROM sys.objects WHERE  type = 'U'

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id 
        AND system_type_id IN (167, 175, 231, 239)

    OPEN columns_cur

    FETCH NEXT FROM columns_cur INTO @column_name
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + '] 
            LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''

            EXECUTE(@sql_string)

        FETCH NEXT FROM columns_cur INTO @column_name
        END

    CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END

CLOSE tables_cur
DEALLOCATE tables_cur

What is the difference between Integer and int in Java?

An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.

If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.

This is straight out of the documentation for the Integer class:

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

Retrieve data from a ReadableStream object?

Little bit late to the party but had some problems with getting something useful out from a ReadableStream produced from a Odata $batch request using the Sharepoint Framework.

Had similar issues as OP, but the solution in my case was to use a different conversion method than .json(). In my case .text() worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.

Understanding implicit in Scala

In scala implicit works as:

Converter

Parameter value injector

Extension method

There are 3 types of use of Implicit

  1. Implicitly type conversion : It converts the error producing assignment into intended type

    val x :String = "1"
    
    val y:Int = x
    

String is not the sub type of Int , so error happens in line 2. To resolve the error the compiler will look for such a method in the scope which has implicit keyword and takes a String as argument and returns an Int .

so

implicit def z(a:String):Int = 2

val x :String = "1"

val y:Int = x // compiler will use z here like val y:Int=z(x)

println(y) // result 2  & no error!
  1. Implicitly receiver conversion: We generally by receiver call object's properties, eg. methods or variables . So to call any property by a receiver the property must be the member of that receiver's class/object.

     class Mahadi{
    
     val haveCar:String ="BMW"
    
     }
    

    class Johnny{

    val haveTv:String = "Sony"

    }

   val mahadi = new Mahadi



   mahadi.haveTv // Error happening

Here mahadi.haveTv will produce an error. Because scala compiler will first look for the haveTv property to mahadi receiver. It will not find. Second it will look for a method in scope having implicit keyword which take Mahadi object as argument and returns Johnny object. But it does not have here. So it will create error. But the following is okay.

class Mahadi{

val haveCar:String ="BMW"

}

class Johnny{

val haveTv:String = "Sony"

}

val mahadi = new Mahadi

implicit def z(a:Mahadi):Johnny = new Johnny

mahadi.haveTv // compiler will use z here like new Johnny().haveTv

println(mahadi.haveTv)// result Sony & no error
  1. Implicitly parameter injection: If we call a method and do not pass its parameter value, it will cause an error. The scala compiler works like this - first will try to pass value, but it will get no direct value for the parameter.

     def x(a:Int)= a
    
     x // ERROR happening
    

Second if the parameter has any implicit keyword it will look for any val in the scope which have the same type of value. If not get it will cause error.

def x(implicit a:Int)= a

x // error happening here

To slove this problem compiler will look for a implicit val having the type of Int because the parameter a has implicit keyword.

def x(implicit a:Int)=a

implicit val z:Int =10

x // compiler will use implicit like this x(z)
println(x) // will result 10 & no error.

Another example:

def l(implicit b:Int)

def x(implicit a:Int)= l(a)

we can also write it like-

def x(implicit a:Int)= l

Because l has a implicit parameter and in scope of method x's body, there is an implicit local variable(parameters are local variables) a which is the parameter of x, so in the body of x method the method-signature l's implicit argument value is filed by the x method's local implicit variable(parameter) a implicitly.

So

 def x(implicit a:Int)= l

will be in compiler like this

def x(implicit a:Int)= l(a)

Another example:

def c(implicit k:Int):String = k.toString

def x(a:Int => String):String =a

x{
x => c
}

it will cause error, because c in x{x=>c} needs explicitly-value-passing in argument or implicit val in scope.

So we can make the function literal's parameter explicitly implicit when we call the method x

x{
implicit x => c // the compiler will set the parameter of c like this c(x)
}

This has been used in action method of Play-Framework

in view folder of app the template is declared like
@()(implicit requestHreader:RequestHeader)

in controller action is like

def index = Action{
implicit request =>

Ok(views.html.formpage())  

}

if you do not mention request parameter as implicit explicitly then you must have been written-

def index = Action{
request =>

Ok(views.html.formpage()(request))  

}
  1. Extension Method

Think, we want to add new method with Integer object. The name of the method will be meterToCm,

> 1 .meterToCm 
res0 100 

to do this we need to create an implicit class within a object/class/trait . This class can not be a case class.

object Extensions{
    
    implicit class MeterToCm(meter:Int){
        
        def  meterToCm={
             meter*100
        }

    }

}

Note the implicit class will only take one constructor parameter.

Now import the implicit class in the scope you are wanting to use

import  Extensions._

2.meterToCm // result 200

"The public type <<classname>> must be defined in its own file" error in Eclipse

You can have only one public class in a file else you will get the error what you are getting now and name of file must be the name of public class

Arrays.fill with multidimensional array in Java

Don't we all sometimes wish there was a
<T>void java.util.Arrays.deepFill(T[]…multiDimensional). Problems start with
Object threeByThree[][] = new Object[3][3];
threeByThree[1] = null; and
threeByThree[2][1] = new int[]{42}; being perfectly legal.
(If only Object twoDim[]final[] was legal and well defined…)
(Using one of the public methods from below keeps loops from the calling source code.
If you insist on using no loops at all, substitute the loops and the call to Arrays.fill()(!) using recursion.)

/** Fills matrix {@code m} with {@code value}.
 * @return {@code m}'s dimensionality.
 * @throws java.lang.ArrayStoreException if the component type
 *  of a subarray of non-zero length at the bottom level
 *  doesn't agree with {@code value}'s type. */
public static <T>int deepFill(Object[] m, T value) {
    Class<?> components; 
    if (null == m ||
        null == (components = m.getClass().getComponentType()))
        return 0;
    int dim = 0;
    do
        dim++;
    while (null != (components = components.getComponentType()));
    filler((Object[][])m, value, dim);
    return dim;
}
/** Fills matrix {@code m} with {@code value}.
 * @throws java.lang.ArrayStoreException if the component type
 *  of a subarray of non-zero length at level {@code dimensions}
 *  doesn't agree with {@code value}'s type. */
public static <T>void fill(Object[] m, T value, int dimensions) {
    if (null != m)
        filler(m, value, dimensions);
}

static <T>void filler(Object[] m, T value, int toGo) {
    if (--toGo <= 0)
        java.util.Arrays.fill(m, value);
    else
        for (Object[] subArray : (Object[][])m)
            if (null != subArray)
                filler(subArray, value, toGo);
}

Using JAXB to unmarshal/marshal a List<String>

@GET
@Path("/test2")
public Response test2(){
   List<String> list=new Vector<String>();
   list.add("a");
   list.add("b");

   final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { };
   return Response.ok().entity(entity).build();
}

How to start an Intent by passing some parameters to it?

I think you want something like this:

Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);

or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topic in the dev guide for more information.

What is the difference between \r and \n?

In C and C++, \n is a concept, \r is a character, and \r\n is (almost always) a portability bug.

Think of an old teletype. The print head is positioned on some line and in some column. When you send a printable character to the teletype, it prints the character at the current position and moves the head to the next column. (This is conceptually the same as a typewriter, except that typewriters typically moved the paper with respect to the print head.)

When you wanted to finish the current line and start on the next line, you had to do two separate steps:

  1. move the print head back to the beginning of the line, then
  2. move it down to the next line.

ASCII encodes these actions as two distinct control characters:

  • \x0D (CR) moves the print head back to the beginning of the line. (Unicode encodes this as U+000D CARRIAGE RETURN.)
  • \x0A (LF) moves the print head down to the next line. (Unicode encodes this as U+000A LINE FEED.)

In the days of teletypes and early technology printers, people actually took advantage of the fact that these were two separate operations. By sending a CR without following it by a LF, you could print over the line you already printed. This allowed effects like accents, bold type, and underlining. Some systems overprinted several times to prevent passwords from being visible in hardcopy. On early serial CRT terminals, CR was one of the ways to control the cursor position in order to update text already on the screen.

But most of the time, you actually just wanted to go to the next line. Rather than requiring the pair of control characters, some systems allowed just one or the other. For example:

  • Unix variants (including modern versions of Mac) use just a LF character to indicate a newline.
  • Old (pre-OSX) Macintosh files used just a CR character to indicate a newline.
  • VMS, CP/M, DOS, Windows, and many network protocols still expect both: CR LF.
  • Old IBM systems that used EBCDIC standardized on NL--a character that doesn't even exist in the ASCII character set. In Unicode, NL is U+0085 NEXT LINE, but the actual EBCDIC value is 0x15.

Why did different systems choose different methods? Simply because there was no universal standard. Where your keyboard probably says "Enter", older keyboards used to say "Return", which was short for Carriage Return. In fact, on a serial terminal, pressing Return actually sends the CR character. If you were writing a text editor, it would be tempting to just use that character as it came in from the terminal. Perhaps that's why the older Macs used just CR.

Now that we have standards, there are more ways to represent line breaks. Although extremely rare in the wild, Unicode has new characters like:

  • U+2028 LINE SEPARATOR
  • U+2029 PARAGRAPH SEPARATOR

Even before Unicode came along, programmers wanted simple ways to represent some of the most useful control codes without worrying about the underlying character set. C has several escape sequences for representing control codes:

  • \a (for alert) which rings the teletype bell or makes the terminal beep
  • \f (for form feed) which moves to the beginning of the next page
  • \t (for tab) which moves the print head to the next horizontal tab position

(This list is intentionally incomplete.)

This mapping happens at compile-time--the compiler sees \a and puts whatever magic value is used to ring the bell.

Notice that most of these mnemonics have direct correlations to ASCII control codes. For example, \a would map to 0x07 BEL. A compiler could be written for a system that used something other than ASCII for the host character set (e.g., EBCDIC). Most of the control codes that had specific mnemonics could be mapped to control codes in other character sets.

Huzzah! Portability!

Well, almost. In C, I could write printf("\aHello, World!"); which rings the bell (or beeps) and outputs a message. But if I wanted to then print something on the next line, I'd still need to know what the host platform requires to move to the next line of output. CR LF? CR? LF? NL? Something else? So much for portability.

C has two modes for I/O: binary and text. In binary mode, whatever data is sent gets transmitted as-is. But in text mode, there's a run-time translation that converts a special character to whatever the host platform needs for a new line (and vice versa).

Great, so what's the special character?

Well, that's implementation dependent, too, but there's an implementation-independent way to specify it: \n. It's typically called the "newline character".

This is a subtle but important point: \n is mapped at compile time to an implementation-defined character value which (in text mode) is then mapped again at run time to the actual character (or sequence of characters) required by the underlying platform to move to the next line.

\n is different than all the other backslash literals because there are two mappings involved. This two-step mapping makes \n significantly different than even \r, which is simply a compile-time mapping to CR (or the most similar control code in whatever the underlying character set is).

This trips up many C and C++ programmers. If you were to poll 100 of them, at least 99 will tell you that \n means line feed. This is not entirely true. Most (perhaps all) C and C++ implementations use LF as the magic intermediate value for \n, but that's an implementation detail. It's feasible for a compiler to use a different value. In fact, if the host character set is not a superset of ASCII (e.g., if it's EBCDIC), then \n will almost certainly not be LF.

So, in C and C++:

  • \r is literally a carriage return.
  • \n is a magic value that gets translated (in text mode) at run-time to/from the host platform's newline semantics.
  • \r\n is almost always a portability bug. In text mode, this gets translated to CR followed by the platform's newline sequence--probably not what's intended. In binary mode, this gets translated to CR followed by some magic value that might not be LF--possibly not what's intended.
  • \x0A is the most portable way to indicate an ASCII LF, but you only want to do that in binary mode. Most text-mode implementations will treat that like \n.

can't load package: package .: no buildable Go source files

To resolve this for my situation:

I had to specify a more specific sub-package to install.

Wrong:

go get github.com/garyburd/redigo

Correct:

go get github.com/garyburd/redigo/redis

What is the difference between Left, Right, Outer and Inner Joins?

Inner join: Only show rows, when has it data from both of the tables.

Outer join: (left/right): Show the all result from the left / right table with the paired row(s), if it exists or not.

In nodeJs is there a way to loop through an array without using array size?

    var count=0;
    let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
    var data = JSON.parse(myArray);
    for (let key in data) {
      let value =  data[key]; // get the value by key
      console.log("key: , value:", key, value);
      count = count + 1;
    }
   console.log("size:",count);

Python: finding an element in a list

how's this one?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

Usage:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:

/usr/bin/mysql_upgrade -u root -p

Login as root:

mysql -u root -p

Run this commands:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
mysql> FLUSH PRIVILEGES;

Align Div at bottom on main Div

I guess you'll need absolute position

.vertical_banner {position:relative;}
#bottom_link{position:absolute; bottom:0;}

How generate unique Integers based on GUIDs

Here is the simplest way:

Guid guid = Guid.NewGuid();
Random random = new Random();
int i = random.Next();

You'll notice that guid is not actually used here, mainly because there would be no point in using it. Microsoft's GUID algorithm does not use the computer's MAC address any more - GUID's are actually generated using a pseudo-random generator (based on time values), so if you want a random integer it makes more sense to use the Random class for this.

Update: actually, using a GUID to generate an int would probably be worse than just using Random ("worse" in the sense that this would be more likely to generate collisions). This is because not all 128 bits in a GUID are random. Ideally, you would want to exclude the non-varying bits from a hashing function, although it would be a lot easier to just generate a random number, as I think I mentioned before. :)

How to split a string after specific character in SQL Server and update this value to specific column

Use CHARINDEX. Perhaps make user function. If you use this split often.
I would create this function:

CREATE FUNCTION [dbo].[Split]
(
    @String VARCHAR(max),
    @Delimiter varCHAR(1)
)
RETURNS TABLE 
AS
RETURN 
(
    WITH Split(stpos,endpos) 
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'INT_COLUMN' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'STRING_COLUMN' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)
GO

Avoid web.config inheritance in child web application using inheritInChildApplications

As the commenters for the previous answer mentioned, you cannot simply add the line...

<location path="." inheritInChildApplications="false">

...just below <configuration>. Instead, you need to wrap the individual web.config sections for which you want to disable inheritance. For example:

<!-- disable inheritance for the connectionStrings section -->
<location path="." inheritInChildApplications="false">
   <connectionStrings>
   </connectionStrings>
</location>

<!-- leave inheritance enabled for appSettings -->
<appSettings>
</appSettings>

<!-- disable inheritance for the system.web section -->
<location path="." inheritInChildApplications="false">
   <system.web>
        <webParts>
        </webParts>
        <membership>
        </membership>

        <compilation>
        </compilation>
      </system.web>
 </location>

While <clear /> may work for some configuration sections, there are some that instead require a <remove name="..."> directive, and still others don't seem to support either. In these situations, it's probably appropriate to set inheritInChildApplications="false".

Validate that text field is numeric usiung jQuery

I know there isn't any need to add a plugin for this.

But this can be useful if you are doing so many things with numbers. So checkout this plugin at least for a knowledge point of view.

The rest of karim79's answer is super cool.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.numeric.js"></script>
    </head>

    <body>
        <form>
            Numbers only:
            <input class="numeric" type="text" />
            Integers only:
            <input class="integer" type="text" />
            No negative values:
            <input class="positive" type="text" />
            No negative values (integer only):
            <input class="positive-integer" type="text" />
            <a href="#" id="remove">Remove numeric</a>
        </form>

        <script type="text/javascript">
            $(".numeric").numeric();

            $(".integer").numeric(false, function() {
                alert("Integers only");
                this.value = "";
                this.focus();
            });

            $(".positive").numeric({ negative: false },
                function() {
                    alert("No negative values");
                    this.value = "";
                    this.focus();
                });

            $(".positive-integer").numeric({ decimal: false, negative: false },
                function() {
                    alert("Positive integers only");
                    this.value = "";
                    this.focus();
                });

            $("#remove").click(
                function(e)
                {
                    e.preventDefault();
                    $(".numeric,.integer,.positive").removeNumeric();
                }
            );
        </script>

    </body>
</html>

Return JSON with error status code MVC

I found the solution here

I had to create a action filter to override the default behaviour of MVC

Here is my exception class

class ValidationException : ApplicationException
{
    public JsonResult exceptionDetails;
    public ValidationException(JsonResult exceptionDetails)
    {
        this.exceptionDetails = exceptionDetails;
    }
    public ValidationException(string message) : base(message) { }
    public ValidationException(string message, Exception inner) : base(message, inner) { }
    protected ValidationException(
    System.Runtime.Serialization.SerializationInfo info,
    System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
}

Note that I have constructor which initializes my JSON. Here is the action filter

public class HandleUIExceptionAttribute : FilterAttribute, IExceptionFilter
{
    public virtual void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }
        if (filterContext.Exception != null)
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
            filterContext.Result = ((ValidationException)filterContext.Exception).myJsonError;
        }
    }

Now that I have the action filter, I will decorate my controller with the filter attribute

[HandleUIException]
public JsonResult UpdateName(string objectToUpdate)
{
   var response = myClient.ValidateObject(objectToUpdate);
   if (response.errors.Length > 0)
     throw new ValidationException(Json(response));
}

When the error is thrown the action filter which implements IExceptionFilter get called and I get back the Json on the client on error callback.

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I had this issue my requirement i wanted to allow user to write to specific path

{
            "Sid": "raspiiotallowspecificBucket",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::<bucketname>/scripts",
                "arn:aws:s3:::<bucketname>/scripts/*"
            ]
        },

and problem was solved with this change

{
            "Sid": "raspiiotallowspecificBucket",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::<bucketname>",
                "arn:aws:s3:::<bucketname>/*"
            ]
        },

How To Change DataType of a DataColumn in a DataTable?

DataTable DT = ...
// Rename column to OLD:
DT.Columns["ID"].ColumnName = "ID_OLD";
// Add column with new type:
DT.Columns.Add( "ID", typeof(int) );
// copy data from old column to new column with new type:
foreach( DataRow DR in DT.Rows )
{ DR["ID"] = Convert.ToInt32( DR["ID_OLD"] ); }
// remove "OLD" column
DT.Columns.Remove( "ID_OLD" );

MySQL error 1241: Operand should contain 1 column(s)

Another way to make the parser raise the same exception is the following incorrect clause.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
                     system_user_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The nested SELECT statement in the IN clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.

For sake of completeness, the correct syntax is as follows.

SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
                 FROM role_members m
                 WHERE r.id = m.role_id
                 AND m.system_user_id = intIdSystemUser
             )

The stored procedure of which this query is a portion not only parsed, but returned the expected result.

Error inflating when extending a class

in my case I added such cyclic resource:

<drawable name="above_shadow">@drawable/above_shadow</drawable>

then changed to

<drawable name="some_name">@drawable/other_name</drawable>

and it worked

How to implement Rate It feature in Android App

My one using DialogFragment:

public class RateItDialogFragment extends DialogFragment {
    private static final int LAUNCHES_UNTIL_PROMPT = 10;
    private static final int DAYS_UNTIL_PROMPT = 3;
    private static final int MILLIS_UNTIL_PROMPT = DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000;
    private static final String PREF_NAME = "APP_RATER";
    private static final String LAST_PROMPT = "LAST_PROMPT";
    private static final String LAUNCHES = "LAUNCHES";
    private static final String DISABLED = "DISABLED";

    public static void show(Context context, FragmentManager fragmentManager) {
        boolean shouldShow = false;
        SharedPreferences sharedPreferences = getSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        long currentTime = System.currentTimeMillis();
        long lastPromptTime = sharedPreferences.getLong(LAST_PROMPT, 0);
        if (lastPromptTime == 0) {
            lastPromptTime = currentTime;
            editor.putLong(LAST_PROMPT, lastPromptTime);
        }

        if (!sharedPreferences.getBoolean(DISABLED, false)) {
            int launches = sharedPreferences.getInt(LAUNCHES, 0) + 1;
            if (launches > LAUNCHES_UNTIL_PROMPT) {
                if (currentTime > lastPromptTime + MILLIS_UNTIL_PROMPT) {
                    shouldShow = true;
                }
            }
            editor.putInt(LAUNCHES, launches);
        }

        if (shouldShow) {
            editor.putInt(LAUNCHES, 0).putLong(LAST_PROMPT, System.currentTimeMillis()).commit();
            new RateItDialogFragment().show(fragmentManager, null);
        } else {
            editor.commit();
        }
    }

    private static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, 0);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                .setTitle(R.string.rate_title)
                .setMessage(R.string.rate_message)
                .setPositiveButton(R.string.rate_positive, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getActivity().getPackageName())));
                        getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
                        dismiss();
                    }
                })
                .setNeutralButton(R.string.rate_remind_later, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss();
                    }
                })
                .setNegativeButton(R.string.rate_never, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
                        dismiss();
                    }
                }).create();
    }
}

Then use it in onCreate() of your main FragmentActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    RateItDialogFragment.show(this, getFragmentManager());

}

Pandas convert dataframe to array of tuples

A generic way:

[tuple(x) for x in data_set.to_records(index=False)]

How can I verify if an AD account is locked?

This ScriptingGuy guest post links to a script by a Microsoft Powershell Expert can help you find this information, but to fully audit why it was locked and which machine triggered the lock you probably need to turn on additional levels of auditing via GPO.

https://gallery.technet.microsoft.com/scriptcenter/Get-LockedOutLocation-b2fd0cab#content

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

Datepicker: How to popup datepicker when click on edittext

Date Picker Dialog

                Calendar c=Calendar.getInstance();
                Integer month=c.get(Calendar.MONTH);
                Integer day=c.get(Calendar.DAY_OF_MONTH);
                Integer year=c.get(Calendar.YEAR);

                DatePickerDialog datePickerDialog =new DatePickerDialog(Expenture_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        et_from.setText(dayOfMonth+"/"+month+"/"+year);
                    }
                },year,month,day);
                datePickerDialog.show();

VBA setting the formula for a cell

If you want to make address directly, the worksheet must exist.

Turning off automatic recalculation want help you :)

But... you can get value indirectly...

.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"

At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.

But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.

How to get the full url in Express?

My code looks like this,

params['host_url'] = req.protocol + '://' + req.headers.host + req.url;

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How to split elements of a list?

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Count number of matches of a regex in Javascript

As mentioned in my earlier answer, you can use RegExp.exec() to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using String.match().

var re = /\s/g,
count = 0;

while (re.exec(text) !== null) {
    ++count;
}

return count;

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

Apache error: _default_ virtualhost overlap on port 443

It is highly unlikely that adding NameVirtualHost *:443 is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).

If you're running a relatively stock Apache configuration, you probably have this somewhere:

<VirtualHost _default_:443>

Your best bet is to either:

  • Place your additional SSL configuration into this existing VirtualHost container, or
  • Comment out this entire VirtualHost block and create a new one. Don't forget to include all the relevant SSL options.

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

Make browser window blink in task Bar

Supposedly you can do this on windows with the growl for windows javascript API:

http://ajaxian.com/archives/growls-for-windows-and-a-web-notification-api

Your users will have to install growl though.

Eventually this is going to be part of google gears, in the form of the NotificationAPI:

http://code.google.com/p/gears/wiki/NotificationAPI

So I would recommend using the growl approach for now, falling back to window title updates if possible, and already engineering in attempts to use the Gears Notification API, for when it eventually becomes available.

printf format specifiers for uint32_t and size_t

All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long is at least 32 bits, so %lu together with (unsigned long)k is always correct:

uint32_t k;
printf("%lu\n", (unsigned long)k);

size_t is trickier, which is why %zu was added in C99. If you can't use that, then treat it just like k (long is the biggest type in C89, size_t is very unlikely to be larger).

size_t sz;
printf("%zu\n", sz);  /* C99 version */
printf("%lu\n", (unsigned long)sz);  /* common C89 version */

If you don't get the format specifiers correct for the type you are passing, then printf will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

DATE(readingstamp) BETWEEN '2016-07-21' AND '2016-07-31' AND TIME(readingstamp) BETWEEN '08:00:00' AND '17:59:59'

simply separate the casting of date and time

Is there a way to automatically generate getters and setters in Eclipse?

All the other answers are just focus on the IDE level, these are not the most effective and elegant way to generate getters and setters. If you have tens of attributes, the relevant getters and setters methods will make your class code very verbose.

The best way I ever used to generate getters and setters automatically is using project lombok annotations in your java project, lombok.jar will generate getter and setter method when you compile java code.

You just focus on class attributes/variables naming and definition, lombok will do the rest. This is easy to maintain your code.

For example, if you want to add getter and setter method for age variable, you just add two lombok annotations:

@Getter @Setter 
public int age = 10;

This is equal to code like that:

private int age = 10;
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

You can find more details about lombok here: Project Lombok

Correct way to write line to file?

You can also try filewriter

pip install filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]

Writes into my_file.txt

Takes an iterable or an object with __str__ support.

Unsupported major.minor version 52.0 in my app

The Simplest solution is you have to update your JDK to latest, version . Because Cordova supports only latest JDK .

1. First of all you have to update your Android SDK. Then,

2. If you are not able to update through your terminal , Got to your Software center of Linux destro and search the Latest (which one you want to install) and install that one .

Then again run Cordova build .

It will solve the problem .

In ,my case it worked.

Plotting in a non-blocking way with Matplotlib

A lot of these answers are super inflated and from what I can find, the answer isn't all that difficult to understand.

You can use plt.ion() if you want, but I found using plt.draw() just as effective

For my specific project I'm plotting images, but you can use plot() or scatter() or whatever instead of figimage(), it doesn't matter.

plt.figimage(image_to_show)
plt.draw()
plt.pause(0.001)

Or

fig = plt.figure()
...
fig.figimage(image_to_show)
fig.canvas.draw()
plt.pause(0.001)

If you're using an actual figure.
I used @krs013, and @Default Picture's answers to figure this out
Hopefully this saves someone from having launch every single figure on a separate thread, or from having to read these novels just to figure this out

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

C# Regex for Guid

In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods to Parse GUID. Here is example for this.

    //Generate New GUID
    Guid objGuid = Guid.NewGuid();
    //Take invalid guid format
    string strGUID = "aaa-a-a-a-a";

    Guid newGuid;

    if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
    {
        Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
    }
    else
    {
        Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
    }


    Guid newTmpGuid;

    if (Guid.TryParse(strGUID, out newTmpGuid) == true)
    {
        Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
    }
    else
    {
        Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
    }

In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.

Dialog to pick image from gallery or from camera

You can implement this code to select image from gallery or camera :-

private ImageView imageview;
private Button btnSelectImage;
private Bitmap bitmap;
private File destination = null;
private InputStream inputStreamImg;
private String imgPath = null;
private final int PICK_IMAGE_CAMERA = 1, PICK_IMAGE_GALLERY = 2;

Now on button click event, you can able to call your method of select Image. This is inside activity's onCreate.

imageview = (ImageView) findViewById(R.id.imageview);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);

//OnbtnSelectImage click event...
btnSelectImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });

Outside of your activity's oncreate.

// Select image from camera and gallery
private void selectImage() {
    try {
        PackageManager pm = getPackageManager();
        int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
        if (hasPerm == PackageManager.PERMISSION_GRANTED) {
            final CharSequence[] options = {"Take Photo", "Choose From Gallery","Cancel"};
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
            builder.setTitle("Select Option");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take Photo")) {
                        dialog.dismiss();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, PICK_IMAGE_CAMERA);
                    } else if (options[item].equals("Choose From Gallery")) {
                        dialog.dismiss();
                        Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        } else
            Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    inputStreamImg = null;
    if (requestCode == PICK_IMAGE_CAMERA) {
        try {
            Uri selectedImage = data.getData();
            bitmap = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);

            Log.e("Activity", "Pick from Camera::>>> ");

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            destination = new File(Environment.getExternalStorageDirectory() + "/" +
                    getString(R.string.app_name), "IMG_" + timeStamp + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            imgPath = destination.getAbsolutePath();
            imageview.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (requestCode == PICK_IMAGE_GALLERY) {
        Uri selectedImage = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
            Log.e("Activity", "Pick from Gallery::>>> ");

            imgPath = getRealPathFromURI(selectedImage);
            destination = new File(imgPath.toString());
            imageview.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Audio.Media.DATA};
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Atlast, finally add the camera and write external storage permission to AndroidManifest.xml

It works for me greatly, hope it will also works for you.

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Easy — just use Font Awesome 5's default fa-[size]x classes. You can scale icons up to 10x of the parent element's font-size Read the docs about icon sizing.

Examples:

<span class="fas fa-info-circle fa-6x"></span>
<span class="fas fa-info-circle fa-7x"></span>
<span class="fas fa-info-circle fa-8x"></span>
<span class="fas fa-info-circle fa-9x"></span>
<span class="fas fa-info-circle fa-10x"></span>

Getting the ID of the element that fired an event

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/

Stopping a JavaScript function when a certain condition is met

The return statement exits a function from anywhere within the function:

function something(x)
{
    if (x >= 10)
        // this leaves the function if x is at least 10.
        return;

    // this message displays only if x is less than 10.
    alert ("x is less than 10!");
}

How to use doxygen to create UML class diagrams from C++ source

The 2 highest upvoted answers are correct. As of today, the only thing I needed to change (from default settings) was to enable generation using dot instead of the built-in generator.

Some important notes:

  • Doxygen will not generate an actual full diagram of all classes in the project. It will generate a separate image for each hierarchy. If you have multiple, unrelated class hierarchies you will get multiple images.
  • All these diagrams can be found in html/inherits.html or (from the website navigation) classes => class hierarchy => "Go to the textual class hierarchy".
  • This is a C++ question, so let's talk about templates. Especially if you inherit from T.
    • Each template instantiation will be correctly considered a different type by Doxygen. Types which inherit from different instantations will have different parent classes on the diagram.
    • If a class template foo inherits from T and the T template type parameter has a default, such default will be assumed. If there is a type bar which inherits from foo<U> where U is different than the default, bar will have a foo<U> parent. foo<> and bar<U> will not have a common parent.
    • If there are multiple class templates which inherit from at least one of their template parameters, Doxygen will assume a common parent for these class templates as long as the template type parameters have exactly the same names in the code. This incentivizes for consistency in naming.
    • CRTP and reverse CRTP just work.
    • Recursive template inheritance trees are not expanded. Any variant instantiation will be displayed to inherit from variant<Ts...>.
    • Class templates with no instantiations are being drawn. They will have a <...> string in their name representing type and non-type parameters which did not have defaults.
    • Class template full and partial specializations are also being drawn. Doxygen generates correct graphs if specializations inherit from different types.

How to check edittext's text is email address or not?

On Android 2.2+ use this:

boolean isEmailValid(CharSequence email) {
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

for example:

EditText emailid = (EditText) loginView.findViewById(R.id.login_email);
String getEmailId = emailid.getText().toString();

// Check if email id is valid or not
       if (!isEmailValid(getEmailId)){
        new CustomToast().Show_Toast(getActivity(), loginView,
                "Your Email Id is Invalid.");
 }

What is the easiest way to remove all packages installed by pip?

On Windows if your path is configured correctly, you can use:

pip freeze > unins && pip uninstall -y -r unins && del unins

It should be a similar case for Unix-like systems:

pip freeze > unins && pip uninstall -y -r unins && rm unins

Just a warning that this isn't completely solid as you may run into issues such as 'File not found' but it may work in some cases nonetheless

EDIT: For clarity: unins is an arbitrary file which has data written out to it when this command executes: pip freeze > unins

That file that it written in turn is then used to uninstall the aforementioned packages with implied consent/prior approval via pip uninstall -y -r unins

The file is finally deleted upon completion.

T-SQL substring - separating first and last name

This will take care of names like "Firstname Z. Lastname" and "First Z Last"

SELECT
CASE 
    WHEN CHARINDEX(' ',name) = 0 THEN name
    WHEN CHARINDEX(' ',name) = PATINDEX('% _[., ]%',name) THEN RTRIM(SUBSTRING(name, 1, CHARINDEX(' ',name) + 2)) 
    ELSE SUBSTRING(name,1, CHARINDEX(' ',name))
END [firstname]
,CASE 
    WHEN CHARINDEX(' ',name) = 0 THEN ''
    WHEN CHARINDEX(' ',name) = PATINDEX('% _[., ]%',name) THEN LTRIM(SUBSTRING(name, CHARINDEX(' ',name) + 3,1000)) 
    ELSE SUBSTRING(name,CHARINDEX(' ',name)+1,1000)
END [lastname]
FROM [myTable]

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

Split List into Sublists with LINQ

I find this little snippet does the job quite nicely.

public static IEnumerable<List<T>> Chunked<T>(this List<T> source, int chunkSize)
{
    var offset = 0;

    while (offset < source.Count)
    {
        yield return source.GetRange(offset, Math.Min(source.Count - offset, chunkSize));
        offset += chunkSize;
    }
}

How to insert pandas dataframe via mysqldb into database?

The to_sql method works for me.

However, keep in mind that the it looks like it's going to be deprecated in favor of SQLAlchemy:

FutureWarning: The 'mysql' flavor with DBAPI connection is deprecated and will be removed in future versions. MySQL will be further supported with SQLAlchemy connectables. chunksize=chunksize, dtype=dtype)

Trigger a Travis-CI rebuild without pushing a commit?

You can do this using the Travis CLI. As described in the documentation, first install the CLI tool, then:

travis login --org --auto
travis token

You can keep this token in an environment variable TRAVIS_TOKEN, as long as the file you keep it in is not version-controlled somewhere public.

I use this function to submit triggers:

function travis_trigger() {
     local org=$1 && shift
     local repo=$1 && shift
     local branch=${1:-master} && shift

     body="{
             \"request\": {
               \"branch\": \"${branch}\"
              }
           }"

     curl -s -X POST \
          -H "Content-Type: application/json" \
          -H "Accept: application/json" \
          -H "Travis-API-Version: 3" \
          -H "Authorization: token $TRAVIS_TOKEN" \
          -d "$body" \
          "https://api.travis-ci.org/repo/${org}%2F${repo}/requests"
 }

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

Posting form to different MVC post action depending on the clicked submit button

This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in both client and server for this.

At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.

<script type="text/javascript">
    $(function() {
        // this code detects a button click and sets an `option` attribute
        // in the form to be the `name` attribute of whichever button was clicked
        $('form input[type=submit]').click(function() {
            var $form = $('form');
            form.removeAttr('option');
            form.attr('option', $(this).attr('name'));
        });
        // this code updates the URL before the form is submitted
        $("form").submit(function(e) { 
            var option = $(this).attr("option");
            if (option) {
                e.preventDefault();
                var currentUrl = $(this).attr("action");
                $(this).attr('action', currentUrl + "/" + option).submit();     
            }
        });
    });
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />

Now at the server side we can add a new route to handle the excel request

routes.MapRoute(
    name: "ExcelExport",
    url: "SearchDisplay/Submit/excel",
    defaults: new
    {
        controller = "SearchDisplay",
        action = "SubmitExcel",
    });

You can setup 2 distinct actions

public ActionResult SubmitExcel(SearchCostPage model)
{
   ...
}

public ActionResult Submit(SearchCostPage model)
{
   ...
}

Or you can use the ActionName attribute as an alias

public ActionResult Submit(SearchCostPage model)
{
   ...
}

[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
   ...
}

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);

Breaking up long strings on multiple lines in Ruby without stripping newlines

I had this problem when I try to write a very long url, the following works.

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

how to update spyder on anaconda

One way to avoid errors during installing or updating packages is to run the Anaconda prompt as Administrator. Hope it helps!

Filter multiple values on a string column in dplyr

You need %in% instead of ==:

library(dplyr)
target <- c("Tom", "Lynn")
filter(dat, name %in% target)  # equivalently, dat %>% filter(name %in% target)

Produces

  days name
1   88 Lynn
2   11  Tom
3    1  Tom
4  222 Lynn
5    2 Lynn

To understand why, consider what happens here:

dat$name == target
# [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE

Basically, we're recycling the two length target vector four times to match the length of dat$name. In other words, we are doing:

 Lynn == Tom
  Tom == Lynn
Chris == Tom
 Lisa == Lynn
 ... continue repeating Tom and Lynn until end of data frame

In this case we don't get an error because I suspect your data frame actually has a different number of rows that don't allow recycling, but the sample you provide does (8 rows). If the sample had had an odd number of rows I would have gotten the same error as you. But even when recycling works, this is clearly not what you want. Basically, the statement dat$name == target is equivalent to saying:

return TRUE for every odd value that is equal to "Tom" or every even value that is equal to "Lynn".

It so happens that the last value in your sample data frame is even and equal to "Lynn", hence the one TRUE above.

To contrast, dat$name %in% target says:

for each value in dat$name, check that it exists in target.

Very different. Here is the result:

[1]  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE

Note your problem has nothing to do with dplyr, just the mis-use of ==.

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

All of the above seem to work when spliced in, but gobyexample's signals page has a really clean and complete example of signal capturing. Worth adding to this list.

Determine when a ViewPager changes pages

Use the ViewPager.onPageChangeListener:

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
    public void onPageScrollStateChanged(int state) {}
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    public void onPageSelected(int position) {
        // Check if this is the page you want.
    }
});

How to center content in a bootstrap column?

col-lg-4 col-md-6 col-sm-8 col-11 mx-auto

 1. col-lg-4 = 1200px (popular 1366, 1600, 1920+)
 2. col-md-6 = 970px (popular 1024, 1200)
 3. col-sm-8 = 768px (popular 800, 768)
 4. col-11 set default smaller devices for gutter (popular 600,480,414,375,360,312)
 5. mx-auto = always block center


How to execute shell command in Javascript

In IE, you can do this :

var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

What is hashCode used for? Is it unique?

After learning what it is all about, I thought to write a hopefully simpler explanation via analogy:

Summary: What is a hashcode?

  • It's a fingerprint. We can use this finger print to identify people of interest.

Read below for more details:

Think of a Hashcode as us trying to To Uniquely Identify Someone

I am a detective, on the look out for a criminal. Let us call him Mr Cruel. (He was a notorious murderer when I was a kid -- he broke into a house kidnapped and murdered a poor girl, dumped her body and he's still out on the loose - but that's a separate matter). Mr Cruel has certain peculiar characteristics that I can use to uniquely identify him amongst a sea of people. We have 25 million people in Australia. One of them is Mr Cruel. How can we find him?

Bad ways of Identifying Mr Cruel

Apparently Mr Cruel has blue eyes. That's not much help because almost half the population in Australia also has blue eyes.

Good ways of Identifying Mr Cruel

What else can i use? I know: I will use a fingerprint!

Advantages:

  • It is really really hard for two people to have the same finger print (not impossible, but extremely unlikely).
  • Mr Cruel's fingerprint will never change.
  • Every single part of Mr Cruel's entire being: his looks, hair colour, personality, eating habits etc must (ideally) be reflected in his fingerprint, such that if he has a brother (who is very similar but not the same) - then both should have different finger prints. I say "should" because we cannot guarantee 100% that two people in this world will have different fingerprints.
  • But we can always guarantee that Mr Cruel will always have the same finger print - and that his fingerprint will NEVER change.

The above characteristics generally make for good hash functions.

So what's the deal with 'Collisions'?

So imagine if I get a lead and I find someone matching Mr Cruel's fingerprints. Does this mean I have found Mr Cruel?

........perhaps! I must take a closer look. If i am using SHA256 (a hashing function) and I am looking in a small town with only 5 people - then there is a very good chance I found him! But if I am using MD5 (another famous hashing function) and checking for fingerprints in a town with +2^1000 people, then it is a fairly good possibility that two entirely different people might have the same fingerprint.

So what is the benefit of all this anyways?

The only real benefit of hashcodes is if you want to put something in a hash table - and with hash tables you'd want to find objects quickly - and that's where the hash code comes in. They allow you to find things in hash tables really quickly. It's a hack that massively improves performance, but at a small expense of accuracy.

So let's imagine we have a hash table filled with people - 25 million suspects in Australia. Mr Cruel is somewhere in there..... How can we find him really quickly? We need to sort through them all: to find a potential match, or to otherwise acquit potential suspects. You don't want to consider each person's unique characteristics because that would take too much time. What would you use instead? You'd use a hashcode! A hashcode can tell you if two people are different. Whether Joe Bloggs is NOT Mr Cruel. If the prints don't match then you know it's definitely NOT Mr Cruel. But, if the finger prints do match then depending on the hash function you used, chances are already fairly good you found your man. But it's not 100%. The only way you can be certain is to investigate further: (i) did he/she have an opportunity/motive, (ii) witnesses etc etc.

When you are using computers if two objects have the same hash code value, then you again need to investigate further whether they are truly equal. e.g. You'd have to check whether the objects have e.g. the same height, same weight etc, if the integers are the same, or if the customer_id is a match, and then come to the conclusion whether they are the same. this is typically done perhaps by implementing an IComparer or IEquality interfaces.

Key Summary

So basically a hashcode is a finger print.

Digital Fingerprint - Picture attribute to Pixabay - Freely available for use at: https://pixabay.com/en/finger-fingerprint-security-digital-2081169/

  1. Two different people/objects can theoretically still have the same fingerprint. Or in other words. If you have two fingerprints that are the same.........then they need not both come from the same person/object.
  2. Buuuuuut, the same person/object will always return the same fingerprint.
  3. Which means that if two objects return different hash codes then you know for 100% certainty that those objects are different.

It takes a good 3 minutes to get your head around the above. Perhaps read it a few times till it makes sense. I hope this helps someone because it took a lot of grief for me to learn it all!

sprintf like functionality in Python

To insert into a very long string it is nice to use names for the different arguments, instead of hoping they are in the right positions. This also makes it easier to replace multiple recurrences.

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'

Taken from Format examples, where all the other Format-related answers are also shown.

How to customize an end time for a YouTube video?

Today I found, that the old ways are not working very well.

So I used: "Customize YouTube Start and End Time - Acetrot.com" from http://www.youtubestartend.com/

They provide a link into https://xxxx.app.goo.gl/yyyyyyyyyy e.g. https://v637g.app.goo.gl/Cs2SV9NEeoweNGGy9 Link contain forward to format like this https://www.youtube.com/embed/xyzabc123?start=17&end=21&version=3&autoplay=1

Best way to get child nodes

Don't let white space fool you. Just test this in a console browser.

Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.

How to get around white space with querySelector() then childNodes[] js fiddle link: https://jsfiddle.net/aparadise/56njekdo/

var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';

<ul class="list">
    <li>8</li>
    <li>9</li>
    <li>100</li>
</ul>

<ul class="list">
    <li>ABC</li>
    <li>DEF</li>
    <li>XYZ</li>
</ul>

When to use IMG vs. CSS background-image?

IMG load first because the src is in the html file itself whereas in the case of background-image the source is mentioned in stylesheet so the image loads after the stylesheet loaded, delaying the loading of the webpage.

CSS: Set Div height to 100% - Pixels

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
  background-color:gray;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Codeigniter : calling a method of one controller from other

I posted a somewhat similar question a while back, but regarding a model on CI.

Returning two separate query results within a model function

Although your question is not exactly the same, I believe the solution follows the same principle: if you're proposing to do what you mention in your question, there may be something wrong in the way you're coding and some refactoring could be in order.

The take home message is that what you're asking is not the way to go when working with MVC.

The best practice is to either use a Model to place reusable functions and call them in a controller that outputs the data through a view -- or even better use helpers or libraries (for functions that may be needed repeatedly).

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

Select from multiple tables without a join?

You could try something like this:

SELECT ...
FROM (
    SELECT f1,f2,f3 FROM table1
    UNION
    SELECT f1,f2,f3 FROM table2
)
WHERE ...

jQuery preventDefault() not triggered

If e.preventDefault(); is not working you must use e.stopImmediatePropagation(); instead.

For further informations take a look at : What's the difference between event.stopPropagation and event.preventDefault?

$("div.subtab_left li.notebook a").click(function(e) {
    e.stopImmediatePropagation();
    return false;
});

How can I define fieldset border color?

I added it for all fieldsets with

fieldset {
        border: 1px solid lightgray;
    }

I didnt work if I set it separately using for example

border-color : red

. Then a black line was drawn next to the red line.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

SELECT * FROM multiple tables. MySQL

You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?

Bootstrap table without stripe / borders

similar to the rest, but more specific:

    table.borderless td,table.borderless th{
     border: none !important;
}

How do you define a class of constants in Java?

My preferred method is not to do that at all. The age of constants pretty much died when Java 5 introduced typesafe enums. And even before then Josh Bloch published a (slightly more wordy) version of that, which worked on Java 1.4 (and earlier).

Unless you need interoperability with some legacy code there's really no reason to use named String/integer constants anymore.

Python list iterator behavior and next(iterator)

Something is wrong with your Python/Computer.

a = iter(list(range(10)))
for i in a:
   print(i)
   next(a)

>>> 
0
2
4
6
8

Works like expected.

Tested in Python 2.7 and in Python 3+ . Works properly in both

Difference between View and ViewGroup in Android

A ViewGroup describes the layout of the Views in its group. The two basic examples of ViewGroups are LinearLayout and RelativeLayout. Breaking LinearLayout even further, you can have either Vertical LinearLayout or Horizontal LinearLayout. If you choose Vertical LinearLayout, your Views will stack vertically on your screen. The two most basic examples of Views are TextView and Button. Thus, if you have a ViewGroup of Vertical LinearLayout, your Views (e.g. TextViews and Buttons) would line up vertically down your screen.

When the other posters show nested ViewGroups, what they mean is, for example, one of the rows in my Vertical LinearLayout might actually, at the lower level, be several items arranged horizontally. In that case, I'd have a Horizontal LinearLayout as one of the children of my top level Vertical LinearLayout.

Example of Nested ViewGroups:
Parent ViewGroup = Vertical LinearLayout

Row1: TextView1
Row2: Button1
Row3: Image TextView2 Button2 <-- Horizontal Linear nested in Vertical Linear
Row4: TextView3
Row5: Button3

Getting DOM node from React child element

This may be possible by using the refs attribute.

In the example of wanting to to reach a <div> what you would want to do is use is <div ref="myExample">. Then you would be able to get that DOM node by using React.findDOMNode(this.refs.myExample).

From there getting the correct DOM node of each child may be as simple as mapping over this.refs.myExample.children(I haven't tested that yet) but you'll at least be able to grab any specific mounted child node by using the ref attribute.

Here's the official react documentation on refs for more info.

Project has no default.properties file! Edit the project properties to set one

In my case I went to My Project then to > Properties > Android > and checked Google API box. Clicking 'Okay' caused it to then work for me.

PHP: Split string

$string_val = 'a.b';

$parts = explode('.', $string_val);

print_r($parts);

Docs: http://us.php.net/manual/en/function.explode.php

How to get HttpRequestMessage data

  System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
  reader.BaseStream.Position = 0;
  string requestFromPost = reader.ReadToEnd();

Web API optional parameters

Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values

Alternative for <blink>

The blick tag is deprecated, and the effect is kind of old :) Current browsers don't support it anymore. Anyway, if you need the blinking effect, you should use javascript or CSS solutions.

CSS Solution

_x000D_
_x000D_
blink {_x000D_
    animation: blinker 0.6s linear infinite;_x000D_
    color: #1c87c9;_x000D_
}_x000D_
@keyframes blinker {  _x000D_
    50% { opacity: 0; }_x000D_
}_x000D_
.blink-one {_x000D_
    animation: blinker-one 1s linear infinite;_x000D_
}_x000D_
@keyframes blinker-one {  _x000D_
    0% { opacity: 0; }_x000D_
}_x000D_
.blink-two {_x000D_
    animation: blinker-two 1.4s linear infinite;_x000D_
}_x000D_
@keyframes blinker-two {  _x000D_
    100% { opacity: 0; }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Title of the document</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <h3>_x000D_
      <blink>Blinking text</blink>_x000D_
    </h3>_x000D_
    <span class="blink-one">CSS blinking effect for opacity starting with 0%</span>_x000D_
    <p class="blink-two">CSS blinking effect for opacity starting with 100%</p>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

sourse: HTML blink Tag

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

.htaccess rewrite to redirect root URL to subdirectory

Formerly I use the following code which is work correctly to redirect root URL of each of my domains/subdomains to their correspondence subdirectories which are named exactly as the sub/domain it self as below:

RewriteCond %{HTTP_HOST} ^sub1.domain1.com
RewriteCond %{REQUEST_URI} !subs/sub1.domain1.com/
RewriteRule ^(.*)$ subs/%{HTTP_HOST}/$1 [L,QSA]

RewriteCond %{HTTP_HOST} ^sub2.domain1.com
RewriteCond %{REQUEST_URI} !subs/sub1.domain2.com/
RewriteRule ^(.*)$ subs/%{HTTP_HOST}/$1 [L,QSA]

RewriteCond %{HTTP_HOST} ^sub1.domain2.com
RewriteCond %{REQUEST_URI} !subs/sub1.domain2.com/
RewriteRule ^(.*)$ subs/%{HTTP_HOST}/$1 [L,QSA]

RewriteCond %{HTTP_HOST} ^sub2.domain2.com
RewriteCond %{REQUEST_URI} !subs/sub2.domain2.com/
RewriteRule ^(.*)$ subs/%{HTTP_HOST}/$1 [L,QSA]

However when I want to add another subs or domains then it will need to be added in the above code. It should be much more convenient to simplify it to work like wildcard (*) as below:

RewriteCond %{HTTP_HOST} ^sub
RewriteCond %{REQUEST_URI} !/subs/
RewriteRule ^(.*)$ subs/%{HTTP_HOST}/$1 [L,QSA]

So whenever another subdomains/domains is added as long as the subdomain name has a prefix of sub (like: sub3.domain1.com, sub1.domain3.com etc.) the code will remain valid.

How to Install pip for python 3.7 on Ubuntu 18?

pip3 not pip. You can create an alias like you did with python3 if you like.

What properties does @Column columnDefinition make redundant?

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

  • length
  • precision
  • scale
  • nullable
  • unique

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

Rationale follows.


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

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

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

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


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

  1. In JPA Spec & javadoc:

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

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

    • The following examples are provided:

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

    Does columnDefinition override other properties provided in the same annotation?

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

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

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

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


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

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

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

How can I tell jaxb / Maven to generate multiple schema packages?

I had to specify different generateDirectory (without this, the plugin was considering that files were up to date and wasn't generating anything during the second execution). And I recommend to follow the target/generated-sources/<tool> convention for generated sources so that they will be imported in your favorite IDE automatically. I also recommend to declare several execution instead of declaring the plugin twice (and to move the configuration inside each execution element):

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.7.1</version>
  <executions>
    <execution>
      <id>schema1-generate</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <schemaDirectory>src/main/resources/dir1</schemaDirectory>
        <schemaIncludes>
          <include>shiporder.xsd</include>
        </schemaIncludes>
        <generatePackage>com.stackoverflow.package1</generatePackage>
        <generateDirectory>${project.build.directory}/generated-sources/xjc1</generateDirectory>
      </configuration>
    </execution>
    <execution>
      <id>schema2-generate</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <schemaDirectory>src/main/resources/dir2</schemaDirectory>
        <schemaIncludes>
          <include>books.xsd</include>
        </schemaIncludes>
        <generatePackage>com.stackoverflow.package2</generatePackage>
        <generateDirectory>${project.build.directory}/generated-sources/xjc2</generateDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>

With this setup, I get the following result after a mvn clean compile

$ tree target/
target/
+-- classes
¦   +-- com
¦   ¦   +-- stackoverflow
¦   ¦       +-- App.class
¦   ¦       +-- package1
¦   ¦       ¦   +-- ObjectFactory.class
¦   ¦       ¦   +-- Shiporder.class
¦   ¦       ¦   +-- Shiporder$Item.class
¦   ¦       ¦   +-- Shiporder$Shipto.class
¦   ¦       +-- package2
¦   ¦           +-- BookForm.class
¦   ¦           +-- BooksForm.class
¦   ¦           +-- ObjectFactory.class
¦   ¦           +-- package-info.class
¦   +-- dir1
¦   ¦   +-- shiporder.xsd
¦   +-- dir2
¦       +-- books.xsd
+-- generated-sources
    +-- xjc
    ¦   +-- META-INF
    ¦       +-- sun-jaxb.episode
    +-- xjc1
    ¦   +-- com
    ¦       +-- stackoverflow
    ¦           +-- package1
    ¦               +-- ObjectFactory.java
    ¦               +-- Shiporder.java
    +-- xjc2
        +-- com
            +-- stackoverflow
                +-- package2
                    +-- BookForm.java
                    +-- BooksForm.java
                    +-- ObjectFactory.java
                    +-- package-info.java

Which seems to be the expected result.

onclick or inline script isn't working in extension

I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.

In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.

  • I found out that by placing the script before the DIV with ID that was called, the script did not work.
  • If the script was in another DIV, also it does not work
  • The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told

        <body>
        <a id=id_page href ="#loving"   onclick="load_services()"> loving   </a>
    
            <script>
                    // This script MUST BE under the "ID" that is calling
                    // Do not transfer it to a differ DIV than the caller "ID"
                    document.getElementById("id_page").addEventListener("click", function(){
                    document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
                </script>
        </body>
    
      <div id="mainbody" class="main_body">
            "here is loaded the external html file when the loving link will 
             be  clicked. "
      </div>
    

C# Get/Set Syntax Usage

You are not able to access those properties as they are marked as protected meaning:

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

How do I send a file as an email attachment using Linux command line?

I use SendEmail, which was created for this scenario. It's packaged for Ubuntu so I assume it's available

sendemail -f [email protected] -t [email protected] -m "Here are your files!" -a file1.jpg file2.zip

http://caspian.dotconf.net/menu/Software/SendEmail/

Set UITableView content inset permanently

This is how it can be fixed easily through Storyboard (iOS 11 and Xcode 9.1):

Select Table View > Size Inspector > Content Insets: Never

Why Anaconda does not recognize conda command?

Faced the same problem running on Windows 10 and using the Windows cmd.

Solved it by running the following command in the Anaconda Prompt which comes with Anaconda3 (as administrator):

conda install -c menpo opencv3=3.1.0

Command found on the official website: https://anaconda.org/menpo/opencv3

How to Navigate from one View Controller to another using Swift

Swift 4

You can switch the screen by pushing navigation controller first of all you have to set the navigation controller with UIViewController

let vc = self.storyboard?.instantiateViewController(withIdentifier: "YourStoryboardID") as! swiftClassName

self.navigationController?.pushViewController(vc, animated: true)

Gradients on UIView and UILabels On iPhone

You can use Core Graphics to draw the gradient, as pointed to in Mike's response. As a more detailed example, you could create a UIView subclass to use as a background for your UILabel. In that UIView subclass, override the drawRect: method and insert code similar to the following:

- (void)drawRect:(CGRect)rect 
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35,  // Start color
         1.0, 1.0, 1.0, 0.06 }; // End color

    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    CGRect currentBounds = self.bounds;
    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);

    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace); 
}

This particular example creates a white, glossy-style gradient that is drawn from the top of the UIView to its vertical center. You can set the UIView's backgroundColor to whatever you like and this gloss will be drawn on top of that color. You can also draw a radial gradient using the CGContextDrawRadialGradient function.

You just need to size this UIView appropriately and add your UILabel as a subview of it to get the effect you desire.

EDIT (4/23/2009): Per St3fan's suggestion, I have replaced the view's frame with its bounds in the code. This corrects for the case when the view's origin is not (0,0).

Share Text on Facebook from Android App via ACTION_SEND

ShareDialog shareDialog = new ShareDialog(this);
if(ShareDialog.canShow(ShareLinkContent.class)) {

    ShareLinkContent linkContent = new ShareLinkContent.Builder().setContentTitle(strTitle).setContentDescription(strDescription)
                            .setContentUrl(Uri.parse(strNewsHtmlUrl))
                            .build();
    shareDialog.show(linkContent);

}

SVG fill color transparency / alpha?

As a not yet fully standardized solution (though in alignment with the color syntax in CSS3) you can use e.g fill="rgba(124,240,10,0.5)". Works fine in Firefox, Opera, Chrome.

Here's an example.

MySQL count occurrences greater than 2

The HAVING option can be used for this purpose and query should be

SELECT word, COUNT(*) FROM words 
GROUP BY word
HAVING COUNT(*) > 1;

Postman addon's like in firefox

The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).

Now I'm settled with Fiddler (Inspectors > WebView)

Multiple "style" attributes in a "span" tag: what's supposed to happen?

In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.

So your example:

<span style="color:blue" style="font-style:italic">Test</span>

is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.


Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.

(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:

Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

How to solve static declaration follows non-static declaration in GCC C code?

You have declared a function as nonstatic in some file and you have implemented as static in another file or somewhere in the same file can cause this problem also. For example, the following code will produce this error.

void inlet_update_my_ratio(object_t *myobject);
//some where the implementation is like this
static void inlet_update_my_ratio(object_t *myobject) {
//code
}

If you remove the static from the implementation, the error will go away as below.

 void inlet_update_my_ratio(object_t *myobject) {
    //code
    }

how to rename an index in a cluster?

As indicated in Elasticsearch reference for snapshot module,

The rename_pattern and rename_replacement options can be also used to rename index on restore using regular expression

how to get the last character of a string?

str.charAt(str.length - 1)

Some browsers allow (as a non-standard extension) you to shorten this to:

str[str.length - 1];

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/)

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

Error in Eclipse: "The project cannot be built until build path errors are resolved"

I also had this problem in my system, but after looking inside the project I saw the XML structure of the .classpath file in the project path was incorrect. After amending that file the problem was solved.

javascript setTimeout() not working

Please change your code as follows:

<script>
    var button = document.getElementById("reactionTester");
    var start = document.getElementById("start");
    function init() {
        var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
        setTimeout(startTimer,startInterval); 
    }
    function startTimer(){
        document.write("hey");
    }
</script>

See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.

How to add line break for UILabel?

Just using label.numberOfLines = 0;

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

I've seen a couple cases where this error occurs:

1. using the not equals operator != in a where clause with a list of multiple or values

such as:

where columnName !=('A'||'B')

This can be resolved by using

where columnName not in ('A','B')

2. missing a comparison operator in an if() function:

select if(col1,col1,col2);

in order to select the value in col1 if it exists and otherwise show the value in col2...this throws the error; it can be resolved by using:

select if(col1!='',col1,col2);

Styling Form with Label above Inputs

There is no need to add any extra div wrapper as others suggest.

The simplest way is to wrap your input element inside a related label tag and set input style to display:block.

Bonus point earned: now you don't need to set the labels for attribute. Because every label target the nested input.

<form name="message" method="post">
    <section>
        <label class="left">
            Name
            <input id="name" type="text" name="name">
        </label>
        <label class="right">
            Email
            <input id="email" type="text" name="email">
        </label>
    </section>
</form>

https://jsfiddle.net/Tomanek1/sguh5k17/15/

How to loop through an associative array and get the key?

foreach($array as $k => $v)

Where $k is the key and $v is the value

Or if you just need the keys use array_keys()

Where is Android Studio layout preview?

If you see a message at the bottom saying something like, "Android Framework detected. Click to configure", DO IT.

After doing this, my Text and Design bottom-tabs appeared.

Angular 2: How to style host element of the component?

Try the :host > /deep/ :

Add the following to the parent.component.less file

:host {
    /deep/ app-child-component {
       //your child style
    }
}

Replace the app-child-component by your child selector

how to loop through json array in jquery?

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});

Using fonts with Rails asset pipeline

I had a similar issue when I upgraded my Rails 3 app to Rails 4 recently. My fonts were not working properly as in the Rails 4+, we are only allowed to keep the fonts under app/assets/fonts directory. But my Rails 3 app had a different font organization. So I had to configure the app so that it still works with Rails 4+ having my fonts in a different place other than app/assets/fonts. I have tried several solutions but after I found non-stupid-digest-assets gem, it just made it so easy.

Add this gem by adding the following line to your Gemfile:

gem 'non-stupid-digest-assets'

Then run:

bundle install

And finally add the following line in your config/initializers/non_digest_assets.rb file:

NonStupidDigestAssets.whitelist = [ /\.(?:svg|eot|woff|ttf)$/ ]

That's it. This solved my problem nicely. Hope this helps someone who have encountered similar problem like me.

How to set image to fit width of the page using jsPDF?

The API changed since this commit, using version 1.4.1 it's now

var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();

Difference between /res and /assets directories

If you need to refer them somewhere in the Java Code, you'd rahter put your files into the "res" directory.

And all files in the res folder will be indexed in the R file, which makes it much faster (and much easier!) to load them.

Read only file system on Android

If there's a failure in copying the read-only file you can try locating the original file in the root directory and modify it with a root text editor (preferably) RB text editor, it comes with ROM Toolbox app.

Send file using POST from a Python script

The only thing that stops you from using urlopen directly on a file object is the fact that the builtin file object lacks a len definition. A simple way is to create a subclass, which provides urlopen with the correct file. I have also modified the Content-Type header in the file below.

import os
import urllib2
class EnhancedFile(file):
    def __init__(self, *args, **keyws):
        file.__init__(self, *args, **keyws)

    def __len__(self):
        return int(os.fstat(self.fileno())[6])

theFile = EnhancedFile('a.xml', 'r')
theUrl = "http://example.com/abcde"
theHeaders= {'Content-Type': 'text/xml'}

theRequest = urllib2.Request(theUrl, theFile, theHeaders)

response = urllib2.urlopen(theRequest)

theFile.close()


for line in response:
    print line

Split Spark Dataframe string column into multiple columns

pyspark.sql.functions.split() is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem() to retrieve each part of the array as a column itself:

split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))

The result will be:

col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
  18 |  856-yygrm |   856 | yygrm
 201 |  777-psgdg |   777 | psgdg

I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.

What's the simplest way of detecting keyboard input in a script from the terminal?

I wrote a more easy-to-use implementation for @enrico.bacis's answer. It supports both Linux(python2.7 and python3.5) and Windows(python2.7). It may support Mac OS, but I didn't test it. If you tried it on Mac, please tell me the result.

'''
Author: Yu Lou
Date: 2017-02-23

Based on the answer by @enrico.bacis in http://stackoverflow.com/a/13207724/4398908
and @Phylliida in http://stackoverflow.com/a/31736883/4398908
'''

# Import modules
try:
    try:
        import termios, fcntl, sys, os, curses # Import modules for Linux
    except ImportError:
        import msvcrt # Import module for Windows
except ImportError:
    raise Exception('This platform is not supported.')

class KeyGetterLinux:
    '''
    Implemented kbhit(), getch() and getchar() in Linux.

    Tested on Ubuntu 16.10(Linux 4.8.0), Python 2.7.12 and Python 3.5.2
    '''
    def __init__(self):
        self.buffer = '' # A buffer to store the character read by kbhit
        self.started = False # Whether initialization is complete

    def kbhit(self, echo = False):
        '''
        Return whether a key is hitten.
        '''
        if not self.buffer:
            if echo:
                self.buffer = self.getchar(block = False)
            else:
                self.buffer = self.getch(block = False)

        return bool(self.buffer)

    def getch(self, block = True):
        '''
        Return a single character without echo.
        If block is False and no input is currently available, return an empty string without waiting.
        '''
        try:
            curses.initscr()
            curses.noecho()
            return self.getchar(block)
        finally:
            curses.endwin()

    def getchar(self, block = True):
        '''
        Return a single character and echo.
        If block is False and no input is currently available, return an empty string without waiting.
        '''
        self._start()
        try:
            return self._getchar(block)
        finally:
            self._stop()

    def _getchar(self, block = True):
        '''
        Return a single character and echo.
        If block is False and no input is currently available, return a empty string without waiting.
        Should be called between self._start() and self._end()
        '''
        assert self.started, ('_getchar() is called before _start()')

        # Change the terminal setting
        if block:
            fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags & ~os.O_NONBLOCK)
        else:
            fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags | os.O_NONBLOCK)

        if self.buffer: # Use the character in buffer first
            result = self.buffer
            self.buffer = ''
        else:
            try:
                result = sys.stdin.read(1)
            except IOError: # In python 2.7, using read() when no input is available will result in IOError.
                return ''

        return result

    def _start(self):
        '''
        Initialize the terminal.
        '''
        assert not self.started, '_start() is called twice'

        self.fd = sys.stdin.fileno()

        self.old_attr = termios.tcgetattr(self.fd)

        new_attr = termios.tcgetattr(self.fd)
        new_attr[3] = new_attr[3] & ~termios.ICANON
        termios.tcsetattr(self.fd, termios.TCSANOW, new_attr)

        self.old_flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)

        self.started = True

    def _stop(self):
        '''
        Restore the terminal.
        '''
        assert self.started, '_start() is not called'

        termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_attr)
        fcntl.fcntl(self.fd, fcntl.F_SETFL, self.old_flags)

        self.started = False

    # Magic functions for context manager
    def __enter__(self):
        self._start()
        self.getchar = self._getchar # No need for self._start() now
        return self

    def __exit__(self, type, value, traceback):
        self._stop()
        return False

class KeyGetterWindows:
    '''
    kbhit() and getchar() in Windows.

    Tested on Windows 7 64 bit, Python 2.7.1
    '''
    def kbhit(self, echo):
        return msvcrt.kbhit()

    def getchar(self, block = True):
        if not block and not msvcrt.kbhit():
            return ''
        return msvcrt.getchar()

    def getch(self, block = True):
        if not block and not msvcrt.kbhit():
            return ''
        return msvcrt.getch()

    _getchar = getchar

    # Magic functions for context manager
    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        return False

try:
    import termios
    KeyGetter = KeyGetterLinux # Use KeyGetterLinux if termios exists
except ImportError:
    KeyGetter = KeyGetterWindows # Use KeyGetterWindows otherwise

This is an example(assume that you saved the codes above in 'key_getter.py'):

from key_getter import KeyGetter
import time

def test1(): # Test with block=False
    print('test1')

    k = KeyGetter()
    try:
        while True:
            if k.kbhit():
                print('Got', repr(k.getch(False)))
                print('Got', repr(k.getch(False)))
            else:
                print('Nothing')

            time.sleep(0.5)
    except KeyboardInterrupt:
        pass
    print(input('Enter something:'))

def test2(): # Test context manager with block=True
    print('test2')

    with KeyGetter() as k:
        try:
            while True:
                if k.kbhit():
                    print('Got', repr(k.getchar(True)))
                    print('Got', repr(k.getchar(True)))
                else:
                    print('Nothing')

                time.sleep(0.5)
        except KeyboardInterrupt:
            pass
    print(input('Enter something:'))

test1()
test2()

Is it possible to use jQuery .on and hover?

If you need it to have as a condition in an other event, I solved it this way:

$('.classname').hover(
     function(){$(this).data('hover',true);},
     function(){$(this).data('hover',false);}
);

Then in another event, you can easily use it:

 if ($(this).data('hover')){
      //...
 }

(I see some using is(':hover') to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

CSS pseudo elements in React

You can use styled components.

Install it with npm i styled-components

import React from 'react';
import styled from 'styled-components';

const YourEffect = styled.div`
  height: 50px;
  position: relative;
  &:after {
    // whatever you want with normal CSS syntax. Here, a custom orange line as example
    content: '';
    width: 60px;
    height: 4px;
    background: orange
    position: absolute;
    bottom: 0;
    left: 0;
  },

const YourComponent = props => {
  return (
    <YourEffect>...</YourEffect>
  )
}

export default YourComponent

Eclipse interface icons very small on high resolution screen in Windows 8.1

Here is my solution Inspired by @Sigh's solution (this one doesn't use maven):

https://github.com/gitAmrit/EclipseIconEnlarger/tree/master#eclipseiconenlarger

This works by searching for all images smaller or equal to 16x16px and scaling them up by whatever factor the user wants.

running the utility: java images.EclipseIconEnlarger eclipseBasePath magnificaitonfactor

eg: java images.EclipseIconEnlarger C:\Users\Amrit\Codes\eclipse 2

eclipseBasePath = path where eclipse.exe is located, for e.g. C:\Users\Amrit\Codes\eclipse magnificationfactor = factor by which the image should be enlarged, for e.g. 2 = double

What is lexical scope?

I normally learn by example, and here's a little something:

const lives = 0;

function catCircus () {
    this.lives = 1;
    const lives = 2;

    const cat1 = {
        lives: 5,
        jumps: () => {
            console.log(this.lives);
        }
    };
    cat1.jumps(); // 1
    console.log(cat1); // { lives: 5, jumps: [Function: jumps] }

    const cat2 = {
        lives: 5,
        jumps: () => {
            console.log(lives);
        }
    };
    cat2.jumps(); // 2
    console.log(cat2); // { lives: 5, jumps: [Function: jumps] }

    const cat3 = {
        lives: 5,
        jumps: () => {
            const lives = 3;
            console.log(lives);
        }
    };
    cat3.jumps(); // 3
    console.log(cat3); // { lives: 5, jumps: [Function: jumps] }

    const cat4 = {
        lives: 5,
        jumps: function () {
            console.log(lives);
        }
    };
    cat4.jumps(); // 2
    console.log(cat4); // { lives: 5, jumps: [Function: jumps] }

    const cat5 = {
        lives: 5,
        jumps: function () {
            var lives = 4;
            console.log(lives);
        }
    };
    cat5.jumps(); // 4
    console.log(cat5); // { lives: 5, jumps: [Function: jumps] }

    const cat6 = {
        lives: 5,
        jumps: function () {
            console.log(this.lives);
        }
    };
    cat6.jumps(); // 5
    console.log(cat6); // { lives: 5, jumps: [Function: jumps] }

    const cat7 = {
        lives: 5,
        jumps: function thrownOutOfWindow () {
            console.log(this.lives);
        }
    };
    cat7.jumps(); // 5
    console.log(cat7); // { lives: 5, jumps: [Function: thrownOutOfWindow] }
}

catCircus();

Does not contain a static 'main' method suitable for an entry point

Perhaps unintentional, but moving my docker file to the solution folder instead of the project eliminated the error. This was helpful when I still wanted to run the solution independently of docker

This Activity already has an action bar supplied by the window decor

 <style name="AppCompatTheme" parent="@style/Theme.AppCompat.Light">
            <item name="android:windowActionBar">false</item>
    </style>

    Change this to NoActionBar 

        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <!-- Customize your theme here. -->

        </style>

    This one worked for me

angular2: Error: TypeError: Cannot read property '...' of undefined

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

Escape quote in web.config connection string

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

Since the web.config is XML, you need to escape the five special characters:

&amp; -> & ampersand, U+0026
&lt; -> < left angle bracket, less-than sign, U+003C
&gt; -> > right angle bracket, greater-than sign, U+003E
&quot; -> " quotation mark, U+0022
&apos; -> ' apostrophe, U+0027

+ is not a problem, I suppose.


Duc Filan adds: You should also wrap your password with single quote ':

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

How to convert Double to int directly?

try casting the value

double d = 1.2345;
long l = (long) d;

Detect when a window is resized using JavaScript ?

Another way of doing this, using only JavaScript, would be this:

window.addEventListener('resize', functionName);

This fires every time the size changes, like the other answer.

functionName is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).

textarea's rows, and cols attribute in CSS

As far as I know, you can't.

Besides, that isnt what CSS is for anyway. CSS is for styling and HTML is for markup.

How can I fill a div with an image while keeping it proportional?

Here is an answer with support to IE using object-fit so you won't lose ratio

Using a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

_x000D_
_x000D_
//ES6 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('img[data-object-fit]').forEach(image => {
      (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
      image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
    })
  })
}

//ES5 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', function() {
    Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
      (image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
      image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
    }));
  });
}
_x000D_
img {
  display: inline-flex;
  width: 175px;
  height: 175px;
  margin-right: 10px;
  border: 1px solid red
}


/*for browsers which support object fit */

[data-object-fit='cover'] {
  object-fit: cover
}

[data-object-fit='contain'] {
  object-fit: contain
}
_x000D_
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />
_x000D_
_x000D_
_x000D_


Note: There are also a few object-fit polyfills out there that will make object-fit work.

Here are a few examples:

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The add_subplot() method has several call signatures:

  1. add_subplot(nrows, ncols, index, **kwargs)
  2. add_subplot(pos, **kwargs)
  3. add_subplot(ax)
  4. add_subplot() <-- since 3.1.0

Calls 1 and 2:

Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:

f.add_subplot(3,4,1) 
# is equivalent to:
f.add_subplot(341)

Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.

This code illustrates the limitations of using call 2:

#!/usr/bin/env python3
import matplotlib.pyplot as plt

def plot_and_text(axis, text):
  '''Simple function to add a straight line
  and text to an axis object'''
  axis.plot([0,1],[0,1])
  axis.text(0.02, 0.9, text)

f = plt.figure()
f2 = plt.figure()

_max = 12
for i in range(_max):
  axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
  plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))

  # If this check isn't in place, a 
  # ValueError: num must be 1 <= num <= 15, not 0 is raised
  if i < 9:
    axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
    plot_and_text(axis,chr(i+97) + ') ' + str(341+i))

f.tight_layout()
f2.tight_layout()
plt.show()

subplots

You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.

I.e it illustrates this point from the documentation:

pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.


Call 3

In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.


Call 4 (since 3.1.0):

If no positional arguments are passed, defaults to (1, 1, 1).

i.e., reproducing the call fig.add_subplot(111) in the question.

To switch from vertical split to horizontal split fast in Vim

Ctrl-w followed by H, J, K or L (capital) will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.

The lower case equivalents move focus instead of moving the window.

How to get the data-id attribute?

HTML

<span id="spanTest" data-value="50">test</span>

JS

$(this).data().value;

or

$("span#spanTest").data().value;

ANS : 50

Works for me!

Installing Apple's Network Link Conditioner Tool

It's in an additional download. Use this menu item:

Xcode > Open Developer Tool > More Developer Tools...

and get "Hardware IO Tools for Xcode".

For Xcode 8+, get "Additional Tools for Xcode [version]".

Double-click on a .prefPane file to install. If you already have an older .prefPane installed, you'll need to remove it from /Library/PreferencePanes.

Scroll Automatically to the Bottom of the Page

This will guaranteed scroll to the bottom

Head Codes

<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script language="javascript" type="text/javascript">
function scrollToBottom() {
  $('#html, body').scrollTop($('#html, body')[0].scrollHeight);
}
</script>

Body code

<a href="javascript:void(0);" onmouseover="scrollToBottom();" title="Scroll to Bottom">&#9660; Bottom &#9660;</a>

SQL Query to fetch data from the last 30 days?

The easiest way would be to specify

SELECT productid FROM product where purchase_date > sysdate-30;

Remember this sysdate above has the time component, so it will be purchase orders newer than 03-06-2011 8:54 AM based on the time now.

If you want to remove the time conponent when comparing..

SELECT productid FROM product where purchase_date > trunc(sysdate-30);

And (based on your comments), if you want to specify a particular date, make sure you use to_date and not rely on the default session parameters.

SELECT productid FROM product where purchase_date > to_date('03/06/2011','mm/dd/yyyy')

And regardng the between (sysdate-30) - (sysdate) comment, for orders you should be ok with usin just the sysdate condition unless you can have orders with order_dates in the future.

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

curl Failed to connect to localhost port 80

If anyone else comes across this and the accepted answer doesn't work (it didn't for me), check to see if you need to specify a port other than 80. In my case, I was running a rails server at localhost:3000 and was just using curl http://localhost, which was hitting port 80.

Changing the command to curl http://localhost:3000 is what worked in my case.

How to generate service reference with only physical wsdl file

There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.

1. To create it via the IDE:

In the solution explorer pane, right click on the project that you would like to add the Service to:

enter image description here

Then, you can enter the path to your service WSDL and hit go:

enter image description here

2. To create it via the command line:

Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:

WSDL /verbose C:\path\to\wsdl

WSDL.exe will then output a .cs file for your consumption.

If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:

WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd

If you need VB output, use /language:VB in addition to the /verbose.

Are list-comprehensions and functional functions faster than "for loops"?

I wrote a simple script that test the speed and this is what I found out. Actually for loop was fastest in my case. That really suprised me, check out bellow (was calculating sum of squares).

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        i = i**2
        a += i
    return a

def square_sum3(numbers):
    sqrt = lambda x: x**2
    return sum(map(sqrt, numbers))

def square_sum4(numbers):
    return(sum([int(i)**2 for i in numbers]))


time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.302000 #Reduce
0:00:00.144000 #For loop
0:00:00.318000 #Map
0:00:00.390000 #List comprehension

What is a CSRF token? What is its importance and how does it work?

The site generates a unique token when it makes the form page. This token is required to post/get data back to the server.

Since the token is generated by your site and provided only when the page with the form is generated, some other site can't mimic your forms -- they won't have the token and therefore can't post to your site.

How can I select all children of an element except the last child?

When IE9 comes, it will be easier. A lot of the time though, you can switch the problem to one requiring :first-child and style the opposite side of the element (IE7+).

How to set environment variable or system property in spring tests?

For Unit Tests, the System variable is not instantiated yet when I do "mvn clean install" because there is no server running the application. So in order to set the System properties, I need to do it in pom.xml. Like so:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.21.0</version>
    <configuration>
        <systemPropertyVariables>
            <propertyName>propertyValue</propertyName>
            <MY_ENV_VAR>newValue</MY_ENV_VAR>
            <ENV_TARGET>olqa</ENV_TARGET>
            <buildDirectory>${project.build.directory}</buildDirectory>
        </systemPropertyVariables>
    </configuration>
</plugin>

How to show what a commit did?

TL;DR

git show <commit>


Show

To show what a commit did with stats:

git show <commit> --stat

Log

To show commit log with differences introduced for each commit in a range:

git log -p <commit1> <commit2>

What is <commit>?

Each commit has a unique id we reference here as <commit>. The unique id is an SHA-1 hash – a checksum of the content you’re storing plus a header. #TMI

If you don't know your <commit>:

  1. git log to view the commit history

  2. Find the commit you care about.

HTTP Ajax Request via HTTPS Page

Still, this can be done with the following steps:

  1. send an https ajax request to your web-site (the same domain)

    jQuery.ajax({
        'url'      : '//same_domain.com/ajax_receiver.php',
        'type'     : 'get',
        'data'     : {'foo' : 'bar'},
        'success'  : function(response) {
            console.log('Successful request');
        }
    }).fail(function(xhr, err) {
        console.error('Request error');
    });
    
  2. get ajax request, for example, by php, and make a CURL get request to any desired website via http.

    use linslin\yii2\curl;
    $curl = new curl\Curl();
    $curl->get('http://example.com');
    

Need to find element in selenium by css

Only using class names is not sufficient in your case.

  • By.cssSelector(".ban") has 15 matching nodes
  • By.cssSelector(".hot") has 11 matching nodes
  • By.cssSelector(".ban.hot") has 5 matching nodes

Therefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.

Option 1: Using list items' index (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes

Example:

driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));

Option 2: Using Selenium's FindElements, then index them. (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes
  • Not the native selector's way

Example:

// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];

Option 3: Using text (XPath only)

Limitations

  • Not for multilanguage sites
  • Only for XPath, not for Selenium's CssSelector

Example:

driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));

Option 4: Index the grouped selector (XPath only)

Limitations

  • Not stable enough if site's structure changes
  • Only for XPath, not CssSelector

Example:

driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));

Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)

Limitations

  • Only for XPath, not CssSelector
  • Low performance
  • Tricky XPath

Example:

driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));

Read environment variables in Node.js

If you want to use a string key generated in your Node.js program, say, var v = 'HOME', you can use process.env[v].

Otherwise, process.env.VARNAME has to be hardcoded in your program.

python list by value not by reference

As mentioned by phihag in his answer,

b = a[:]

will work for your case since slicing a list creates a new memory id of the list (meaning you are no longer referencing the same object in your memory and the changes you make to one will not be reflected in the other.)

However, there is a slight problem. If your list is multidimensional, as in lists within lists, simply slicing will not solve this problem. Changes made in the higher dimensions, i.e. the lists within the original list, will be shared between the two.

Do not fret, there is a solution. The module copy has a nifty copying technique that takes care of this issue.

from copy import deepcopy

b = deepcopy(a)

will copy a list with a new memory id no matter how many levels of lists it contains!

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

I had the same issue. In my home folder I've got a script named sqlplus.sh that takes care of this for me, containing:

ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_HOME
ORACLE_SID=XE
export ORACLE_SID
NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export NLS_LANG
PATH=$ORACLE_HOME/bin:$PATH
export PATH
sqlplus /nolog

Getting the names of all files in a directory with PHP

I have smaller code todo this:

$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
    echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}

How can I convert tabs to spaces in every file of a directory?

My recommendation is to use:

find . -name '*.lua' -exec ex '+%s/\t/  /g' -cwq {} \;

Comments:

  1. Use in place editing. Keep backups in a VCS. No need to produce *.orig files. It's good practice to diff the result against your last commit to make sure this worked as expected, in any case.
  2. sed is a stream editor. Use ex for in place editing. This avoids creating extra temp files and spawning shells for each replacement as in the top answer.
  3. WARNING: This messes with all tabs, not only those used for indentation. Also it does not do context aware replacement of tabs. This was sufficient for my use case. But might not be acceptable for you.
  4. EDIT: An earlier version of this answer used find|xargs instead of find -exec. As pointed out by @gniourf-gniourf this leads to problems with spaces, quotes and control chars in file names cf. Wheeler.

Integrating Dropzone.js into existing HTML form with other fields

Here's another way to do it: add a div in your form with a classname dropzone, and implement dropzone programmatically.

HTML :

<div id="dZUpload" class="dropzone">
      <div class="dz-default dz-message"></div>
</div>

JQuery:

$(document).ready(function () {
    Dropzone.autoDiscover = false;
    $("#dZUpload").dropzone({
        url: "hn_SimpeFileUploader.ashx",
        addRemoveLinks: true,
        success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded :" + imgName);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
        }
    });
});

Note : Disabling autoDiscover, otherwise Dropzone will try to attach twice

Blog Article : Dropzone js + Asp.net: Easy way to upload Bulk images

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

Object spread vs. Object.assign

I think one big difference between the spread operator and Object.assign that doesn't seem to be mentioned in the current answers is that the spread operator will not copy the the source object’s prototype to the target object. If you want to add properties to an object and you don't want to change what instance it is of, then you will have to use Object.assign.

Edit: I've actually realised that my example is misleading. The spread operator desugars to Object.assign with the first parameter set to an empty object. In my code example below, I put error as the first parameter of the Object.assign call so the two are not equivalent. The first parameter of Object.assign is actually modified and then returned which is why it retains its prototype. I have added another example below:

_x000D_
_x000D_
const error = new Error();
error instanceof Error // true

const errorExtendedUsingSpread = {
  ...error,
  ...{
    someValue: true
  }
};
errorExtendedUsingSpread instanceof Error; // false

// What the spread operator desugars into
const errorExtendedUsingImmutableObjectAssign = Object.assign({}, error, {
    someValue: true
});
errorExtendedUsingImmutableObjectAssign instanceof Error; // false

// The error object is modified and returned here so it keeps its prototypes
const errorExtendedUsingAssign = Object.assign(error, {
  someValue: true
});
errorExtendedUsingAssign instanceof Error; // true
_x000D_
_x000D_
_x000D_

See also: https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md

Change all files and folders permissions of a directory to 644/755

The easiest way is to do:

chmod -R u+rwX,go+rX,go-w /path/to/dir

which basically means:

to change file modes -Recursively by giving:

  • user: read, write and eXecute permissions,
  • group and other users: read and eXecute permissions, but not -write permission.

Please note that X will make a directory executable, but not a file, unless it's already searchable/executable.

+X - make a directory or file searchable/executable by everyone if it is already searchable/executable by anyone.

Please check man chmod for more details.

See also: How to chmod all directories except files (recursively)? at SU

How to convert a date to milliseconds

The 2017 answer is: Use the date and time classes introduced in Java 8 (and also backported to Java 6 and 7 in the ThreeTen Backport).

If you want to interpret the date-time string in the computer’s time zone:

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atZone(ZoneId.systemDefault())
            .toInstant()
            .toEpochMilli();

If another time zone, fill that zone in instead of ZoneId.systemDefault(). If UTC, use

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atOffset(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();

Cocoa Touch: How To Change UIView's Border Color And Thickness?

Add following @IBInspectables in UIView extension

extension UIView {

  @IBInspectable var borderWidth: CGFloat {
    get {
      return layer.borderWidth
    }
    set(newValue) {
      layer.borderWidth = newValue
    }
  }

  @IBInspectable var borderColor: UIColor? {
    get {
      if let color = layer.borderColor {
        return UIColor(CGColor: color)
      }
      return nil
    }
    set(newValue) {
      layer.borderColor = newValue?.CGColor
    }
  }
}

And then you should be able to set borderColor and borderWidth attributes directly from Attribute inspector. See attached image

Attributes Inspector

How to maximize a plt.show() window using Python

import matplotlib.pyplot as plt
def maximize():
    plot_backend = plt.get_backend()
    mng = plt.get_current_fig_manager()
    if plot_backend == 'TkAgg':
        mng.resize(*mng.window.maxsize())
    elif plot_backend == 'wxAgg':
        mng.frame.Maximize(True)
    elif plot_backend == 'Qt4Agg':
        mng.window.showMaximized()

Then call function maximize() before plt.show()

No module named _sqlite3

Putting answer for anyone who lands on this page searching for a solution for Windows OS:

You have to install pysqlite3 or db-sqlite3 if not already installed. you can use following to install.

  • pip install pysqlite3
  • pip install db-sqlite3

For me the issue was with DLL file of sqlite3.

Solution:

  1. I took DLL file from sqlite site. This might vary based on your version of python installation.

  2. I pasted it in the DLL directory of the env. for me it was "C:\Anaconda\Lib\DLLs", but check for yours. Before and After placing DLL file

npm throws error without sudo

I found that if you only sudo -s "it just starts up a shell with root permissions as a one step" and it really works for me. I don't know if it's a good practice or not.

I hope it helps.

Reference: https://apple.stackexchange.com/posts/14423/revisions

What is Android's file system?

Similar to Linux:

  • /boot

  • /system

  • /recovery

  • /data

  • /cache

  • /misc

Difference between java HH:mm and hh:mm on SimpleDateFormat

Use the built-in localized formats

If this is for showing a time of day to a user, then in at least 19 out of 20 you don’t need to care about kk, HH nor hh. I suggest that you use something like this:

    DateTimeFormatter defaultTimeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    System.out.format("%s: %s%n",
            Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));

The point is that it gives different output in different default locales. For example:

en_SS: 12:00 AM
fr_BL: 00:00
ps_AF: 0:00
es_CO: 12:00 a.m.

The localized formats have been designed to conform with the expectations of different cultures. So they generally give the user a better experience and they save you of writing a format pattern string, which is always error-prone.

I furthermore suggest that you don’t use SimpleDateFormat. That class is notoriously troublesome and fortunately long outdated. Instead I use java.time, the modern Java date and time API. It is so much nicer to work with.

Four pattern letters for hour: H, h, k and K

Of course if you need to parse a string with a specified format, and also if you have a very specific formatting requirement, it’s good to use a format pattern string. There are actually four different pattern letters to choose from for hour (quoted from the documentation):

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-day (1-24)    number            24
   H       hour-of-day (0-23)          number            0

In practice H and h are used. As far as I know k and K are not (they may just have been included for the sake of completeness). But let’s just see them all in action:

    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("hh:mm a  HH:mm  kk:mm  KK:mm a", Locale.ENGLISH);
    System.out.println(LocalTime.of(0, 0).format(timeFormatter));
    System.out.println(LocalTime.of(1, 15).format(timeFormatter));
    System.out.println(LocalTime.of(11, 25).format(timeFormatter));
    System.out.println(LocalTime.of(12, 35).format(timeFormatter));
    System.out.println(LocalTime.of(13, 40).format(timeFormatter));
12:00 AM  00:00  24:00  00:00 AM
01:15 AM  01:15  01:15  01:15 AM
11:25 AM  11:25  11:25  11:25 AM
12:35 PM  12:35  12:35  00:35 PM
01:40 PM  13:40  13:40  01:40 PM

If you don’t want the leading zero, just specify one pattern letter, that is h instead of hh or H instead of HH. It will still accept two digits when parsing, and if a number to be printed is greater than 9, two digits will still be printed.

Links

Regex to extract substring, returning 2 results for some reason

match returns an array.

The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:

var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);

Keras, How to get the output of each layer?

Based on all the good answers of this thread, I wrote a library to fetch the output of each layer. It abstracts all the complexity and has been designed to be as user-friendly as possible:

https://github.com/philipperemy/keract

It handles almost all the edge cases

Hope it helps!

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}