Programs & Examples On #Cdata

CDATA (literally, character data) is data that will not be parsed as markup in XML and SGML documents.

What does <![CDATA[]]> in XML mean?

Usually used for embedding custom data, like pictures or sound data within an XML document.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;

// or with parent element:

$foo = simplexml_load_string(
    '<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;

You might have better luck with LIBXML_NOCDATA:

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
    , null
    , LIBXML_NOCDATA
);

When is a CDATA section necessary within a script tag?

CDATA indicates that the contents within are not XML.

Here is an explanation on wikipedia

What is CDATA in HTML?

A way to write a common subset of HTML and XHTML

In the hope of greater portability.

In HTML, <script> is magic escapes everything until </script> appears.

So you can write:

<script>x = '<br/>';

and <br/> won't be considered a tag.

This is why strings such as:

x = '</scripts>'

must be escaped like:

x = '</scri' + 'pts>'

See: Why split the <script> tag when writing it with document.write()?

But XML (and thus XHTML, which is a "subset" of XML, unlike HTML), doesn't have that magic: <br/> would be seen as a tag.

<![CDATA[ is the XHTML way to say:

don't parse any tags until the next ]]>, consider it all a string

The // is added to make the CDATA work well in HTML as well.

In HTML <![CDATA[ is not magic, so it would be run by JavaScript. So // is used to comment it out.

The XHTML also sees the //, but will observe it as an empty comment line which is not a problem:

//

That said:

  • compliant browsers should recognize if the document is HTML or XHTML from the initial doctype <!DOCTYPE html> vs <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  • compliant websites could rely on compliant browsers, and coordinate doctype with a single valid script syntax

But that violates the golden rule of the Internet:

don't trust third parties, or your product will break

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

How to access URL segment(s) in blade in Laravel 5?

Try this

{{ Request::segment(1) }}

How to turn off gcc compiler optimization to enable buffer overflow

You don't need to disable ASLR in order to do a buffer overflow! Although ASLR is enabled (kernel_randomize_va_space = 2), it will not take effect unless the compiled executable is PIE. So unless you compiled your file with -fPIC -pie flag, ASLR will not take effect.

I think only disabling the canaries with -fno-stack-protector is enough. If you want to check if ASLR is working or not (Position independent code must be set), use:

hardening-check executable_name

How can I select an element with multiple classes in jQuery?

The problem you're having, is that you are using a Group Selector, whereas you should be using a Multiples selector! To be more specific, you're using $('.a, .b') whereas you should be using $('.a.b').

For more information, see the overview of the different ways to combine selectors herebelow!


Group Selector : ","

Select all <h1> elements AND all <p> elements AND all <a> elements :

$('h1, p, a')

Multiples selector : "" (no character)

Select all <input> elements of type text, with classes code and red :

$('input[type="text"].code.red')

Descendant Selector : " " (space)

Select all <i> elements inside <p> elements:

$('p i')

Child Selector : ">"

Select all <ul> elements that are immediate children of a <li> element:

$('li > ul')

Adjacent Sibling Selector : "+"

Select all <a> elements that are placed immediately after <h2> elements:

$('h2 + a')

General Sibling Selector : "~"

Select all <span> elements that are siblings of <div> elements:

$('div ~ span')

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

Using CSS for a fade-in effect on page load

You can use the onload="" HTML attribute and use JavaScript to adjust the opacity style of your element.

Leave your CSS as you proposed. Edit your HTML code to:

<body onload="document.getElementById(test).style.opacity='1'">
    <div id="test">
        <p>?This is a test</p>
    </div>
</body>

This also works to fade-in the complete page when finished loading:

HTML:

<body onload="document.body.style.opacity='1'">
</body>

CSS:

body{ 
    opacity: 0;
    transition: opacity 2s;
    -webkit-transition: opacity 2s; /* Safari */
}

Check the W3Schools website: transitions and an article for changing styles with JavaScript.

How to pass a parameter to routerLink that is somewhere inside the URL?

Maybe it is really late answer but if you want to navigate another page with param you can,

[routerLink]="['/user', user.id, 'details']"

also you shouldn't forget about routing config like ,

 [path: 'user/:id/details', component:userComponent, pathMatch: 'full']

jQuery Get Selected Option From Dropdown

Straight forward and pretty easy:

Your dropdown

<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>

Jquery code to get the selected value

$('#aioConceptName').change(function() {
    var $option = $(this).find('option:selected');

    //Added with the EDIT
    var value = $option.val(); //returns the value of the selected option.
    var text = $option.text(); //returns the text of the selected option.
});

Seedable JavaScript random number generator

I use a JavaScript port of the Mersenne Twister: https://gist.github.com/300494 It allows you to set the seed manually. Also, as mentioned in other answers, the Mersenne Twister is a really good PRNG.

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

`require': no such file to load -- mkmf (LoadError)

The problem is still is recursive on Ubuntu 13/04/13.10/14.04

and

sudo apt-get install ruby1.9.1-dev

worked out for me okay. So If you are using Ubuntu 13.04/13.10/14.04 then using this will really come in handy.

This works even if ruby version is 1.9.3. This is because there is no ruby1.9.3-dev available in the Repository...

How can I change the default Django date template format?

What you need is a date template filter.

e.g:

<td>Joined {{user.date_created|date:"F Y" }}<td>

This returns Joined December 2018

how to get 2 digits after decimal point in tsql?

SELECT CAST(12.0910239123 AS DECIMAL(15, 2))

SQL Server dynamic PIVOT query?

The below code provides the results which replaces NULL to zero in the output.

Table creation and data insertion:

create table test_table
 (
 date nvarchar(10),
 category char(3),
 amount money
 )

 insert into test_table values ('1/1/2012','ABC',1000.00)
 insert into test_table values ('2/1/2012','DEF',500.00)
 insert into test_table values ('2/1/2012','GHI',800.00)
 insert into test_table values ('2/10/2012','DEF',700.00)
 insert into test_table values ('3/1/2012','ABC',1100.00)

Query to generate the exact results which also replaces NULL with zeros:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

OUTPUT :

enter image description here

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

Git: See my last commit

After you do several commits or clone/pull a repository, you might want to see what commits have been made. Just check these simple solutions to see your commit history (from last/recent commit to the first one).

For the last commit, just fire this command: git log -1. For more interesting things see below -

  1. To see the commit ID (SHA-1 checksum), Author name <mail ID>, Date along with time, and commit message -

    git log
    
  2. To see some more stats, such as the names of all the files changed during that commit and number of insertions/deletions. This comes in very handy while reviewing the code -

    git log --stat
    
  3. To see commit histories in some pretty formats :) (This is followed by some prebuild options)-

    • If you have too many commits to review, this command will show them in a neat single line:

      git log --pretty=oneline
      
    • To see short, medium, full, or even more details of your commit, use following, respectively -

      git log --pretty=short
      git log --pretty=medium
      git log --pretty=full
      git log --pretty=fuller
      
  4. You can even use your own output format using the format option -

    git log --pretty=format:"%an, %ae - %s"
    

    where %an - author name, %ae - author email, %s - subject of commit, etc.

This can help you with your commit histories. For more information, click here.

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

no need to do so many things. for set value using multiple select2 var selectedvalue="1,2,3"; //if first 3 products are selected. $('#ddlProduct').val(selectedvalue);

Git branching: master vs. origin/master vs. remotes/origin/master

Technically there aren't actually any "remote" things at all1 in your Git repo, there are just local names that should correspond to the names on another, different repo. The ones named origin/whatever will initially match up with those on the repo you cloned-from:

git clone ssh://some.where.out.there/some/path/to/repo # or git://some.where...

makes a local copy of the other repo. Along the way it notes all the branches that were there, and the commits those refer-to, and sticks those into your local repo under the names refs/remotes/origin/.

Depending on how long you go before you git fetch or equivalent to update "my copy of what's some.where.out.there", they may change their branches around, create new ones, and delete some. When you do your git fetch (or git pull which is really fetch plus merge), your repo will make copies of their new work and change all the refs/remotes/origin/<name> entries as needed. It's that moment of fetching that makes everything match up (well, that, and the initial clone, and some cases of pushing too—basically whenever Git gets a chance to check—but see caveat below).

Git normally has you refer to your own refs/heads/<name> as just <name>, and the remote ones as origin/<name>, and it all just works because it's obvious which one is which. It's sometimes possible to create your own branch names that make it not obvious, but don't worry about that until it happens. :-) Just give Git the shortest name that makes it obvious, and it will go from there: origin/master is "where master was over there last time I checked", and master is "where master is over here based on what I have been doing". Run git fetch to update Git on "where master is over there" as needed.


Caveat: in versions of Git older than 1.8.4, git fetch has some modes that don't update "where master is over there" (more precisely, modes that don't update any remote-tracking branches). Running git fetch origin, or git fetch --all, or even just git fetch, does update. Running git fetch origin master doesn't. Unfortunately, this "doesn't update" mode is triggered by ordinary git pull. (This is mainly just a minor annoyance and is fixed in Git 1.8.4 and later.)


1Well, there is one thing that is called a "remote". But that's also local! The name origin is the thing Git calls "a remote". It's basically just a short name for the URL you used when you did the clone. It's also where the origin in origin/master comes from. The name origin/master is called a remote-tracking branch, which sometimes gets shortened to "remote branch", especially in older or more informal documentation.

Increasing the timeout value in a WCF service

Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.

From there you can change the binding options for both the client and the services, one of these options will be for time-outs.

Error: vector does not name a type

You need to either qualify vector with its namespace (which is std), or import the namespace at the top of your CPP file:

using namespace std;

How do you clear Apache Maven's cache?

So there are some commands which you can use for cleaning

 1. mvn clean cache   
 2. mvn clean install 
 3. mvn clean install -Pclean-database

also deleting repository folder from .m2 can help.

How to get cookie's expire time

It seems there's a list of all cookies sent to browser in array returned by php's headers_list() which among other data returns "Set-Cookie" elements as follows:

Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain

This way you can also get deleted ones since their value is deleted:

Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain

From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie() has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.

This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.

For more info see:

https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

A more appropriate approach is to specify a Locale region as a parameter in the constructor. The example below uses a US Locale region. Date formatting is locale-sensitive and uses the Locale to tailor information relative to the customs and conventions of the user's region Locale (Java Platform SE 7)

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());

How to load a model from an HDF5 file in Keras?

load_weights only sets the weights of your network. You still need to define its architecture before calling load_weights:

def create_model():
   model = Sequential()
   model.add(Dense(64, input_dim=14, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5)) 
   model.add(Dense(64, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(2, init='uniform'))
   model.add(Activation('softmax'))
   return model

def train():
   model = create_model()
   sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
   model.compile(loss='binary_crossentropy', optimizer=sgd)

   checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
   model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])

def load_trained_model(weights_path):
   model = create_model()
   model.load_weights(weights_path)

PostgreSQL: role is not permitted to log in

Using pgadmin4 :

  1. Select roles in side menu
  2. Select properties in dashboard.
  3. Click Edit and select privileges

Now there you can enable or disable login, roles and other options

java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

Convert a double to a QString

Use QString's number method (docs are here):

double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);

What is the command for cut copy paste a file from one directory to other directory

mv in unix-ish systems, move in dos/windows.

e.g.

C:\> move c:\users\you\somefile.txt   c:\temp\newlocation.txt

and

$ mv /home/you/somefile.txt /tmp/newlocation.txt

Implementing a simple file download servlet

Assuming you have access to servlet as below

http://localhost:8080/myapp/download?id=7

I need to create a servlet and register it to web.xml

web.xml

<servlet>
     <servlet-name>DownloadServlet</servlet-name>
     <servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>DownloadServlet</servlet-name>
     <url-pattern>/download</url-pattern>
</servlet-mapping>

DownloadServlet.java

public class DownloadServlet extends HttpServlet {


    protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         String id = request.getParameter("id");

         String fileName = "";
         String fileType = "";
         // Find this file id in database to get file name, and file type

         // You must tell the browser the file type you are going to send
         // for example application/pdf, text/plain, text/html, image/jpg
         response.setContentType(fileType);

         // Make sure to show the download dialog
         response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");

         // Assume file name is retrieved from database
         // For example D:\\file\\test.pdf

         File my_file = new File(fileName);

         // This should send the file to browser
         OutputStream out = response.getOutputStream();
         FileInputStream in = new FileInputStream(my_file);
         byte[] buffer = new byte[4096];
         int length;
         while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
         }
         in.close();
         out.flush();
    }
}

Returning pointer from a function

Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:

int *fun()
{
    int *point;
    *point=12;  <<<<<<  your program crashed here.
    return point;
}

The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.

Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.

int *fun()
{
    int point;
    point = 12;
    return (&point);
}

or almost identically:

int *fun()
{
    int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:

int *fun()
{
    static int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

or

int *fun()
{
    static int point;
    point = 12;
    return (&point);
}

As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.

How to convert jsonString to JSONObject in Java

If you are using http://json-lib.sourceforge.net (net.sf.json.JSONObject)

it is pretty easy:

String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);

or

JSONObject json = JSONSerializer.toJSON(myJsonString);

get the values then with json.getString(param), json.getInt(param) and so on.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Put the select statement in a dynamic PL/SQL block.

CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2) 
RETURN NUMBER
IS
  v_query_str VARCHAR2(1000);
  v_num_of_employees NUMBER;
BEGIN
  v_query_str := 'begin SELECT COUNT(*) INTO :into_bind FROM emp_' 
                 || p_loc
                 || ' WHERE job = :bind_job; end;';
  EXECUTE IMMEDIATE v_query_str
    USING out v_num_of_employees, p_job;
  RETURN v_num_of_employees;
END;
/

Tomcat 7 "SEVERE: A child container failed during start"

This seems like that the servlet api version which you using is older than the xsd you are using in web.xml eg 3.0

use this one ****http://java.sun.com/xml/ns/javaee/" id="WebApp_ID" version="2.5"> ****

How to style UITextview to like Rounded Rect text field?

this code worked well for me:

    [yourTextView.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
    [yourTextView.layer setBorderColor: [[UIColor grayColor] CGColor]];
    [yourTextView.layer setBorderWidth: 1.0];
    [yourTextView.layer setCornerRadius:8.0f];
    [yourTextView.layer setMasksToBounds:YES];

How to set Linux environment variables with Ansible

This is the best option. As said Michal Gasek (first answer), since the pull request was merged (https://github.com/ansible/ansible/pull/8651), we are able to set permanent environment variables easily by play level.

- hosts: all
  roles:
     - php
     - nginx
  environment:
    MY_ENV_VARIABLE: whatever_value

Web colors in an Android color xml resource file

Edit Answer of @rolnad :-Remove White space from name

<color name="Black">#000000</color>
<color name="Gunmetal">#2C3539</color>
<color name="Midnight">#2B1B17</color>
<color name="Charcoal">#34282C</color>
<color name="DarkSlateGrey">#25383C</color>
<color name="Oil">#3B3131</color>
<color name="BlackCat">#413839</color>
<color name="BlackEel">#463E3F</color>
<color name="BlackCow">#4C4646</color>
<color name="GrayWolf">#504A4B</color>
<color name="VampireGray">#565051</color>
<color name="GrayDolphin">#5C5858</color>
<color name="CarbonGray">#625D5D</color>
<color name="AshGray">#666362</color>
<color name="CloudyGray">#6D6968</color>
<color name="SmokeyGray">#726E6D</color>
<color name="Gray">#736F6E</color>
<color name="Granite">#837E7C</color>
<color name="BattleshipGray">#848482</color>
<color name="GrayCloud">#B6B6B4</color>
<color name="GrayGoose">#D1D0CE</color>
<color name="Platinum">#E5E4E2</color>
<color name="MetallicSilver">#BCC6CC</color>
<color name="BlueGray">#98AFC7</color>
<color name="LightSlateGray">#6D7B8D</color>
<color name="SlateGray">#657383</color>
<color name="JetGray">#616D7E</color>
<color name="MistBlue">#646D7E</color>
<color name="MarbleBlue">#566D7E</color>
<color name="SteelBlue">#4863A0</color>
<color name="BlueJay">#2B547E</color>
<color name="DarkSlateBlue">#2B3856</color>
<color name="MidnightBlue">#151B54</color>
<color name="NavyBlue">#000080</color>
<color name="BlueWhale">#342D7E</color>
<color name="LapisBlue">#15317E</color>
<color name="EarthBlue">#0000A0</color>
<color name="CobaltBlue">#0020C2</color>
<color name="BlueberryBlue">#0041C2</color>
<color name="SapphireBlue">#2554C7</color>
<color name="BlueEyes">#1569C7</color>
<color name="RoyalBlue">#2B60DE</color>
<color name="BlueOrchid">#1F45FC</color>
<color name="BlueLotus">#6960EC</color>
<color name="LightSlateBlue">#736AFF</color>
<color name="Slate_Blue">#357EC7</color>
<color name="SilkBlue">#488AC7</color>
<color name="BlueIvy">#3090C7</color>
<color name="BlueKoi">#659EC7</color>
<color name="ColumbiaBlue">#87AFC7</color>
<color name="BabyBlue">#95B9C7</color>
<color name="LightSteelBlue">#728FCE</color>
<color name="OceanBlue">#2B65EC</color>
<color name="BlueRibbon">#306EFF</color>
<color name="BlueDress">#157DEC</color>
<color name="DodgerBlue">#1589FF</color>
<color name="Cornflower_Blue">#6495ED</color>
<color name="ButterflyBlue">#38ACEC</color>
<color name="Iceberg">#56A5EC</color>
<color name="CrystalBlue">#5CB3FF</color>
<color name="DeepSkyBlue">#3BB9FF</color>
<color name="DenimBlue">#79BAEC</color>
<color name="LightSkyBlue">#82CAFA</color>
<color name="SkyBlue">#82CAFF</color>
<color name="JeansBlue">#A0CFEC</color>
<color name="BlueAngel">#B7CEEC</color>
<color name="PastelBlue">#B4CFEC</color>
<color name="SeaBlue">#C2DFFF</color>
<color name="PowderBlue">#C6DEFF</color>
<color name="CoralBlue">#AFDCEC</color>
<color name="LightBlue">#ADDFFF</color>
<color name="RobinEggBlue">#BDEDFF</color>
<color name="PaleBlueLily">#CFECEC</color>
<color name="LightCyan">#E0FFFF</color>
<color name="Water">#EBF4FA</color>
<color name="AliceBlue">#F0F8FF</color>
<color name="Azure">#F0FFFF</color>
<color name="LightSlate">#CCFFFF</color>
<color name="LightAquamarine">#93FFE8</color>
<color name="ElectricBlue">#9AFEFF</color>
<color name="Aquamarine">#7FFFD4</color>
<color name="CyanorAqua">#00FFFF</color>
<color name="TronBlue">#7DFDFE</color>
<color name="BlueZircon">#57FEFF</color>
<color name="BlueLagoon">#8EEBEC</color>
<color name="Celeste">#50EBEC</color>
<color name="BlueDiamond">#4EE2EC</color>
<color name="TiffanyBlue">#81D8D0</color>
<color name="CyanOpaque">#92C7C7</color>
<color name="BlueHosta">#77BFC7</color>
<color name="NorthernLightsBlue">#78C7C7</color>
<color name="MediumTurquoise">#48CCCD</color>
<color name="Turquoise">#43C6DB</color>
<color name="Jellyfish">#46C7C7</color>
<color name="MascawBlueGreen">#43BFC7</color>
<color name="LightSeaGreen">#3EA99F</color>
<color name="DarkTurquoise">#3B9C9C</color>
<color name="SeaTurtleGreen">#438D80</color>
<color name="MediumAquamarine">#348781</color>
<color name="GreenishBlue">#307D7E</color>
<color name="GrayishTurquoise">#5E7D7E</color>
<color name="BeetleGreen">#4C787E</color>
<color name="Teal">#008080</color>
<color name="SeaGreen">#4E8975</color>
<color name="CamouflageGreen">#78866B</color>
<color name="HazelGreen">#617C58</color>
<color name="VenomGreen">#728C00</color>
<color name="FernGreen">#667C26</color>
<color name="DarkForrestGreen">#254117</color>
<color name="MediumSeaGreen">#306754</color>
<color name="MediumForestGreen">#347235</color>
<color name="SeaweedGreen">#437C17</color>
<color name="PineGreen">#387C44</color>
<color name="JungleGreen">#347C2C</color>
<color name="ShamrockGreen">#347C17</color>
<color name="MediumSpringGreen">#348017</color>
<color name="ForestGreen">#4E9258</color>
<color name="GreenOnion">#6AA121</color>
<color name="SpringGreen">#4AA02C</color>
<color name="LimeGreen">#41A317</color>
<color name="CloverGreen">#3EA055</color>
<color name="GreenSnake">#6CBB3C</color>
<color name="AlienGreen">#6CC417</color>
<color name="GreenApple">#4CC417</color>
<color name="YellowGreen">#52D017</color>
<color name="KellyGreen">#4CC552</color>
<color name="ZombieGreen">#54C571</color>
<color name="FrogGreen">#99C68E</color>
<color name="GreenPeas">#89C35C</color>
<color name="DollarBillGreen">#85BB65</color>
<color name="DarkSeaGreen">#8BB381</color>
<color name="IguanaGreen">#9CB071</color>
<color name="AvocadoGreen">#B2C248</color>
<color name="PistachioGreen">#9DC209</color>
<color name="SaladGreen">#A1C935</color>
<color name="HummingbirdGreen">#7FE817</color>
<color name="NebulaGreen">#59E817</color>
<color name="StoplightGoGreen">#57E964</color>
<color name="AlgaeGreen">#64E986</color>
<color name="JadeGreen">#5EFB6E</color>
<color name="Green">#00FF00</color>
<color name="EmeraldGreen">#5FFB17</color>
<color name="LawnGreen">#87F717</color>
<color name="Chartreuse">#8AFB17</color>
<color name="DragonGreen">#6AFB92</color>
<color name="Mintgreen">#98FF98</color>
<color name="GreenThumb">#B5EAAA</color>
<color name="LightJade">#C3FDB8</color>
<color name="TeaGreen">#CCFB5D</color>
<color name="GreenYellow">#B1FB17</color>
<color name="SlimeGreen">#BCE954</color>
<color name="Goldenrod">#EDDA74</color>
<color name="HarvestGold">#EDE275</color>
<color name="SunYellow">#FFE87C</color>
<color name="Yellow">#FFFF00</color>
<color name="CornYellow">#FFF380</color>
<color name="Parchment">#FFFFC2</color>
<color name="Cream">#FFFFCC</color>
<color name="LemonChiffon">#FFF8C6</color>
<color name="Cornsilk">#FFF8DC</color>
<color name="Beige">#F5F5DC</color>
<color name="AntiqueWhite">#FAEBD7</color>
<color name="BlanchedAlmond">#FFEBCD</color>
<color name="Vanilla">#F3E5AB</color>
<color name="TanBrown">#ECE5B6</color>
<color name="Peach">#FFE5B4</color>
<color name="Mustard">#FFDB58</color>
<color name="RubberDuckyYellow">#FFD801</color>
<color name="BrightGold">#FDD017</color>
<color name="Goldenbrown">#EAC117</color>
<color name="MacaroniandCheese">#F2BB66</color>
<color name="Saffron">#FBB917</color>
<color name="Beer">#FBB117</color>
<color name="Cantaloupe">#FFA62F</color>
<color name="BeeYellow">#E9AB17</color>
<color name="BrownSugar">#E2A76F</color>
<color name="BurlyWood">#DEB887</color>
<color name="DeepPeach">#FFCBA4</color>
<color name="GingerBrown">#C9BE62</color>
<color name="SchoolBusYellow">#E8A317</color>
<color name="SandyBrown">#EE9A4D</color>
<color name="FallLeafBrown">#C8B560</color>
<color name="Gold">#D4A017</color>
<color name="Sand">#C2B280</color>
<color name="CookieBrown">#C7A317</color>
<color name="Caramel">#C68E17</color>
<color name="Brass">#B5A642</color>
<color name="Khaki">#ADA96E</color>
<color name="Camelbrown">#C19A6B</color>
<color name="Bronze">#CD7F32</color>
<color name="TigerOrange">#C88141</color>
<color name="Cinnamon">#C58917</color>
<color name="DarkGoldenrod">#AF7817</color>
<color name="Copper">#B87333</color>
<color name="Wood">#966F33</color>
<color name="OakBrown">#806517</color>
<color name="Moccasin">#827839</color>
<color name="ArmyBrown">#827B60</color>
<color name="Sandstone">#786D5F</color>
<color name="Mocha">#493D26</color>
<color name="Taupe">#483C32</color>
<color name="Coffee">#6F4E37</color>
<color name="BrownBear">#835C3B</color>
<color name="RedDirt">#7F5217</color>
<color name="Sepia">#7F462C</color>
<color name="OrangeSalmon">#C47451</color>
<color name="Rust">#C36241</color>
<color name="RedFox">#C35817</color>
<color name="Chocolate">#C85A17</color>
<color name="Sedona">#CC6600</color>
<color name="PapayaOrange">#E56717</color>
<color name="HalloweenOrange">#E66C2C</color>
<color name="PumpkinOrange">#F87217</color>
<color name="ConstructionConeOrange">#F87431</color>
<color name="SunriseOrange">#E67451</color>
<color name="MangoOrange">#FF8040</color>
<color name="DarkOrange">#F88017</color>
<color name="Coral">#FF7F50</color>
<color name="BasketBallOrange">#F88158</color>
<color name="LightSalmon">#F9966B</color>
<color name="Tangerine">#E78A61</color>
<color name="DarkSalmon">#E18B6B</color>
<color name="LightCoral">#E77471</color>
<color name="BeanRed">#F75D59</color>
<color name="ValentineRed">#E55451</color>
<color name="ShockingOrange">#E55B3C</color>
<color name="Red">#FF0000</color>
<color name="Scarlet">#FF2400</color>
<color name="RubyRed">#F62217</color>
<color name="FerrariRed">#F70D1A</color>
<color name="FireEngineRed">#F62817</color>
<color name="LavaRed">#E42217</color>
<color name="LoveRed">#E41B17</color>
<color name="Grapefruit">#DC381F</color>
<color name="ChestnutRed">#C34A2C</color>
<color name="CherryRed">#C24641</color>
<color name="Mahogany">#C04000</color>
<color name="ChilliPepper">#C11B17</color>
<color name="Cranberry">#9F000F</color>
<color name="RedWine">#990012</color>
<color name="Burgundy">#8C001A</color>
<color name="BloodRed">#7E3517</color>
<color name="Sienna">#8A4117</color>
<color name="Sangria">#7E3817</color>
<color name="Firebrick">#800517</color>
<color name="Maroon">#810541</color>
<color name="PlumPie">#7D0541</color>
<color name="VelvetMaroon">#7E354D</color>
<color name="PlumVelvet">#7D0552</color>
<color name="RosyFinch">#7F4E52</color>
<color name="Puce">#7F5A58</color>
<color name="DullPurple">#7F525D</color>
<color name="RosyBrown">#B38481</color>
<color name="KhakiRose">#C5908E</color>
<color name="PinkBow">#C48189</color>
<color name="LipstickPink">#C48793</color>
<color name="Rose">#E8ADAA</color>
<color name="DesertSand">#EDC9AF</color>
<color name="PigPink">#FDD7E4</color>
<color name="CottonCandy">#FCDFFF</color>
<color name="PinkBubblegum">#FFDFDD</color>
<color name="MistyRose">#FBBBB9</color>
<color name="Pink">#FAAFBE</color>
<color name="LightPink">#FAAFBA</color>
<color name="FlamingoPink">#F9A7B0</color>
<color name="PinkRose">#E7A1B0</color>
<color name="PinkDaisy">#E799A3</color>
<color name="CadillacPink">#E38AAE</color>
<color name="CarnationPink">#F778A1</color>
<color name="BlushRed">#E56E94</color>
<color name="HotPink">#F660AB</color>
<color name="WatermelonPink">#FC6C85</color>
<color name="VioletRed">#F6358A</color>
<color name="DeepPink">#F52887</color>
<color name="PinkCupcake">#E45E9D</color>
<color name="PinkLemonade">#E4287C</color>
<color name="NeonPink">#F535AA</color>
<color name="Magenta">#FF00FF</color>
<color name="DimorphothecaMagenta">#E3319D</color>
<color name="BrightNeonPink">#F433FF</color>
<color name="PaleVioletRed">#D16587</color>
<color name="TulipPink">#C25A7C</color>
<color name="MediumVioletRed">#CA226B</color>
<color name="RoguePink">#C12869</color>
<color name="BurntPink">#C12267</color>
<color name="BashfulPink">#C25283</color>
<color name="Carnation_Pink">#C12283</color>
<color name="Plum">#B93B8F</color>
<color name="ViolaPurple">#7E587E</color>
<color name="PurpleIris">#571B7E</color>
<color name="PlumPurple">#583759</color>
<color name="Indigo">#4B0082</color>
<color name="PurpleMonster">#461B7E</color>
<color name="PurpleHaze">#4E387E</color>
<color name="Eggplant">#614051</color>
<color name="Grape">#5E5A80</color>
<color name="PurpleJam">#6A287E</color>
<color name="DarkOrchid">#7D1B7E</color>
<color name="PurpleFlower">#A74AC7</color>
<color name="MediumOrchid">#B048B5</color>
<color name="PurpleAmethyst">#6C2DC7</color>
<color name="DarkViolet">#842DCE</color>
<color name="Violet">#8D38C9</color>
<color name="PurpleSageBush">#7A5DC7</color>
<color name="LovelyPurple">#7F38EC</color>
<color name="Purple">#8E35EF</color>
<color name="AztechPurple">#893BFF</color>
<color name="MediumPurple">#8467D7</color>
<color name="JasminePurple">#A23BEC</color>
<color name="PurpleDaffodil">#B041FF</color>
<color name="TyrianPurple">#C45AEC</color>
<color name="CrocusPurple">#9172EC</color>
<color name="PurpleMimosa">#9E7BFF</color>
<color name="HeliotropePurple">#D462FF</color>
<color name="Crimson">#E238EC</color>
<color name="PurpleDragon">#C38EC7</color>
<color name="Lilac">#C8A2C8</color>
<color name="BlushPink">#E6A9EC</color>
<color name="Mauve">#E0B0FF</color>
<color name="WiseriaPurple">#C6AEC7</color>
<color name="BlossomPink">#F9B7FF</color>
<color name="Thistle">#D2B9D3</color>
<color name="Periwinkle">#E9CFEC</color>
<color name="LavenderPinocchio">#EBDDE2</color>
<color name="Lavender">#E3E4FA</color>
<color name="Pearl">#FDEEF4</color>
<color name="SeaShell">#FFF5EE</color>
<color name="MilkWhite">#FEFCFF</color>
<color name="White">#FFFFFF</color>

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

php_network_getaddresses: getaddrinfo failed: Name or service not known

$url = "http://user:[email protected]/abc.php?var1=def";
$contents = file_get_contents($url);
echo $contents;

How to parse XML using vba

Here is a short sub to parse a MicroStation Triforma XML file that contains data for structural steel shapes.

'location of triforma structural files
'c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml

Sub ReadTriformaImperialData()
Dim txtFileName As String
Dim txtFileLine As String
Dim txtFileNumber As Long

Dim Shape As String
Shape = "w12x40"

txtFileNumber = FreeFile
txtFileName = "c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml"

Open txtFileName For Input As #txtFileNumber

Do While Not EOF(txtFileNumber)
Line Input #txtFileNumber, txtFileLine
    If InStr(1, UCase(txtFileLine), UCase(Shape)) Then
        P1 = InStr(1, UCase(txtFileLine), "D=")
        D = Val(Mid(txtFileLine, P1 + 3))

        P2 = InStr(1, UCase(txtFileLine), "TW=")
        TW = Val(Mid(txtFileLine, P2 + 4))

        P3 = InStr(1, UCase(txtFileLine), "WIDTH=")
        W = Val(Mid(txtFileLine, P3 + 7))

        P4 = InStr(1, UCase(txtFileLine), "TF=")
        TF = Val(Mid(txtFileLine, P4 + 4))

        Close txtFileNumber
        Exit Do
    End If
Loop
End Sub

From here you can use the values to draw the shape in MicroStation 2d or do it in 3d and extrude it to a solid.

How can I generate random number in specific range in Android?

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Div Scrollbar - Any way to style it?

No, you can't in Firefox, Safari, etc. You can in Internet Explorer. There are several scripts out there that will allow you to make a scroll bar.

How to disable scrolling in UITableView table when the content fits on the screen

You can edit this in your storyboard (if you are using one). Under the table view there is a checkbox that says "Scrolling Enabled". Uncheck it and you're done.

Download File Using Javascript/jQuery

I have had good results with using a FORM tag since it works everywhere and you don't have to create temporarily files on server. The method works like this.

On the client side (page HTML) you create an invisible form like this

<form method="POST" action="/download.php" target="_blank" id="downloadForm">
    <input type="hidden" name="data" id="csv">
</form>

Then you add this Javascript code to your button:

$('#button').click(function() {
     $('#csv').val('---your data---');
     $('#downloadForm').submit();
}

The on the server-side you have the following PHP code in download.php:

<?php
header('Content-Type: text/csv');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=out.csv');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($data));

echo $_REQUEST['data'];
exit();

You can even create zip files of your data like this:

<?php

$file = tempnam("tmp", "zip");

$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
$zip->addFromString('test.csv', $_REQUEST['data']);
$zip->close();

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file); 

The best part is it does not leave any residual files on your server since everything is created and destroyed on the fly!

Error Code: 1406. Data too long for column - MySQL

Besides the answer given above, I just want to add that this error can also occur while importing data with incorrect lines terminated character.

For example I save the dump file in csv format in windows. then while importing

LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
 FIELDS TERMINATED BY ',' 
 ENCLOSED BY '"'
 ESCAPED BY '"'
 LINES TERMINATED BY '\n'
IGNORE 1 LINES;

Windows saved end of line as \r\n (i.e. CF LF) where as I was using \n. I was getting crazy why phpMyAdmin was able to import the file while I couldn't. Only when I open the file in notepadd++ and saw the end of file then I realized that mysql was unable to find any lines terminated symbol (and I guess it consider all the lines as input to the field; making it complain.)

Anyway after making from \n to \r\n; it work like a charm.

LOAD DATA INFILE '/path_to_csv_folder/db.csv' INTO TABLE table1
 FIELDS TERMINATED BY ',' 
 ENCLOSED BY '"'
 ESCAPED BY '"'
 LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Is there a library function for Root mean square error (RMSE) in python?

Just in case someone finds this thread in 2019, there is a library called ml_metrics which is available without pre-installation in Kaggle's kernels, pretty lightweighted and accessible through pypi ( it can be installed easily and fast with pip install ml_metrics):

from ml_metrics import rmse
rmse(actual=[0, 1, 2], predicted=[1, 10, 5])
# 5.507570547286102

It has few other interesting metrics which are not available in sklearn, like mapk.

References:

How do I print out the contents of an object in Rails for easy debugging?

define the to_s method in your model. For example

class Person < ActiveRecord::Base
  def to_s
    "Name:#{self.name} Age:#{self.age} Weight: #{self.weight}"
  end
end

Then when you go to print it with #puts it will display that string with those variables.

In Excel, sum all values in one column in each row where another column is a specific value

You could do this using SUMIF. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:

 -   A         B
 1   100       YES
 2   100       YES
 3   100       NO

Using the formula: =SUMIF(B1:B3, "YES", A1:A3), you will get the result of 200.

Here's a screenshot of a working example I just did in Excel:

Excel SUMIF Example

Set initially selected item in Select list in Angular2

If you use

<select [ngModel]="object">
    <option *ngFor="let object of objects" [ngValue]="object">{{object.name}}</option>
</select>

You need to set the property object in you components class to the item from objects that you want to have pre-selected.

class MyComponent {
  object;
  objects = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
  constructor() {
    this.object = this.objects[1];
  }
}

Compression/Decompression string with C#

With the advent of .NET 4.0 (and higher) with the Stream.CopyTo() methods, I thought I would post an updated approach.

I also think the below version is useful as a clear example of a self-contained class for compressing regular strings to Base64 encoded strings, and vice versa:

public static class StringCompression
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Here’s another approach using the extension methods technique to extend the String class to add string compression and decompression. You can drop the class below into an existing project and then use thusly:

var uncompressedString = "Hello World!";
var compressedString = uncompressedString.Compress();

and

var decompressedString = compressedString.Decompress();

To wit:

public static class Extensions
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(this string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(this string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Bash integer comparison

The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1.

(("$#" < 1)) && ( (("$1" != 1)) ||  (("$1" -ne 0q)) )

Your boolean logic is also a bit confused:

(( "$#" < 1 && # If the number of arguments is less than one…
  "$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?

This is probably what you want:

(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1

How to parse a JSON string to an array using Jackson

I finally got it:

ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));

Which websocket library to use with Node.js?

Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.

  • ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.

  • websocket-node WebSocket server and client for node.js

  • websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node

  • faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs

  • socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.

  • sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks

  • faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages

  • deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response

  • socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.

  • primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.

When to use:

  • use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities

  • use the fallback libraries when you care about browser fallbacks

  • use the full featured libraries when you care about channels

  • use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.

Where to test:

Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.

Make $JAVA_HOME easily changable in Ubuntu

Try these steps.

--We are going to edit "etc\profile". The environment variables are to be input at the bottom of the file. Since Ubuntu does not give access to root folder, we will have to use a few commands in the terminal

Step1: Start Terminal. Type in command: gksudo gedit /etc/profile

Step2: The profile text file will open. Enter the environment variables at the bottom of the page........... Eg: export JAVA_HOME=/home/alex/jdk1.6.0_22/bin/java

export PATH=/home/alex/jdk1.6.0_22/bin:$PATH

step3: save and close the file. Check if the environment variables are set by using echo command........ Eg echo $PATH

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

Remove all whitespaces from NSString

- (NSString *)removeWhitespaces {
  return [[self componentsSeparatedByCharactersInSet:
                    [NSCharacterSet whitespaceCharacterSet]]
      componentsJoinedByString:@""];
}

Get $_POST from multiple checkboxes

Edit To reflect what @Marc said in the comment below.

You can do a loop through all the posted values.

HTML:

<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />

PHP:

foreach($_POST['check_list'] as $item){
  // query to delete where item = $item
}

How to pass data to view in Laravel?

You can pass your table data to view using compact.

$users = RoleModel::get();
 return view('super-admin',compact('users'));

How can I autoplay a video using the new embed code style for Youtube?

Actually, you will have to use the "?" instead of "&" for your first parameter only. If you use more than one parameter, you will then have to add "&" to the chain.

For instance, if you want to add autoplay and closed captioning, you will have to add this portion to your embedded video URL: ?autoplay=1&cc_load_policy=1.

It would look like this:

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0?autoplay=1&cc_load_policy=1" frameborder="0"
allowfullscreen></iframe>

How to update primary key

You shouldn't really do this but insert in a new record instead and update it that way.
But, if you really need to, you can do the following:

  • Disable enforcing FK constraints temporarily (e.g. ALTER TABLE foo WITH NOCHECK CONSTRAINT ALL)
  • Then update your PK
  • Then update your FKs to match the PK change
  • Finally enable back enforcing FK constraints

How to reference image resources in XAML?

  1. Add folders to your project and add images to these through "Existing Item".
  2. XAML similar to this: <Image Source="MyRessourceDir\images\addButton.png"/>
  3. F6 (Build)

What is makeinfo, and how do I get it?

If you build packages from scratch:

Specifically, if you build bash from source, install docs, including man pages, will fail (silently) without makeinfo available.

MySQL select 10 random rows from 600K rows fast

A great post handling several cases, from simple, to gaps, to non-uniform with gaps.

http://jan.kneschke.de/projects/mysql/order-by-rand/

For most general case, here is how you do it:

SELECT name
  FROM random AS r1 JOIN
       (SELECT CEIL(RAND() *
                     (SELECT MAX(id)
                        FROM random)) AS id)
        AS r2
 WHERE r1.id >= r2.id
 ORDER BY r1.id ASC
 LIMIT 1

This supposes that the distribution of ids is equal, and that there can be gaps in the id list. See the article for more advanced examples

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

Declare an empty two-dimensional array in Javascript?

You can fill an array with arrays using a function:

var arr = [];
var rows = 11;
var columns = 12;

fill2DimensionsArray(arr, rows, columns);

function fill2DimensionsArray(arr, rows, columns){
    for (var i = 0; i < rows; i++) {
        arr.push([0])
        for (var j = 0; j < columns; j++) {
            arr[i][j] = 0;
        }
    }
}

The result is:

Array(11)
0:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
6:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
8:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
10:(12)[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Saving an Excel sheet in a current directory with VBA

Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:

workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"

Only works if your file structure contains one instance of the text used to replace. YMMV.

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Non-recursive depth first search algorithm

Suppose you want to execute a notification when each node in a graph is visited. The simple recursive implementation is:

void DFSRecursive(Node n, Set<Node> visited) {
  visited.add(n);
  for (Node x : neighbors_of(n)) {  // iterate over all neighbors
    if (!visited.contains(x)) {
      DFSRecursive(x, visited);
    }
  }
  OnVisit(n);  // callback to say node is finally visited, after all its non-visited neighbors
}

Ok, now you want a stack-based implementation because your example doesn't work. Complex graphs might for instance cause this to blow the stack of your program and you need to implement a non-recursive version. The biggest issue is to know when to issue a notification.

The following pseudo-code works (mix of Java and C++ for readability):

void DFS(Node root) {
  Set<Node> visited;
  Set<Node> toNotify;  // nodes we want to notify

  Stack<Node> stack;
  stack.add(root);
  toNotify.add(root);  // we won't pop nodes from this until DFS is done
  while (!stack.empty()) {
    Node current = stack.pop();
    visited.add(current);
    for (Node x : neighbors_of(current)) {
      if (!visited.contains(x)) {
        stack.add(x);
        toNotify.add(x);
      }
    }
  }
  // Now issue notifications. toNotifyStack might contain duplicates (will never
  // happen in a tree but easily happens in a graph)
  Set<Node> notified;
  while (!toNotify.empty()) {
  Node n = toNotify.pop();
  if (!toNotify.contains(n)) {
    OnVisit(n);  // issue callback
    toNotify.add(n);
  }
}

It looks complicated but the extra logic needed for issuing notifications exists because you need to notify in reverse order of visit - DFS starts at root but notifies it last, unlike BFS which is very simple to implement.

For kicks, try following graph: nodes are s, t, v and w. directed edges are: s->t, s->v, t->w, v->w, and v->t. Run your own implementation of DFS and the order in which nodes should be visited must be: w, t, v, s A clumsy implementation of DFS would maybe notify t first and that indicates a bug. A recursive implementation of DFS would always reach w last.

How to have a a razor action link open in a new tab?

You are setting it't type as submit. That means that browser should post your <form> data to the server.

In fact a tag has no type attribute according to w3schools.

So remote type attribute and it should work for you.

Search a text file and print related lines in Python?

Note the potential for an out-of-range index with "i+3". You could do something like:

with open("file.txt", "r") as f:
    searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        k=min(i+3,j)
        for l in searchlines[i:k]: print l,
        print

Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

Get final URL after curl is redirected

Thank you. I ended up implementing your suggestions: curl -i + grep

curl -i http://google.com -L | egrep -A 10 '301 Moved Permanently|302 Found' | grep 'Location' | awk -F': ' '{print $2}' | tail -1

Returns blank if the website doesn't redirect, but that's good enough for me as it works on consecutive redirections.

Could be buggy, but at a glance it works ok.

Get Android shared preferences value in activity/normal class

This is the procedure that seems simplest to me:

SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();

    if (sp.getString("sharedString", null).equals("true")
            || sp.getString("sharedString", null) == null) {
        e.putString("sharedString", "false").commit();
        // Do something
    } else {
        // Do something else
    }

Two divs side by side - Fluid display

Using this CSS for my current site. It works perfect!

#sides{
margin:0;
}
#left{
float:left;
width:75%;
overflow:hidden;
}
#right{
float:left;
width:25%;
overflow:hidden;
} 

Undo a git stash

This will also restore the staging directory:

git stash apply --index

How to merge two files line by line in Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

Downloading an entire S3 bucket?

You may simple get it with s3cmd command:

s3cmd get --recursive --continue s3://test-bucket local-directory/

jQuery - Trigger event when an element is removed from the DOM

Just checked, it is already built-in in current version of JQuery:

jQuery - v1.9.1

jQuery UI - v1.10.2

$("#myDiv").on("remove", function () {
    alert("Element was removed");
})

Important: This is functionality of Jquery UI script (not JQuery), so you have to load both scripts (jquery and jquery-ui) to make it work. Here is example: http://jsfiddle.net/72RTz/

Laravel Eloquent limit and offset

laravel have own function skip for offset and take for limit. just like below example of laravel query :-

Article::where([['user_id','=',auth()->user()->id]])
                ->where([['title','LIKE',"%".$text_val."%"]])
                ->orderBy('id','DESC')
                ->skip(0)
                ->take(2)
                ->get();

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5).

How to use setprecision in C++

The answer above is absolutely correct. Here is a Turbo C++ version of it.

#include <iomanip.h>
#include <iostream.h>

void main()
{
    double num1 = 3.12345678;
    cout << setiosflags(fixed) << setiosflags(showpoint);
    cout << setprecision(2);
    cout << num1 << endl;
}

For fixed and showpoint, I think the setiosflags function should be used.

How to change background Opacity when bootstrap modal is open

You can override the modal-backdrop opacity in your stylesheet [take note of the .in class]

.modal-backdrop.in {
    opacity: 0.9;
}

http://jsfiddle.net/ThisIsMarkSantiago/r0gwn005/1/

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Check if null Boolean is true results in exception

as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.

PHP-FPM doesn't write to error log

This worked for me:

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Default Value: no
catch_workers_output = yes

Edit:

The file to edit is the file that configure your desired pool. By default its: /etc/php-fpm.d/www.conf

How to store values from foreach loop into an array?

this question seem quite old but incase you come pass it, you can use the PHP inbuilt function array_push() to push data in an array using the example below.

<?php
    $item = array();
    foreach($group_membership as $i => $username) {
        array_push($item, $username);
    }
    print_r($items);
?>

How to get bitmap from a url in android?

This should do the trick:

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
} // Author: silentnuke

Don't forget to add the internet permission in your manifest.

A column-vector y was passed when a 1d array was expected

format_train_y=[]
for n in train_y:
    format_train_y.append(n[0])

Formatting DataBinder.Eval data

Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'

This works for the format as you want

MSOnline can't be imported on PowerShell (Connect-MsolService error)

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Create AMI -> Boot AMI on large instance.

More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html

You can do this all from the admin console too at aws.amazon.com

how to count length of the JSON array element

Before going to answer read this Documentation once. Then you clearly understand the answer.

Try this It may work for you.

Object.keys(data.shareInfo[i]).length

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Login to remote site with PHP cURL

This is how I solved this in ImpressPages:

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

C# Test if user has write access to a folder

Simply trying to access the file in question isn't necessarily enough. The test will run with the permissions of the user running the program - Which isn't necessarily the user permissions you want to test against.

Date Conversion from String to sql Date in Java giving different output?

You need to use MM as mm stands for minutes.

There are two ways of producing month pattern.

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01

Full coding snippet:

        String startDate="01-Feb-2013"; // Input String
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
        java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
        java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
        System.out.println(sqlStartDate); // Outputs : 2013-02-01

Get the latest record with filter in Django

last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')

MAX(DATE) - SQL ORACLE

Try:

SELECT MEMBSHIP_ID
  FROM user_payment
 WHERE user_id=1 
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);

Or:

SELECT MEMBSHIP_ID
FROM (
  SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
      FROM user_payment
     WHERE user_id=1 )
WHERE rn = 1

How to convert DateTime to VarChar

CONVERT(VARCHAR, GETDATE(), 23)

How should I escape commas and speech marks in CSV files so they work in Excel?

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

What does the "@" symbol do in SQL?

Its a parameter the you need to define. to prevent SQL Injection you should pass all your variables in as parameters.

How to overlay image with color in CSS?

#header.overlay {
    background-color: SlateGray;
    position:relative;
    width: 100%;
    height: 100%;
    opacity: 0.20;
    -moz-opacity: 20%;
    -webkit-opacity: 20%;
    z-index: 2;
}

Something like this. Just add the overlay class to the header, obviously.

How do you define a class of constants in Java?

Aren't enums best choice for these kinds of stuff?

When to favor ng-if vs. ng-show/ng-hide?

ng-if on ng-include and on ng-controller will have a big impact matter on ng-include it will not load the required partial and does not process unless flag is true on ng-controller it will not load the controller unless flag is true but the problem is when a flag gets false in ng-if it will remove from DOM when flag gets true back it will reload the DOM in this case ng-show is better, for one time show ng-if is better

Accessing bash command line args $@ vs $*

$*

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

$@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Source: Bash man

Using an if statement to check if a div is empty

If you want a quick demo how you check for empty divs I'd suggest you to try this link:

http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/


Below you have some short examples:

Using CSS

If your div is empty without anything even no white-space, you can use CSS:

.someDiv:empty {
    display: none;
}

Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y

.someDiv:empty ~ .anotherDiv {
    display: none;
}

Using jQuery

Checking text length of element with text() function

if ( $('#leftmenu').text().length == 0 ) {
    // length of text is 0
}

Check if element has any children tags inside

if ( $('#leftmenu').children().length == 0 ) {
    // div has no other tags inside it
}

Check for empty elements if they have white-space

if ( $.trim( $('.someDiv').text() ).length == 0 ) {
    // white-space trimmed, div is empty
}

Command copy exited with code 4 when building - Visual Studio restart solves it

Run VS in Administrator mode and it should work fine.

Postgres Error: More than one row returned by a subquery used as an expression

The fundamental problem can often be simply solved by changing an = to IN, in cases where you've got a one-to-many relationship. For example, if you wanted to update or delete a bunch of accounts for a given customer:

WITH accounts_to_delete AS 
    ( 
        SELECT     account_id
        FROM       accounts a
        INNER JOIN customers c
                ON a.customer_id = c.id
        WHERE      c.customer_name='Some Customer'
    )

-- this fails if "Some Customer" has multiple accounts, but works if there's 1:
DELETE FROM accounts
 WHERE accounts.guid = 
( 
    SELECT account_id 
    FROM   accounts_to_delete 
);

-- this succeeds with any number of accounts:
DELETE FROM accounts
 WHERE accounts.guid IN   
( 
    SELECT account_id 
    FROM   accounts_to_delete 
);

Add querystring parameters to link_to

In case you want to pass in a block, say, for a glyphicon button, as in the following:

<%= link_to my_url, class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Then passing querystrings params could be accomplished through:

<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

JFrame.dispose() vs System.exit()

JFrame.dispose()

public void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

System.exit()

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

How to make gradient background in android

Or you can use in code whatever you might think of in PSD:

    private void FillCustomGradient(View v) {
        final View view = v;
        Drawable[] layers = new Drawable[1];

        ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
            @Override
            public Shader resize(int width, int height) {
                LinearGradient lg = new LinearGradient(
                        0,
                        0,
                        0,
                        view.getHeight(),
                        new int[] {
                                 getResources().getColor(R.color.color1), // please input your color from resource for color-4
                                 getResources().getColor(R.color.color2),
                                 getResources().getColor(R.color.color3),
                                 getResources().getColor(R.color.color4)},
                        new float[] { 0, 0.49f, 0.50f, 1 },
                        Shader.TileMode.CLAMP);
                return lg;
            }
        };
        PaintDrawable p = new PaintDrawable();
        p.setShape(new RectShape());
        p.setShaderFactory(sf);
        p.setCornerRadii(new float[] { 5, 5, 5, 5, 0, 0, 0, 0 });
        layers[0] = (Drawable) p;

        LayerDrawable composite = new LayerDrawable(layers);
        view.setBackgroundDrawable(composite);
    }

Insert Update trigger how to determine if insert or update

I like solutions that are "computer science elegant." My solution here hits the [inserted] and [deleted] pseudotables once each to get their statuses and puts the result in a bit mapped variable. Then each possible combination of INSERT, UPDATE and DELETE can readily be tested throughout the trigger with efficient binary evaluations (except for the unlikely INSERT or DELETE combination).

It does make the assumption that it does not matter what the DML statement was if no rows were modified (which should satisfy the vast majority of cases). So while it is not as complete as Roman Pekar's solution, it is more efficient.

With this approach, we have the possibility of one "FOR INSERT, UPDATE, DELETE" trigger per table, giving us A) complete control over action order and b) one code implementation per multi-action-applicable action. (Obviously, every implementation model has its pros and cons; you will need to evaluate your systems individually for what really works best.)

Note that the "exists (select * from «inserted/deleted»)" statements are very efficient since there is no disk access (https://social.msdn.microsoft.com/Forums/en-US/01744422-23fe-42f6-9ab0-a255cdf2904a).

use tempdb
;
create table dbo.TrigAction (asdf int)
;
GO
create trigger dbo.TrigActionTrig
on dbo.TrigAction
for INSERT, UPDATE, DELETE
as
declare @Action tinyint
;
-- Create bit map in @Action using bitwise OR "|"
set @Action = (-- 1: INSERT, 2: DELETE, 3: UPDATE, 0: No Rows Modified 
  (select case when exists (select * from inserted) then 1 else 0 end)
| (select case when exists (select * from deleted ) then 2 else 0 end))
;
-- 21 <- Binary bit values
-- 00 -> No Rows Modified
-- 01 -> INSERT -- INSERT and UPDATE have the 1 bit set
-- 11 -> UPDATE <
-- 10 -> DELETE -- DELETE and UPDATE have the 2 bit set

raiserror(N'@Action = %d', 10, 1, @Action) with nowait
;
if (@Action = 0) raiserror(N'No Data Modified.', 10, 1) with nowait
;
-- do things for INSERT only
if (@Action = 1) raiserror(N'Only for INSERT.', 10, 1) with nowait
;
-- do things for UPDATE only
if (@Action = 3) raiserror(N'Only for UPDATE.', 10, 1) with nowait
;
-- do things for DELETE only
if (@Action = 2) raiserror(N'Only for DELETE.', 10, 1) with nowait
;
-- do things for INSERT or UPDATE
if (@Action & 1 = 1) raiserror(N'For INSERT or UPDATE.', 10, 1) with nowait
;
-- do things for UPDATE or DELETE
if (@Action & 2 = 2) raiserror(N'For UPDATE or DELETE.', 10, 1) with nowait
;
-- do things for INSERT or DELETE (unlikely)
if (@Action in (1,2)) raiserror(N'For INSERT or DELETE.', 10, 1) with nowait
-- if already "return" on @Action = 0, then use @Action < 3 for INSERT or DELETE
;
GO

set nocount on;

raiserror(N'
INSERT 0...', 10, 1) with nowait;
insert dbo.TrigAction (asdf) select top 0 object_id from sys.objects;

raiserror(N'
INSERT 3...', 10, 1) with nowait;
insert dbo.TrigAction (asdf) select top 3 object_id from sys.objects;

raiserror(N'
UPDATE 0...', 10, 1) with nowait;
update t set asdf = asdf /1 from dbo.TrigAction t where asdf <> asdf;

raiserror(N'
UPDATE 3...', 10, 1) with nowait;
update t set asdf = asdf /1 from dbo.TrigAction t;

raiserror(N'
DELETE 0...', 10, 1) with nowait;
delete t from dbo.TrigAction t where asdf < 0;

raiserror(N'
DELETE 3...', 10, 1) with nowait;
delete t from dbo.TrigAction t;
GO

drop table dbo.TrigAction
;
GO

Detect encoding and make everything UTF-8

php.net/mb_detect_encoding

echo mb_detect_encoding($str, "auto");

or

echo mb_detect_encoding($str, "UTF-8, ASCII, ISO-8859-1");

i really don't know what the results are, but i'd suggest you just take some of your feeds with different encodings and try if mb_detect_encoding works or not.

update
auto is short for "ASCII,JIS,UTF-8,EUC-JP,SJIS". it returns the detected charset, which you can use to convert the string to utf-8 with iconv.

<?php
function convertToUTF8($str) {
    $enc = mb_detect_encoding($str);

    if ($enc && $enc != 'UTF-8') {
        return iconv($enc, 'UTF-8', $str);
    } else {
        return $str;
    }
}
?>

i haven't tested it, so no guarantee. and maybe there's a simpler way.

Could not find server 'server name' in sys.servers. SQL Server 2014

I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"

What's the best practice for primary keys in tables?

You should use a 'composite' or 'compound' primary key that comprises of multiple fields.

This is a perfectly acceptable solution, go here for more info :)

Get index of a key/value pair in a C# dictionary based on the value

In your comment to max's answer, you say that what you really wanted to get is the key in, and not the index of, the KeyValuePair that contains a certain value. You could edit your question to make it more clear.

It is worth pointing out (EricM has touched upon this in his answer) that a value might appear more than once in the dictionary, in which case one would have to think which key he would like to get: e.g. the first that comes up, the last, all of them?

If you are sure that each key has a unique value, you could have another dictionary, with the values from the first acting as keys and the previous keys acting as values. Otherwise, this second dictionary idea (suggested by Jon Skeet) will not work, as you would again have to think which of all the possible keys to use as value in the new dictionary.

If you were asking about the index, though, EricM's answer would be OK. Then you could get the KeyValuePair in question by using:

yourDictionary.ElementAt(theIndexYouFound);

provided that you do not add/remove things in yourDictionary.

PS: I know it's been almost 7 years now, but what the heck. I thought it best to formulate my answer as addressing the OP, but of course by now one can say it is an answer for just about anyone else but the OP. Fully aware of that, thank you.

how to refresh my datagridview after I add new data

In the code of the button that saves the changes to the database eg the update button, add the following lines of code:

MyDataGridView.DataSource = MyTableBindingSource

MyDataGridView.Update()

MyDataGridView.RefreshEdit()

Group by in LINQ

The following example uses the GroupBy method to return objects that are grouped by PersonID.

var results = persons.GroupBy(x => x.PersonID)
              .Select(x => (PersonID: x.Key, Cars: x.Select(p => p.car).ToList())
              ).ToList();

Or

 var results = persons.GroupBy(
               person => person.PersonID,
               (key, groupPerson) => (PersonID: key, Cars: groupPerson.Select(x => x.car).ToList()));

Or

 var results = from person in persons
               group person by person.PersonID into groupPerson
               select (PersonID: groupPerson.Key, Cars: groupPerson.Select(x => x.car).ToList());

Or you can use ToLookup, Basically ToLookup uses EqualityComparer<TKey>.Default to compare keys and do what you should do manually when using group by and to dictionary. i think it's excuted inmemory

 ILookup<int, string> results = persons.ToLookup(
            person => person.PersonID,
            person => person.car);

API Gateway CORS: no 'Access-Control-Allow-Origin' header

Another root cause of this problem might be a difference between HTTP/1.1 and HTTP/2.

Symptom: Some users, not all of them, reported to get a CORS error when using our Software.

Problem: The Access-Control-Allow-Origin header was missing sometimes.

Context: We had a Lambda in place, dedicated to handling OPTIONS request and replying with the corresponding CORS headers, such as Access-Control-Allow-Origin matching a whitelisted Origin.

Solution: The API Gateway seems to transform all headers to lower-case for HTTP/2 calls, but maintains capitalization for HTTP/1.1. This caused the access to event.headers.origin to fail.

Check if you're having this issue too:

Assuming your API is located at https://api.example.com, and your front-end is at https://www.example.com. Using CURL, make a request using HTTP/2:

curl -v -X OPTIONS -H 'Origin: https://www.example.com' https://api.example.com

The response output should include the header:

< Access-Control-Allow-Origin: https://www.example.com

Repeat the same step using HTTP/1.1 (or with a lowercase Origin header):

curl -v -X OPTIONS --http1.1 -H 'Origin: https://www.example.com' https://api.example.com

If the Access-Control-Allow-Origin header is missing, you might want to check case sensitivity when reading the Origin header.

How to drop columns using Rails migration

Heres one more from rails console

ActiveRecord::Migration.remove_column(:table_name, :column_name)

Create Directory if it doesn't exist with Ruby

Simple way:

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

find the array index of an object with a specific key value in underscore

Lo-Dash, which extends Underscore, has findIndex method, that can find the index of a given instance, or by a given predicate, or according to the properties of a given object.

In your case, I would do:

var index = _.findIndex(tv, { id: voteID });

Give it a try.

GitLab git user password

You may usually if you have multiple keys setup via ssh on your system (my device is running Windows 10), you will encounter this issue, the fix is to:

Precondition: Setup up your SSH Keys as indicated by GitLab

  1. open /c/Users//.ssh/config file with Notepad++ or your favourite editor
  2. paste the following inside it. Host IdentityFile ~/.ssh/

Please note, there is a space before the second line, very important to avoid this solution not working.

How to refresh Android listview?

I was the same when, in a fragment, I wanted to populate a ListView (in a single TextView) with the mac address of BLE devices scanned over some time.

What I did was this:

public class Fragment01 extends android.support.v4.app.Fragment implements ...
{
    private ListView                listView;
    private ArrayAdapter<String>    arrayAdapter_string;

...

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    ...
    this.listView= (ListView) super.getActivity().findViewById(R.id.fragment01_listView);
    ...
    this.arrayAdapter_string= new ArrayAdapter<String>(super.getActivity(), R.layout.dispositivo_ble_item, R.id.fragment01_item_textView_titulo);
    this.listView.setAdapter(this.arrayAdapter_string);
}


@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
    ...
    super.getActivity().runOnUiThread(new RefreshListView(device));
}


private class RefreshListView implements Runnable
{
    private BluetoothDevice bluetoothDevice;

    public RefreshListView(BluetoothDevice bluetoothDevice)
    {
        this.bluetoothDevice= bluetoothDevice;
    }

    @Override
    public void run()
    {
        Fragment01.this.arrayAdapter_string.add(new String(bluetoothDevice.toString()));
        Fragment01.this.arrayAdapter_string.notifyDataSetChanged();
    }
}

Then the ListView began to dynamically populate with the mac address of the devices found.

Using a dictionary to select function to execute

class CallByName():
    
    def method1(self):
        pass

    def method2(self):
        pass

    def method3(self):
        pass

    def get_method(self, method_name):
        method = getattr(self, method_name)
        return method()


callbyname = CallByName()
method1 = callbyname.get_method(method_name)

```

Setting an int to Infinity in C++

This is a message for me in the future:

Just use: (unsigned)!((int)0)

It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned

Even better

#define INF (unsigned)!((int)0)

And then just use INF in your code

C# adding a character in a string

string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
  newAlpha = alpha.Insert(i, "-");
  alpha = newAlpha;
}

Offset a background image from the right using CSS

yes! well to position a background image as though 0px from the right-hand side of the browser instead of the left - i use:

background-position: 100% 0px;

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

Stacked Tabs in Bootstrap 3

You should not need to add this back in. This was removed purposefully. The documentation has changed somewhat and the CSS class that is necessary ("nav-stacked") is only mentioned under the pills component, but should work for tabs as well.

This tutorial shows how to use the Bootstrap 3 setup properly to do vertical tabs:
tutsme-webdesign.info/bootstrap-3-toggable-tabs-and-pills

Java int to String - Integer.toString(i) vs new Integer(i).toString()

new Integer(i).toString() first creates a (redundant) wrapper object around i (which itself may be a wrapper object Integer).

Integer.toString(i) is preferred because it doesn't create any unnecessary objects.

Displaying the Error Messages in Laravel after being Redirected from controller

{!! Form::text('firstname', null !!}

@if($errors->has('firstname')) 
    {{ $errors->first('firstname') }} 
@endif

Critical t values in R

The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:

abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))

Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value

abs(qt(0.01/2, 40)) # 99% confidence, 2 sided

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

I liked Jed's solution but the issue with that was every time I built my project in debug mode, it would deploy my database project and removed the user again. so I added this MySQL script to the Post-Deployment script. it practically does what Jed said but creates the user every time I deploy.

CREATE USER [NT AUTHORITY\NETWORK SERVICE]
    FOR LOGIN [NT AUTHORITY\NETWORK SERVICE]
    WITH DEFAULT_SCHEMA = dbo;
Go

EXEC sp_addrolemember 'db_owner', 'NT AUTHORITY\NETWORK SERVICE'

How do I add the contents of an iterable to a set?

Use list comprehension.

Short circuiting the creation of iterable using a list for example :)

>>> x = [1, 2, 3, 4]
>>> 
>>> k = x.__iter__()
>>> k
<listiterator object at 0x100517490>
>>> l = [y for y in k]
>>> l
[1, 2, 3, 4]
>>> 
>>> z = Set([1,2])
>>> z.update(l)
>>> z
set([1, 2, 3, 4])
>>> 

[Edit: missed the set part of question]

(413) Request Entity Too Large | uploadReadAheadSize

For me, setting the uploadReadAheadSize to int.MaxValue also fixed the problem, after also increasing the limits on the WCF binding.

It seems that, when using SSL, the entire request entity body is preloaded, for which this metabase property is used.

For more info, see:

The page was not displayed because the request entity is too large. iis7

Correct way of getting Client's IP Addresses from http.Request

Looking at http.Request you can find the following member variables:

// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header

// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string

You can use RemoteAddr to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).

