Programs & Examples On #Mpmovieplayer

iOS API : A movie player (of type MPMoviePlayerController) that manages the playback of a movie from a file or a network stream. MPMoviePlayerController was replaced in iOS 8 by AVKit classes such as `AVPlayerViewController`, and is formally deprecated in iOS 9

iPhone SDK:How do you play video inside a view? Rather than fullscreen

As of the 3.2 SDK you can access the view property of MPMoviePlayerController, modify its frame and add it to your view hierarchy.

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
player.view.frame = CGRectMake(184, 200, 400, 300);
[self.view addSubview:player.view];
[player play];

There's an example here: http://www.devx.com/wireless/Article/44642/1954

Python progression path - From apprentice to guru

Not precisely what you're asking for, but I think it's good advice.

Learn another language, doesn't matter too much which. Each language has it's own ideas and conventions that you can learn from. Learn about the differences in the languages and more importantly why they're different. Try a purely functional language like Haskell and see some of the benefits (and challenges) of functions free of side-effects. See how you can apply some of the things you learn from other languages to Python.

The simplest possible JavaScript countdown timer?

You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.

http://jsfiddle.net/ayyadurai/GXzhZ/1/

_x000D_
_x000D_
window.onload = function() {_x000D_
  var minute = 5;_x000D_
  var sec = 60;_x000D_
  setInterval(function() {_x000D_
    document.getElementById("timer").innerHTML = minute + " : " + sec;_x000D_
    sec--;_x000D_
    if (sec == 00) {_x000D_
      minute --;_x000D_
      sec = 60;_x000D_
      if (minute == 0) {_x000D_
        minute = 5;_x000D_
      }_x000D_
    }_x000D_
  }, 1000);_x000D_
}
_x000D_
Registration closes in <span id="timer">05:00<span> minutes!
_x000D_
_x000D_
_x000D_

Change form size at runtime in C#

As a complement to the answers given above; do not forget about Form MinimumSize Property, in case you require to create smaller Forms.

Example Bellow:

private void SetDefaultWindowSize()
{
   int sizeW, sizeH;
   sizeW = 180;
   sizeH = 100;

   var size = new Size(sizeW, sizeH);

   Size = size;
   MinimumSize = size;
}

private void SetNewSize()
{
   Size = new Size(Width, 10);
}

How to save picture to iPhone photo library?

homeDirectoryPath = NSHomeDirectory();
unexpandedPath = [homeDirectoryPath stringByAppendingString:@"/Pictures/"];

folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];

unexpandedImagePath = [folderPath stringByAppendingString:@"/image.png"];

imagePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];

if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:folderPath attributes:nil];
}

Creating a triangle with for loops

private static void printStar(int x) {
    int i, j;
    for (int y = 0; y < x; y++) { // number of row of '*'

        for (i = y; i < x - 1; i++)
            // number of space each row
            System.out.print(' ');

        for (j = 0; j < y * 2 + 1; j++)
            // number of '*' each row
            System.out.print('*');

        System.out.println();
    }
}

Compare two date formats in javascript/jquery

To comapre dates of string format (mm-dd-yyyy).

    var job_start_date = "10-1-2014"; // Oct 1, 2014
    var job_end_date = "11-1-2014"; // Nov 1, 2014
    job_start_date = job_start_date.split('-');
    job_end_date = job_end_date.split('-');

    var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
    var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);

    if(new_end_date <= new_start_date) {
      // your code
    }

Using Java to pull data from a webpage?

Here's my solution using URL and try with resources phrase to catch the exceptions.

