text:
<BroadcastMonitor>
  <updated>2015-08-11T07:55:10</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-11T07:55:10</startTime>
    <itemId>1000080622:1245304</itemId>
    <titleId>216087803</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** Hey ya (EERST JAAP) (Outkast cover)</titleName>
    <artistName>Alice Russell</artistName>
    <albumName></albumName>
    <CategoryCode>841</CategoryCode>
    <CategoryName>Live Muziek</CategoryName>
    <itemDuration>181</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-11T07:58:12</startTime>
    <itemId>1000080622:1244114</itemId>
    <titleId>216118584</titleId>
    <itemCode>08735</itemCode>
    <itemReference></itemReference>
    <titleName>Lo And Behold</titleName>
    <artistName>Sarah Marie Young</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>203</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
package ualberta.cmput301w16t16.glamorousborrowingwhaleapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * This activity shows ONE of the current user's available items. It gives the user the
 * chance to edit any of the information associated with the item (size, sport,
 * status etc). This class also allows the user to delete an item if they want. Careful! If
 * deleted, it is gooonneee forever.
 * @author adam, andrew, erin, laura, martina
 */

public class MyItemActivity extends AppCompatActivity {
    private Item item;
    private EditText owner;
    private TextView status;
    private EditText name;
    private EditText size;
    private EditText sport;
    private EditText description;
    private TextView highestBid;
    private ImageView photo;
    private User user;
    private Boolean boolStatus;
    private String oldID;
    private String newID;
    private int result;
    private byte[] photoStream = new byte[65536];
    private ArrayAdapter<Bid> adapter;
    private ArrayList<Bid> bids = new ArrayList<>();
    private Button acceptButton;
    private Button rejectButton;
    private RatingBar myItemRatingBar;
    private float calcRating; // calculated average rating

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_item);
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("My Item");
        actionBar.setHomeButtonEnabled(true);
        //setTitle("My Item");
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        /**
         * Sets the user and item for this activity and grabs the EditText things for use.
         */
        item = ItemController.getItem();
        user = UserController.getUser();
        owner = (EditText) findViewById(R.id.owner);
        status = (TextView) findViewById(R.id.status);
        name = (EditText) findViewById(R.id.name);
        size = (EditText) findViewById(R.id.size);
        sport = (EditText) findViewById(R.id.sport);
        description = (EditText) findViewById(R.id.description);
        photo = (ImageView) findViewById(R.id.pictureView);
        myItemRatingBar = (RatingBar) findViewById(R.id.myRatingBar);

        ImageButton saveButton = (ImageButton) findViewById(R.id.save);
        ImageButton deleteButton = (ImageButton) findViewById(R.id.delete);
        ImageButton myComment = (ImageButton) findViewById(R.id.myItemComment);
        Button bidsOnThisItem = (Button) findViewById(R.id.viewAllBidsButton);

        //The view is updated by asking the user object for its information.
        owner.setText(UserController.getUser().getUsername()); // shouldn't be on this page unless current user = owner
        boolStatus = item.getAvailability();
        if (boolStatus == false) {
            status.setText("Borrowed by "+item.getRenterID());
        } else {
            if (item.getBids().isEmpty()) {
                status.setText("Available");
            } else {
                status.setText("Bidded");
            }
        }
        name.setText(item.getTitle());
        description.setText(item.getDescription());
        size.setText(item.getSize());
        sport.setText(item.getSport());

        bidsOnThisItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyItemActivity.this, BidsForOneItemActivity.class);
                startActivity(intent);
            }
        });

        if (item.getPhoto() != null) {
            photo.setImageBitmap(item.getPhoto());
        }

        //Bids is not implemented yet.
        //Removing setBids activities for now.
        //bids = item.getBids();

        /**
         * saveButton is onClick and leverages the ItemController for its item.
         * The item's attributes are then set from the EditText boxes.
         */

        //TODO needs error checking and type check etc.
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtil.getConnectivityStatus(v.getContext()) == 1) {
                    item = ItemController.getItem();
                    // picture management
                    if (photo == null) {
                        photo.setImageResource(R.drawable.glamorouswhale1);
                    }
                    Bitmap image = ((BitmapDrawable) photo.getDrawable()).getBitmap();
                    ByteArrayOutputStream photosNeedToBeCompressedToThis = new ByteArrayOutputStream();
                    image.compress(Bitmap.CompressFormat.JPEG, 100, photosNeedToBeCompressedToThis);
                    photoStream = photosNeedToBeCompressedToThis.toByteArray();
                    item.setTitle(name.getText().toString());
                    item.setDescription(description.getText().toString());
                    item.setSize(size.getText().toString());
                    item.setPhoto(photoStream);
                    //item.setBids(bids);
                    item.setOwnerID(user.getID());
                    oldID = item.getID();
                    ItemController.updateItemElasticSearch(item);
                    newID = item.getID();
                    user.removeMyItem(oldID);
                    user.addMyItem(newID);
                    UserController.updateUserElasticSearch(user);
                    Toast.makeText(MyItemActivity.this, "Thing Saved!", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(MyItemActivity.this, "You are not connected to the internet.", Toast.LENGTH_SHORT).show();
                }
            }
        });

        /**
         * deleteButton deletes the item in the current view. (Recall the ItemController has the
         * item object).
         * Involves legit removing the item from the user's itemsRenting list. This can have a negative
         * impact as it may set the list to null (or worse) - to combat this we control it.
         * If an action will set the list to null, we leverage the ItemController and set that to
         * null, essentially "bypassing" the null list and it's many issues. Since the ItemController
         * is in a "controlled" null state, code may be implemented elsewhere that can handle this
         * simple condition.
         */

        // TODO: set myItemRatingBar.rating = average rating
        // use function 'avgRating' in RatingList activity
        //calcRating = item.calcAverageRating(item.ratings);
        myItemRatingBar.setRating(2.5f); // TODO: don't forget to change this, set constant for testing

        // Taken from http://stackoverflow.com/questions/7146976/android-how-to-set-the-rating-bar-is-non-clickable-and-touchable-in-htc-mobile
        // code makes rating bar non-clickable (UNTESTED)
        myItemRatingBar.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        myItemRatingBar.setFocusable(false);

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtil.getConnectivityStatus(v.getContext()) == 1) {
                new AlertDialog.Builder(MyItemActivity.this)
                        .setTitle("Delete Item?")
                        .setMessage("Are you sure you want to delete this item?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                    user.removeMyItem(item.getID());
                                    new ElasticSearch.elasticDeleteItem().execute(item);
                                    UserController.updateUserElasticSearch(user);
                                    ItemList itemList = ItemController.getItemList();
                                    itemList.remove(item);
                                    ItemController.setItemList(itemList);
                                    Toast.makeText(MyItemActivity.this, "Thing Deleted!", Toast.LENGTH_SHORT).show();
                                    setResult(Activity.RESULT_OK);
                                    finish();
                            }
                        })
                        .setNegativeButton("No", null)
                        .show();
                } else {
                    Toast.makeText(v.getContext(), "You are not connected to the internet", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // this is the gallery selection method for pictures
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int result = 0;
                Intent bringTheGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(bringTheGallery, result);
            }
        });

        myComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // code for when my comment button is pressed
                // view comments on item
            }
        });

    }
    //setting up the action bar icons
    //taken from http://www.androidhive.info/2013/11/android-working-with-action-bar/
    // Apr3/16
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.home:
                goToHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void goToHome() {
        Intent i = new Intent(MyItemActivity.this, MyProfileViewActivity.class);
        startActivity(i);
    }

    // this gets the returns from the photo and location Activities
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = data.getData();
                    photo.setImageURI(selectedImage);
                } else {
                    Toast.makeText(this, "Could not load image", Toast.LENGTH_SHORT).show();
                }
                break;
            case 1:
                if (resultCode == RESULT_OK) {
                    Location location = data.getParcelableExtra("location");
                    item.setLatitude(location.getLatitude());
                    item.setLongitude(location.getLongitude());
                } else {
                    Toast.makeText(this, "Could not get location", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        item = ItemController.getItem();
    }

    protected void onStop() {
        super.onStop();
    }

    public void launchGetLocation(View view) {
        Intent intent = new Intent(view.getContext(), GetLocationActivity.class);
        final int result = 1;
        startActivityForResult(intent, result);
    }

    public void deletePhoto(View view) {
        photo.setImageResource(R.drawable.glamorouswhale1);
        Toast.makeText(this, "photo returned to default!", Toast.LENGTH_SHORT).show();
    }

    public void deleteLocation(View view) {
        item.setLatitude(0);
        item.setLongitude(0);
        Toast.makeText(this, "location deleted!", Toast.LENGTH_SHORT).show();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/app.css">
  </head>
  <body>
    <div class="button-wrap">
      <button type="button" id="start">Start</button>
      <button type="button" id="stop">Stop</button>
    </div>

    <script src="/bundle.js"></script>
  </body>
</html>


text:
from __future__ import division, print_function, unicode_literals
__doc__ = """
Run this script AFTER doing Component from Selection on the Q tail and naming it _tail.Q.
"""

from copy import copy as copy
thisFont = Glyphs.font # frontmost font
O = thisFont.glyphs["O"]
Q = thisFont.glyphs["Q"]
tailGlyph = thisFont.glyphs["_tail.Q"]
anchorName = "bottom"
newAnchorName = "_" + anchorName

if not O or not Q or not tailGlyph:
	Message(title="Missing glyphs", message="For this script, you need 'O', 'Q' and '_tail.Q' in your font.", OKButton=None)
else:
	# del thisFont.glyphs["Q"]
	# thisFont.newGlyphWithName_("O+_tail.Q=Q")
	for thisLayer in tailGlyph.layers:
		thisMaster = thisLayer.associatedFontMaster()
		masterID = thisMaster.id

		# if necessary, add anchors to _tail.Q
		if not thisLayer.anchors[newAnchorName]:
			defaultPosition = O.layers[masterID].anchors[anchorName].position
			newAnchor = GSAnchor(newAnchorName, defaultPosition)
			thisLayer.anchors.append(newAnchor)

		# rebuild Q from O:
		targetLayer = Q.layers[masterID]
		targetLayer.clear()
		for componentName in (O.name, tailGlyph.name):
			newComponent = GSComponent(componentName)
			newComponent.automaticAlignment = True
			targetLayer.components.append(newComponent)

	# add special layers to _tail.Q:
	for layerIndex in range(len(Q.layers) - 1, -1, -1):
		thisLayer = Q.layers[layerIndex]
		if not thisLayer.isMasterLayer and thisLayer.isSpecialLayer:
			tailLayer = copy(thisLayer)

			# remove (O) components:
			for i in range(len(tailLayer.shapes) - 1, -1, -1):
				if type(tailLayer.shapes[i]) == GSComponent:
					del tailLayer.shapes[i]

			# add anchor:
			newAnchor = GSAnchor()
			newAnchor.name = newAnchorName
			newAnchor.position = O.layers[thisLayer.associatedMasterId].anchors[anchorName].position
			tailLayer.anchors.append(newAnchor)

			# add layer to _tail.Q:
			tailGlyph.layers.append(tailLayer)

			# remove layer from Q:
			del Q.layers[layerIndex]


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>dan200.computercraft.api (ComputerCraft 1.63)</title>
<meta name="date" content="2014-04-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

dan200.computercraft.api

Classes

ComputerCraftAPI


text:
In Mac use this command to manage the host from docker-machine.

```sh
docker-machine create -d=generic \
--generic-ip-address="192.168.80.100" \
--generic-ssh-key="/Users/$USER/.vagrant.d/insecure_private_key" \
--generic-ssh-user="core" docker-atlassian

# Export docker envs
eval "$(docker-machine env docker-atlassian)"
```
Now you can manage docker outside vagrant in your terminal as usual.

> Vagrant users: You will have to perform the `docker-compose up` within vagrant
> in `/var/docker/` otherwise docker-compose won't find `setup-jira-db.sh` and
> it will be mounted as a directory so Postgres won't be setup.


text:
class Counter(object):
  ''' Stores all the samples for a given counter.
  '''
  def __init__(self, parent, category, name):
    self.parent = parent
    self.full_name  = category + '.' + name
    self.category = category
    self.name = name
    self.samples = []
    self.timestamps = []
    self.series_names = []
    self.totals = []
    self.max_total = 0
    self._bounds = None

  @property
  def min_timestamp(self):
    if not self._bounds:
      self.UpdateBounds()
    return self._bounds[0]

  @property
  def max_timestamp(self):
    if not self._bounds:
      self.UpdateBounds()
    return self._bounds[1]

  @property
  def num_series(self):
    return len(self.series_names)

  @property
  def num_samples(self):
    return len(self.timestamps)

  def UpdateBounds(self):
    if self.num_series * self.num_samples != len(self.samples):
      raise ValueError(
          'Length of samples must be a multiple of length of timestamps.')

    self.totals = []
    self.max_total = 0
    if not len(self.samples):
      return

    self._bounds = (self.timestamps[0], self.timestamps[-1])

    max_total = None
    for i in xrange(self.num_samples):
      total = 0
      for j in xrange(self.num_series):
        total += self.samples[i * self.num_series + j]
        self.totals.append(total)
      if max_total is None or total > max_total:
        max_total = total
    self.max_total = max_total


text:
using std::ifstream;
using std::string;
using std::vector;
using YAML::Node;

namespace industrial_extrinsic_cal {

  void parsePoints(ifstream &points_input_file,vector<Point3d> &points)
  {
    // parse points
    try
      {
	YAML::Node points_doc = YAML::LoadFile(points_input_file.c_str());

	// read in all points
	points.clear();
	const YAML::Node points_node = points_doc("points");
	for (int j = 0; j < points_node.size(); j++){
	  const YAML::Node pnt_node = points_node[j]("pnt");
	  vector<float> temp_pnt;
	  temp_pnt =t_node.at< vector<float> >();
	  Point3d temp_pnt3d;
	  temp_pnt3d.x = temp_pnt[0];
	  temp_pnt3d.y = temp_pnt[1];
	  temp_pnt3d.z = temp_pnt[2];
	  points.push_back(temp_pnt3d);
	}
      }
    catch (YAML::ParserException& e){
      ROS_INFO_STREAM("Failed to read points file ");
    }
    ROS_INFO_STREAM("Successfully read in " <<(int) points.size() << " points");
  }// end of parse_points()

}// end of namespace industrial_extrinsic_cal


text:
The IMS Learning Tools Interoperability specification aims to establish a standard for integrating learning tools into a variety of platforms, such as an institution's learning management system. But what is LTI, specifically? How do you go about designing software to take advantage of it? And how do you actually integrate it with an LMS? Join us on a journey that starts with the basics of LTI—what it is and what it does—and ends with the implementation of a simple LTI tool that can be integrated into various LMS frameworks.

**OBJECTIVES:**
- Understand the basics of the LTI specification
- Know how to build a simple LTI tool in one of your favorite web application development languages such as PHP or Python
- Be able to integrate your LTI tool into your favorite LMS
- Gain access to a variety of LTI resources, such as tutorials, online courses, code libraries, and more

[Source](http://www.educause.edu/nercomp-conference/2014/2014/building-tools-learning-tool-interoperability-specification)

## Demo Quickstart

You will need [vagrant](http://www.vagrantup.com/), [virtual box](https://www.virtualbox.org/), and [git](http://git-scm.com/) installed.

```sh
$ git clone https://github.com/Harvard-ATG/nercomp-lti-basic.git
$ cd nercomp-lti-basic/demo
$ vagrant up
```

Open [http://localhost:8080/](http://localhost:8080). You should see a message saying *It works!*.

To view, modify, or just play around with the LTI demo tool code:

```sh
$ vagrant ssh
$ cd /var/www/lti-basic
$ ls -l
```

Good luck, have fun!


text:
"use strict";

function traverseDoc(doc, onEnter, onExit) {
  var hasStopped = false;
  function traverseDocRec(doc) {
    if (onEnter) {
      hasStopped = hasStopped || onEnter(doc) === false;
    }
    if (hasStopped) {
      return;
    }

    if (doc.type === "concat") {
      for (var i = 0; i < doc.parts.length; i++) {
        traverseDocRec(doc.parts[i]);
      }
    } else if (doc.type === "if-break") {
      if (doc.breakContents) {
        traverseDocRec(doc.breakContents);
      }
      if (doc.flatContents) {
        traverseDocRec(doc.flatContents);
      }
    } else if (doc.contents) {
      traverseDocRec(doc.contents);
    }

    if (onExit) {
      onExit(doc);
    }
  }

  traverseDocRec(doc);
}

function mapDoc(doc, func) {
  doc = func(doc);

  if (doc.type === "concat") {
    return Object.assign({}, doc, {
      parts: doc.parts.map(d => mapDoc(d, func))
    });
  } else if (doc.type === "if-break") {
    return Object.assign({}, doc, {
      breakContents: doc.breakContents && mapDoc(doc.breakContents, func),
      flatContents: doc.flatContents && mapDoc(doc.flatContents, func)
    });
  } else if (doc.contents) {
    return Object.assign({}, doc, { contents: mapDoc(doc.contents, func) });
  } else {
    return doc;
  }
}

function findInDoc(doc, fn, defaultValue) {
  var result = defaultValue;
  traverseDoc(doc, function(doc) {
    var maybeResult = fn(doc);
    if (maybeResult !== undefined) {
      result = maybeResult;
      return false;
    }
  });
  return result;
}

function isEmpty(n) {
  return typeof n === "string" && n.length === 0;
}

function getFirstString(doc) {
  return findInDoc(
    doc,
    doc => {
      if (typeof doc === "string" && doc.trim().length !== 0) {
        return doc;
      }
    },
    null
  );
}

function isLineNext(doc) {
  return findInDoc(
    doc,
    doc => {
      if (typeof doc === "string") {
        return false;
      }
      if (doc.type === "line") {
        return true;
      }
    },
    false
  );
}

function willBreak(doc) {
  return findInDoc(
    doc,
    doc => {
      if (doc.type === "group" && doc.break) {
        return true;
      }
      if (doc.type === "line" && doc.hard) {
        return true;
      }
      if (doc.type === "break-parent") {
        return true;
      }
    },
    false
  );
}

function breakParentGroup(groupStack) {
  if (groupStack.length > 0) {
    const parentGroup = groupStack[groupStack.length - 1];
    // Breaks are not propagated through conditional groups because
    // the user is expected to manually handle what breaks.
    if (!parentGroup.expandedStates) {
      parentGroup.break = true;
    }
  }
  return null;
}

function propagateBreaks(doc) {
  const groupStack = [];
  traverseDoc(
    doc,
    doc => {
      if (doc.type === "break-parent") {
        breakParentGroup(groupStack);
      }
      if (doc.type === "group") {
        groupStack.push(doc);
      }
    },
    doc => {
      if (doc.type === "group") {
        const group = groupStack.pop();
        if (group.break) {
          breakParentGroup(groupStack);
        }
      }
    }
  );
}

module.exports = {
  isEmpty,
  getFirstString,
  willBreak,
  isLineNext,
  traverseDoc,
  mapDoc,
  propagateBreaks
};


text:
'use strict';

var AppSettings = {
  appTitle: 'StackViz',
  healthRoot: 'http://status.openstack.org/openstack-health'
};

module.exports = AppSettings;


text:
import java.util.*;

public class BadExam {
    public double newAverage(int[] marks) {
        double average = 0;

        int max = Integer.MIN_VALUE;

        for(int i = 0; i < marks.length; i++) {
            max = Math.max(max, marks[i]);
        }

        for(int i = 0; i < marks.length; i++) {
            average += marks[i] * 100.0 / max;

        }

        return (average / marks.length);
    }
}

// Powered by FileEdit


text:
layout: default
---

# Week 4 Homework Feedback

## Weather Report

#### Specific Tests Once You Have Mocking

The mocking work that you all did was excellent.  Once you have it set up, though, you can be more specific with your tests.  Take this one, for instance:

    def test_wind
      wind = CurrentConditions.new(82009)
      assert wind.display_wind.match(/\d*?\.\d MPH/)
    end

No need to use broad regular expressions on this one; now that you've got a data set in a JSON file, you can be very specific about which MPH you expect to get.  You'd hate to be matching a different field that happens to use MPH and not realize it.

#### Testing Mocking

Here's a mock I saw:

    class SunRiseSet
      private def get_data
        JSON.parse(File.open("astronomy.json").read)
      end
    end

Looks good... except the actual class in your application was `SunUpDown`.  This means that your mock wasn't a monkey-patch of an existing class, so the mock never ran.

In order to test that you've mocked properly, you can always shut off your wifi and see if your tests will still run.

#### No User Input on Tests

Here's what I got when I ran a test suite:

    [masonfmatthews weather_report]$ ruby test.rb
    What zip code would you like to search for weather details? Press enter
    to exit

When you write tests, you want to make sure that no user input is needed.  If the user has to type something, the tests are (a) slower and (b) potentially brittle.

#### Class Variables

OH NOOOOOO!!!

    class WeatherTest < Minitest::Test

      @@summary = ConditionsSummary.new(27516)
      @@tenday = TenDayForecast.new(27516)
      @@alerts = Alerts.new(70032)
      @@astronomy = Astronomy.new(27516)
      @@hurricanes = Hurricanes.new

      def test...
      end

      ...
    end

Please no!  Never class variables!  This is somewhat better:

    class WeatherTest < Minitest::Test

      def setup
        @summary = ConditionsSummary.new(27516)
        @tenday = TenDayForecast.new(27516)
        @alerts = Alerts.new(70032)
        @astronomy = Astronomy.new(27516)
        @hurricanes = Hurricanes.new
      end

      def test...
      end

      ...
    end

The best, though, is to create them as you need them rather than all the time.  Code duplication in tests is no big deal.

#### Breaking out of Loops

Someone added a feature that let users continue to enter zip codes until they chose to stop.  Here's a section of the code:

    ...

    def repeat
      loop do
        puts
        print "Wanna go again?(Y/N): "
        input = gets.chomp
        puts
        break if input == 'y' || input == 'Y'
        exit if input == 'n' || input == 'N'
      end
    end

    welcome
    loop do
      zip = input
      forecast(zip)
      repeat
    end

This gives `repeat` a ton of power, including the ability to bring everything to a screeching halt with `exit`.  It's not good to give methods that power, because they can trash everything that calls them.  Here's a better way to accomplish the same thing:

    ...

    def repeat
      loop do
        puts
        print "Wanna go again?(Y/N): "
        input = gets.chomp
        puts
        return true if input == 'y' || input == 'Y'
        return false if input == 'n' || input == 'N'
      end
    end

    welcome
    loop do
      zip = input
      forecast(zip)
      break unless repeat
    end

#### `p` vs. `puts`

As you know, `p` is great for putting arrays to the console.  However, it gets weird with strings:

    What location would you like information for?
    27278
    "The temperature is now 88.7ºF."
    "Sunrise was at 6:03am."
    "The sun will set at 8:23pm today."

This is the output that I got when running one program.  The extra quotes are because of using `p`.  For simple things like strings, just use `puts`.

## Voter API

#### Being the RIGHT user, not just ANY user

Some submissions had a line like this:

    user = Voter.where(security_key: api_key).first if api_key

This looks up a user based on an key.  However, this would let me in if I had ANY valid key.  In other words, I could use my personal key to vote as ANYONE.  As we discussed in class, you should look the Voter up by `params[:id]`, then check to see if the key matches that specific user.

#### The magic number to rule them all

So...

    test "shows only one race" do
      senate = Race.create!(name: "Senate")
      get :show, {id: 980190963}
      assert_response :success
    end

That's a serious magic number.  Instead of putting that in (which might be different every time), do this:

    test "shows only one race" do
      senate = Race.create!(name: "Senate")
      get :show, {id: senate.id}
      assert_response :success
    end

#### More magic numbers

This test... probably won't work:

    test "should be able to destroy" do
      assert_difference("Vote.count") do
        delete :destroy, {voter_id: 1, candidate_id: 1, race_id: 2}
      end
    end

First off, if you're deleting something, it's best to assert that the difference will be negative one, like this: `assert_difference("Vote.count", -1)`.

Second, when you destroy, all you need to pass it is an `id`.

Beyond that, the numbers are really arbitrary.  The right way to do this is to write fixtures, then change your test to look more like this.

    test "should be able to destroy" do
      assert_difference("Vote.count", -1) do
        delete :destroy, id: vote(:one).id
      end
    end

#### Positive and negative in most tests

Here's a test that works well:

    test "candidate_id" do
      two = Vote.new(voter_id: 1)
      refute two.save
    end

It will be better, though, if it also had an `assert`.  Right now this test would be perfectly happy if it was always impossible to save a vote.  Probably want to make sure that it WILL save if you give it everything that it needs.

#### Where to put `before_action`

This code (which did not run) is worth discussing:

    def show
      before_action :require_security_key
      render json: Voter.find_by_id(params[:id])
    end

If you're going to use `before_action`, it goes outside the method.  If you want it to apply to EVERY action in the controller, you write it like this:

    class VotersController...
      before_action :require_security_key
      ...
    end

If you want to apply to ONLY the show action, you write it like this:

    class VotersController...
      before_action :require_security_key, only: [:show]
      ...
    end

You can put more things in that array if you want it to only apply to a few actions.


text:
def order_is_delivered(order_number)
  puts "Using order number: #{order_number}!"

  if Order.any? { |o| o.supplier_order_id.eql?(order_number) && o.order_events.any? { |e| "delivery_done".eql?(e.name) } }
    puts "Success! Order is delivered!"
    exit 0
  end

  puts "Failure! Order is NOT delivered!"
  exit 2
end

if ARGV.length < 1
  puts "Insufficient parameters passed."
  puts "Usage: #{$0} <supplier_order_number>"
  exit 2
end

order_is_delivered(ARGV[0].chomp)


text:
package org.secureauth.sarestapi.data;

import java.util.Hashtable;

public class SAConfig {
    private Hashtable<String, Object> config;
    private Boolean oldIdpSupport = false;
    private static volatile SAConfig instance = null;

    private SAConfig () {

    }

    public static synchronized SAConfig getInstance() {
        if (instance == null) {
            instance = new SAConfig();
        }
        return instance;
    }

    public void updateConfig( Hashtable<String, Object> newConfig ) {
        config = newConfig;
        oldIdpSupport = (Boolean) config.get("support.deprecated.idp");
    }

    public Boolean getOldIdPSupport() {
        return oldIdpSupport;
    }
}


text:
An online geocoding iOS sample app, modernized with suggestions and category support.The samples use ArcGIS Online basemaps and services.  Learn more [here](http://www.arcgis.com/about/).

![App](geocoding-with-suggestions-and-categories.png)

## Features
* Geocoding - Find and display addresses and POIs interactively
* Suggestions - Generate auto-complete suggestions interactively for search input
* Categories - Refine suggestions and geocoding based upon category selections

## Instructions

1. Fork and then clone the repo.
2. Run and try the samples.

## Requirements

* ArcGIS Runtime SDK for iOS
* Xcode
* OSX

## Resources

* [ArcGIS Geocoding REST API doc](https://developers.arcgis.com/rest/geocode/api-reference/overview-world-geocoding-service.htm)
* [ArcGIS Geocoding REST API - Suggest Operation doc](https://developers.arcgis.com/rest/geocode/api-reference/geocoding-suggest.htm)
* [ArcGIS Geocoding REST API - Category parameter doc](https://developers.arcgis.com/rest/geocode/api-reference/geocoding-category-filtering.htm)
* [ArcGIS iOS SDK](https://developers.arcgis.com/ios/)
* [ArcGIS iOS Sample apps](https://github.com/Esri/arcgis-runtime-samples-ios)

## Issues

Find a bug or want to request a new feature?  Please let us know by submitting an issue.

## Contributing

Esri welcomes contributions from anyone and everyone. Please see our [guidelines for contributing](https://github.com/esri/contributing).

## Licensing
Copyright 2015 Esri

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

A copy of the license is available in the repository's [license.txt](license.txt) file.

[](Esri Tags: ArcGIS Geocoding Suggestions Categories)
[](Esri Language: Objective-C)


text:
using System;
using System.Xml;
using NUnit.Common;
using NUnit.Engine.Internal;
using NUnit.Engine.Services;

namespace NUnit.Engine.Runners
{
    /// <summary>
    /// Summary description for ProcessRunner.
    /// </summary>
    public class ProcessRunner : AbstractTestRunner
    {
        private const int NORMAL_TIMEOUT = 30000;               // 30 seconds
        private const int DEBUG_TIMEOUT = NORMAL_TIMEOUT * 10;  // 5 minutes

        private static readonly Logger log = InternalTrace.GetLogger(typeof(ProcessRunner));

        private ITestAgent _agent;
        private ITestEngineRunner _remoteRunner;
        private TestAgency _agency;

        public ProcessRunner(IServiceLocator services, TestPackage package) : base(services, package)
        {
            _agency = Services.GetService<TestAgency>();
        }

        #region Properties

        public RuntimeFramework RuntimeFramework { get; private set; }

        #endregion

        #region AbstractTestRunner Overrides

        /// <summary>
        /// Explore a TestPackage and return information about
        /// the tests found.
        /// </summary>
        /// <param name="filter">A TestFilter used to select tests</param>
        /// <returns>A TestEngineResult.</returns>
        protected override TestEngineResult ExploreTests(TestFilter filter)
        {
            try
            {
                return _remoteRunner.Explore(filter);
            }
            catch (Exception e)
            {
                log.Error("Failed to run remote tests {0}", e.Message);
                return CreateFailedResult(e);
            }
        }

        /// <summary>
        /// Load a TestPackage for possible execution
        /// </summary>
        /// <returns>A TestEngineResult.</returns>
        protected override TestEngineResult LoadPackage()
        {
            log.Info("Loading " + TestPackage.Name);
            Unload();

            try
            {
                if (_agent == null)
                {
                    // Increase the timeout to give time to attach a debugger
                    bool debug = TestPackage.GetSetting(PackageSettings.DebugAgent, false) ||
                                 TestPackage.GetSetting(PackageSettings.PauseBeforeRun, false);

                    _agent = _agency.GetAgent(TestPackage, debug ? DEBUG_TIMEOUT : NORMAL_TIMEOUT);

                    if (_agent == null)
                        throw new Exception("Unable to acquire remote process agent");
                }

                if (_remoteRunner == null)
                    _remoteRunner = _agent.CreateRunner(TestPackage);

                return _remoteRunner.Load();
            }
            catch(Exception)
            {
                // TODO: Check if this is really needed
                // Clean up if the load failed
                Unload();
                throw;
            }
        }

        /// <summary>
        /// Unload any loaded TestPackage and clear
        /// the reference to the remote runner.
        /// </summary>
        public override void UnloadPackage()
        {
            try
            {
                if (_remoteRunner != null)
                {
                    log.Info("Unloading remote runner");
                    _remoteRunner.Unload();
                    _remoteRunner = null;
                }
            }
            catch (Exception e)
            {
                log.Warning("Failed to unload the remote runner. {0}", e.Message);
                _remoteRunner = null;
                throw;
            }
        }

        /// <summary>
        /// Count the test cases that would be run under
        /// the specified filter.
        /// </summary>
        /// <param name="filter">A TestFilter</param>
        /// <returns>The count of test cases</returns>
        protected override int CountTests(TestFilter filter)
        {
            try
            {
                return _remoteRunner.CountTestCases(filter);
            }
            catch (Exception e)
            {
                log.Error("Failed to count remote tests {0}", e.Message);
                return 0;
            }
        }

        /// <summary>
        /// Run the tests in a loaded TestPackage
        /// </summary>
        /// <param name="listener">An ITestEventHandler to receive events</param>
        /// <param name="filter">A TestFilter used to select tests</param>
        /// <returns>A TestResult giving the result of the test execution</returns>
        protected override TestEngineResult RunTests(ITestEventListener listener, TestFilter filter)
        {
            try
            {
                return _remoteRunner.Run(listener, filter);
            }
            catch (Exception e)
            {
                log.Error("Failed to run remote tests {0}", e.Message);
                return CreateFailedResult(e);
            }
        }

        /// <summary>
        /// Start a run of the tests in the loaded TestPackage, returning immediately.
        /// The tests are run asynchronously and the listener interface is notified
        /// as it progresses.
        /// </summary>
        /// <param name="listener">An ITestEventHandler to receive events</param>
        /// <param name="filter">A TestFilter used to select tests</param>
        /// <returns>An AsyncTestRun that will provide the result of the test execution</returns>
        protected override AsyncTestEngineResult RunTestsAsync(ITestEventListener listener, TestFilter filter)
        {
            try
            {
                return _remoteRunner.RunAsync(listener, filter);
            }
            catch (Exception e)
            {
                log.Error("Failed to run remote tests {0}", e.Message);
                var result = new AsyncTestEngineResult();
                result.SetResult(CreateFailedResult(e));
                return result;
            }
        }

        /// <summary>
        /// Cancel the ongoing test run. If no  test is running, the call is ignored.
        /// </summary>
        /// <param name="force">If true, cancel any ongoing test threads, otherwise wait for them to complete.</param>
        public override void StopRun(bool force)
        {
            try
            {
                _remoteRunner.StopRun(force);
            }
            catch (Exception e)
            {
                log.Error("Failed to stop the remote run. {0}", e.Message);
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            try
            {
                if (disposing && _agent != null)
                {
                    log.Info("Stopping remote agent");
                    _agent.Stop();
                    _agent = null;
                }
            }
            catch (Exception e)
            {
                log.Error("Failed to stop the remote agent. {0}", e.Message);
                _agent = null;
            }
        }

        TestEngineResult CreateFailedResult(Exception e)
        {
            var suite = XmlHelper.CreateTopLevelElement("test-suite");
            XmlHelper.AddAttribute(suite, "type", "Assembly");
            XmlHelper.AddAttribute(suite, "id", TestPackage.ID);
            XmlHelper.AddAttribute(suite, "name", TestPackage.Name);
            XmlHelper.AddAttribute(suite, "fullname", TestPackage.FullName);
            XmlHelper.AddAttribute(suite, "runstate", "NotRunnable");
            XmlHelper.AddAttribute(suite, "testcasecount", "1");
            XmlHelper.AddAttribute(suite, "result", "Failed");
            XmlHelper.AddAttribute(suite, "label", "Error");
            XmlHelper.AddAttribute(suite, "start-time", DateTime.UtcNow.ToString("u"));
            XmlHelper.AddAttribute(suite, "end-time", DateTime.UtcNow.ToString("u"));
            XmlHelper.AddAttribute(suite, "duration", "0.001");
            XmlHelper.AddAttribute(suite, "total", "1");
            XmlHelper.AddAttribute(suite, "passed", "0");
            XmlHelper.AddAttribute(suite, "failed", "1");
            XmlHelper.AddAttribute(suite, "inconclusive", "0");
            XmlHelper.AddAttribute(suite, "skipped", "0");
            XmlHelper.AddAttribute(suite, "asserts", "0");

            var failure = suite.AddElement("failure");
            var message = failure.AddElementWithCDataSection("message", e.Message);
            var stack = failure.AddElementWithCDataSection("stack-trace", e.StackTrace);

            return new TestEngineResult(suite);
        }

        #endregion
    }
}


text:
Estamos en: Fase 1
------------
Fase 1:

  - Determinación del plan de estudios. División en módulos y, dentro de éstos, unidades
  - Esbozo de los proyectos prácticos dentro de cada módulo y/o unidad
  - Redacción de "Nuestra misión y nuestros valores"

Fase 2:

  - Redacción del Módulo 0
  - Búsqueda de recursos en español para cada una de las unidades. Texto, videos, cursos online...

Fase 3:

  - Redacción de las introducciones a los módulos. Poniendo coherencia al conjunto.
  - Importancia extrema de los proyectos prácticos. Planteamiento de su estructura y opciones de corrección.
  - Asesorarse sobre el aspecto psicológico del curso. Mantener la motivación
  - Redacción periódica de artículos en medium o similar.

Fase 4:

  - Creación de la página web. Perfil del estudiante. Gamificación. Desbloqueo secuencial de la información...
  - Imagen de marca, logo, colores, diseño.
  - Ampliar base de colaboradores del proyecto
  - Determinar y planificar el papel de los mentores
  - Financiar el proyecto con la gratuidad de acceso como base.
  - Búsqueda de estudiantes piloto

Fase 5:

  - Publicitar el proyecto. Marketing, medios de comunicación y comunidad
  - Feedback y reformulación
  - Mentores locales, reuniones y "vida real"

Fase 6:

  - Sustitución progresiva del material 'externo' de las unidades por material propio, cuando se considere necesario.


text:
'use strict';

module.exports = makeError;
function makeError(code, message, options) {
  var line = options.line;
  var filename = options.filename;
  var src = options.src;
  var fullMessage;
  if (src) {
    var lines = src.split('\n');
    var start = Math.max(line - 3, 0)
    var end = Math.min(lines.length, line + 3);
    // Error context
    var context = lines.slice(start, end).map(function(text, i){
      var curr = i + start + 1;
      return (curr == line ? '  > ' : '    ')
        + curr
        + '| '
        + text;
    }).join('\n');
    fullMessage = (filename || 'Jade') + ':' + line + '\n' + context + '\n\n' + message;
  } else {
    fullMessage = (filename || 'Jade') + ':' + line + '\n\n' + message;
  }
  var err = new Error(fullMessage);
  err.code = 'JADE:' + code;
  err.msg = message;
  err.line = line;
  err.filename = filename;
  err.src = src;
  return err;
}


text:
class Article < ActiveRecord::Base
  has_one :friendly_url, validate: true
end


text:
package org.alien4cloud.tosca.model.workflow;

import org.alien4cloud.tosca.model.workflow.activities.AbstractWorkflowActivity;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
@Getter
@Setter
public class NodeWorkflowStep extends WorkflowStep {

    /** The node id of the host where the step will be executed **/
    private String hostId;

    public NodeWorkflowStep(String target, String hostId, AbstractWorkflowActivity activity) {
        setTarget(target);
        this.hostId = hostId;
        setActivity(activity);
    }

    @JsonIgnore
    public String getStepAsString() {
        String target = getTarget() != null ? getTarget() : "inline";
        return target + "_" + getActivity().getRepresentation();
    }
}


text:
var data;

var createCORSRequest = function(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // Most browsers.
	  console.log(url)
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // IE8 & IE9
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
};

var url = '${url}';
var method = 'GET';
var xhr = createCORSRequest(method, url);

xhr.onload = function(e) {
	data = 1
};

xhr.onerror = function() {
	data = -1
	console.log('"' + xhr.responseText + '"')
};

xhr.send();


text:
static const void *y_ycy_loadingCount = &y_ycy_loadingCount;
static const void *y_ycy_maxLoadCount = &y_ycy_maxLoadCount;
static const void *y_ycy_currentURL = &y_ycy_currentURL;
static const void *y_ycy_interactive = &y_ycy_interactive;
static const void *y_ycy_progress = &y_ycy_progress;
static const void *y_ycy_contentSize = &y_ycy_contentSize;

static const void *y_ycy_readyState = &y_ycy_readyState;

static const void *y_ycy_realDelegate = &y_ycy_realDelegate;
static const void *y_ycy_webViewLoadChangeBlock = &y_ycy_webViewLoadChangeBlock;

NSString *ycy_completeRPCURLPath = @"/ycywebviewprogressproxy/complete";

@implementation UIWebView (ycyLoadStatus)
-(void)setYcy_loadingCount:(NSUInteger)ycy_loadingCount{
    NSNumber *number = [[NSNumber alloc]initWithInteger:ycy_loadingCount];
    objc_setAssociatedObject(self,y_ycy_loadingCount, number, OBJC_ASSOCIATION_ASSIGN);
}

-(NSUInteger)ycy_loadingCount{
    return [objc_getAssociatedObject(self, y_ycy_loadingCount) integerValue];
}

-(void)setYcy_maxLoadCount:(NSUInteger)ycy_maxLoadCount{
    NSNumber *number = [[NSNumber alloc]initWithInteger:ycy_maxLoadCount];
    objc_setAssociatedObject(self,y_ycy_maxLoadCount, number, OBJC_ASSOCIATION_ASSIGN);
}

-(NSUInteger)ycy_maxLoadCount{
    return [objc_getAssociatedObject(self, y_ycy_maxLoadCount) integerValue];
}

-(void)setYcy_currentURL:(NSURL*)ycy_currentURL{
    objc_setAssociatedObject(self,y_ycy_currentURL, ycy_currentURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSURL*)ycy_currentURL{
    return objc_getAssociatedObject(self, y_ycy_currentURL) ;
}

-(void)setYcy_interactive:(BOOL)ycy_interactive{
    NSNumber *number = [[NSNumber alloc]initWithBool:ycy_interactive];
    objc_setAssociatedObject(self,y_ycy_interactive, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)ycy_interactive{
    return [objc_getAssociatedObject(self, y_ycy_interactive) boolValue];
}

-(void)setYcy_progress:(float)ycy_progress{
    NSNumber *number = [[NSNumber alloc]initWithFloat:ycy_progress];
    objc_setAssociatedObject(self,y_ycy_progress, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)ycy_progress{
    return [objc_getAssociatedObject(self, y_ycy_progress) floatValue];
}

-(void)setYcy_contentSize:(CGSize)ycy_contentSize{
    objc_setAssociatedObject(self,y_ycy_progress, NSStringFromCGSize(ycy_contentSize), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(CGSize)ycy_contentSize{
    return CGSizeFromString(objc_getAssociatedObject(self, y_ycy_progress));
}

-(void)setYcy_readyState:(YCYReadyState)ycy_readyState{
    objc_setAssociatedObject(self,y_ycy_readyState, @(ycy_readyState), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(YCYReadyState)ycy_readyState{
    return (YCYReadyState)[objc_getAssociatedObject(self, y_ycy_readyState) integerValue];
}

-(void)setYcy_realDelegate:(id<UIWebViewDelegate>)ycy_realDelegate{
    objc_setAssociatedObject(self,y_ycy_realDelegate, ycy_realDelegate, OBJC_ASSOCIATION_ASSIGN);
}

-(id<UIWebViewDelegate>)ycy_realDelegate{
    return objc_getAssociatedObject(self, y_ycy_realDelegate);
}

-(void (^)(UIWebView *, float))ycy_webViewLoadChangeBlock{
    return objc_getAssociatedObject(self, y_ycy_webViewLoadChangeBlock);
}

- (void)setYcy_webViewLoadChangeBlock:(ycy_webViewLoadChangeBlock)ycy_webViewLoadChangeBlock
{
    [self ycy_setDelegateIfNoDelegateSet];
    objc_setAssociatedObject(self, y_ycy_webViewLoadChangeBlock, ycy_webViewLoadChangeBlock, OBJC_ASSOCIATION_COPY);
}

#pragma mark --delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.path isEqualToString:ycy_completeRPCURLPath]) {
        [self ycy_completeProgress];
        return NO;
    }

    BOOL ret = YES;
    if ([self.ycy_realDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
        ret = [self.ycy_realDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }

    BOOL isFragmentJump = NO;
    if (request.URL.fragment) {
        NSString *nonFragmentURL = [request.URL.absoluteString stringByReplacingOccurrencesOfString:[@"#" stringByAppendingString:request.URL.fragment] withString:@""];
        isFragmentJump = [nonFragmentURL isEqualToString:webView.request.URL.absoluteString];
    }

    BOOL isTopLevelNavigation = [request.mainDocumentURL isEqual:request.URL];

    BOOL isHTTPOrLocalFile = [request.URL.scheme isEqualToString:@"http"] || [request.URL.scheme isEqualToString:@"https"] || [request.URL.scheme isEqualToString:@"file"];
    if (ret && !isFragmentJump && isHTTPOrLocalFile && isTopLevelNavigation) {
        self.ycy_currentURL = request.URL;
        [self ycy_reset];
    }
    return ret;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    self.ycy_readyState = YCY_YCYReadyState_loading;

    if ([self.ycy_realDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
        [self.ycy_realDelegate webViewDidStartLoad:webView];
    }

    self.ycy_loadingCount++;
    self.ycy_maxLoadCount = fmax(self.ycy_maxLoadCount, self.ycy_loadingCount);
    [self ycy_startProgress];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if ([self.ycy_realDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [self.ycy_realDelegate webViewDidFinishLoad:webView];
    }

    self.ycy_loadingCount--;
    [self ycy_incrementProgress];

    NSString *readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];

    BOOL interactive = [readyState isEqualToString:@"interactive"];
    if (interactive) {
        self.ycy_interactive = YES;
        self.ycy_readyState = YCY_YCYReadyState_interactive;

        NSString *waitForCompleteJS = [NSString stringWithFormat:@"window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '%@://%@%@'; document.body.appendChild(iframe);  }, false);", webView.request.mainDocumentURL.scheme, webView.request.mainDocumentURL.host, ycy_completeRPCURLPath];
        [webView stringByEvaluatingJavaScriptFromString:waitForCompleteJS];
    }

    BOOL isNotRedirect = self.ycy_currentURL && [self.ycy_currentURL isEqual:webView.request.mainDocumentURL];
    BOOL complete = [readyState isEqualToString:@"complete"];
    if (complete && isNotRedirect) {
        [self ycy_completeProgress];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if ([self.ycy_realDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
        [self.ycy_realDelegate webView:webView didFailLoadWithError:error];
    }

    self.ycy_loadingCount--;
    [self ycy_incrementProgress];

    NSString *readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];

    BOOL interactive = [readyState isEqualToString:@"interactive"];
    if (interactive) {
        self.ycy_interactive = YES;
        NSString *waitForCompleteJS = [NSString stringWithFormat:@"window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '%@://%@%@'; document.body.appendChild(iframe);  }, false);", webView.request.mainDocumentURL.scheme, webView.request.mainDocumentURL.host, ycy_completeRPCURLPath];
        [webView stringByEvaluatingJavaScriptFromString:waitForCompleteJS];
    }

    BOOL isNotRedirect = self.ycy_currentURL && [self.ycy_currentURL isEqual:webView.request.mainDocumentURL];
    BOOL complete = [readyState isEqualToString:@"complete"];
    if ((complete && isNotRedirect) || error) {
        [self ycy_completeProgress];
    }
}

- (void)ycy_startProgress
{
    if (self.ycy_progress < 0.1) {
        [self ycy_updateProgress:0.1];
    }
}
- (void)ycy_incrementProgress
{
    float progress = self.ycy_progress;
    float maxProgress = self.ycy_interactive ? 0.9 : 0.5f;
    float remainPercent = (float)self.ycy_loadingCount / (float)self.ycy_maxLoadCount;
    float increment = (maxProgress - progress) * remainPercent;
    progress += increment;
    progress = fmin(progress, maxProgress);
    [self ycy_updateProgress:progress];
}

- (void)ycy_completeProgress
{
    self.ycy_readyState = YCY_YCYReadyState_complete;
    [self ycy_updateProgress:1.0];
//    CGFloat webViewHeight= [[self stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]floatValue];
//    NSLog(@"body.offsetHeight:%lf",webViewHeight);
//
//    CGFloat webViewHeight2=self.scrollView.contentSize.height;
//    NSLog(@"scrollView contentSize:%lf",webViewHeight2);
}

- (void)ycy_updateProgress:(float)progress
{
    if (progress > self.ycy_progress || progress == 0) {
        self.ycy_progress = progress;
        if (self.ycy_webViewLoadChangeBlock) {
           self.ycy_webViewLoadChangeBlock(self,progress,self.scrollView.contentSize);
        }
    }
}
- (void)ycy_reset
{
    self.ycy_maxLoadCount = self.ycy_loadingCount = 0;
    self.ycy_interactive = NO;
    [self ycy_updateProgress:0.0];
    self.ycy_readyState = YCY_YCYReadyState_uninitialized;
}
//会影响未包含头文件的webview
//-(void)awakeFromNib{
//    [super awakeFromNib];
//    [self ycy_setDelegateIfNoDelegateSet];
//}
//
//- (instancetype)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//        [self ycy_setDelegateIfNoDelegateSet];
//    }
//    return self;
//}
#pragma mark - Delegate Forwarder
- (void)ycy_setDelegateIfNoDelegateSet
{
    if (self.delegate != (id<UIWebViewDelegate>)self) {
        self.ycy_realDelegate  = self.delegate;
        self.delegate = (id<UIWebViewDelegate>)self;
    }
}

//- (void)setDelegate:(id<UIWebViewDelegate>)delegate {
//
//    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){
//        // UIScrollView delegate keeps some flags that mark whether the delegate implements some methods (like scrollViewDidScroll:)
//        // setting *the same* delegate doesn't recheck the flags, so it's better to simply nil the previous delegate out
//        // we have to setup the realDelegate at first, since the flag check happens in setter
////        [super setDelegate:nil];
////        self.delegate = nil;
//        self.ycy_realDelegate = delegate != self ? delegate : nil;
////        [super setDelegate:delegate ? self : nil];
//        self.delegate = delegate ? self : nil;
//
//    }else {
////        [super setDelegate:delegate];
////        self.delegate = delegate;
//
//    }
//}

//- (BOOL)respondsToSelector:(SEL)selector {
//    return [super respondsToSelector:selector] || [self.ycy_realDelegate respondsToSelector:selector];
//}
//- (id)forwardingTargetForSelector:(SEL)selector {
//    id delegate = self.ycy_realDelegate;
//    return [delegate respondsToSelector:selector] ? delegate : [super forwardingTargetForSelector:selector];
//}
@end


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// bthread - A M:N threading library to make applications more concurrent.

// Date: Sun Aug  3 12:46:15 CST 2014

#include "butil/atomicops.h"
#include "butil/macros.h"                         // BAIDU_CASSERT
#include "bthread/butex.h"                       // butex_*
#include "bthread/types.h"                       // bthread_cond_t

namespace bthread {
struct CondInternal {
    butil::atomic<bthread_mutex_t*> m;
    butil::atomic<int>* seq;
};

BAIDU_CASSERT(sizeof(CondInternal) == sizeof(bthread_cond_t),
              sizeof_innercond_must_equal_cond);
BAIDU_CASSERT(offsetof(CondInternal, m) == offsetof(bthread_cond_t, m),
              offsetof_cond_mutex_must_equal);
BAIDU_CASSERT(offsetof(CondInternal, seq) ==
              offsetof(bthread_cond_t, seq),
              offsetof_cond_seq_must_equal);
}

extern "C" {

extern int bthread_mutex_unlock(bthread_mutex_t*);
extern int bthread_mutex_lock_contended(bthread_mutex_t*);

int bthread_cond_init(bthread_cond_t* __restrict c,
                      const bthread_condattr_t*) {
    c->m = NULL;
    c->seq = bthread::butex_create_checked<int>();
    *c->seq = 0;
    return 0;
}

int bthread_cond_destroy(bthread_cond_t* c) {
    bthread::butex_destroy(c->seq);
    c->seq = NULL;
    return 0;
}

int bthread_cond_signal(bthread_cond_t* c) {
    bthread::CondInternal* ic = reinterpret_cast<bthread::CondInternal*>(c);
    // ic is probably dereferenced after fetch_add, save required fields before
    // this point
    butil::atomic<int>* const saved_seq = ic->seq;
    saved_seq->fetch_add(1, butil::memory_order_release);
    // don't touch ic any more
    bthread::butex_wake(saved_seq);
    return 0;
}

int bthread_cond_broadcast(bthread_cond_t* c) {
    bthread::CondInternal* ic = reinterpret_cast<bthread::CondInternal*>(c);
    bthread_mutex_t* m = ic->m.load(butil::memory_order_relaxed);
    butil::atomic<int>* const saved_seq = ic->seq;
    if (!m) {
        return 0;
    }
    void* const saved_butex = m->butex;
    // Wakeup one thread and requeue the rest on the mutex.
    ic->seq->fetch_add(1, butil::memory_order_release);
    bthread::butex_requeue(saved_seq, saved_butex);
    return 0;
}

int bthread_cond_wait(bthread_cond_t* __restrict c,
                      bthread_mutex_t* __restrict m) {
    bthread::CondInternal* ic = reinterpret_cast<bthread::CondInternal*>(c);
    const int expected_seq = ic->seq->load(butil::memory_order_relaxed);
    if (ic->m.load(butil::memory_order_relaxed) != m) {
        // bind m to c
        bthread_mutex_t* expected_m = NULL;
        if (!ic->m.compare_exchange_strong(
                expected_m, m, butil::memory_order_relaxed)) {
            return EINVAL;
        }
    }
    bthread_mutex_unlock(m);
    int rc1 = 0;
    if (bthread::butex_wait(ic->seq, expected_seq, NULL) < 0 &&
        errno != EWOULDBLOCK && errno != EINTR/*note*/) {
        // EINTR should not be returned by cond_*wait according to docs on
        // pthread, however spurious wake-up is OK, just as we do here
        // so that users can check flags in the loop often companioning
        // with the cond_wait ASAP. For example:
        //   mutex.lock();
        //   while (!stop && other-predicates) {
        //     cond_wait(&mutex);
        //   }
        //   mutex.unlock();
        // After interruption, above code should wake up from the cond_wait
        // soon and check the `stop' flag and other predicates.
        rc1 = errno;
    }
    const int rc2 = bthread_mutex_lock_contended(m);
    return (rc2 ? rc2 : rc1);
}

int bthread_cond_timedwait(bthread_cond_t* __restrict c,
                           bthread_mutex_t* __restrict m,
                           const struct timespec* __restrict abstime) {
    bthread::CondInternal* ic = reinterpret_cast<bthread::CondInternal*>(c);
    const int expected_seq = ic->seq->load(butil::memory_order_relaxed);
    if (ic->m.load(butil::memory_order_relaxed) != m) {
        // bind m to c
        bthread_mutex_t* expected_m = NULL;
        if (!ic->m.compare_exchange_strong(
                expected_m, m, butil::memory_order_relaxed)) {
            return EINVAL;
        }
    }
    bthread_mutex_unlock(m);
    int rc1 = 0;
    if (bthread::butex_wait(ic->seq, expected_seq, abstime) < 0 &&
        errno != EWOULDBLOCK && errno != EINTR/*note*/) {
        // note: see comments in bthread_cond_wait on EINTR.
        rc1 = errno;
    }
    const int rc2 = bthread_mutex_lock_contended(m);
    return (rc2 ? rc2 : rc1);
}

}  // extern "C"


text:
/**
 * \mainpage
 * \section board STK600 development board
 * \section intro Introduction
 * This example demonstrates how to set up correct clock settings for
 * the megaAVR devices. The goal of this example is to use the libc delay
 * functions.
 *
 * \section files Files:
 * - mega_clock_example.c: megaAVR STK600 clock example application
 *
 * \section exampledescription Brief description of the example application
 * The example application set up the correct clock setting to use the
 * libc delay functions. The only thing this application will do is to
 * demonstrate how to call the libc delay functions. There are no output
 * in form of leds. To verify operation of this example it is recommended
 * to use debugging and break on different lines.
 *
 * \note Optimization must to be enabled for the delay functions to work correctly,
 * please refer to
 * libc
 * for more information.
 *
 * \section compinfo Compilation Info
 * This software was written for the GNU GCC
 * for AVR. \n
 * Other compilers may or may not work.
 *
 * \section contactinfo Contact Information
 * For further information, visit
 * Atmel.\n
 */
 /**
 * Support and FAQ: visit Atmel Support
 */
#include "compiler.h"

/* set the correct clock frequency based on fuse settings or external clock/crystal
 * has to be done before including delay.h */
#include "conf_clock.h"
#include <util/delay.h>

#ifndef __OPTIMIZE__
#warning "Please use compiler optimization for correct operation of the delay \
functions."
#endif

 /**
 * \brief Maximum possible delay is 262.14 ms / F_CPU in MHz.
 *
 * Please refer to
 *
 * libc for more information.
 */
#define MAX_MS_DELAY (262.14 / (F_CPU / 1000000UL))

/**
 * \brief Maximum possible delay is 768 us / F_CPU in MHz.
 *
 * Please refer to
 *
 * libc for more information.
 */
#define MAX_US_DELAY (768 / (F_CPU / 1000000UL))

/**
 * \brief Example application on how to use the libc delay functions.
 *
 * This application shows the basic usage of the delay functions from the
 * avr libc library.
 *
 * \note The delay functions will not operate correctly if compiled without
 * optimization.
 */
int main(void)
{
	// busy wait the maximum number of milliseconds
	_delay_ms(MAX_MS_DELAY);

	// busy wait the maximum number of microseconds
	_delay_us(MAX_US_DELAY);

	// busy wait for 10us
	_delay_us(10);

	// busy wait for 10ms
	_delay_ms(10);

	// loop for ever
	while (true);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Docums Mycol. 19(no. 74): 26 (1988)

#### Original name
Inocybe tetragonospora Kühner

### Remarks
null


text:
module DSP.FIR.Common where

import qualified Clash.Prelude as Clash
import Clash.Prelude (Signal, Vec(..), BitVector, Index, Signed, Unsigned, SFixed, Bit, SNat(..),
                      simulate, simulate_lazy, listToVecTH, KnownNat, pack, unpack, (++#), mealy, mux, bundle, unbundle,
                      HiddenClockResetEnable, type (+), extend, NFDataX, System, fromList, singleton, sample, regEn)
import Control.Applicative
import Test.Hspec
import Test.QuickCheck hiding (sample)

import Clash.DSP.FIR.Filter
import Clash.DSP.FIR.SemiParallel
import Clash.DSP.FIR.Polyphase

--Golden model
goldenFIR
    :: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
    => Vec (n + 1) a
    -> Signal dom Bool
    -> Signal dom a
    -> Signal dom a
goldenFIR = fir (*) (+)

goldenExpect coeffs input
    = take (length input)
    $ sample @System
    $ goldenFIR coeffs (pure True) (fromList $ 0 : input ++ repeat 0)

--Dummy test MAC units
macRealReal c i a = c * i + a

macPreAddRealReal c x y a = c * (x + y) + a

macRealRealPipelined en c i a = regEn 0 en (c * i) + a

macPreAddRealRealPipelined en c x y a = regEn 0 en (regEn 0 en c * regEn 0 en (x + y)) + a

liftA4 f w x y z = f <$> w <*> x <*> y <*> z

--A type for filters that can take an input and produce an output every cycle
type FilterNoReady dom a
    =  Signal dom Bool   -- ^ Input valid
    -> Signal dom a      -- ^ Sample
    -> Signal dom a      -- ^ (Output valid, output data)

streamList
    :: (HiddenClockResetEnable dom, NFDataX a)
    => [a]
    -> [Bool]
    -> Signal dom Bool
    -> (Signal dom Bool, Signal dom a)
streamList samples enables = unbundle . mealy step (samples, enables)
    where
    step :: ([a], [Bool]) -> Bool -> (([a], [Bool]), (Bool, a))
    step (l@(x:xs), es@(True:_)) False = ((l, es),  (True, x))
    step (l@(x:xs), e:es)        False = ((l, es),  (e, x))
    step (l@(x:xs), False:es)    True  = ((l, es),  (False, x))
    step (   x:xs,  True:es)     True  = ((xs, es), (True, x))
    step ([],       _)           _     = error "Data list empty"
    step (_,        [])          _     = error "Enable list empty"

systemNoReady
    :: forall dom a
    .  (HiddenClockResetEnable dom, NFDataX a, Num a)
    => FilterNoReady dom a
    -> [a]
    -> [Bool]
    -> Signal dom (Bool, a)
systemNoReady filter samples ens = bundle (valids, out)
    where
    (valids, sampleStream) = streamList (samples ++ repeat 0) ens (pure True)
    out                    = filter valids sampleStream

system
    :: forall dom a
    .  (HiddenClockResetEnable dom, NFDataX a, Num a)
    => Filter dom a
    -> [a]
    -> [Bool]
    -> Signal dom (Bool, a)
system filter samples ens = bundle (vld, out)
    where
    (valids, sampleStream) = streamList (samples ++ repeat 0) ens ready
    (vld, out, ready)      = filter valids sampleStream

stride :: Int -> [a] -> [a]
stride s = go
    where
    go (x:xs) = x : go (Prelude.drop s xs)
    go _      = []


text:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace NgxLib.Cameras
{
    /// <summary>
    /// Represents the 2D view port
    /// </summary>
    public class Camera2D
    {
        private NgxRectangle _viewport;
        private Matrix _transform;
        private Vector2 _position;

        public GraphicsDevice Graphics { get; private set; }
        public Vector2 ScreenCenter { get; protected set; }
        public float Rotation { get; set; }
        public Vector2 Origin { get; set; }
        public float Scale { get; set; }
        public float MoveSpeed { get; set; }
        public int Follow { get; set; }

        public Matrix Transform
        {
            get { return _transform; }
        }

        public NgxRectangle Viewport
        {
            get { return _viewport; }
        }

        public Vector2 Position
        {
            get { return _position; }
        }

        public Camera2D(GraphicsDevice graphics)
        {
            Graphics = graphics;
        }

        /// <summary>
        /// Called when the GameComponent needs to be initialized.
        /// </summary>
        public void Initialize()
        {
            _viewport.Width = Graphics.Viewport.Width;
            _viewport.Height = Graphics.Viewport.Height;
            ScreenCenter = _viewport.Center;
            Scale = 1;
            MoveSpeed = 1.25f;
        }

        public void Update()
        {
            _transform = Matrix.Identity *
                        Matrix.CreateTranslation(-_position.X, -_position.Y, 0) *
                        Matrix.CreateRotationZ(Rotation) *
                        Matrix.CreateTranslation(Origin.X, Origin.Y, 0) *
                        Matrix.CreateScale(new Vector3(Scale, Scale, Scale));

            Origin = ScreenCenter / Scale;
        }

        public void Move(float x, float y)
        {
            var cx = _position.X + (x - _position.X) * MoveSpeed;
            var cy = _position.Y + (y - _position.Y) * MoveSpeed;
            SetPosition(cx, cy);
        }

        public void SetPosition(float x, float y)
        {
            _position.X = x;
            _position.Y = y;
            _viewport.X = x - (_viewport.Width * 0.5f) / Scale;
            _viewport.Y = y - (_viewport.Height * 0.5f) / Scale;
        }

        public Vector2 Translate(Vector2 location)
        {
            return Vector2.Transform(location, _transform);
        }
    }
}


text:
set -e
set -v

sudo apt-get update
sudo apt-get -y install mariadb-server


text:
import plugit
from flask import abort, send_from_directory
from plugit.utils import cache

import config
import server
from SPI.utils import *
from actions_utils import with_client_identification

@plugit.app.route('/radiodns/epg/XSI.xml')
@with_client_identification
def xsi_1_xml(client_identifier):
    """
    Route for RadioEPG 1.1 XSI file

    :param client_identifier: The client identifier if any.
    :return: The requested file or its location if the SI/PI service is enabled. 404 if the requested resource was
     not found. 501 otherwise.
    """

    if not config.SPISERVING_ENABLED:
        abort(501)

    codops = get_codops_from_request()
    if not codops and not config.DEBUG:
        abort(404)
    return server.SPI_handler.on_request_xsi_1(codops, client_identifier)

@plugit.app.route('/radiodns/spi/3.1/SI.xml')
@with_client_identification
def si_3_xml(client_identifier):
    """
    Route for SPI 3.1 SI file
    :param client_identifier: The client identifier if any.
    :return: The requested file or its location if the SI/PI service is enabled. 404 if the requested resource was
     not found. 501 otherwise.
    """

    if not config.SPISERVING_ENABLED:
        abort(501)

    codops = get_codops_from_request()
    if not codops and not config.DEBUG:
        abort(404)
    return server.SPI_handler.on_request_si_3(codops, client_identifier)

@plugit.app.route('/radiodns/logo/<int:id>/<int:w>/<int:h>/logo.png')
def logo(id, w, h):
    """Return a logo for a station"""

    from models import Station
    import os

    station = Station.query.filter(Station.id == id).first()

    if not station:
        abort(404)

    dest_file = 'media/uploads/radioepg/cache/S%s_W%s_H%s_L%s.png' % (
        str(int(id)), str(int(w)), str(int(h)), str(station.epg_picture_id) if station.epg_picture_id else 'B')

    if not os.path.isfile(dest_file):
        from PIL import Image
        size = (w, h)
        image = Image.open(
            station.epg_picture.filename if station.epg_picture else 'media/uploads/radioepg/default.png')
        image.thumbnail(size, Image.ANTIALIAS)
        background = Image.new('RGBA' if station.epg_picture else 'RGB', size, (255, 255, 255, 0))
        background.paste(image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))

        background.save(dest_file)

    return send_from_directory(".", dest_file)

@plugit.app.route('/radiodns/epg/<path:path>/<int:date>_PI.xml')
def pi_1_xml(path, date):
    """
    Route for RadioEPG 1.1 PI file

    :param path: the service identifier of the requested file. The service identifier is described
                    in the RadioDNS Lookup specification
    :param date: date in format YYYYMMDD
    :return: The requested file or its location if the SI/PI service is enabled. 404 if the requested resource was
     not found. 501 otherwise.
    """

    if not config.SPISERVING_ENABLED:
        abort(501)

    return server.SPI_handler.on_request_pi_1(path, date)

@plugit.app.route('/radiodns/spi/3.1/<path:path>/<int:date>_PI.xml')
def pi_3_xml(path, date):
    """
    Route for RadioEPG 1.1 PI file

    :param path: the service identifier of the requested file. The service identifier is described
                    in the RadioDNS Lookup specification
    :param date: date in format YYYYMMDD
    :return: The requested file or its location if the SI/PI service is enabled. 404 if the requested resource was
     not found. 501 otherwise.
    """

    if not config.SPISERVING_ENABLED:
        abort(501)

    return server.SPI_handler.on_request_pi_3(path, date)


text:
package org.smartdata.hdfs.action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An action to do fsck check.
 */
public class FsckAction extends HdfsAction {
  private static final Logger LOG = LoggerFactory.getLogger(FsckAction.class);

  @Override
  protected void execute() throws Exception {
  }
}


text:
---
uid: SolidEdgeFrameworkSupport.ComplexString2d.Scale(System.Double)
summary:
remarks:
syntax:
    parameters:
    - id: Factor
      description: Specifies the factor by which the referenced object is to be scaled.
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgeFrameworkSupport.ComplexString2d.Scale.vb]
[!code-csharp[Main](..\snippets\SolidEdgeFrameworkSupport.ComplexString2d.Scale.cs]


text:
//
//  Copyright (c) 2014, Kevin Thompson
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice, this
//     list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
//  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

using System;
using System.Runtime.InteropServices;

namespace Cassandra.DataStax.Auth.Sspi
{
    /// <summary>
    /// Stores information about a particular security package.
    /// </summary>
    [StructLayout( LayoutKind.Sequential )]
    internal class SecPkgInfo
    {
        /// <summary>
        /// The packages capabilities and options.
        /// </summary>
        public SecPkgCapability Capabilities;

        /// <summary>
        /// The package's version number.
        /// </summary>
        public short Version;

        /// <summary>
        /// The package's Id when used in RPC contexts.
        /// </summary>
        public short RpcId;

        /// <summary>
        /// The maximum size, in bytes, of tokens generated by the package.
        /// </summary>
        public int MaxTokenLength;

        /// <summary>
        /// The human-readable name of the package.
        /// </summary>
        [MarshalAs( UnmanagedType.LPWStr )]
        public string Name;

        /// <summary>
        /// A short description of the package.
        /// </summary>
        [MarshalAs( UnmanagedType.LPWStr )]
        public string Comment;
    }

    /// <summary>
    /// Describes the capabilities of a security package.
    /// </summary>
    [Flags]
    internal enum SecPkgCapability : uint
    {
        /// <summary>
        /// Whether the package supports generating messages with integrity information. Required for MakeSignature and VerifySignature.
        /// </summary>
        Integrity       = 0x1,

        /// <summary>
        /// Whether the package supports generating encrypted messages. Required for EncryptMessage and DecryptMessage.
        /// </summary>
        Privacy         = 0x2,

        /// <summary>
        /// Whether the package uses any other buffer information than token buffers.
        /// </summary>
        TokenOnly       = 0x4,

        /// <summary>
        /// Whether the package supports datagram-style authentication.
        /// </summary>
        Datagram        = 0x8,

        /// <summary>
        /// Whether the package supports creating contexts with connection semantics
        /// </summary>
        Connection      = 0x10,

        /// <summary>
        /// Multiple legs are neccessary for authentication.
        /// </summary>
        MultiLeg        = 0x20,

        /// <summary>
        /// Server authentication is not supported.
        /// </summary>
        ClientOnly      = 0x40,

        /// <summary>
        /// Supports extended error handling facilities.
        /// </summary>
        ExtendedError   = 0x80,

        /// <summary>
        /// Supports client impersonation on the server.
        /// </summary>
        Impersonation   = 0x100,

        /// <summary>
        /// Understands Windows princple and target names.
        /// </summary>
        AcceptWin32Name = 0x200,

        /// <summary>
        /// Supports stream semantics
        /// </summary>
        Stream          = 0x400,

        /// <summary>
        /// Package may be used by the Negiotiate meta-package.
        /// </summary>
        Negotiable      = 0x800,

        /// <summary>
        /// Compatible with GSS.
        /// </summary>
        GssCompatible   = 0x1000,

        /// <summary>
        /// Supports LsaLogonUser
        /// </summary>
        Logon           = 0x2000,

        /// <summary>
        /// Token buffers are in Ascii format.
        /// </summary>
        AsciiBuffers    = 0x4000,

        /// <summary>
        /// Supports separating large tokens into multiple buffers.
        /// </summary>
        Fragment        = 0x8000,

        /// <summary>
        /// Supports mutual authentication between a client and server.
        /// </summary>
        MutualAuth      = 0x10000,

        /// <summary>
        /// Supports credential delegation from the server to a third context.
        /// </summary>
        Delegation      = 0x20000,

        /// <summary>
        /// Supports calling EncryptMessage with the read-only-checksum flag, which protects data only
        /// with a checksum and does not encrypt it.
        /// </summary>
        ReadOnlyChecksum = 0x40000,

        /// <summary>
        /// Whether the package supports handling restricted tokens, which are tokens derived from existing tokens
        /// that have had restrictions placed on them.
        /// </summary>
        RestrictedTokens = 0x80000,

        /// <summary>
        /// Extends the negotiate package; only one such package may be registered at any time.
        /// </summary>
        ExtendsNego     = 0x00100000,

        /// <summary>
        /// This package is negotiated by the package of type ExtendsNego.
        /// </summary>
        Negotiable2     = 0x00200000,
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<NeurologyFormTotalsModel>
  <NeurologyForm>
    <Id>0</Id>
    <ExamDate>0001-01-01T00:00:00</ExamDate>
    <AnalContraction>NT</AnalContraction>
    <AnalSensation>NT</AnalSensation>
    <RightLowestNonKeyMuscleWithMotorFunction>0</RightLowestNonKeyMuscleWithMotorFunction>
    <LeftLowestNonKeyMuscleWithMotorFunction>0</LeftLowestNonKeyMuscleWithMotorFunction>
    <Comments>
      ISNCSCI NT Case 4
      Previous abdominoperitoneal surgery (no rectum) & skin grafts on bottom.
    </Comments>
    <Dermatomes>
      <Dermatome name="C2">
        <RightTouch>2</RightTouch>
        <LeftTouch>2</LeftTouch>
        <RightPrick>2</RightPrick>
        <LeftPrick>2</LeftPrick>
      </Dermatome>
      <Dermatome name="C3">
        <RightTouch>2</RightTouch>
        <LeftTouch>2</LeftTouch>
        <RightPrick>2</RightPrick>
        <LeftPrick>2</LeftPrick>
      </Dermatome>
      <Dermatome name="C4">
        <RightTouch>2</RightTouch>
        <LeftTouch>2</LeftTouch>
        <RightPrick>2</RightPrick>
        <LeftPrick>2</LeftPrick>
      </Dermatome>
      <Dermatome name="C5">
        <RightMotor>5</RightMotor>
        <LeftMotor>5</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="C6">
        <RightMotor>2</RightMotor>
        <LeftMotor>2</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="C7">
        <RightMotor>1</RightMotor>
        <LeftMotor>1</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="C8">
        <RightMotor>1</RightMotor>
        <LeftMotor>1</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T1">
        <RightMotor>1</RightMotor>
        <LeftMotor>1</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T2">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T3">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T4">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T5">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T6">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T7">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T8">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T9">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T10">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T11">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="T12">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="L1">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="L2">
        <RightMotor>3</RightMotor>
        <LeftMotor>3</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="L3">
        <RightMotor>3</RightMotor>
        <LeftMotor>3</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="L4">
        <RightMotor>4</RightMotor>
        <LeftMotor>4</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="L5">
        <RightMotor>3</RightMotor>
        <LeftMotor>3</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="S1">
        <RightMotor>3</RightMotor>
        <LeftMotor>3</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="S2">
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="S3">
        <RightTouch>NT</RightTouch>
        <LeftTouch>NT</LeftTouch>
        <RightPrick>NT</RightPrick>
        <LeftPrick>NT</LeftPrick>
      </Dermatome>
      <Dermatome name="S4_5">
        <RightTouch>NT</RightTouch>
        <LeftTouch>NT</LeftTouch>
        <RightPrick>NT</RightPrick>
        <LeftPrick>NT</LeftPrick>
      </Dermatome>
    </Dermatomes>
  </NeurologyForm>
  <NeurologyFormTotals>
    <RightUpperMotorTotal>10</RightUpperMotorTotal>
    <RightUpperMotorContainsNt>false</RightUpperMotorContainsNt>
    <LeftUpperMotorTotal>10</LeftUpperMotorTotal>
    <LeftUpperMotorContainsNt>false</LeftUpperMotorContainsNt>
    <RightLowerMotorTotal>16</RightLowerMotorTotal>
    <RightLowerMotorContainsNt>false</RightLowerMotorContainsNt>
    <LeftLowerMotorTotal>16</LeftLowerMotorTotal>
    <LeftLowerMotorContainsNt>false</LeftLowerMotorContainsNt>
    <RightTouchTotal>29</RightTouchTotal>
    <RightTouchContainsNt>true</RightTouchContainsNt>
    <LeftTouchTotal>29</LeftTouchTotal>
    <LeftTouchContainsNt>true</LeftTouchContainsNt>
    <RightPrickTotal>29</RightPrickTotal>
    <RightPrickContainsNt>true</RightPrickContainsNt>
    <LeftPrickTotal>29</LeftPrickTotal>
    <LeftPrickContainsNt>true</LeftPrickContainsNt>
    <RightMotorTotal>26</RightMotorTotal>
    <LeftMotorTotal>26</LeftMotorTotal>
    <UpperMotorTotal>20</UpperMotorTotal>
    <LowerMotorTotal>32</LowerMotorTotal>
    <TouchTotal>58</TouchTotal>
    <PrickTotal>58</PrickTotal>
    <RightSensory>C4</RightSensory>
    <LeftSensory>C4</LeftSensory>
    <RightMotor>C5</RightMotor>
    <LeftMotor>C5</LeftMotor>
    <NeurologicalLevelOfInjury>C4</NeurologicalLevelOfInjury>
    <RightSensoryZpp>S2,S3</RightSensoryZpp>
    <LeftSensoryZpp>S2,S3</LeftSensoryZpp>
    <RightMotorZpp>S1</RightMotorZpp>
    <LeftMotorZpp>S1</LeftMotorZpp>
    <AsiaImpairmentScale>A, D</AsiaImpairmentScale>
  </NeurologyFormTotals>
</NeurologyFormTotalsModel>


text:
package learn2crack.chat;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LoginFragment extends Fragment {
    SharedPreferences prefs;
    EditText name, mobno;
    Button login;
    List<NameValuePair> params;
    ProgressDialog progress;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_fragment, container, false);
        prefs = getActivity().getSharedPreferences("Chat", 0);

        name = (EditText)view.findViewById(R.id.name);
        mobno = (EditText)view.findViewById(R.id.mobno);
        login = (Button)view.findViewById(R.id.log_btn);
        progress = new ProgressDialog(getActivity());
        progress.setMessage("Registering ...");
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setIndeterminate(true);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progress.show();
                SharedPreferences.Editor edit = prefs.edit();
                edit.putString("REG_FROM", mobno.getText().toString());
                edit.putString("FROM_NAME", name.getText().toString());
                edit.commit();
                new Login().execute();
            }
        });

        return view;
    }
    private class Login extends AsyncTask<String, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser json = new JSONParser();
            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name.getText().toString()));
            params.add(new BasicNameValuePair("mobno", mobno.getText().toString()));
            params.add((new BasicNameValuePair("reg_id",prefs.getString("REG_ID",""))));

            JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2:8080/login",params);
            return jObj;

        }
        @Override
        protected void onPostExecute(JSONObject json) {
            progress.dismiss();
            try {
                String res = json.getString("response");
                if(res.equals("Sucessfully Registered")) {
                    Fragment reg = new UserFragment();
                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.content_frame, reg);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.addToBackStack(null);
                    ft.commit();
                }else{
                    Toast.makeText(getActivity(),res,Toast.LENGTH_SHORT).show();

                }

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

        }
    }

}


text:
@implementation CyclePageViewLoadStyleDemoController

- (void (^)(HyCyclePageViewConfigure * _Nonnull))configPageView {
    return ^(HyCyclePageViewConfigure * _Nonnull configure){
        [configure loadStyle:HyCycleViewLoadStyleWillAppear];
    };
}

@end