This is all you have for sure.

Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:

req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter

This is because internally http.Header.Get will normalise the key for you. (If you want to access header map directly, and not through Get, you would need to use http.CanonicalHeaderKey first.)

Finally, "X-Forwarded-For" is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:

// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
    fmt.Println(ip)
}

will produce:

10.0.0.1
10.0.0.2
10.0.0.3

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

You just need to add three file and two css links. You can either cdn's as well. Links for the js files and css files are as such :-

  1. jQuery.dataTables.min.js
  2. dataTables.bootstrap.min.js
  3. dataTables.bootstrap.min.css
  4. bootstrap-datepicker.css
  5. bootstrap-datepicker.js

They are valid if you are using bootstrap in your project.

I hope this will help you. Regards, Vivek Singla

What are the differences between B trees and B+ trees?

B+ Trees are especially good in block-based storage (eg: hard disk). with this in mind, you get several advantages, for example (from the top of my head):

  • high fanout / low depth: that means you have to get less blocks to get to the data. with data intermingled with the pointers, each read gets less pointers, so you need more seeks to get to the data

  • simple and consistent block storage: an inner node has N pointers, nothing else, a leaf node has data, nothing else. that makes it easy to parse, debug and even reconstruct.

  • high key density means the top nodes are almost certainly on cache, in many cases all inner nodes get quickly cached, so only the data access has to go to disk.