/**
 * Created by mona on 5/27/16.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadFromWeb {
    public static void readFromWeb(String webURL) throws IOException {
        URL url = new URL(webURL);
        InputStream is =  url.openStream();
        try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MalformedURLException("URL is malformed!!");
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IOException();
        }

    }
    public static void main(String[] args) throws IOException {
        String url = "https://madison.craigslist.org/search/sub";
        readFromWeb(url);
    }

}

You could additionally save it to file based on your needs or parse it using XML or HTML libraries.

Use of True, False, and None as return values in Python functions

For True, not None:

if foo:

For false, None:

if not foo:

importing a CSV into phpmyadmin

In phpMyAdmin, click the table, and then click the Import tab at the top of the page.

Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:

Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto

Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.

Now click the Go button, and it should run successfully.

Convert DOS line endings to Linux line endings in Vim

I prefer to use the following command:

:set fileformat=unix

You can also use mac or dos to respectively convert your file to Mac or MS-DOS/Windows file convention. And it does nothing if the file is already in the correct format.

For more information, see the Vim help:

:help fileformat

Selenium WebDriver can't find element by link text

A CSS selector approach could definitely work here. Try:

driver.findElement(By.CssSelector("a.item")).Click();

This will not work if there are other anchors before this one of the class item. You can better specify the exact element if you do something like "#my_table > a.item" where my_table is the id of a table that the anchor is a child of.

How to "EXPIRE" the "HSET" child key in redis?

There is a Redisson java framework which implements hash Map object with entry TTL support. It uses hmap and zset Redis objects under the hood. Usage example:

RMapCache<Integer, String> map = redisson.getMapCache('map');
map.put(1, 30, TimeUnit.DAYS); // this entry expires in 30 days

This approach is quite useful.

Tracking CPU and Memory usage per process

Although I have not tried this out, ProcDump seems like a better solution.

Description from site:

ProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike. ProcDump also includes hung window monitoring (using the same definition of a window hang that Windows and Task Manager use), unhandled exception monitoring and can generate dumps based on the values of system performance counters. It also can serve as a general process dump utility that you can embed in other scripts.

C# SQL Server - Passing a list to a stored procedure

If you're using SQL Server 2008, there's a new featured called a User Defined Table Type. Here is an example of how to use it:

Create your User Defined Table Type:

CREATE TYPE [dbo].[StringList] AS TABLE(
    [Item] [NVARCHAR](MAX) NULL
);

Next you need to use it properly in your stored procedure:

CREATE PROCEDURE [dbo].[sp_UseStringList]
    @list StringList READONLY
AS
BEGIN
    -- Just return the items we passed in
    SELECT l.Item FROM @list l;
END

Finally here's some sql to use it in c#:

using (var con = new SqlConnection(connstring))
{
    con.Open();

    using (SqlCommand cmd = new SqlCommand("exec sp_UseStringList @list", con))
    {
        using (var table = new DataTable()) {
          table.Columns.Add("Item", typeof(string));

          for (int i = 0; i < 10; i++)
            table.Rows.Add("Item " + i.ToString());

          var pList = new SqlParameter("@list", SqlDbType.Structured);
          pList.TypeName = "dbo.StringList";
          pList.Value = table;

          cmd.Parameters.Add(pList);

          using (var dr = cmd.ExecuteReader())
          {
            while (dr.Read())
                Console.WriteLine(dr["Item"].ToString());
          }
         }
    }
}

To execute this from SSMS

DECLARE @list AS StringList

INSERT INTO @list VALUES ('Apple')
INSERT INTO @list VALUES ('Banana')
INSERT INTO @list VALUES ('Orange')

-- Alternatively, you can populate @list with an INSERT-SELECT
INSERT INTO @list
   SELECT Name FROM Fruits

EXEC sp_UseStringList @list

How do I import a .sql file in mysql database using PHP?

function restoreDatabase($db_name,$file_path)
{

    //checking valid extension file
    $path_parts = pathinfo($file_path);
    $ext_file = $path_parts['extension'];
    $filename = $path_parts['basename'];

    if($ext_file == "sql")
    {
         $c = new Config();

         $confJson = $c->getConfig();
         $conf = json_decode($confJson);

         $dbhost   = "127.0.0.1";
         $dbuser   = $conf->db_username;  
         $dbpwd    = $conf->db_password;
         $dbname   = $db_name;   

         $dumpfile = $file_path;

         $is_file = file_exists($file_path);
         if($is_file == TRUE)
         {

             //passthru("/usr/bin/mysqldump --opt --host=$dbhost --user=$dbuser --password=$dbpwd $dbname < $dumpfile");

             //passthru("tail -1 $dumpfile");
             system('mysql --user='.$dbuser.' --password='.$dbpwd.' '.$db_name.' < '.$file_path);
             return "Database was restored from $filename ";

         }
         else 
         {
             return "Restore database was aborted due ".$filename." does not exist!";
         }


    }
    else
    {
        return "Invalid file format.Require sql file to restore this ".$db_name." database. ".$filename." is not sql file format\n(eg. mybackupfile.sql).";
    }
}

Android ACTION_IMAGE_CAPTURE Intent

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED)
    {
        //do not process data, I use return; to resume activity calling camera intent
        enter code here
    }
}

Restore a postgres backup file using the command line?

Try to see if the following commands can help you:

sudo su - yourdbuser
psql
\i yourbackupfile

Fatal error: "No Target Architecture" in Visual Studio

Use #include <windows.h> instead of #include <windef.h>.

From the windows.h wikipedia page:

There are a number of child header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.

windef.h is one of the files automatically included with windows.h.

Query to convert from datetime to date mysql

Try to cast it as a DATE

SELECT CAST(orders.date_purchased AS DATE) AS DATE_PURCHASED

SVN- How to commit multiple files in a single shot

You can use --targets ARG option where ARG is the name of textfile containing the targets for commit.

svn ci --targets myfiles.txt -m "another commit"

add created_at and updated_at fields to mongoose schemas

As of Mongoose 4.0 you can now set a timestamps option on the Schema to have Mongoose handle this for you:

var thingSchema = new Schema({..}, { timestamps: true });

You can change the name of the fields used like so:

var thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } });

http://mongoosejs.com/docs/guide.html#timestamps

Is it possible to compile a program written in Python?

Python, as a dynamic language, cannot be "compiled" into machine code statically, like C or COBOL can. You'll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation.

You can "translate" source code in bytecode, which is just an intermediate process that the interpreter does to speed up the load of the code, It converts text files, with comments, blank spaces, words like 'if', 'def', 'in', etc in binary code, but the operations behind are exactly the same, in Python, not in machine code or any other language. This is what it's stored in .pyc files and it's also portable between architectures.

Probably what you need it's not "compile" the code (which it's not possible) but to "embed" an interpreter (in the right architecture) with the code to allow running the code without an external installation of the interpreter. To do that, you can use all those tools like py2exe or cx_Freeze.

Maybe I'm being a little pedantic on this :-P

How to run .sh on Windows Command Prompt?

I use Windows 10 Bash shell aka Linux Subsystem aka Ubuntu in Windows 10 as guided here

twitter bootstrap 3.0 typeahead ajax example

Here is my step by step experience, inspired by typeahead examples, from a Scala/PlayFramework app we are working on.

In a script LearnerNameTypeAhead.coffee (convertible of course to JS) I have:

$ ->
  learners = new Bloodhound(
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value")
    queryTokenizer: Bloodhound.tokenizers.whitespace
    remote: "/learner/namelike?nameLikeStr=%QUERY"
  )
  learners.initialize()
  $("#firstName").typeahead 
    minLength: 3
    hint: true
    highlight:true
   ,
    name: "learners"
    displayKey: "value"
    source: learners.ttAdapter()

I included the typeahead bundle and my script on the page, and there is a div around my input field as follows:

<script [email protected]("javascripts/typeahead.bundle.js")></script>
<script [email protected]("javascripts/LearnerNameTypeAhead.js") type="text/javascript" ></script>
<div>
  <input name="firstName" id="firstName" class="typeahead" placeholder="First Name" value="@firstName">
</div>

The result is that for each character typed in the input field after the first minLength (3) characters, the page issues a GET request with a URL looking like /learner/namelike?nameLikeStr= plus the currently typed characters. The server code returns a json array of objects containing fields "id" and "value", for example like this:

[ {
    "id": "109",
    "value": "Graham Jones"
  },
  {
    "id": "5833",
    "value": "Hezekiah Jones"
} ]

For play I need something in the routes file:

GET /learner/namelike controllers.Learners.namesLike(nameLikeStr:String)

And finally, I set some of the styling for the dropdown, etc. in a new typeahead.css file which I included in the page's <head> (or accessible .css)

.tt-dropdown-menu {
  width: 252px;
  margin-top: 12px;
  padding: 8px 0;
  background-color: #fff;
  border: 1px solid #ccc;
  border: 1px solid rgba(0, 0, 0, 0.2);
  -webkit-border-radius: 8px;
     -moz-border-radius: 8px;
          border-radius: 8px;
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
          box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.typeahead {
  background-color: #fff;
}
.typeahead:focus {
  border: 2px solid #0097cf;
}
.tt-query {
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
  color: #999
}
.tt-suggestion {
  padding: 3px 20px;
  font-size: 18px;
  line-height: 24px;
}
.tt-suggestion.tt-cursor {
  color: #fff;
  background-color: #0097cf;
}
.tt-suggestion p {
  margin: 0;
}

PHP isset() with multiple parameters

You just need:

if (!empty($_POST['search_term']) && !empty($_POST['postcode']))

isset && !empty is redundant.

Where is SQL Server Management Studio 2012?

Full or"Complete Management Studio" as opposed to "Express".

I was very confused at a perceived lack of Management Studio on a newly provisioned SQL Server 2012 SP1 standard and enterprise edition on Azure running on Windows Server 2012.

Normally it would be found from the Start Button Shortcuts or at least in C:\Program Files somewhere.

Eventually, I located C:\SQLServer_11.0_Full, the image install path - executed and confirmed Management Studio was in fact installed by default even although it could not been seen via Add Remove Programs.

In short, if you provision an SQL Server 2012 VM on Windows Server 2012 on Azure simply run PowerShell and then enter ssms.exe to access Management Studio.

C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\ssms.exe

Update a column in MySQL

UPDATE table1 SET col_a = 'newvalue'

Add a WHERE condition if you want to only update some of the rows.

How to submit a form using Enter key in react.js?

Use keydown event to do it:

   input: HTMLDivElement | null = null;

   onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
      // 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopPropagation();
        this.onSubmit();
      }
    }

    onSubmit = (): void => {
      if (input.textContent) {
         this.props.onSubmit(input.textContent);
         input.focus();
         input.textContent = '';
      }
    }

    render() {
      return (
         <form className="commentForm">
           <input
             className="comment-input"
             aria-multiline="true"
             role="textbox"
             contentEditable={true}
             onKeyDown={this.onKeyDown}
             ref={node => this.input = node} 
           />
           <button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
         </form>
      );
    }

MySQL JOIN with LIMIT 1 on joined table

The With clause would do the trick. Something like this:

WITH SELECTION AS (SELECT id FROM products LIMIT 1)
SELECT a.id, c.id, c.title FROM selection a JOIN categories c ON (c.id = a.id);

How does MySQL process ORDER BY and LIMIT in a query?

Just as @James says, it will order all records, then get the first 20 rows.

As it is so, you are guaranteed to get the 20 first published articles, the newer ones will not be shown.

In your situation, I recommend that you add desc to order by publish_date, if you want the newest articles, then the newest article will be first.

If you need to keep the result in ascending order, and still only want the 10 newest articles you can ask mysql to sort your result two times.

This query below will sort the result descending and limit the result to 10 (that is the query inside the parenthesis). It will still be sorted in descending order, and we are not satisfied with that, so we ask mysql to sort it one more time. Now we have the newest result on the last row.

select t.article 
from 
    (select article, publish_date 
     from table1
     order by publish_date desc limit 10) t 

order by t.publish_date asc;

If you need all columns, it is done this way:

select t.* 
from 
    (select * 
     from table1  
     order by publish_date desc limit 10) t 

order by t.publish_date asc;

I use this technique when I manually write queries to examine the database for various things. I have not used it in a production environment, but now when I bench marked it, the extra sorting does not impact the performance.

Bash script processing limited number of commands in parallel

Use the wait built-in:

process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait

For the above example, 4 processes process1 ... process4 would be started in the background, and the shell would wait until those are completed before starting the next set.

From the GNU manual:

wait [jobspec or pid ...]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

storing user input in array

You're not actually going out after the values. You would need to gather them like this:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;

You could put all of these in one array:

var myArray = [ title, name, tickets ];

Or many arrays:

var titleArr   = [ title ];
var nameArr    = [ name ];
var ticketsArr = [ tickets ];

Or, if the arrays already exist, you can use their .push() method to push new values onto it:

var titleArr = [];

function addTitle ( title ) {
  titleArr.push( title );
  console.log( "Titles: " + titleArr.join(", ") );
}

Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:

I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit

The new form follows:

<form>
  <h1>Please enter data</h1>
  <input id="title" type="text" />
  <input id="name" type="text" />
  <input id="tickets" type="text" />
  <input type="button" value="Save" onclick="insert()" />
  <input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>

There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).

I've also made some changes to your JavaScript. I start by creating three empty arrays:

var titles  = [];
var names   = [];
var tickets = [];

Now that we have these, we'll need references to our input fields.

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

I'm also getting a reference to our message display box.

var messageBox  = document.getElementById("display");

The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.

Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.

function clearAndShow () {
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
  messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
  messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}

The final result can be used online at http://jsbin.com/ufanep/2/edit

HTML text-overflow ellipsis detection

I think the better way to detect it is use getClientRects(), it seems each rect has the same height, so we can caculate lines number with the number of different top value.

getClientRects work like this

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

getRowRects work like this

you can detect like this

What does the return keyword do in a void method in Java?

You can have return in a void method, you just can't return any value (as in return 5;), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:

void someFunct(int arg)
{
    if (arg == 0)
    {
        //Leave because this is a bad value
        return;
    }
    //Otherwise, do something
}

How to make link not change color after visited?

Something like this should work:

a, a:visited { 
    color:red; text-decoration:none; 
    }

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Browser detection

    private void BindDataBInfo()
    {
        System.Web.HttpBrowserCapabilities browser = Request.Browser;
        Literal1.Text = "<table border=\"1\" cellspacing=\"3\" cellpadding=\"2\">";
        foreach (string key in browser.Capabilities.Keys)
        {
            Literal1.Text += "<tr><td>" + key + "</td><td>" + browser[key] + "</tr>";
        }
        Literal1.Text += "</table>";
        browser = null;
    }

Best/Most Comprehensive API for Stocks/Financial Data

Yahoo's api provides a CSV dump:

Example: http://finance.yahoo.com/d/quotes.csv?s=msft&f=price

I'm not sure if it is documented or not, but this code sample should showcase all of the features (namely the stat types [parameter f in the query string]. I'm sure you can find documentation (official or not) if you search for it.

http://www.goldb.org/ystockquote.html

Edit

I found some unofficial documentation:

http://ilmusaham.wordpress.com/tag/stock-yahoo-data/

Android RecyclerView addition & removal of items

In case you are wondering like I did where can we get the adapter position in the method getadapterposition(); its in viewholder object.so you have to put your code like this

mdataset.remove(holder.getadapterposition());

Override back button to act like home button

I have use @Mirko N. answser using made the new Custom EditText

 public class EditViewCustom extends EditText {

    Button cancelBtn;
    RelativeLayout titleReleLayout;
    public EditViewCustom(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public EditViewCustom(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditViewCustom(Context context) {
        super(context);
    }

    public void setViews(Button cancelBtn,RelativeLayout titleReleLayout){
        this.cancelBtn = cancelBtn;
        this.titleReleLayout = titleReleLayout;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            Log.d("KEYCODE_BACK","KEYCODE_BACK");
            cancelBtn.setVisibility(View.GONE);
            this.setFocusableInTouchMode(false);
            this.setFocusable(false);
            titleReleLayout.setVisibility(View.VISIBLE);

            return super.onKeyPreIme(keyCode, event);
          }

        return super.onKeyPreIme(keyCode, event);
    }

}

Then set data from your activity

 searchEditView.setViews(cancelBtn, titleRelativeLayout);

Thank you.

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

What in the world are Spring beans?

Spring have the IoC container which carry the Bag of Bean ; creation maintain and deletion are the responsibilities of Spring Container. We can put the bean in to Spring by Wiring and Auto Wiring. Wiring mean we manually configure it into the XML file and "Auto Wiring" mean we put the annotations in the Java file then Spring automatically scan the root-context where java configuration file, make it and put into the bag of Spring.

Here is the detail URI where you got more information about Beans

How to join two JavaScript Objects, without using JQUERY

This simple function recursively merges JSON objects, please notice that this function merges all JSON into first param (target), if you need new object modify this code.

var mergeJSON = function (target, add) {
    function isObject(obj) {
        if (typeof obj == "object") {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    return true; // search for first object prop
                }
            }
        }
        return false;
    }
    for (var key in add) {
        if (add.hasOwnProperty(key)) {
            if (target[key] && isObject(target[key]) && isObject(add[key])) {
                this.mergeJSON(target[key], add[key]);
            } else {
                target[key] = add[key];
            }
        }
    }
    return target;
};

BTW instead of isObject() function may be used condition like this:

JSON.stringify(add[key])[0] == "{"

but this is not good solution, because it's will take a lot of resources if we have large JSON objects.

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

How to hide Bootstrap modal with javascript?

I used this simple code:

$("#MyModal .close").click();

Best practices for SQL varchar column length

Always check with your business domain expert. If that's you, look for an industry standard. If, for example, the domain in question is a natural person's family name (surname) then for a UK business I'd go to the UK Govtalk data standards catalogue for person information and discover that a family name will be between 1 and 35 characters.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

How to run Pip commands from CMD

Little side note for anyone new to Python who didn't figure it out by theirself: this should be automatic when installing Python, but just in case, note that to run Python using the python command in Windows' CMD you must first add it to the PATH environment variable, as explained here.


To execute Pip, first of all make sure you have it installed, so type in your CMD:

> python
>>> import pip
>>>

And it should proceed with no error. Otherwise, if this fails, you can look here to see how to install it. Now that you are sure you've got Pip, you can run it from CMD with Python using the -m (module) parameter, like this:

> python -m pip <command> <args>

Where <command> is any Pip command you want to run, and <args> are its relative arguments, separated by spaces.

For example, to install a package:

> python -m pip install <package-name>

PHP If Statement with Multiple Conditions

Try this piece of code:

$first = $string[0]; 
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') {
   $v='starts with vowel';
} 
else {
   $v='does not start with vowel';
}

How to Convert string "07:35" (HH:MM) to TimeSpan

You can convert the time using the following code.

TimeSpan _time = TimeSpan.Parse("07:35");

But if you want to get the current time of the day you can use the following code:

TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;

The result will be:

03:54:35.7763461

With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

How do you fix the "element not interactable" exception?

Found a workaround years later after encountering the same problem again - unable to click element even though it SHOULD be clickable. The solution is to catch ElementNotInteractable exception and attempt to execute a script to click the element.

Example in Typescript

async clickElement(element: WebElement) {
    try {
        return await element.click();
    } catch (error) {
        if (error.name == 'ElementNotInteractableError') {
            return await this.driver.executeScript((element: WebElement) => {
                element.click();
            }, element);
        }
    }
}

python, sort descending dataframe with pandas

New syntax (either):

 test = df.sort_values(['one'], ascending=[False])
 test = df.sort_values(['one'], ascending=[0])

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

If you know that the bean exists and its just a problem of the inspections, then just add the following before the variable declaration:

@SuppressWarnings("SpringJavaAutowiringInspection")
@Inject MyClass myVariable;

Sometimes IntelliJ cannot resolve if a bean has been declared, for example when the bean is included conditionally and the condition resolution happens at runtime.

Android Studio error: "Environment variable does not point to a valid JVM installation"

I also had similar issue. Had correctly installed the application, had appropriately setup the JAVA_HOME, still it was not able to find the JDK and complains about the ver 1.6.0_17.

I no longer have any such version installed on my machine. After much digging I got onto the "HKEY_LOCAL_MACHINE\software\javasoft\Java Development Kit\" where I found multiple JDK version being mentioned.

I removed all except 1.8.0_25 that I currently have on my machine. Restarted the Android Studio, and it worked without any problem. May be someone visit this page, facing similar issue, might help.

Wildcards in jQuery selectors

for classes you can use:

div[class^="jander"]

Beautiful Soup and extracting a div and its contents by ID

I used:

soup.findAll('tag', attrs={'attrname':"attrvalue"})

As my syntax for find/findall; that said, unless there are other optional parameters between the tag and attribute list, this shouldn't be different.

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

The hamcrest-core-1.3.jar available on maven repository is deprecated.

Download working hamcrest-core-1.3.jar from official Junit4 github link . If you want to download from maven repository, use latest hamcrest-XX.jar.

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

Can't connect to MySQL server on 'localhost' (10061)

Another possibility:

There are two ways the MySQL client can connect to the server: over TCP/IP, or using sockets. It's possible you have your MySQL server configured to support socket connections, but not network connections.

ImportError: No module named six

Ubuntu 18.04.5 LTS (Bionic Beaver):

apt --reinstall install python3-debian
apt --reinstall install python3-six

If /usr/bin/chardet3 fails with error "ModuleNotFoundError: No module named 'pkg_resources'":

apt --reinstall install python3-pkg-resources

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Your import has a subtle error:

import java.awt.List;

It should be:

import java.util.List;

The problem is that both awt and Java's util package provide a class called List. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList extends java.util.List, not java.awt.List so if it wasn't for the generics, it would have still been a problem.

Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.

import org.omg.DynamicAny.NameValuePair;

should be

import org.apache.http.NameValuePair

nameValuePairs now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity, which is List<? extends NameValuePair>, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair did not extend org.apache.http.NameValuePair and the shortened type name NameValuePair evaluated to org.omg... in your file, but org.apache... in their code.

Have log4net use application config file for configuration data

Have you tried adding a configsection handler to your app.config? e.g.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

Unioning two tables with different number of columns

for any extra column if there is no mapping then map it to null like the following SQL query

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2````

How can I list the contents of a directory in Python?

Since Python 3.5, you can use os.scandir.

The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file to know if it's a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:

example to list a directory and print files bigger than max_value bytes:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

(read an extensive performance-based answer of mine here)

Rendering raw html with reactjs

I needed to use a link with onLoad attribute in my head where div is not allowed so this caused me significant pain. My current workaround is to close the original script tag, do what I need to do, then open script tag (to be closed by the original). Hope this might help someone who has absolutely no other choice:

<script dangerouslySetInnerHTML={{ __html: `</script>
   <link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

why should I make a copy of a data frame in pandas

Assumed you have data frame as below

df1
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

When you would like create another df2 which is identical to df1, without copy

df2=df1
df2
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

And would like modify the df2 value only as below

df2.iloc[0,0]='changed'

df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

At the same time the df1 is changed as well

df1
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Since two df as same object, we can check it by using the id

id(df1)
140367679979600
id(df2)
140367679979600

So they as same object and one change another one will pass the same value as well.


If we add the copy, and now df1 and df2 are considered as different object, if we do the same change to one of them the other will not change.

df2=df1.copy()
id(df1)
140367679979600
id(df2)
140367674641232

df1.iloc[0,0]='changedback'
df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Good to mention, when you subset the original dataframe, it is safe to add the copy as well in order to avoid the SettingWithCopyWarning

C# "as" cast vs classic cast

The as keyword is useful when you genuinely don't know what type the variable might be. If you have a single function that will follow different code paths depending upon the actual type of the parameter, then you have two choices:

First, using a normal cast:

if(myObj is string)
{
    string value = (string)myObj;

    ... do something
}
else if(myObj is MyClass)
{
    MyClass = (MyClass)myObj;
}

This requires that you check the type of the object using is so that you don't try to cast it to something that will fail. This is also slightly redundant, as the is-type checking is done again in the cast (so that it can throw the exception if required).

The alternative is to use as.

string myString = myObj as string;
MyClass myClass = myObj as MyClass;

if(myString != null)
{

}
else if(myClass != null)
{

}

This makes the code somewhat shorter and also eliminates the redundant type checking.

How to save .xlsx data to file as a blob

The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.

Here's what I did on the server side (asp.net mvc core):

string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);

On the client side, I did the following code:

const xhr = new XMLHttpRequest();

xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");

xhr.onload = () => {
    var bin = atob(xhr.response);
    var ab = s2ab(bin); // from example above
    var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'demo.xlsx';

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
};

xhr.send();

And it works perfectly for me.

Xcode - ld: library not found for -lPods

The below solution worked for me for the core-plot 2.3 version. Do the below changes under other linker flags section.

1.Add $(inherited) and drag this item to top position 2.Remove "Pods-" prefix from -l"Pods-fmemopen”, l"Pods-NSAttributedStringMarkdownParser” and -l"Pods-MagicalRecord”.

if still issue persists, Finally see if PODS_ROOT is set or not. You can check it under user defined section.

What is the difference between single-quoted and double-quoted strings in PHP?

Things get evaluated in double quotes but not in single:

$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.

How to read a file in other directory in python

In case you're not in the specified directory (i.e. direct), you should use (in linux):

x_file = open('path/to/direct/filename.txt')

Note the quotes and the relative path to the directory.

This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.

MySQL "NOT IN" query

Be carefull NOT IN is not an alias for <> ANY, but for <> ALL!

http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

SELECT c FROM t1 LEFT JOIN t2 USING (c) WHERE t2.c IS NULL

cant' be replaced by

SELECT c FROM t1 WHERE c NOT IN (SELECT c FROM t2)

You must use

SELECT c FROM t1 WHERE c <> ANY (SELECT c FROM t2)

How to use HTML to print header and footer on every printed page of a document?

I believe the correct answer is that HTML 5 and CSS3 have no support for printing page header and footers in print media.

And while you might be able to simulate it with:

  • tables
  • fixed position blocks

they each have bugs that prevent them from being the ideal general solution.

Java: how to use UrlConnection to post request with authorization?

I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:

// HTTP POST request
private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:

static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

The encode function translates the string into application/x-www-form-urlencoded.

Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.

For this particular scenario, the following should work:

String data = "product[title]=" + title +
                "&product[content]=" + content + 
                "&product[price]=" + price.toString() +
                "&tags=" + tags;

Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.

Configure apache to listen on port other than 80

Run this command if your ufw(Uncomplicatd Firewall) is enabled . Add for Example port 8080

$ sudo ufw allow 8080/tcp

And you can check the status by running

$ sudo ufw status

For more info check : https://linuxhint.com/ubuntu_allow_port_firewall

Parsing string as JSON with single quotes?

I know it's an old post, but you can use JSON5 for this purpose.

<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>

Testing whether a value is odd or even

_x000D_
_x000D_
for(var a=0; a<=20;a++){
   if(a%2!==0){
       console.log("Odd number "+a);
   }
}

for(var b=0; b<=20;a++){
    if(b%2===0){
        console.log("Even number "+b);  
    }     
 }
_x000D_
_x000D_
_x000D_

python: how to get information about a function?

In python: help(my_list.append) for example, will give you the docstring of the function.

>>> my_list = []
>>> help(my_list.append)

    Help on built-in function append:

    append(...)
        L.append(object) -- append object to end

Redirect from an HTML page

Just for good measure:

<?php
header("Location: [email protected]", TRUE, 303);
exit;
?>

Make sure there are no echo's above the script otherwise it will be ignored. http://php.net/manual/en/function.header.php

Creating an empty list in Python

Just to highlight @Darkonaut answer because I think it should be more visible.

new_list = [] or new_list = list() are both fine (ignoring performance), but append() returns None, as result you can't do new_list = new_list.append(something).

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

Why should I use core.autocrlf=true in Git?

The only specific reasons to set autocrlf to true are:

  • avoid git status showing all your files as modified because of the automatic EOL conversion done when cloning a Unix-based EOL Git repo to a Windows one (see issue 83 for instance)
  • and your coding tools somehow depends on a native EOL style being present in your file:

Unless you can see specific treatment which must deal with native EOL, you are better off leaving autocrlf to false (git config --global core.autocrlf false).

Note that this config would be a local one (because config isn't pushed from repo to repo)

If you want the same config for all users cloning that repo, check out "What's the best CRLF handling strategy with git?", using the text attribute in the .gitattributes file.

Example:

*.vcproj    text eol=crlf
*.sh        text eol=lf

Note: starting git 2.8 (March 2016), merge markers will no longer introduce mixed line ending (LF) in a CRLF file.
See "Make Git use CRLF on its “<<<<<<< HEAD” merge lines"

Footnotes for tables in LaTeX

In tables I have used \footnotetext.

How to drop a unique constraint from table column?

ALTER TABLE users
DROP CONSTRAINT 'constraints_name'

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

sequelize findAll sort order in nodejs

In sequelize you can easily add order by clauses.

exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        }, 
        // Add order conditions here....
        order: [
            ['id', 'DESC'],
            ['name', 'ASC'],
        ],
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
    });
};

See how I've added the order array of objects?

order: [
      ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],

Edit:

You might have to order the objects once they've been recieved inside the .then() promise. Checkout this question about ordering an array of objects based on a custom order:

How do I sort an array of objects based on the ordering of another array?

OS X cp command in Terminal - No such file or directory

I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).

I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.

So, as an example:

cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]

How to margin the body of the page (html)?

Yeah a CSS primer will not hurt here so you can do two things: 1 - within the tags of your html you can open a style tag like this:

<style type="text/css">
  body {
   margin: 0px;
  }
  /*
   * this is the same as writing
   * body { margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px;}
   * I'm adding px here for clarity sake but the unit is not really needed if you have 0
   * look into em, pt and % for other unit types 
   * the rules are always clockwise: top, right, bottom, left
  */
</style>

2- the above though will only work on the page you have this code embeded, so if if you wanted to reuse this in 10 files, then you will have to copy it over on all 10 files, and if you wanted to make a change let's say have a margin of 5px instead, you would have to open all those files and make the edit. That's why using an external style sheet is a golden rule in front end coding. So save the body declaration in a separate file named style.css for example and from your add this to your html instead:

<link rel="stylesheet" type="text/css" href="style.css"/>

Now you can put this in the of all pages that will benefit from these styles and whenever needed to change them you will only need to do so in one place. Hope it helps. Cheers

Find out whether radio button is checked with JQuery?

If you don't want a click function use Jquery change function

$('#radio_button :checked').live('change',function(){
alert('Something is checked.');
});

This should be the answer that you are looking for. if you are using Jquery version above 1.9.1 try to use on as live function had been deprecated.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

I also encountered this error. I have a Cordova application and the problem was that in config.xml I had a duplicated element <icon src="icon.png">, one pointing to an non-existing path.

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

Another option is using command line:

code -d left.txt right.txt

Note: You may need to add code to your path first. See: How to call VS Code Editor from command line

JUNIT testing void methods

If it is possible in your case, you could make your methods method1(arg1) ... method7() protected instead of private so they could be accesible from test class within the same package. Then you can simply test all theese methods separately.