Exception is never thrown in body of corresponding try statement

Any class which extends Exception class will be a user defined Checked exception class where as any class which extends RuntimeException will be Unchecked exception class. as mentioned in User defined exception are checked or unchecked exceptions So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.

Checked exception are the exceptions that are checked at compile time.

Unchecked exception are the exceptions that are not checked at compiled time

add controls vertically instead of horizontally using flow layout

JPanel testPanel = new JPanel();
testPanel.setLayout(new BoxLayout(testPanel, BoxLayout.Y_AXIS));
/*add variables here and add them to testPanel
        e,g`enter code here`
        testPanel.add(nameLabel);
        testPanel.add(textName);
*/
testPanel.setVisible(true);

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

<meta property="og:url" content="http://www.mywebaddress.com"/>

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

Stopping a thread after a certain amount of time

If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.

If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).

Trying to load local JSON file to show data in a html page using JQuery

You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.

index.html:

<html>
<head>
</head>
<body>
  <script src="data.js"></script>
</body>
</html>

data.js:

var data = {
  "start": {
    "count": "5",
    "title": "start",
    "priorities": [{
      "txt": "Work"
    }, {
      "txt": "Time Sense"
    }, {
      "txt": "Dicipline"
    }, {
      "txt": "Confidence"
    }, {
      "txt": "CrossFunctional"
    }]
  }
}