Could not open input file: artisan

After installing composer, you need to create the project:

composer create-project laravel/laravel /path/to/tour/project

You can see the documentation, for your php version the lastest Laravel you can install is 5.0.

Now days here is the lastest version and require > php7.0. Here is the documentation.

Random record from MongoDB

you can also use shuffle-array after executing your query

var shuffle = require('shuffle-array');

Accounts.find(qry,function(err,results_array){ newIndexArr=shuffle(results_array);

What does "while True" mean in Python?

A while loop takes a conditional argument (meaning something that is generally either true or false, or can be interpreted as such), and only executes while the condition yields True.

As for while True? Well, the simplest true conditional is True itself! So this is an infinite loop, usually good in a game that requires lots of looping. (More common from my perspective, though, is to set some sort of "done" variable to false and then making that true to end the game, and the loop would look more like while not done: or whatever.)

If Browser is Internet Explorer: run an alternative script instead

This article is quite explanatory: http://msdn.microsoft.com/en-us/library/ms537509%28v=vs.85%29.aspx.

If your JS is unobtrusive, you can just use:

<![if !IE]>
   <script src...
<![endif]>

How to get device make and model on iOS?

Swift 3 compatible

// MARK: - UIDevice Extension -

private let DeviceList = [
/* iPod 5 */          "iPod5,1": "iPod Touch 5",
/* iPhone 4 */        "iPhone3,1":  "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4",
/* iPhone 4S */       "iPhone4,1": "iPhone 4S",
/* iPhone 5 */        "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5",
/* iPhone 5C */       "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C",
/* iPhone 5S */       "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S",
/* iPhone 6 */        "iPhone7,2": "iPhone 6",
/* iPhone 6 Plus */   "iPhone7,1": "iPhone 6 Plus",
/* iPhone 6S */       "iPhone8,1": "iPhone 6S",
/* iPhone 6S Plus */  "iPhone8,2": "iPhone 6S Plus",
/* iPhone SE */       "iPhone8,4": "iPhone SE",
/* iPhone 7 */        "iPhone9,1": "iPhone 7",
/* iPhone 7 */        "iPhone9,3": "iPhone 7",
/* iPhone 7 Plus */   "iPhone9,2": "iPhone 7 Plus",
/* iPhone 7 Plus */   "iPhone9,4": "iPhone 7 Plus",
/* iPad 2 */          "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2",
/* iPad 3 */          "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3":     "iPad 3",
/* iPad 4 */          "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4",
/* iPad Air */        "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air",
/* iPad Air 2 */      "iPad5,1": "iPad Air 2", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2",
/* iPad Mini */       "iPad2,5": "iPad Mini 1", "iPad2,6": "iPad Mini 1", "iPad2,7": "iPad Mini 1",
/* iPad Mini 2 */     "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2",
/* iPad Mini 3 */     "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3",
/* iPad Pro 12.9 */   "iPad6,7": "iPad Pro 12.9", "iPad6,8": "iPad Pro 12.9",
/* iPad Pro  9.7 */   "iPad6,3": "iPad Pro 9.7", "iPad6,4": "iPad Pro 9.7",
/* Simulator */       "x86_64": "Simulator", "i386": "Simulator"
]

extension UIDevice {

    static var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)

        let machine = systemInfo.machine
        let mirror = Mirror(reflecting: machine)

        var identifier = ""

        for child in mirror.children {
            if let value = child.value as? Int8, value != 0 {
                identifier += String(UnicodeScalar(UInt8(value)))
            }
        }
        return DeviceList[identifier] ?? identifier
    }

    static var isIphone4: Bool {
        return modelName == "iPhone 5" || modelName == "iPhone 5C" || modelName == "iPhone 5S" || UIDevice.isSimulatorIPhone4
    }

    static var isIphone5: Bool {
        return modelName == "iPhone 4S" || modelName == "iPhone 4" || UIDevice.isSimulatorIPhone5
    }

    static var isIphone6: Bool {
        return modelName == "iPhone 6" || UIDevice.isSimulatorIPhone6
    }
    static var isIphone6Plus: Bool {
        return modelName == "iPhone 6 Plus" || UIDevice.isSimulatorIPhone6Plus
    }

    static var isIpad: Bool {
        if UIDevice.current.model.contains("iPad") {
            return true
        }
        return false
    }

    static var isIphone: Bool {
        return !self.isIpad
    }

    /// Check if current device is iPhone4S (and earlier) relying on screen heigth
    static var isSimulatorIPhone4: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(480)
    }

    /// Check if current device is iPhone5 relying on screen heigth
    static var isSimulatorIPhone5: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(568)
    }

    /// Check if current device is iPhone6 relying on screen heigth
    static var isSimulatorIPhone6: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(667)
    }

    /// Check if current device is iPhone6 Plus relying on screen heigth
    static var isSimulatorIPhone6Plus: Bool {
        return UIDevice.isSimulatorWithScreenHeigth(736)
    }

    private static func isSimulatorWithScreenHeigth(_ heigth: CGFloat) -> Bool {
        let screenSize: CGRect = UIScreen.main.bounds
        return modelName == "Simulator" && screenSize.height == heigth
    }

}

Spring security CORS Filter

There's 8 hours of my life I will never get back...

Make sure that you set both Exposed Headers AND Allowed Headers in your CorsConfiguration

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

git checkout tag, git pull fails in branch

In order to just download updates:

git fetch origin master

However, this just updates a reference called origin/master. The best way to update your local master would be the checkout/merge mentioned in another comment. If you can guarantee that your local master has not diverged from the main trunk that origin/master is on, you could use git update-ref to map your current master to the new point, but that's probably not the best solution to be using on a regular basis...

Can you center a Button in RelativeLayout?

It's really easy. Try the code below,

<RelativeLayout
    android:id="@+id/second_RL"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/first_RL"
    android:background="@android:color/holo_blue_bright"
    android:gravity="center">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</RelativeLayout>

How to Import Excel file into mysql Database from PHP

For >= 2nd row values insert into table-

$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    //print_r($emapData);
    //exit();
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
      mysql_query($sql);
    }                                              // add this line
}

How to do select from where x is equal to multiple values?

You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

How to get a list of column names

Easiest way to get the column names of the most recently executed SELECT is to use the cursor's description property. A Python example:

print_me = "("
for description in cursor.description:
    print_me += description[0] + ", "
print(print_me[0:-2] + ')')
# Example output: (inp, output, reason, cond_cnt, loop_likely)

Export result set on Dbeaver to CSV

The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.

iOS: Multi-line UILabel in Auto Layout

I was just fighting with this exact scenario, but with quite a few more views that needed to resize and move down as necessary. It was driving me nuts, but I finally figured it out.

Here's the key: Interface Builder likes to throw in extra constraints as you add and move views and you may not notice. In my case, I had a view half way down that had an extra constraint that specified the size between it and its superview, basically pinning it to that point. That meant that nothing above it could resize larger because it would go against that constraint.

An easy way to tell if this is the case is by trying to resize the label manually. Does IB let you grow it? If it does, do the labels below move as you expect? Make sure you have both of these checked before you resize to see how your constraints will move your views:

IB Menu

If the view is stuck, follow the views that are below it and make sure one of them doesn't have a top space to superview constraint. Then just make sure your number of lines option for the label is set to 0 and it should take care of the rest.

How to SSH into Docker?

I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.

However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

Select mySQL based only on month and year

$q="SELECT * FROM projects WHERE YEAR(date) = 2012 AND MONTH(date) = 1;

Need to find a max of three numbers in java

Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

In Summary, change below:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

Remove Sub String by using Python

import re
re.sub('<.*?>', '', string)
"i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"

The re.sub function takes a regular expresion and replace all the matches in the string with the second parameter. In this case, we are searching for all tags ('<.*?>') and replacing them with nothing ('').

The ? is used in re for non-greedy searches.

More about the re module.

Best way to restrict a text field to numbers only?

I use this:

    oEl.keypress(function(ev)
    {
        var sKey = String.fromCharCode(ev.which);
        if (!sKey.match(/[0-9]/) || !sKey === "") 
            ev.preventDefault();            
    });

The advantage is, that every key which does not provide an input to the field is still allowed, so you don't have to worry about every single special key. Even combos like CTRL + R do still work.

EDIT As this is not working in Firefox I had to modify the function a little:

    oEl.keypress(function(ev)
    {
        var iKeyCode = ev.which || ev.keyCode;
        var aSpecialKeysForFirefox = [8, 9, 13, 27, 37, 38, 39, 40, 46];
        var sKey = String.fromCharCode(iKeyCode);
        if (sKey !== "" && $.inArray(iKeyCode, aSpecialKeysForFirefox ) < 0 && !sKey.match(/[0-9]/)) {
            ev.preventDefault();
        }
    });

Explanation All Browsers handle jquerys keypress event differently. To make it work in FF the $.inArray check is added. As firefoxs keypress-event doesn't trigger when combinations like strg+tab are used, but the others do, the key.match approach still adds a little value to the latter, as it enables those combinations.

mssql '5 (Access is denied.)' error during restoring database

There are several causes for this error, I got this error because I checked "Reallocate all files to folder" in the Files tab of Restore Database window but the default path did not exist on my local machine. I had the ldf/mdf files in another folder, once I changed that I was able to restore.

Show animated GIF