Html.DropDownList - Disabled/Readonly

Regarding the catch 22:

If we use @disabled, the field is not sent to the action (Mamoud) And if we use @readonly, the drop down bug still lets you change the value

Workaround: use @disabled, and add the field hidden after the drop down:

@Html.HiddenFor(model => model.xxxxxxxx)

Then it is truly disabled, and sent to the to the action too.

How to append binary data to a buffer in node.js

Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.

However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.

Revert a jQuery draggable object back to its original container on out event of droppable

$(function() {
    $("#draggable").draggable({
        revert : function(event, ui) {
            // on older version of jQuery use "draggable"
            // $(this).data("draggable")
            // on 2.x versions of jQuery use "ui-draggable"
            // $(this).data("ui-draggable")
            $(this).data("uiDraggable").originalPosition = {
                top : 0,
                left : 0
            };
            // return boolean
            return !event;
            // that evaluate like this:
            // return event !== false ? false : true;
        }
    });
    $("#droppable").droppable();
});

Choosing line type and color in Gnuplot 4.0

You need to use linecolor instead of lc, like:

set style line 1 lt 1 lw 3 pt 3 linecolor rgb "red"

"help set style line" gives you more info.

Hexadecimal to Integer in Java

Try this

public static long Hextonumber(String hexval)
    {
        hexval="0x"+hexval;
//      String decimal="0x00000bb9";
        Long number = Long.decode(hexval);
//.......       System.out.println("String [" + hexval + "] = " + number);
        return number;
        //3001
    }

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