Using swing you could simply use a JLabel

 public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("<URL to your Animated GIF>");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);

        JFrame f = new JFrame("Animation");
        f.getContentPane().add(label);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

Display current time in 12 hour format with AM/PM

Using Java 8:

LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(localTime.format(dateTimeFormatter));

The output is in AM/PM Format.

Sample output:  3:00 PM

The import org.apache.commons cannot be resolved in eclipse juno

You could also add the external jar file to the project. Go to your project-->properties-->java build path-->libraries, add external JARS. Then add your downloaded jar file.

How can I check that JButton is pressed? If the isEnable() is not work?

Use this Command

if(JButton.getModel().isArmed()){
    //your code here.
    //your code will be only executed if JButton is clicked.
}

Answer is short. But it worked for me. Use the variable name of your button instead of "JButton".

Enable binary mode while restoring a Database from an SQL dump

The file you are trying to import is a zip file. Unzip the file and then try to import again.

How do I make a burn down chart in Excel?

Thank you for your answers! They definitely led me on the right track. But none of them completely got me everything I wanted, so here's what I actually ended up doing.

The key piece of information I was missing was that I needed to put the data together in one big block, but I could still leave empty cells in it. Something like this:

  Date         Actual remaining     Desired remaining
7/13/2009            7350                 7350
7/15/2009            7100
7/21/2009            7150
7/23/2009            6600
7/27/2009            6550
8/8/2009             6525
8/16/2009            6200
11/3/2009                                  0

Now I have something Excel is a little better at charting. So long as I set the chart options to "Show empty cells as: Connect data points with line," it ends up looking pretty nice. Using the above test data:

Book burn down chart

Then I just needed my update macro to insert new rows above the last one to fill in new data whenever I want. My macro looks something like this:

' Find the last cell on the left going down.  This will be the last cell 
' in the "Date" column
Dim left As Range
Set left = Range("A1").End(xlDown)

' Move two columns to the right and select so we have the 3 final cells, 
' including "Date", "Actual remaining", and "Desired remaining"
Dim bottom As Range
Set bottom = Range(left.Cells(1), left.Offset(0, 2))

' Insert a new blank row, and then move up to account for it
bottom.Insert (xlShiftDown)
Set bottom = bottom.Offset(-1)

' We are now sitting on some blank cells very close to the end of the data,
' and are ready to paste in new values for the date and new pages remaining

' (I do this by grabbing some other cells and doing a PasteSpecial into bottom)

Improvement suggestions on that macro are welcome. I just fiddled with it until it worked.

Now I have a pretty chart and I can nerd out all I want with my nerdy books for nerds.

Reverse engineering from an APK file to a project

There is a new way to do this.

Android Studio 2.2 has APK Analyzer it will give lot of info about apk, checkout it here :- http://android-developers.blogspot.in/2016/05/android-studio-22-preview-new-ui.html

Ap

ActionLink htmlAttributes

@Html.ActionLink("display name", "action", "Contorller"
    new { id = 1 },Html Attribute=new {Attribute1="value"})

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

How do I initialize an empty array in C#?

You can define array size at runtime.

This will allow you to do whatever to dynamically compute the array's size. But, once defined the size is immutable.

Array a = Array.CreateInstance(typeof(string), 5);

How to determine if .NET Core is installed

After all the other answers, this might prove useful.

Open your application in Visual Studio. In Solutions Explorer, right click your project. Click Properties. Click Application. Under "Target Framework" click the dropdown button and there you are, all of the installed frameworks.

BTW - you may now choose which framework you want.

Is 'bool' a basic datatype in C++?

Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

Transpose/Unzip Function (inverse of zip)?

I like to use zip(*iterable) (which is the piece of code you're looking for) in my programs as so:

def unzip(iterable):
    return zip(*iterable)

I find unzip more readable.

Printing chars and their ASCII-code in C

This prints out all ASCII values:

int main()
{
    int i;
    i=0;
    do
    {
        printf("%d %c \n",i,i);
        i++;
    }
    while(i<=255);
    return 0;
}

and this prints out the ASCII value for a given character:

int main()
{
    int e;
    char ch;
    clrscr();
    printf("\n Enter a character : ");
    scanf("%c",&ch);
    e=ch;
    printf("\n The ASCII value of the character is : %d",e);
    getch();
    return 0;
}

How to get an absolute file path in Python

In case someone is using python and linux and looking for full path to file:

>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file

UIView touch event in controller

Updating @Crashalot's answer for Swift 3.x:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

GUI-based or Web-based JSON editor that works like property explorer

Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.

Converting a structure to JSON is very straightforward:

use strict;
use warnings;
use JSON::Any;

my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);

Filter Java Stream to 1 and only 1 element

Inspired by @skiwi, I solved it the following way:

public static <T> T toSingleton(Stream<T> stream) {
    List<T> list = stream.limit(1).collect(Collectors.toList());
    if (list.isEmpty()) {
        return null;
    } else {
        return list.get(0);
    }
}

And then:

User user = toSingleton(users.stream().filter(...).map(...));

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

How to change webservice url endpoint?

To add some clarification here, when you create your service, the service class uses the default 'wsdlLocation', which was inserted into it when the class was built from the wsdl. So if you have a service class called SomeService, and you create an instance like this:

SomeService someService = new SomeService();

If you look inside SomeService, you will see that the constructor looks like this:

public SomeService() {
        super(__getWsdlLocation(), SOMESERVICE_QNAME);
}

So if you want it to point to another URL, you just use the constructor that takes a URL argument (there are 6 constructors for setting qname and features as well). For example, if you have set up a local TCP/IP monitor that is listening on port 9999, and you want to redirect to that URL:

URL newWsdlLocation = new URL("http://theServerName:9999/somePath");
SomeService someService = new SomeService(newWsdlLocation);

and that will call this constructor inside the service:

public SomeService(URL wsdlLocation) {
    super(wsdlLocation, SOMESERVICE_QNAME);
}

C# Timer or Thread.Sleep

I required a thread to fire once every minute (see question here) and I've now used a DispatchTimer based on the answers I received.

The answers provide some references which you might find useful.

test if display = none

Try this instead to only select the visible elements under the tbody:

$('tbody :visible').highlight(myArray[i]);

How to get directory size in PHP

Regarding Johnathan Sampson's Linux example, watch out when you are doing an intval on the outcome of the "du" function, if the size is >2GB, it will keep showing 2GB.

Replace:

$totalSize = intval(fgets($io, 80));

by:

strtok(fgets($io, 80), " ");

supposed your "du" function returns the size separated with space followed by the directory/file name.

What's the difference between SCSS and Sass?

SCSS is the new syntax for Sass. In Extension wise, .sass for the SASS while .scss for the SCSS. Here SCSS has more logical and complex approach for coding than SASS. Therefore, for a newbie to software field the better choice is SCSS.

How do I increase the capacity of the Eclipse output console?

For C++ users, to increase the Build console output size see here

ie Windows > Preference > C/C++ > Build > Console

ASP.NET Custom Validator Client side & Server Side validation not firing

Server-side validation won't fire if client-side validation is invalid, the postback is not send.

Don't you have some other validation that doesn't pass?

The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient" and this will look for a function named TextBoxDTownCityClient as validation function, but the function name should be TextBoxDAddress1Client

(as you wrote)

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

If you only need two search terms, arguably the most readable approach is to run each search and intersect the results:

 comm -12 <(grep -rl word1 . | sort) <(grep -rl word2 . | sort)

The most efficient way to implement an integer based power function pow(int, int)

An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.

struct IeeeFloat
{

    unsigned int base : 23;
    unsigned int exponent : 8;
    unsigned int signBit : 1;
};


union IeeeFloatUnion
{
    IeeeFloat brokenOut;
    float f;
};

inline float twoToThe(char exponent)
{
    // notice how the range checking is already done on the exponent var 
    static IeeeFloatUnion u;
    u.f = 2.0;
    // Change the exponent part of the float
    u.brokenOut.exponent += (exponent - 1);
    return (u.f);
}

You can get more powers of 2 by using a double as the base type. (Thanks a lot to commenters for helping to square this post away).

There's also the possibility that learning more about IEEE floats, other special cases of exponentiation might present themselves.

Largest and smallest number in an array

using System;

namespace greatest
{

    class Greatest
    {
        public static void Main(String[] args)
        {   
            //get the number of elements
            Console.WriteLine("enter the number of elements");
            int i;
            i=Convert.ToInt32(Console.ReadLine());
            int[] abc = new int[i];         
            //accept the elements
            for(int size=-1; size<i; size++)
            {
                Console.WriteLine("enter the elements");
                abc[size]=Convert.ToInt32(Console.ReadLine());
            }
            //Greatest
            int max=abc.Max();
            int min=abc.Min();
            Console.WriteLine("the m", max);
            Console.WriteLine("the mi", min);

            Console.Read();
        }
    }
}

Any way to make plot points in scatterplot more transparent in R?

If you decide to use ggplot2, you can set transparency of overlapping points using the alpha argument.

e.g.

library(ggplot2)
ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 1/40)

How to save SELECT sql query results in an array in C# Asp.net

Use a SQL DATA READER:

In this example i use a List instead an array.

try
{
    SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);
    connection.Open();

    SqlDataReader reader = comm.ExecuteReader();
    List<string> str = new List<string>();
    int i=0;
    while (reader.Read())
    {
        str.Add( reader.GetValue(i).ToString() );
        i++;
    }
    reader.Close();
}
catch (Exception)
{
    throw;
}
finally
{
    connection.Close();
}

How to SELECT a dropdown list item by value programmatically

This is a simple way to select an option from a dropdownlist based on a string val

private void SetDDLs(DropDownList d,string val)
    {
        ListItem li;
        for (int i = 0; i < d.Items.Count; i++)
        {
            li = d.Items[i];
            if (li.Value == val)
            {
                d.SelectedIndex = i;
                break;
            }
        }
    }

Generate unique random numbers between 1 and 100

Modern JS Solution using Set (and average case O(n))

_x000D_
_x000D_
const nums = new Set();_x000D_
while(nums.size !== 8) {_x000D_
  nums.add(Math.floor(Math.random() * 100) + 1);_x000D_
}_x000D_
_x000D_
console.log([...nums]);
_x000D_
_x000D_
_x000D_

How to call a Parent Class's method from Child Class in Python?

ImmediateParentClass.frotz(self)

will be just fine, whether the immediate parent class defined frotz itself or inherited it. super is only needed for proper support of multiple inheritance (and then it only works if every class uses it properly). In general, AnyClass.whatever is going to look up whatever in AnyClass's ancestors if AnyClass doesn't define/override it, and this holds true for "child class calling parent's method" as for any other occurrence!

How do I redirect with JavaScript?

To redirect to another page, you can use:

window.location = "http://www.yoururl.com";

VS 2017 Git Local Commit DB.lock error on every commit

VS 2017 Git Local Commit DB.lock error on every commit

This issue must have been caused by a corrupt .ignore file.

If your IDE is Visual Studio please follow these steps to resolve this issue:

  1. Delete the .gitignore file from your project folder
  2. Go to Team Explorer
  3. Go to Home in Team Explorer
  4. Go to Settings
  5. Under GIT, Click Repository Settings
  6. Under - Ignore & Attributes Files - Under Ignore File - Click Add. You should see a notification that the Ignore File has been successfully created
  7. Build your solution. It will take a little while and create a new .ignore file once build is successful
  8. You should now be able to Commit and Push without any further issue

NB: Bear in mind that your version of visual studio might place these options differently. I am using Visual Studio 2019 Community Edition.

How do I express "if value is not empty" in the VBA language?

I am not sure if this is what you are looking for

if var<>"" then
           dosomething

or

if isempty(thisworkbook.sheets("sheet1").range("a1").value)= false then

the ISEMPTY function can be used as well

Repeat a task with a time delay?

In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

How to write a test which expects an Error to be thrown in Jasmine?

For coffeescript lovers

expect( => someMethodCall(arg1, arg2)).toThrow()

WCF Service , how to increase the timeout?

The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.

Open PDF in new browser full window

I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I was still having problems after trying all of these ideas. This was my problem:

My remote heroku repository was funked. I refreshed it as follows:

git remote -v

Then remove the heroku one that is wrong:

git remote rm heroku

Then add the new one

git remote add heroku [email protected]:sitename.git

You can get the sitename from your Heroku settings page for your app. Good Luck!

OnItemCLickListener not working in listview

if you have textviews, buttons or stg clickable or selectable in your row view only

android:descendantFocusability="blocksDescendants"

is not enough. You have to set

android:textIsSelectable="false"

to your textviews and

android:focusable="false"

to your buttons and other focusable items.

Root user/sudo equivalent in Cygwin?

I met this discussion looking for some details on the sudo implementation in different operating systems. Reading it I found that the solution by @brian-white (https://stackoverflow.com/a/42956057/3627676) is useful but can be improved slightly. I avoided creating the temporary file and implemented to execute everything by the single script.

Also I investigated the next step of the improvement to output within the single window/console. Unfortunately, without any success. I tried to use named pipes to capture STDOUT/STDERR and print in the main window. But child process didn't write to named pipes. However writing to a regular file works well.

I dropped any attempts to find the root cause and left the current solution as is. Hope my post can be useful as well.

Improvements:

  • no temporary file
  • no parsing and reconstructing the command line options
  • wait the elevated command
  • use mintty or bash, if the first one not found
  • return the command exit code

    #!/bin/bash

    # Being Administrators, invoke the command directly
    id -G | grep -qw 544 && {
        "$@"
        exit $?
    }

    # The CYG_SUDO variable is used to control the command invocation
    [ -z "$CYG_SUDO" ] && {
        mintty="$( which mintty 2>/dev/null )"
        export CYG_SUDO="$$"
        cygstart --wait --action=runas $mintty /bin/bash "$0" "$@"
        exit $?
    }

    # Now we are able to:
    # -- launch the command
    # -- display the message
    # -- return the exit code
    "$@"
    RETVAL=$?

    echo "$0: Press  to close window..."
    read

    exit $RETVAL

What is the argument for printf that formats a long?

I think you mean:

unsigned long n;
printf("%lu", n);   // unsigned long

or

long n;
printf("%ld", n);   // signed long

using c# .net libraries to check for IMAP messages from gmail servers

LumiSoft.ee - works great, fairly easy. Compiles with .NET 4.0.

Here are the required links to their lib and examples. Downloads Main:

http://www.lumisoft.ee/lsWWW/Download/Downloads/

Code Examples:

are located here: ...lsWWW/Download/Downloads/Examples/

.NET:

are located here: ...lsWWW/Download/Downloads/Net/

I am putting a SIMPLE sample up using their lib on codeplex (IMAPClientLumiSoft.codeplex.com). You must get their libraries directly from their site. I am not including them because I don't maintain their code nor do I have any rights to the code. Go to the links above and download it directly. I set LumiSoft project properties in my VS2010 to build all of it in .NET 4.0 which it did with no errors. Their samples are fairly complex and maybe even overly tight coding when just an example. Although I expect that these are aimed at advanced level developers in general.

Their project worked with minor tweaks. The tweaks: Their IMAP Client Winform example is set in the project properties as "Release" which prevents VS from breaking on debug points. You must use the solution "Configuration Manager" to set the project to "Active(Debug)" for breakpoints to work. Their examples use anonymous methods for event handlers which is great tight coding... not real good as a teaching tool. My project uses "named" event method handlers so you can set breakpoints inside the handlers. However theirs is an excellent way to handle inline code. They might have used the newer Lambda methods available since .NET 3.0 but did not and I didn't try to convert them.

From their samples I simplified the IMAP client to bare minimum.

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

Register DLL file on Windows Server 2008 R2

You might need to register this DLL using the 32 bit version of regsvr32.exe:

c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll

Jenkins fails when running "service start jenkins"

I was trying to install it in kubuntu 18.04, and i was already sure that i had java installed, I confirmed by trying

java -version

I got the output like that

java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

Since I already know that my java PATH variables are defined in /etc/environment file, I added that file to the top of /etc/init.d/jenkins file

source /etc/environment

you can even remove the PATH from /etc/init.d/jenkins file, since it's already defined in /etc/environment

after that, i restarted my jenkins server,and it seemed to start working fine from localhost:8080

Make an Installation program for C# applications and include .NET Framework installer into the setup

Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:

Here is my step-by-step for windows forms application:

  1. Create setup project. You can use Setup Wizard.

    enter image description here

  2. Select project type.

    enter image description here

  3. Select output.

    enter image description here

  4. Hit Finish.

  5. Open setup project properties.

    enter image description here

  6. Chose to include .NET framework.

    enter image description here

  7. Build setup project

  8. Check output

    enter image description here


Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:

Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects

Fastest way to serialize and deserialize .NET objects

Here's your model (with invented CT and TE) using protobuf-net (yet retaining the ability to use XmlSerializer, which can be useful - in particular for migration); I humbly submit (with lots of evidence if you need it) that this is the fastest (or certainly one of the fastest) general purpose serializer in .NET.

If you need strings, just base-64 encode the binary.

[XmlType]
public class CT {
    [XmlElement(Order = 1)]
    public int Foo { get; set; }
}
[XmlType]
public class TE {
    [XmlElement(Order = 1)]
    public int Bar { get; set; }
}
[XmlType]
public class TD {
    [XmlElement(Order=1)]
    public List<CT> CTs { get; set; }
    [XmlElement(Order=2)]
    public List<TE> TEs { get; set; }
    [XmlElement(Order = 3)]
    public string Code { get; set; }
    [XmlElement(Order = 4)]
    public string Message { get; set; }
    [XmlElement(Order = 5)]
    public DateTime StartDate { get; set; }
    [XmlElement(Order = 6)]
    public DateTime EndDate { get; set; }

    public static byte[] Serialize(List<TD> tData) {
        using (var ms = new MemoryStream()) {
            ProtoBuf.Serializer.Serialize(ms, tData);
            return ms.ToArray();
        }            
    }

    public static List<TD> Deserialize(byte[] tData) {
        using (var ms = new MemoryStream(tData)) {
            return ProtoBuf.Serializer.Deserialize<List<TD>>(ms);
        }
    }
}

MINGW64 "make build" error: "bash: make: command not found"

You have to install mingw-get and after that you can run mingw-get install msys-make to have the command make available.

Here is a link for what you want http://www.mingw.org/wiki/getting_started

Formatting a Date String in React Native

The Date constructor is very picky about what it allows. The string you pass in must be supported by Date.parse(), and if it is unsupported, it will return NaN. Different versions of JavaScript do support different formats, if those formats deviate from the official ISO documentation.

See the examples here for what is supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

How do I find the difference between two values without knowing which is larger?

use this function.

its the same convention you wanted. using the simple abs feature of python.

also - sometimes the answers are so simple we miss them, its okay :)