PHP Fatal error: Uncaught exception 'Exception'

This is expected behavior for an uncaught exception with display_errors off.

Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.

 ini_set("display_errors", 1);

or

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");

Android: How to detect double-tap?

public class MyView extends View {

GestureDetector gestureDetector;

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
            // creating new gesture detector
    gestureDetector = new GestureDetector(context, new GestureListener());
}

// skipping measure calculation and drawing

    // delegate the event to the gesture detector
@Override
public boolean onTouchEvent(MotionEvent e) {
    return gestureDetector.onTouchEvent(e);
}


private class GestureListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }
    // event when double tap occurs
    @Override
    public boolean onDoubleTap(MotionEvent e) {
        float x = e.getX();
        float y = e.getY();

        Log.d("Double Tap", "Tapped at: (" + x + "," + y + ")");

        return true;
    }
}
}

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

Regular expression for matching HH:MM time format

You can use this regular expression:

^(2[0-3]|[01]?[0-9]):([1-5]{1}[0-9])$

If you want to exclude 00:00, you can use this expression

^(2[0-3]|[01]?[0-9]):(0[1-9]{1}|[1-5]{1}[0-9])$

Second expression is better option because valid time is 00:01 to 00:59 or 0:01 to 23:59. You can use any of these upon your requirement. Regex101 link