>>> def distance(x,y):
    return abs(x-y)

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

This is a late answer, but I just came across this... To get the indenting correct on any lines that wrap, try it this way:

ul {
  list-style: none;
  margin-left: 0;
  padding-left: 0;
}

li {
  padding-left: 1em;
  text-indent: -1em;
}

li:before {
  content: "+";
  padding-right: 5px;
}

Catching FULL exception message

The following worked well for me

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

The result of this is the following as a string instead of an ErrorRecord object

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

How can I maintain fragment state when added to the back stack?

Perfect solution that find old fragment in stack and load it if exist in stack.

/**
     * replace or add fragment to the container
     *
     * @param fragment pass android.support.v4.app.Fragment
     * @param bundle pass your extra bundle if any
     * @param popBackStack if true it will clear back stack
     * @param findInStack if true it will load old fragment if found
     */
    public void replaceFragment(Fragment fragment, @Nullable Bundle bundle, boolean popBackStack, boolean findInStack) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        String tag = fragment.getClass().getName();
        Fragment parentFragment;
        if (findInStack && fm.findFragmentByTag(tag) != null) {
            parentFragment = fm.findFragmentByTag(tag);
        } else {
            parentFragment = fragment;
        }
        // if user passes the @bundle in not null, then can be added to the fragment
        if (bundle != null)
            parentFragment.setArguments(bundle);
        else parentFragment.setArguments(null);
        // this is for the very first fragment not to be added into the back stack.
        if (popBackStack) {
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        } else {
            ft.addToBackStack(parentFragment.getClass().getName() + "");
        }
        ft.replace(R.id.contenedor_principal, parentFragment, tag);
        ft.commit();
        fm.executePendingTransactions();
    }

use it like

Fragment f = new YourFragment();
replaceFragment(f, null, boolean true, true); 

How to force open links in Chrome not download them?

To make certain file types OPEN on your computer, instead of Chrome Downloading...

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.

Now the file type will always OPEN using your default program.

To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads

Hope this helps.. :-)

Visual Instructions found here:

http://www.presentermedia.com/blog/2013/10/my-file-automatically-opens-instead-of-saving-with-chrome/

Determine if map contains a value for a key?

Boost multindex can be used for proper solution. Following solution is not a very best option but might be useful in few cases where user is assigning default value like 0 or NULL at initialization and want to check if value has been modified.

Ex.
< int , string >
< string , int > 
< string , string > 

consider < string , string >
mymap["1st"]="first";
mymap["second"]="";
for (std::map<string,string>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
{
       if ( it->second =="" ) 
            continue;
}

Using custom fonts using CSS?

To make sure that your font is cross-browser compatible, make sure that you use this syntax:

@font-face {
    font-family: 'Comfortaa Regular';
    src: url('Comfortaa.eot');
    src: local('Comfortaa Regular'), 
         local('Comfortaa'), 
         url('Comfortaa.ttf') format('truetype'),
         url('Comfortaa.svg#font') format('svg'); 
}

Taken from here.

What is the difference between supervised learning and unsupervised learning?

There are many answers already which explain the differences in detail. I found these gifs on codeacademy and they often help me explain the differences effectively.

Supervised Learning

enter image description here Notice that the training images have labels here and that the model is learning the names of the images.

Unsupervised Learning

enter image description here Notice that what's being done here is just grouping(clustering) and that the model doesn't know anything about any image.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

You need to add sudo . I did the following to get it installed :

sudo apt-get install libsm6 libxrender1 libfontconfig1

and then did that (optional! maybe you won't need it)

sudo python3 -m pip install opencv-contrib-python

FINALLY got it done !

A regex for version number parsing

I'd express the format as:

"1-3 dot-separated components, each numeric except that the last one may be *"

As a regexp, that's:

^(\d+\.)?(\d+\.)?(\*|\d+)$

[Edit to add: this solution is a concise way to validate, but it has been pointed out that extracting the values requires extra work. It's a matter of taste whether to deal with this by complicating the regexp, or by processing the matched groups.

In my solution, the groups capture the "." characters. This can be dealt with using non-capturing groups as in ajborley's answer.

Also, the rightmost group will capture the last component, even if there are fewer than three components, and so for example a two-component input results in the first and last groups capturing and the middle one undefined. I think this can be dealt with by non-greedy groups where supported.

Perl code to deal with both issues after the regexp could be something like this:

@version = ();
@groups = ($1, $2, $3);
foreach (@groups) {
    next if !defined;
    s/\.//;
    push @version, $_;
}
($major, $minor, $mod) = (@version, "*", "*");

Which isn't really any shorter than splitting on "." ]

What is the difference between concurrency and parallelism?

Parallelism: Having multiple threads do similar task which are independent of each other in terms of data and resource that they require to do so. Eg: Google crawler can spawn thousands of threads and each thread can do it's task independently.

Concurrency: Concurrency comes into picture when you have shared data, shared resource among the threads. In a transactional system this means you have to synchronize the critical section of the code using some techniques like Locks, semaphores, etc.

Count number of records returned by group by

Try this query:

select top 1 TotalRows = count(*) over () 
from yourTable
group by column1, column2

Fluid width with equally spaced DIVs

If you know the number of elements per "row" and the width of the container you can use a selector to add a margin to the elements you need to cause a justified look.

I had rows of three divs I wanted justified so used the:

.tile:nth-child(3n+2) { margin: 0 10px }

this allows the center div in each row to have a margin that forces the 1st and 3rd div to the outside edges of the container

Also great for other things like borders background colors etc

How to use DISTINCT and ORDER BY in same SELECT statement?

You can use CTE:

WITH DistinctMonitoringJob AS (
    SELECT DISTINCT Category Distinct_Category FROM MonitoringJob 
)

SELECT Distinct_Category 
FROM DistinctMonitoringJob 
ORDER BY Distinct_Category DESC

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

Error: The type exists in both directories

TRY THIS ONE!

Normally, when this happen locally, i clean all the aspnet temp folder. But recently it was happing when i published my website in Azure. So "clean temp aspnet folder" was not a solution.

After searching on the internet, i founded this:

Clear Temp ASP.NET files from Azure Web Site

It works for me!

rand() between 0 and 1

This is the right way:

double randd() {
  return (double)rand() / ((double)RAND_MAX + 1);
}

or

double randd() {
  return (double)rand() / (RAND_MAX + 1.0);
}

Input type DateTime - Value format?

with momentjs i use

moment(value).format("YYYY-MM-DDTHH:mm:ss")

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

How to find a whole word in a String in java

How about something like Arrays.asList(String.split(" ")).contains("xx")?

See String.split() and How can I test if an array contains a certain value.

How to work with string fields in a C struct?

This does not work:

string s = (string)malloc(sizeof string); 

string refers to a pointer, you need the size of the structure itself:

string s = malloc(sizeof (*string)); 

Note the lack of cast as well (conversion from void* (malloc's return type) is implicitly performed).

Also, in your main, you have a globally delcared patient, but that is uninitialized. Try:

 patient.number = 3;     
 patient.name = "John";     
 patient.address = "Baker street";     
 patient.birthdate = "4/15/2012";     
 patient.gender = 'M';     

before you read-access any of its members

Also, strcpy is inherently unsafe as it does not have boundary checking (will copy until the first '\0' is encountered, writing past allocated memory if the source is too long). Use strncpy instead, where you can at least specify the maximum number of characters copied -- read the documentation to ensure you pass the correct value, it is easy to make an off-by-one error.

IE8 support for CSS Media Query

Prior to Internet Explorer 8 there were no support for Media queries. But depending on your case you can try to use conditional comments to target only Internet Explorer 8 and lower. You just have to use a proper CSS files architecture.

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

How to download dependencies in gradle

For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window. enter image description here