How can I return to a parent activity correctly?

In Java class :-

    toolbar = (Toolbar) findViewById(R.id.apptool_bar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setTitle("Snapdeal");

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

In Manifest :-

<activity
            android:name=".SubActivity"
            android:label="@string/title_activity_sub"
            android:theme="@style/AppTheme" >
            <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"></meta-data>
    </activity>

It will help you

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

How to determine if a String has non-alphanumeric characters?

Though it won't work for numbers, you can check if the lowercase and uppercase values are same or not, For non-alphabetic characters they will be same, You should check for number before this for better usability

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

Behavior differences

Some differences on Bash 4.3.11:

  • POSIX vs Bash extension:

  • regular command vs magic

    • [ is just a regular command with a weird name.

      ] is just the last argument of [.

    Ubuntu 16.04 actually has an executable for it at /usr/bin/[ provided by coreutils, but the bash built-in version takes precedence.

    Nothing is altered in the way that Bash parses the command.

    In particular, < is redirection, && and || concatenate multiple commands, ( ) generates subshells unless escaped by \, and word expansion happens as usual.

    • [[ X ]] is a single construct that makes X be parsed magically. <, &&, || and () are treated specially, and word splitting rules are different.

      There are also further differences like = and =~.

    In Bashese: [ is a built-in command, and [[ is a keyword: https://askubuntu.com/questions/445749/whats-the-difference-between-shell-builtin-and-shell-keyword

  • <

  • && and ||

    • [[ a = a && b = b ]]: true, logical and
    • [ a = a && b = b ]: syntax error, && parsed as an AND command separator cmd1 && cmd2
    • [ a = a ] && [ b = b ]: POSIX reliable equivalent
    • [ a = a -a b = b ]: almost equivalent, but deprecated by POSIX because it is insane and fails for some values of a or b like ! or ( which would be interpreted as logical operations
  • (

    • [[ (a = a || a = b) && a = b ]]: false. Without ( ), would be true because [[ && ]] has greater precedence than [[ || ]]
    • [ ( a = a ) ]: syntax error, () is interpreted as a subshell
    • [ \( a = a -o a = b \) -a a = b ]: equivalent, but (), -a, and -o are deprecated by POSIX. Without \( \) would be true because -a has greater precedence than -o
    • { [ a = a ] || [ a = b ]; } && [ a = b ] non-deprecated POSIX equivalent. In this particular case however, we could have written just: [ a = a ] || [ a = b ] && [ a = b ] because the || and && shell operators have equal precedence unlike [[ || ]] and [[ && ]] and -o, -a and [
  • word splitting and filename generation upon expansions (split+glob)

    • x='a b'; [[ $x = 'a b' ]]: true, quotes not needed
    • x='a b'; [ $x = 'a b' ]: syntax error, expands to [ a b = 'a b' ]
    • x='*'; [ $x = 'a b' ]: syntax error if there's more than one file in the current directory.
    • x='a b'; [ "$x" = 'a b' ]: POSIX equivalent
  • =

    • [[ ab = a? ]]: true, because it does pattern matching (* ? [ are magic). Does not glob expand to files in current directory.
    • [ ab = a? ]: a? glob expands. So may be true or false depending on the files in the current directory.
    • [ ab = a\? ]: false, not glob expansion
    • = and == are the same in both [ and [[, but == is a Bash extension.
    • case ab in (a?) echo match; esac: POSIX equivalent
    • [[ ab =~ 'ab?' ]]: false, loses magic with '' in Bash 3.2 and above and provided compatibility to bash 3.1 is not enabled (like with BASH_COMPAT=3.1)
    • [[ ab? =~ 'ab?' ]]: true
  • =~

    • [[ ab =~ ab? ]]: true, POSIX extended regular expression match, ? does not glob expand
    • [ a =~ a ]: syntax error. No bash equivalent.
    • printf 'ab\n' | grep -Eq 'ab?': POSIX equivalent (single line data only)
    • awk 'BEGIN{exit !(ARGV[1] ~ ARGV[2])}' ab 'ab?': POSIX equivalent.

Recommendation: always use []

There are POSIX equivalents for every [[ ]] construct I've seen.

If you use [[ ]] you:

  • lose portability
  • force the reader to learn the intricacies of another bash extension. [ is just a regular command with a weird name, no special semantics are involved.

Thanks to Stéphane Chazelas for important corrections and additions.

/etc/apt/sources.list" E212: Can't open file for writing

change user to root

sodu su -

browse to etc

vi sudoers

look for root user in user priviledge section. you will get it like

root ALL=(ALL:ALL) ALL 

make same entry for your user name. if you username is 'myuser' then add

myuser ALL=(ALL:ALL) ALL

it will look like

root ALL=(ALL:ALL) ALL 

myuser ALL=(ALL:ALL) ALL 

save it. change root user to your user. now try the same where you were getting the sudoers issue

Align DIV's to bottom or baseline

this works (i only tested ie & ff):

<html>
<head>
    <style type="text/css">
        #parent {
            height: 300px;
            width: 300px;
            background-color: #ccc;
            border: 1px solid red;
            position: relative;
        }
        #child  {
            height: 100px;
            width: 30px;
            background-color: #eee;
            border: 1px solid green;
            position: absolute;
            bottom: 0;
            left: 0;
        }
    </style>
</head>
<body>
    <div id="parent">parent
        <div id="child">child</div>
    </div>
    outside
</body>
</html>

hope that helps.

What is useState() in React?

Thanks loelsonk, i did so

_x000D_
_x000D_
const [dataAction, setDataAction] = useState({name: '', description: ''});_x000D_
_x000D_
    const _handleChangeName = (data) => {_x000D_
        if(data.name)_x000D_
            setDataAction( prevState  => ({ ...prevState,   name : data.name }));_x000D_
        if(data.description)_x000D_
            setDataAction( prevState  => ({ ...prevState,   description : data.description }));_x000D_
    };_x000D_
    _x000D_
    ....return (_x000D_
    _x000D_
          <input onChange={(event) => _handleChangeName({name: event.target.value})}/>_x000D_
          <input onChange={(event) => _handleChangeName({description: event.target.value})}/>_x000D_
    )
_x000D_
_x000D_
_x000D_

Put spacing between divs in a horizontal row?

A possible idea would be to:

  1. delete the width: 25%; float:left; from the style of your divs
  2. wrap each of the four colored divs in a div that has style="width: 25%; float:left;"

The advantage with this approach is that all four columns will have equal width and the gap between them will always be 5px * 2.

Here's what it looks like:

_x000D_
_x000D_
.cellContainer {_x000D_
  width: 25%;_x000D_
  float: left;_x000D_
}
_x000D_
<div style="width:100%; height: 200px; background-color: grey;">_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: red;">A</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: orange;">B</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: green;">C</div>_x000D_
  </div>_x000D_
  <div class="cellContainer">_x000D_
    <div style="margin: 5px; background-color: blue;">D</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Format an Excel column (or cell) as Text in C#?

Before your write to Excel need to change the format:

xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")

Dim cells As Excel.Range = xlWorkSheet.Cells

'set each cell's format to Text
cells.NumberFormat = "@"

'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight

Is there a way to use max-width and height for a background image?

It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.

And if I miss-read the question then I humbly accept the votes down. (Still good to know though)

Please consider the following code:

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

This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";

There are some alternatives that can be used with a little bit peace of mind by using jQuery:

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

jQuery:

 $(window).load(function() {    

var theWindow        = $(window),
    $bg              = $("#bg"),
    aspectRatio      = $bg.width() / $bg.height();

function resizeBg() {

    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
        $bg
            .removeClass()
            .addClass('bgheight');
    } else {
        $bg
            .removeClass()
            .addClass('bgwidth');
    }

}

theWindow.resize(resizeBg).trigger("resize");

});

I hope this helps!

Src: Perfect Full Page Background Image

How to make a UILabel clickable?

For swift 3.0 You can also change gesture long press time duration

label.isUserInteractionEnabled = true
let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:))) 
longPress.minimumPressDuration = 0.2
label.addGestureRecognizer(longPress)

Want to make Font Awesome icons clickable

If you don't want it to add it to a link, you can just enclose it within a span and that would work.

<span id='clickableAwesomeFont'><i class="fa fa-behance-square fa-4x"></span>

in your css, then you can:

#clickableAwesomeFont {
     cursor: pointer
}

Then in java script, you can just add a click handler.

In cases where it's actually not a link, I think this is much cleaner and using a link would be changing its semantics and abusing its meaning.

What is the best workaround for the WCF client `using` block issue?

If you don't need IoC or are using an autogenerated client (Service Reference), then you can simple use a wrapper to manage the closing and let the GC take the clientbase when it is in a safe state that will not throw any exception. The GC will call Dispose in serviceclient, and this will call Close. Since it is alread closed, it cannot cause any damage. I am using this without problems in production code.

public class AutoCloseWcf : IDisposable
{

    private ICommunicationObject CommunicationObject;

    public AutoDisconnect(ICommunicationObject CommunicationObject)
    {
        this.CommunicationObject = CommunicationObject;
    }

    public void Dispose()
    {
        if (CommunicationObject == null)
            return;
        try {
            if (CommunicationObject.State != CommunicationState.Faulted) {
                CommunicationObject.Close();
            } else {
                CommunicationObject.Abort();
            }
        } catch (CommunicationException ce) {
            CommunicationObject.Abort();
        } catch (TimeoutException toe) {
            CommunicationObject.Abort();
        } catch (Exception e) {
            CommunicationObject.Abort();
            //Perhaps log this

        } finally {
            CommunicationObject = null;
        }
    }
}

Then when you are accessing the server, you create the client and use using in the autodisconect:

var Ws = new ServiceClient("netTcpEndPointName");
using (new AutoCloseWcf(Ws)) {

    Ws.Open();

    Ws.Test();
}

How to build & install GLFW 3 and use it in a Linux project

Note that you do not need that many -ls if you install glfw with the BUILD_SHARED_LIBS option. (You can enable this option by running ccmake first).

This way sudo make install will install the shared library in /usr/local/lib/libglfw.so. You can then compile the example file with a simple:

g++ main.cpp -L /usr/local/lib/ -lglfw

Then do not forget to add /usr/local/lib/ to the search path for shared libraries before running your program. This can be done using:

export LD_LIBRARY_PATH=/usr/local/lib:${LD_LIBRARY_PATH}

And you can put that in your ~/.bashrc so you don't have to type it all the time.

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

I used the concept from the answer posted by @marcg and it works great with JPA 2.1. His code wasn't quite right, so I'm posted my working implementation. This will convert Boolean entity fields to a Y/N character column in the database.

From my entity class:

@Convert(converter=BooleanToYNStringConverter.class)
@Column(name="LOADED", length=1)
private Boolean isLoadedSuccessfully;

My converter class:

/**
 * Converts a Boolean entity attribute to a single-character
 * Y/N string that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToYNStringConverter 
        implements AttributeConverter<Boolean, String> {

    /**
     * This implementation will return "Y" if the parameter is Boolean.TRUE,
     * otherwise it will return "N" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b.booleanValue()) {
            return "Y";
        }
        return "N";
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is "Y" or "y", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for "N") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (s.equals("Y") || s.equals("y")) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

This variant is also fun if you love emoticons and are just sick and tired of Y/N or T/F in your database. In this case, your database column must be two characters instead of one. Probably not a big deal.

/**
 * Converts a Boolean entity attribute to a happy face or sad face
 * that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToHappySadConverter 
        implements AttributeConverter<Boolean, String> {

    public static final String HAPPY = ":)";
    public static final String SAD = ":(";

    /**
     * This implementation will return ":)" if the parameter is Boolean.TRUE,
     * otherwise it will return ":(" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     * @return String or null
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b) {
            return HAPPY;
        }
        return SAD;
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is ":)", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for ":(") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     * @return Boolean or null
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (HAPPY.equals(s)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Angular Directive refresh on parameter change

angular.module('app').directive('conversation', function() {
    return {
        restrict: 'E',
        link: function ($scope, $elm, $attr) {
            $scope.$watch("some_prop", function (newValue, oldValue) {
                  var typeId = $attr.type-id;
                  // Your logic.
            });
        }
    };
}

Java SecurityException: signer information does not match

If you're running it in Eclipse, check the jars of any projects added to the build path; or do control-shift-T and scan for multiple jars matching the same namespace. Then remove redundant or outdated jars from the project's build path.

Mockito How to mock and assert a thrown exception?

I think this should do it for you.

assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..));

Set a thin border using .css() in javascript

Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.

How can I create an Asynchronous function in Javascript?

Next to the great answer by @pimvdb, and just in case you where wondering, async.js does not offer truly asynchronous functions either. Here is a (very) stripped down version of the library's main method:

function asyncify(func) { // signature: func(array)
    return function (array, callback) {
        var result;
        try {
            result = func.apply(this, array);
        } catch (e) {
            return callback(e);
        }
        /* code ommited in case func returns a promise */
        callback(null, result);
    };
}

So the function protects from errors and gracefully hands it to the callback to handle, but the code is as synchronous as any other JS function.

How do I declare an array with a custom class?

You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.

Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.

Here is the working code:

#include <iostream> 
#include <string>  // <-- you need this if you want to use string type

using namespace std; 

class name { 
  public: 
    string first; 
    string last; 

  name(string a, string b){ 
    first = a; 
    last = b; 

  }

  name ()  // <-- this is your explicit parameterless constructor
  {}

}; 

int main (int argc, const char * argv[]) 
{ 

  const int howManyNames = 3; 

  name someName[howManyNames]; 

  return 0; 
}

(BTW, you need to include to make the code compilable.)

An alternative way is to initialize your instances explicitly on declaration

  name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };

Why doesn't JUnit provide assertNotEquals methods?

The obvious reason that people wanted assertNotEquals() was to compare builtins without having to convert them to full blown objects first:

Verbose example:

....
assertThat(1, not(equalTo(Integer.valueOf(winningBidderId))));
....

vs.

assertNotEqual(1, winningBidderId);

Sadly since Eclipse doesn't include JUnit 4.11 by default you must be verbose.

Caveat I don't think the '1' needs to be wrapped in an Integer.valueOf() but since I'm newly returned from .NET don't count on my correctness.

How to convert integer to decimal in SQL Server query?

SELECT CAST(height AS DECIMAL(18,0)) / 10

Edit: How this works under the hood?

The result type is the same as the type of both arguments, or, if they are different, it is determined by the data type precedence table. You can therefore cast either argument to something non-integral.

Now DECIMAL(18,0), or you could equivalently write just DECIMAL, is still a kind of integer type, because that default scale of 0 means "no digits to the right of the decimal point". So a cast to it might in different circumstances work well for rounding to integers - the opposite of what we are trying to accomplish.

However, DECIMALs have their own rules for everything. They are generally non-integers, but always exact numerics. The result type of the DECIMAL division that we forced to occur is determined specially to be, in our case, DECIMAL(29,11). The result of the division will therefore be rounded to 11 places which is no concern for division by 10, but the rounding becomes observable when dividing by 3. You can control the amount of rounding by manipulating the scale of the left hand operand. You can also round more, but not less, by placing another ROUND or CAST operation around the whole expression.

Identical mechanics governs the simpler and nicer solution in the accepted answer:

  SELECT height / 10.0

In this case, the type of the divisor is DECIMAL(3,1) and the type of the result is DECIMAL(17,6). Try dividing by 3 and observe the difference in rounding.

If you just hate all this talk of precisions and scales, and just want SQL server to perform all calculations in good old double precision floating point arithmetics from some point on, you can force that, too:

SELECT height / CAST(10 AS FLOAT(53))

or equivalently just

SELECT height / CAST (10 AS FLOAT)

Best way to integrate Python and JavaScript?

You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.

http://codespeak.net/pypy

Also, check out the informative blog:

http://morepypy.blogspot.com/

Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).

http://bub-n-bros.sourceforge.net

regex for zip-code

I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.

In a previous answer from @kennytm:

^\d{5}(?:[-\s]\d{4})?$

…? = The pattern before it is optional (for condition 1)

If you want to allow both standard 5 digit and +4 zip codes, this is a great example.

To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ? so it will always match the last 5 character group.

A useful tool I recommend for tinkering with RegEx is linked below:

https://regexr.com/

I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.

If I got anything wrong or missed an important piece of information, please correct me.

Sort a List of Object in VB.NET

you must implement IComparer interface.

In this sample I've my custom object JSONReturn, I implement my class like this :

Friend Class JSONReturnComparer
    Implements IComparer(of JSONReturn)

    Public Function Compare(x As JSONReturn, y As JSONReturn) As Integer Implements    IComparer(Of JSONReturn).Compare
        Return String.Compare(x.Name, y.Name)
    End Function

End Class

I call my sort List method like this : alResult.Sort(new JSONReturnComparer())

Maybe it could help you

Array of PHP Objects

Another intuitive solution could be:

class Post
{
    public $title;
    public $date;
}

$posts = array();

$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';

$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';

foreach ($posts as $post) {
  echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}

Retrieving a Foreign Key value with django-rest-framework serializers

In the DRF version 3.6.3 this worked for me

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source='category.name')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

More info can be found here: Serializer Fields core arguments

How to apply CSS to iframe?

The following worked for me.

var iframe = top.frames[name].document;
var css = '' +
          '<style type="text/css">' +
          'body{margin:0;padding:0;background:transparent}' +
          '</style>';
iframe.open();
iframe.write(css);
iframe.close();

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I was also facing this issue

Error- Windows cannot find 'http://127.0.01:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

After some research work, I found out that my HTTPPORT ie. 8080 was occupied by Apace HTTP Server and hence connection by OracleServiceXE could not be established.

What I did to solve this issue was :

  1. Go to Windows -> Services, found out Apache2.4 and manually stopped it to free my 8080 port.
  2. Clicked on Start Database, and I received message :

The OracleServiceXE service is starting.............. The OracleServiceXE service was started successfully.

  1. Manually entered http://127.0.0.1:8080/apex/f?p=4950 url to my browser which auto redirected me to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303

That's it my issue got resolved.

In order to remember this new url and make sure that next time whenever I hit Get Started I should be redirected to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303 instead of http://127.0.0.1:8080/apex/f?p=4950, what I did was :

  1. Browse to Directory:\OracleDatabase\app\oracle\product\11.2.0\server and search for Get_Started.html.
  2. Right Click on Get_Started.html and select Properties
  3. Modify your url and click Apply

Hope this Helps.

How to display a list of images in a ListView in Android?

I came up with a solution that I call “BatchImageDownloader” that has served well. Here’s a quick summary of how it is used:

  • Keep a global HashMap (ideally in your Application object) that serves as a cache of drawable objects

  • In the getView() method of your List Adapter, use the drawable from the cache for populating the ImageView in your list item.

  • Create an instance of BatchImageDownloader, passing in your ListView Adapter

  • Call addUrl() for each image that needs to be fetched/displayed

  • When done, call execute(). This fires an AsyncTask that fetches all images, and as each image is fetched and added to the cache, it refreshes your ListView (by calling notifyDataSetChanged())

The approach has the following advantages:

  • A single worker thread is used to fetch all images, rather than a separate thread for each image/view
  • Once an image is fetched, all list items that use it are instantly updated
  • The code does not access the Image View in your List Item directly – instead it triggers a listview refresh by calling notifyDataSetChanged() on your List Adapter, and the getView() implementation simply pulls the drawable from the cache and displays it. This avoids the problems associated with recycled View objects used in ListViews.

Here is the source code of BatchImageDownloader:

package com.mobrite.androidutils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.BaseAdapter;

public class BatchImageDownloader extends AsyncTask<Void, Void, Void> {

    List<String> imgUrls = new ArrayList<String>();
    BaseAdapter adapter;
    HashMap<String, Drawable> imageCache;

    public BatchImageDownloader(BaseAdapter adapter,
            HashMap<String, Drawable> imageCache) {
        this.adapter = adapter;
        this.imageCache = imageCache;
    }

    public void addUrl(String url) {
        imgUrls.add(url);
    }

    @Override
    protected Void doInBackground(Void... params) {
        for (String url : imgUrls) {
            if (!imageCache.containsKey(url)) {
                Drawable bm = downloadImage(url);
                if (null != bm) {
                    imageCache.put(url, bm);
                    publishProgress();
                }
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPostExecute(Void result) {
        adapter.notifyDataSetChanged();
    }

    public Drawable downloadImage(String url) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(request);
            InputStream stream = response.getEntity().getContent();
            Drawable drawable = Drawable.createFromStream(stream, "src");
            return drawable;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}

Escaping ampersand character in SQL string

I know it sucks. None of the above things were really working, but I found a work around. Please be extra careful to use spaces between the apostrophes [ ' ], otherwise it will get escaped.

SELECT 'Hello ' '&' ' World';

Hello & World

You're welcome ;)

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.

(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)

In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.

For example, lets say you have the following query:

SELECT emp_id FROM employees WHERE months_of_service = 6;

(The months_of_service column has a NOT NULL constraint on it and an ordinary index on it.)

There are two basic plans the optimiser might choose here:

  • Plan 1: Read all the rows from the "employees" table, for each, check if the predicate is true (months_of_service=6).
  • Plan 2: Read the index where months_of_service=6 (this results in a set of ROWIDs), then access the table based on the ROWIDs returned.

Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.

The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.

The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.

As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.

If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".

The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.

How to wait till the response comes from the $http request, in angularjs?

FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put

myservice.$loaded().then(function() {$rootScope.myservice = myservice;});

and in the view I just did

ng-if="myservice" ng-init="somevar=myfunct()"

in the first/parent view element/wrapper so the controller can run everything inside

myfunct()

without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.

No == operator found while comparing structs in C++

You need to explicitly define operator == for MyStruct1.

struct MyStruct1 {
  bool operator == (const MyStruct1 &rhs) const
  { /* your logic for comparision between "*this" and "rhs" */ }
};

Now the == comparison is legal for 2 such objects.

How to check if a stored procedure exists before creating it

In addition to the answer from @Geoff I've created a simple tool which generates a SQL-file which statements for Stored Procedures, Views, Functions and Triggers.

See MyDbUtils @ CodePlex. enter image description here

How to convert Integer to int?

Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.

How do I refresh a DIV content?

For div refreshing without creating div inside yours with same id, you should use this inside your function

$("#yourDiv").load(" #yourDiv > *");