text:
package com.msted.lensrocket.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtilities {
	private static String TAG = "NetworkUtilities";

	public static boolean isNetworkOnline(Context context) {
		boolean status = false;
		try {
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getNetworkInfo(0);
			if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) {
				status = true;
			} else {
				netInfo = cm.getNetworkInfo(1);
				if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) {
					status = true;
				}
			}
		} catch (Exception ex) {
			LensRocketLogger.e(TAG, "Error checking for network connectivity: " + ex.getMessage());
			status = false;
		}
		return status;
	}
}


text:
from __future__ import division, print_function, absolute_import, unicode_literals
import os
import fnmatch
# noinspection PyPackageRequirements
import yaml
from six import string_types

from ..define import get_sys_path

Extensions = {}
CONF_PY_NUM_INDENT = 4

def init(plugin_dir):
    global Extensions

    for root, dirs, files in os.walk(plugin_dir):
        for file_name in fnmatch.filter(files, "ext-*.yml"):
            ext_name = file_name[:-len(".yml")]
            Extensions[ext_name] = Extension(
                ext_name,
                yaml.load(open(os.path.join(root, file_name))),
                root,
            )

def extensions():
    return Extensions.items()

def get(ext_name):
    return Extensions.get(ext_name)

def list_iter():
    for ext_name, ext in Extensions.items():
        yield ext_name, ext

def dependent_packages():
    for ext_name, ext in Extensions.items():
        for package in ext.packages:
            yield package

class Extension(object):
    # TODO: ast check
    def __init__(self, name, ext_setting, ext_path=None):
        self.name = name
        self.base_name = name[len("ext-"):]
        self.ext_setting = ext_setting
        self.ext_path = ext_path

    @property
    def description(self):
        return self.ext_setting.get("description")

    @property
    def extra_code(self):
        conf_py = self.ext_setting.get("conf_py")
        if conf_py:
            return conf_py.get("extra_code")
        return None

    @property
    def local_extension(self):
        return self.conf_py.get("local_extension", False)

    @property
    def local_extension_file(self):
        return os.path.join(get_sys_path(), "extensions", self.base_name + ".py")

    @property
    def packages(self):
        return self.ext_setting.get("packages", [])

    @property
    def conf_py(self):
        return self.ext_setting.get("conf_py", {})

    @property
    def imports(self):
        ret = []
        for imp in self.conf_py.get("imports", []):
            if "from" in imp:
                ret.append("from {} import {}".format(imp["from"], imp["import"]))
            else:
                ret.append("import {}".format(imp["import"]))

        return ret

    @property
    def source_suffix(self):
        ext, parser = self.conf_py.get("source_suffix", (None, None))
        if ext and parser:
            return ext, parser
        return ()

    @property
    def add_extensions(self):
        d = self.conf_py.get("add_extensions")
        if d is None:
            d = self.packages
        elif d is False:
            d = []
        elif isinstance(d, string_types):
            d = [d]

        d = ["'" + x + "'" for x in d]

        return d

    @property
    def exclude_patterns(self):
        return self.conf_py.get("exclude_poatterns", [])

    def has_setting_params(self):
        return bool(self.ext_setting.get("setting_params"))

    @property
    def setting_params(self):
        for ext in self.ext_setting.get("setting_params", []):
            for key, value in ext.items():
                yield key, value

    def generate_py_script(self, params, settings):
        parser = []

        # add imports
        if self.imports:
            for imp in self.imports:
                parser.append(imp)
            parser.append("")

        # add extensions
        if self.add_extensions:
            parser.append("extensions += [")
            for add_ext in self.add_extensions:
                parser.append((" " * CONF_PY_NUM_INDENT) + add_ext + ",")
            parser.append("]")

        # setting params
        for param_name, param_setting in self.setting_params:
            value = params.get(param_name) or settings.get(param_name) or param_setting.get("default")
            if value:
                parser.append("{} = {}".format(param_name, repr(value)))

        # add extra code
        if self.extra_code:
            parser.append(self.extra_code)

        return "\n".join(parser)

redpajama_set_name: RedPajamaGithub


text:
tinyMCE.addI18n('sq.advlink_dlg',{
title:"Fut/edito lidhje",
url:"URL e lidhjes",
target:"Sh\u00EBnjestra",
titlefield:"Titulli",
is_email:"Adresa q\u00EB keni futur duket si email. D\u00EBshironi t\u00EB shtoni prefiksin mailto:?",
is_external:"Adresa q\u00EB keni futur duket si lidhje e jashtme. D\u00EBshironi t\u00EB shtoni prefiksin http://?",
list:"Lista e lidhjeve",
general_tab:"T\u00EB P\u00EBrgjithshme",
popup_tab:"Popup",
events_tab:"Ngjarjet",
advanced_tab:"T\u00EB Avancuara",
general_props:"Tipare t\u00EB p\u00EBrgjithshme",
popup_props:"Tiparet e popup",
event_props:"Ngjarjet",
advanced_props:"Tipare t\u00EB avancuara",
popup_opts:"Opsionet",
anchor_names:"Lidhjet",
target_same:"Hape n\u00EB k\u00EBt\u00EB dritare / frame",
target_parent:"Hape n\u00EB dritaren m\u00EBm\u00EB / frame",
target_top:"Hape n\u00EB frame-in e m\u00EBsip\u00EBrm",
target_blank:"Hape n\u00EB dritare t\u00EB re",
popup:"Popup me Javascript",
popup_url:"URL e popup",
popup_name:"Emri i dritares",
popup_return:"Fut 'return false'",
popup_scrollbars:"Shfaq ashensor\u00EBt",
popup_statusbar:"Shfaq shiritin e statusit",
popup_toolbar:"Shfaq butonat",
popup_menubar:"Shfaq menun\u00EB",
popup_location:"Shfaq shiritin e adres\u00EBs",
popup_resizable:"B\u00EBje dritaren t\u00EB zmadhueshme",
popup_dependent:"I varur (vet\u00EBm Mozilla/Firefox)",
popup_size:"Madh\u00EBsia",
popup_position:"Pozicioni (X/Y)",
id:"Id",
style:"Stili",
classes:"Klasat",
target_name:"Emri",
langdir:"Drejtimi i gjuh\u00EBs",
target_langcode:"Gjuha e sh\u00EBnjestr\u00EBs",
langcode:"Kodi i gjuh\u00EBs",
encoding:"Kodimi i karaktereve t\u00EB sh\u00EBnjestr\u00EBs",
mime:"Tipi MIME i sh\u00EBnjestr\u00EBs",
rel:"Marr\u00EBdh\u00EBnia faqe-sh\u00EBnjest\u00EBr",
rev:"Marr\u00EBdh\u00EBnia sh\u00EBnjest\u00EBr-faqe",
tabindex:"Indeksi i Tab",
accesskey:"Butoni i aksesit",
ltr:"Majtas-Djathtas",
rtl:"Djathtas-Majtas",
link_list:"Lista e lidhjeve"
});


text:
/**
 * Splits an array into 2 arrays
 * The input array should not be modified
 * The first array should be returned as a property called "fst" on the object
 * The second array should be returned as a property called "snd" on the object
 * If arr has length 2n, fst and snd should have length n
 * If arr has length 2n + 1, fst should have length n + 1 and snd should have
 * length n
 * It should be the case that fst.concat(snd) is the same as arr (not === but
 * same values)
 * If the input is not of type Array, throw an error
 *
 * @param {Array} the array to split
 * @returns {Object} the two arrays
 */

function split(arr) {
  const firstBreak = Math.ceil(arr.length / 2);
  const fst = [];
  const snd = [];
  arr.forEach((element, i) => {
    if (i < firstBreak) {
      fst.push(element);
    } else {
      snd.push(element);
    }
  });
  return {
    fst,
    snd
  };
}

module.exports = split;


text:
This demo application shows you how to implement [Backand](https://www.backand.com) user roles in a basic ToDo application written in AngularJS. This demonstrates the security features that Backand's API has to offer, and allows you to see how actions by a user are restricted based upon their assigned role.

The Todo project has the following user roles enabled:
* An *Admin* role, with which the user can perform all available CRUD actions on all items
* A *User* role, which allows the user to read all items, but to only Create, Update, or Delete items that have been created by the user.
* A *ReadOnly* role, which restricts the user to only reading items in the application.

Furthermore, there are two ways to access the application:
* Users with the *Admin* or *User* roles must sign in with their username and password
* Users that browse the app without signing in are assigned the *ReadOnly* role (In the code, those users are referred to as *anonymous users*).

## Prerequisites
To run this project, you will need:
* [Git](http://git-scm.com/), for source control
* [NodeJS and NPM](https://gist.github.com/isaacs/579814), to serve as a web server
* [Backand's Server side REST API](https://www.backand.com), to control the back-end of the application.

## Getting Started
To get the application running, perform the following steps:

1. Create a new application in [Backand](https://www.backand.com/apps).
2. After creation, open the Model under Objects menu, click on 'Model JSON' tab and paste the following JSON. This JSON represents two objects that will be created in your database: the tasks list, named 'todo', and the users list. The two objects are related via the 'created_by' field in the 'todo' object and the collection 'todo' in the object 'users'.

  ```json
  [
    {
      "name": "todo",
      "fields": {
        "created_by": {
          "object": "users"
        },
        "description": {
          "type": "string"
        },
        "completed": {
          "type": "boolean"
        }
      }
    },
    {
      "name": "users",
      "fields": {
        "todo": {
          "collection": "todo",
          "via": "created_by"
        },
        "email": {
          "type": "string"
        },
        "firstName": {
          "type": "string"
        },
        "lastName": {
          "type": "string"
        }
      }
    }
  ]
  ```
3. Press "Validate & Update" to commit the changes.
4. Open a console on your machine, and navigate to (or create) a directory to hold the source code.
5. Run the following commands from the console, to clone the repository and install dependencies:

  ```bash
  git clone https://github.com/backand/todos-with-users.git
  cd todos-with-users

  npm install
  bower install
  ```

6. Run the app:

  ```bash
  grunt serve
  ```
7. Navigate to [localhost:9000](http://localhost:9000) to see the basic app in action!

You can sign into the app using your Back& dashboard credentials along with the name you chose for your app (The app name should later be configured in app/config/consts.js.) You are now able to create, update, view, and delete tasks!

## Configuring the Application
Open your application in [Backand](https://www.backand.com/apps).

#### Configure Security Settings
 Go to the *Security & Auth --> Configuration* page

#### Configure Security Settings - User settings
1. **Change Anonymous Access to Read-Only**
  By default all users have full access to read and update data. Let's change it to read only:
  1. In the drop-down that appeared beneath *Anonymous Access*, select *ReadOnly*.
  2. Copy the Anonymous Token and paste it in app/config/consts.js as the value of 'anonymousToken'.
  3. Refresh the browser window presenting your app and click on 'Sign Out'. You will be able to see the todo list by clicking on the 'view the todo list as a guest (read only)' link in the sign in page. You will not be able to add or modify tasks.

2. **Enable Sign Up from the client code**
	1. From Social & Keys menu copy the API Sign-up Token and paste it in app/config/consts.js as the value of
	signUpToken.

3. **Custom Reset Password Page** (optional)
	3. In Configuration menu set **Custom Reset Password Page** to `http://localhost:9000/#/resetPassword`. This is the
	 link that will be sent by email to users who forgot their password. (This page is also used for signed-in users to change their password.)

At this point, users are able to register for your app. They can register organically using their own email and a password, or via social media provider integration, such as Google, GitHub, or Facebook. New users simply need to select the "New User" checkbox before signing in. All registered users can add or modify tasks.

#### Forgot Password
Once you've updated the **Custom Reset Password** page, you can test the app's 'reset password' functionality. This is accessible from the login page, so you may need to sign out of the application first. On the ensuing reset password page, simply enter the email address of a valid existing user, and that email address will receive a message with a link to your configured "change password" page.

The file `app/views/auth/reset-password.js` shows that this process is based on two methods from the Backand SDK: `requestResetPassword` and `resetPassword`. The resetPassword method is used after the user clicks on the link received in the email message sent in the prior step. The content of this message can be edited in the Backand dashboard on the page *Security & Auth --> Configuration* page, in the `requestResetPassword` on-demand action.

#### Change Password
Only users that are signed in may change their password. You can test this functionality by clicking on 'Change Password'.
The file `app/views/auth/change-password.js` reveals that this code simply uses the Backand SDK's `changePassword` method.

#### Social sign up & sign in
Backand's built-in social sign-in functionality is very easy to use - simply call the Backand SDK with the appropriate provider (Google, Github, or Facebook). You can see how this is done in the file `app/views/auth/login.js`, which shows that the code uses the Backand SDK's `socialSignUp` and `socialSignIn` methods.

#### Managing Signed-Up Users
Back& provides an internal *users* object for your app users. You can see the users table in **Secturity & Auth --> Registered Users**. However, it is highly recommended to keep the 'users' object of the app to hold custom information.  Backand provides three predefined actions that synchronize the internal *users* object with your custom one. You can customize these actions according to your needs. These actions are defined in the bottom of the **Configuration** page: **Create**, **Update** and **Delete My App User**. Some additional actions are predefined here, for instance, **requestResetPassword** sends email to users who forgot their password.
**NOTE:** If you give a different name for your 'users' object, or have different fields you wish to synchronize, you should modify these actions accordingly.
**NOTE:** You can configure your own actions to perform on the *users* object in the **Configuration** page, or on any of the app database object, by selecting the object's name under **Objects** and clicking on the **Actions** tab. The actions can be triggered by database actions (hooks) or on demand, by calling the action's *Request Url* (presented when you test the action). Actions can send emails, execute transactional SQL scripts, and execute server-side JavaScript Code.

#### Saving Additional Parameters in the Sign up
In many cases we would like to collect more information from the user during sign up. The additional information
should be added to the *users* object of the app. This option can be done by sending *parameters* in the client and
update the server side action in order to save it in the object. In our example we will collect the company name of
the user:

1. Update the Model and add company field to *users* object:
    1. Go to *Objects --> Model*
    2. Add this element to the *users* object: *"company": {"type": "string"}*
    3. Click on *Validate & Update*

2. In the code when calling to Backand.signup() send parameters object as the last input parameter. The code looks
like this:
  ```javascript
    Backand.signup(firstName, lastName, username, password, password, {company: self.company}).then(...);
  ```
3. In the server side we need to modified the *Create My App User* action:
    1. Go to *Security & Auth --> Security Actions* and select *Create My App User*
    2. Click on Edit Action
    3. In the Input Parameters yype *company*
    4. Update the Sql Script to include the {{company}} parameter like this:

  ```SQL
    insert into `users` (`email`,`firstName`,`lastName`,`company`) select '{{Username}}','{{FirstName}}','{{LastName}}','{{company}}'  FROM   DUAL  WHERE NOT EXISTS (SELECT * FROM `users` WHERE `email`='{{Username}}' )  LIMIT 1
  ```
4. In the UI make sure you collect the company value or send an empty value

Upon sign up completed you can see the company name in the *users* object Data tab.

## Invite Users to the Application

Once you have completed the above, you are ready to begin inviting users to your application! To invite new users:

1. Navigate to *Security & Auth --> Registered Users*
2. Enter an email in the *invite user(s)* input box. Please use a valid email address that is able to receive messages sent by Backand.
3. Click on *Invite User(s)* button. A new user will be added to the users list, and assigned the *User*. This will also trigger an invitation email that is sent to the entered email address.
4. Open the email message.
5. Click on the invitation link. This will navigate to the sign in/sign up page you set in the configuration page, to complete the sign in process.
6. Check the new user checkbox and enter the sign up details.

## Set Current User Validation
At this point, when new users sign in they will have full access to the application, and will be able to create, update and delete all the tasks. In order to restrict the users to update only tasks they created we will configure a few actions on the 'todo' object.

#### Modifying the Create Action for Todo Objects
1. Go to *Objects --> todo*
2. Click on the *Actions* tab
3. Click on the *New Action* button
4. Name the action *Validate current user on create*
5. In the *Event Trigger...* drop-down, select *Create - During data saved before it committed*
6. Leave the *Input Parameters* empty
7. In the *Type* drop-down, select *Server side JavaScript code*. A text area containing a JavaScript function will be displayed.
8. Paste the following code into the body of the provided function:

  ```javascript
    // if the current user has an *Admin* role then she is allowed to create a todo for another user
    if (userProfile.role == "Admin")
	    return {};
    var createdByFromInput = userInput.created_by;
    // do not allow anonymous users to create a todo
    if (!createdByFromInput)
        throw new Error('The creator of the todo is unknown.');
    var currentUsername = userProfile.username;
    if (!currentUsername)
        throw new Error('The current user is unknown.');

    // get the current user information from the app users table by filter with the email
    var currentUser = null;
    try{
        currentUser = $http({method:"GET",url:CONSTS.apiUrl + '/1/objects/users?filter=[{ fieldName: "email", operator: "equals", value: "' + encodeURIComponent(currentUsername) + '" }]', headers: {"Authorization":userProfile.token}});
    }
    catch (err){
        throw new Error('Failed to get the current user. ' + err.message);
    }
    // get the current user id
    var currentUserId = null;
    if (currentUser && currentUser.data && currentUser.data.length == 1){
        currentUserId = currentUser.data[0].id;
    }
    else {
         throw new Error('Could not find the current user in the app.');
    }
    // do not allow non *Admin* users to create a todo for other users
    if (createdByFromInput !=  currentUserId)
        throw new Error('Please create todo only for yourself.');

	return {};
  ```
9. Save the action.

#### Modifying the Update Action for Todo Objects

A similar modification needs to be made for when a *todo* item is updated.
The only difference here is that we also need to validate that users with *User* role cannot change the creator of the *todo* item.
To make the modifications for the Update action, perform the following steps:

1. Click on the *New Action* button
2. Name the action *Validate current user on update*.
3. In the *Select Trigger...* drop-down, select *Update - During data saved before it committed*
4. Leave the *Input Parameters* empty
5. In the *Type* drop-down, select *Server side JavaScript code*. A text area containing a JavaScript function will be displayed.
6. Enter the following code as the body of the provided JavaScript function:

  ```javascript
    // if the current user has an *Admin* role then he is allowed to update a todo for other users
    if (userProfile.role == "Admin")
	    return {};
    var createdByFromInput = userInput.created_by;
    // do not allow anonymous users to create a todo
    if (!createdByFromInput)
        throw new Error('The creator of the todo is unknown.');
    var createdByFromRow = dbRow.created_by;
    if (!createdByFromRow)
        throw new Error('The creator of the todo is unknown.');
    var currentUsername = userProfile.username;
    if (!currentUsername)
        throw new Error('The current user is unknown.');

    // get the current user information from the app users table by filter with the email
    var currentUser = null;
    try{
        currentUser = $http({method:"GET",url:CONSTS.apiUrl + '/1/objects/users?filter=[{ fieldName: "email", operator: "equals", value: "' + encodeURIComponent(currentUsername) + '" }]', headers: {"Authorization":userProfile.token, "AppName": userProfile.app}});
    }
    catch (err){
        throw new Error('Failed to get the current user. ' + err.message);
    }
    var currentUserId = null;
    // get the current user id
    if (currentUser && currentUser.data && currentUser.data.length == 1){
        currentUserId = currentUser.data[0].id;
    }
    else {
         throw new Error('Could not find the current user in the app.');
    }
    // do not allow non *Admin* users to update a todo for other users
    if (createdByFromRow !=  createdByFromInput)
        throw new Error('You can can not change the creator of the todo.');
    // do not allow non *Admin* users to change the creator of the todo
    if (createdByFromInput !=  currentUserId)
        throw new Error('You can only update your own todo.');
	return {};
  ```
7. Save the action.

#### Modifying the Delete Action for Todo Objects

There is no user input for delete requests, so you only need to verify that the item you about to delete was created by the current user.
To make the modifications for the Update action, perform the following steps:

1. Click on the *New Action* button
2. Name the action *Validate current user on delete*.
3. In the *Select Trigger...* drop-down, select *Delete - During record deleted but before it committed*.
4. Leave the *Input Parameters* empty
5. In the *Type* drop-down, select *Server side JavaScript code*.  A text area containing a JavaScript function will be displayed.
6. Enter the following code as the body of the provided JavaScript function:

  ```javascript
    // if the current user has an *Admin* role then he is allowed to delete a todo that was created by other users
    if (userProfile.role == "Admin")
	    return {};
    var createdByFromRow = dbRow.created_by;
    if (!createdByFromRow)
        throw new Error('The creator of the todo is unknown.');
    var currentUsername = userProfile.username;
    if (!currentUsername)
        throw new Error('The current user is unknown.');

    var currentUser = null;
    // get the current user information from the app users table by filter with the email
    try{
        currentUser = $http({method:"GET",url:CONSTS.apiUrl + '/1/objects/users?filter=[{ fieldName: "email", operator: "equals", value: "' + encodeURIComponent(currentUsername) + '" }]', headers: {"Authorization":userProfile.token, "AppName": userProfile.app}});
    }
    catch (err){
        throw new Error('Failed to get the current user. ' + err.message);
    }
    var currentUserId = null;
    if (currentUser && currentUser.data && currentUser.data.length == 1){
        currentUserId = currentUser.data[0].id;
    }
    else {
         throw new Error('Could not find the current user in the app.');
    }
    // do not allow non *Admin* users to delete a todo created by other users
    if (createdByFromRow !=  currentUserId)
        throw new Error('You can only delete your own todo.');
    return {};
  ```
7. Save the action

## Finished!
At this point, your application is ready to use! You can test the security roles by signing in with a User role and see that you can only delete and update the todo items you create. If you then log out and log back in as a user with the *Admin* role, you will see that you can now perform all CRUD actions on every object in the database! You can also add a new user and see that they are assigned the *User* role by default, and not able to update records that are not their own.

## Testing

As a part of the installation process, NPM installed Karma for unit testing. Run `grunt test` to execute all of the unit tests in the system.

## Building your own application

Now that you've implemented a Todo application, you can build your own. Simply sign-up at [Backand's website](https://wwww.backand.com) and create a new app to get started!


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CategoryCost extends Model
{

    protected $fillable = [
        'name',
        'description',
        'status'
    ];

}


text:
let cleanup_called = false;
let cleanup = function(iter) {
  assertFalse(cleanup_called);
  let holdings_list = [];
  for (holdings of iter) {
    holdings_list.push(holdings);
  }
  assertEquals(holdings_list.length, 2);
  if (holdings_list[0] == 1) {
    assertEquals(holdings_list[1], 2);
  } else {
    assertEquals(holdings_list[0], 2);
    assertEquals(holdings_list[1], 1);
  }
  cleanup_called = true;
}

let fg = new FinalizationGroup(cleanup);
let o1 = {};
let o2 = {};
fg.register(o1, 1);
fg.register(o2, 2);

gc();
assertFalse(cleanup_called);

// Drop the last references to o1 and o2.
o1 = null;
o2 = null;
// GC will reclaim the target objects; the cleanup function will be called the
// next time we enter the event loop.
gc();
assertFalse(cleanup_called);

let timeout_func = function() {
  assertTrue(cleanup_called);
}

setTimeout(timeout_func, 0);


text:
module Tests::AjaxesHelper
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.digitalsingular</groupId>
    <artifactId>wp2jbake</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>Wordpress to JBake Markdown Converter</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
    </dependencies>

</project>


text:
<?php

declare(strict_types=1);

namespace KG\Pager\PagingStrategy;

use KG\Pager\AdapterInterface;
use KG\Pager\PagingStrategyInterface;

/**
 * Splits the paged target to pages with an equal number of items per page. The
 * last page might have less items depending on the total number of items to
 * page.
 */
final class EquallyPaged implements PagingStrategyInterface
{
    /**
     * {@inheritDoc}
     */
    public function getLimit(AdapterInterface $adapter, int $page, int $perPage): array
    {
        $offset = ($page - 1) * $perPage;
        $length = $perPage;

        return array($offset, $length);
    }

    /**
     * {@inheritDoc}
     */
    public function getCount(AdapterInterface $adapter, int $page, int $perPage): int
    {
        return (int) ceil($adapter->getItemCount() / $perPage);
    }
}


text:
package org.apache.syncope.common.lib.search;

import org.apache.cxf.jaxrs.ext.search.client.CompleteCondition;

public interface UserProperty extends SyncopeProperty {

    CompleteCondition inGroups(String group, String... moreGroups);

    CompleteCondition notInGroups(String group, String... moreGroups);

    CompleteCondition inRelationships(String anyObject, String... moreAnyObjects);

    CompleteCondition notInRelationships(String anyObject, String... moreAnyObjects);

    CompleteCondition inRelationshipTypes(String type, String... moreTypes);

    CompleteCondition notInRelationshipTypes(String type, String... moreTypes);

    CompleteCondition inRoles(String role, String... moreRoles);

    CompleteCondition notInRoles(String role, String... moreRoles);

}


text:
package crc32

// simpleMakeTable allocates and constructs a Table for the specified
// polynomial. The table is suitable for use with the simple algorithm
// (simpleUpdate).
func simpleMakeTable(poly uint32) *Table {
	t := new(Table)
	simplePopulateTable(poly, t)
	return t
}

// simplePopulateTable constructs a Table for the specified polynomial, suitable
// for use with simpleUpdate.
func simplePopulateTable(poly uint32, t *Table) {
	for i := 0; i < 256; i++ {
		crc := uint32(i)
		for j := 0; j < 8; j++ {
			if crc&1 == 1 {
				crc = (crc >> 1) ^ poly
			} else {
				crc >>= 1
			}
		}
		t[i] = crc
	}
}

// simpleUpdate uses the simple algorithm to update the CRC, given a table that
// was previously computed using simpleMakeTable.
func simpleUpdate(crc uint32, tab *Table, p []byte) uint32 {
	crc = ^crc
	for _, v := range p {
		crc = tab[byte(crc)^v] ^ (crc >> 8)
	}
	return ^crc
}

// Use slicing-by-8 when payload >= this value.
const slicing8Cutoff = 16

// slicing8Table is array of 8 Tables, used by the slicing-by-8 algorithm.
type slicing8Table [8]Table

// slicingMakeTable constructs a slicing8Table for the specified polynomial. The
// table is suitable for use with the slicing-by-8 algorithm (slicingUpdate).
func slicingMakeTable(poly uint32) *slicing8Table {
	t := new(slicing8Table)
	simplePopulateTable(poly, &t[0])
	for i := 0; i < 256; i++ {
		crc := t[0][i]
		for j := 1; j < 8; j++ {
			crc = t[0][crc&0xFF] ^ (crc >> 8)
			t[j][i] = crc
		}
	}
	return t
}

// slicingUpdate uses the slicing-by-8 algorithm to update the CRC, given a
// table that was previously computed using slicingMakeTable.
func slicingUpdate(crc uint32, tab *slicing8Table, p []byte) uint32 {
	if len(p) >= slicing8Cutoff {
		crc = ^crc
		for len(p) > 8 {
			crc ^= uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24
			crc = tab[0][p[7]] ^ tab[1][p[6]] ^ tab[2][p[5]] ^ tab[3][p[4]] ^
				tab[4][crc>>24] ^ tab[5][(crc>>16)&0xFF] ^
				tab[6][(crc>>8)&0xFF] ^ tab[7][crc&0xFF]
			p = p[8:]
		}
		crc = ^crc
	}
	if len(p) == 0 {
		return crc
	}
	return simpleUpdate(crc, &tab[0], p)
}


text:
comments: true
date: 2009-11-04 21:12:56
layout: post
slug: reverse-gravatar-functionality
title: Reverse Gravatar Functionality
wordpress_id: 135
categories:
- web
tags:
- avatar
- gravatar
---

First off: If you don't know what a [Gravatar](http://gravatar.com) is, watch this video:

Here's a nice feature I didn't know Gravatar had: The url of your avatar image is static. It's not even a 'feature' as such, but what it does mean is that when using websites/forums that don't support Gravatar you can give them this url and your avatar should update along with the cached version on the Gravatar server. Neat, eh?

To take advantage of this functionality, you need the direct link to your image. When managing your Gravatar account, you'll see the link to the image in the lower right:

![Gravatar-link](/a/2009-11-04-reverse-gravatar-functionality/Gravatar-link1.png)

Another little gem: Gravatar converts your image into several different formats for you. The image I uploaded was a png, but the forum I wanted to use it on would only take jpgs. On a hunch I tried just changing the extension on the url. It worked! Gif is also supported like this, and for all I know there may be more. Try it! Just make sure to let me know if you find any more cool stuff there, ok?


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using ArcheageCraft.Models;

namespace ArcheageCraft.Controllers
{
    public class ProfessionsController : ApiController
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: api/Professions
        [ActionName("")]
        public IQueryable<Profession> GetProfessions()
        {
            return db.Professions.OrderBy(p=>p.Name);
        }

        // GET: api/Professions/5
        [ResponseType(typeof(Profession))]
        [ActionName("")]
        public async Task<IHttpActionResult> GetProfession(int id)
        {
            Profession profession = await db.Professions.FindAsync(id);
            if (profession == null)
            {
                return NotFound();
            }

            return Ok(profession);
        }

        // PUT: api/Professions/5
        [ResponseType(typeof(void))]
        [ActionName("")]
        public async Task<IHttpActionResult> PutProfession(int id, Profession profession)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != profession.ProfessionId)
            {
                return BadRequest();
            }

            db.Entry(profession).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProfessionExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Professions
        [ResponseType(typeof(Profession))]
        [ActionName("")]
        public async Task<IHttpActionResult> PostProfession(Profession profession)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Professions.Add(profession);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = profession.ProfessionId }, profession);
        }

        // DELETE: api/Professions/5
        [ResponseType(typeof(Profession))]
        [ActionName("")]
        public async Task<IHttpActionResult> DeleteProfession(int id)
        {
            Profession profession = await db.Professions.FindAsync(id);
            if (profession == null)
            {
                return NotFound();
            }

            db.Professions.Remove(profession);
            await db.SaveChangesAsync();

            return Ok(profession);
        }

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

        private bool ProfessionExists(int id)
        {
            return db.Professions.Count(e => e.ProfessionId == id) > 0;
        }
    }
}


text:
<?php
/**
 * @package Guzzle PHP <http://www.guzzlephp.org>
 * @license See the LICENSE file that was distributed with this source code.
 */

namespace Guzzle\Aws\S3\Command\Object;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Aws\S3\S3Client;

/**
 * The HEAD operation retrieves metadata from an object without returning the
 * object itself. This operation is useful if you're only interested in an
 * object's metadata. To use HEAD, you must have READ access to the object.
 * If READ access is granted to the anonymous user, you can request the
 * object's metadata without an authorization header.
 *
 * A HEAD request has the same options as a GET operation on an object. The
 * response is identical to the GET response, except that there is no response
 * body.
 *
 * @guzzle bucket doc="Bucket where the object is stored" required="true"
 * @guzzle key doc="Object key" required="true"
 * @guzzle headers doc="Headers to set on the request" type="class:Guzzle\Common\Collection"
 * @guzzle range doc="Downloads the specified range of an object"
 * @guzzle if_modified_since" doc="Return the object only if it has been modified since the specified time, otherwise return a 304 (not modified)"
 * @guzzle if_unmodified_since doc="Return the object only if it has not been modified since the specified time, otherwise return a 412 (precondition failed)"
 * @guzzle if_match doc="Return the object only if its entity tag (ETag) is the same as the one specified, otherwise return a 412 (precondition failed)"
 * @guzzle if_none_match doc="Return the object only if its entity tag (ETag) is different from the one specified, otherwise return a 304 (not modified)."
 *
 * @author Michael Dowling <michael@guzzlephp.org>
 */
class HeadObject extends AbstractRequestObject
{
    /**
     * {@inheritdoc}
     */
    protected function build()
    {
        $this->request = $this->client->getS3Request(RequestInterface::HEAD, $this->get('bucket'), $this->get('key'));
        $this->applyDefaults($this->request);
    }
}


text:
import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
  LOGIN: 'LOGIN',
  LOGOUT: 'LOGOUT',
};

export function login(admin) {
  return {
    type: ACTIONS.LOGIN,
    admin
  };
}
export function logout() {
  return {
    type: ACTIONS.LOGOUT,
  };
}
export function loginRequest(admin) {
  return (dispatch) => {
    return callApi('admin/login', 'post', '', {admin}).then(res => {
      if (res.admin && res.admin.code === 'success') {
        dispatch(login(res.admin.admin));
      }
      return res.admin;
    });
  };
}


text:
package com.vaadin.addon.charts.model;

import com.vaadin.addon.charts.model.style.Style;
/**
 * The loading options control the appearance of the loading screen that covers
 * the plot area on chart operations. This screen only appears after an explicit
 * call to chart.showLoading(). It is a utility for developers to
 * communicate to the end user that something is going on, for example while
 * retrieving new data via an XHR connection. The "Loading..." text itself is
 * not part of this configuration object, but part of the lang
 * object.
 */
public class Loading extends AbstractConfigurationObject {

	private static final long serialVersionUID = 1L;
	private Number hideDuration;
	private Style labelStyle;
	private Number showDuration;
	private Style style;

	public Loading() {
	}

	/**
	 * @see #setHideDuration(Number)
	 */
	public Number getHideDuration() {
		return hideDuration;
	}

	/**
	 * The duration in milliseconds of the fade out effect.
	 *

	 * Defaults to: 100
	 */
	public void setHideDuration(Number hideDuration) {
		this.hideDuration = hideDuration;
	}

	/**
	 * @see #setLabelStyle(Style)
	 */
	public Style getLabelStyle() {
		return labelStyle;
	}

	/**
	 * CSS styles for the loading label span.
	 *

	 * Defaults to: { "fontWeight": "bold", "position": "relative", "top": "45%"
	 * }
	 */
	public void setLabelStyle(Style labelStyle) {
		this.labelStyle = labelStyle;
	}

	/**
	 * @see #setShowDuration(Number)
	 */
	public Number getShowDuration() {
		return showDuration;
	}

	/**
	 * The duration in milliseconds of the fade in effect.
	 *

	 * Defaults to: 100
	 */
	public void setShowDuration(Number showDuration) {
		this.showDuration = showDuration;
	}

	/**
	 * @see #setStyle(Style)
	 */
	public Style getStyle() {
		return style;
	}

	/**
	 * CSS styles for the loading screen that covers the plot area. Defaults to:
	 *
	 *

	 * style: {
	 * 		position: 'absolute',
	 * 		backgroundColor: 'white',
	 * 		opacity: 0.5,
	 * 		textAlign: 'center'
	 * 	}
	 *

	 */
	public void setStyle(Style style) {
		this.style = style;
	}
}


text:
<?php

namespace CL\Slack\Tests\Payload;

use CL\Slack\Payload\GroupsMarkPayload;
use CL\Slack\Payload\PayloadInterface;

/**
 * @author Cas Leentfaar <info@casleentfaar.com>
 */
class GroupsMarkPayloadTest extends AbstractPayloadTestCase
{
    /**
     * @inheritdoc
     */
    protected function createPayload()
    {
        $payload = new GroupsMarkPayload();
        $payload->setGroupId('G1234567');
        $payload->setSlackTimestamp('12345678.12345678');

        return $payload;
    }

    /**
     * @inheritdoc
     *
     * @param GroupsMarkPayload $payload
     */
    protected function getExpectedPayloadData(PayloadInterface $payload)
    {
        return [
            'ts' => $payload->getSlackTimestamp(),
            'channel' => $payload->getGroupId(),
        ];
    }
}


text:
call init.bat

rem rmdir /Q /S CB

set CDB_HOME=%curpath%\cdatabase

python test02.py


text:
package proto

// DO NOT EDIT.
// FILE GENERATED BY BSONGEN.

import (
	"bytes"

	"github.com/youtube/vitess/go/bson"
	"github.com/youtube/vitess/go/bytes2"
	mproto "github.com/youtube/vitess/go/mysql/proto"
)

// MarshalBson bson-encodes TransactionInfo.
func (transactionInfo *TransactionInfo) MarshalBson(buf *bytes2.ChunkedWriter, key string) {
	bson.EncodeOptionalPrefix(buf, bson.Object, key)
	lenWriter := bson.NewLenWriter(buf)

	bson.EncodeInt64(buf, "TransactionId", transactionInfo.TransactionId)
	// *mproto.RPCError
	if transactionInfo.Err == nil {
		bson.EncodePrefix(buf, bson.Null, "Err")
	} else {
		(*transactionInfo.Err).MarshalBson(buf, "Err")
	}

	lenWriter.Close()
}

// UnmarshalBson bson-decodes into TransactionInfo.
func (transactionInfo *TransactionInfo) UnmarshalBson(buf *bytes.Buffer, kind byte) {
	switch kind {
	case bson.EOO, bson.Object:
		// valid
	case bson.Null:
		return
	default:
		panic(bson.NewBsonError("unexpected kind %v for TransactionInfo", kind))
	}
	bson.Next(buf, 4)

	for kind := bson.NextByte(buf); kind != bson.EOO; kind = bson.NextByte(buf) {
		switch bson.ReadCString(buf) {
		case "TransactionId":
			transactionInfo.TransactionId = bson.DecodeInt64(buf, kind)
		case "Err":
			// *mproto.RPCError
			if kind != bson.Null {
				transactionInfo.Err = new(mproto.RPCError)
				(*transactionInfo.Err).UnmarshalBson(buf, kind)
			}
		default:
			bson.Skip(buf, kind)
		}
	}
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('proposals', '0002_auto_20150626_0943'),
    ]

    operations = [
        migrations.CreateModel(
            name='Proposal',
            fields=[
                ('proposalbase_ptr', models.OneToOneField(to='proposals.ProposalBase', parent_link=True, primary_key=True, auto_created=True, serialize=False)),
                ('paper', models.BooleanField(default=False, help_text='¿Estarías dispuesto a preparar un paper que acompañe la charla?')),
            ],
            bases=('proposals.proposalbase',),
        ),
    ]


text:
//
// Copyright (c) 2017, Quamotion
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//

using DiscUtils;
using DiscUtils.Nfs;
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;

namespace LibraryTests.Nfs
{
    public class Nfs3ReadDirPlusResultTest
    {
        [Fact]
        public void RoundTripTest()
        {
            Nfs3ReadDirPlusResult result = new Nfs3ReadDirPlusResult()
            {
                CookieVerifier = 1,
                DirAttributes = new Nfs3FileAttributes()
                {
                    AccessTime = new Nfs3FileTime(new DateTime(2017, 1, 1)),
                    BytesUsed = 1,
                    ChangeTime = new Nfs3FileTime(new DateTime(2017, 1, 2)),
                    FileId = 2,
                    FileSystemId = 3,
                    Gid = 4,
                    LinkCount = 5,
                    Mode = UnixFilePermissions.GroupAll,
                    ModifyTime = new Nfs3FileTime(new DateTime(2017, 1, 3)),
                    RdevMajor = 6,
                    RdevMinor = 7,
                    Size = 8,
                    Type = Nfs3FileType.BlockDevice,
                    Uid = 9
                },
                DirEntries = new List<Nfs3DirectoryEntry>()
                {
                    new Nfs3DirectoryEntry()
                    {
                         Cookie = 2,
                         FileAttributes = new Nfs3FileAttributes()
                         {
                            AccessTime = new Nfs3FileTime(new DateTime(2017, 1, 10)),
                            BytesUsed = 11,
                            ChangeTime = new Nfs3FileTime(new DateTime(2017, 1, 12)),
                            FileId = 12,
                            FileSystemId = 13,
                            Gid = 14,
                            LinkCount = 15,
                            Mode = UnixFilePermissions.GroupWrite,
                            ModifyTime = new Nfs3FileTime(new DateTime(2017, 1, 13)),
                            RdevMajor = 16,
                            RdevMinor = 17,
                            Size = 18,
                            Type = Nfs3FileType.Socket,
                            Uid = 19
                         },
                         FileHandle = new Nfs3FileHandle()
                         {
                              Value = new byte[]{0xa}
                         },
                         FileId = 99,
                         Name = "test"
                    }
                },
                Eof = false,
                Status = Nfs3Status.Ok
            };

            Nfs3ReadDirPlusResult clone = null;

            using (MemoryStream stream = new MemoryStream())
            {
                XdrDataWriter writer = new XdrDataWriter(stream);
                result.Write(writer);

                stream.Position = 0;
                XdrDataReader reader = new XdrDataReader(stream);
                clone = new Nfs3ReadDirPlusResult(reader);
            }

            Assert.Equal(result, clone);
        }
    }
}


text:
from io import BytesIO

from .node import (Node, AtomNode, BinaryExpressionNode, BinaryOperatorNode,
                   ConditionalNode, DataNode, IndexNode, KeyValueNode, ListNode,
                   NumberNode, StringNode, UnaryExpressionNode,
                   UnaryOperatorNode, ValueNode, VariableNode)

class ParseError(Exception):
    def __init__(self, filename, line, detail):
        self.line = line
        self.filename = filename
        self.detail = detail
        self.message = f"{self.detail}: {self.filename} line {self.line}"
        Exception.__init__(self, self.message)

eol = object
group_start = object
group_end = object
digits = "0123456789"
open_parens = "[("
close_parens = "])"
parens = open_parens + close_parens
operator_chars = "=!"

unary_operators = ["not"]
binary_operators = ["==", "!=", "and", "or"]

operators = ["==", "!=", "not", "and", "or"]

atoms = {"True": True,
         "False": False,
         "Reset": object()}

def decode(s):
    assert isinstance(s, str)
    return s

def precedence(operator_node):
    return len(operators) - operators.index(operator_node.data)

class TokenTypes:
    def __init__(self) -> None:
        for type in [
            "group_start",
            "group_end",
            "paren",
            "list_start",
            "list_end",
            "separator",
            "ident",
            "string",
            "number",
            "atom",
            # Without an end-of-line token type, we need two different comment
            # token types to distinguish between:
            #   [heading1]  # Comment attached to heading 1
            #   [heading2]
            #
            # and
            #   [heading1]
            #   # Comment attached to heading 2
            #   [heading2]
            "comment",
            "inline_comment",
            "eof",
        ]:
            setattr(self, type, type)

token_types = TokenTypes()

class Tokenizer:
    def __init__(self):
        self.reset()

    def reset(self):
        self.indent_levels = [0]
        self.state = self.line_start_state
        self.next_state = self.data_line_state
        self.line_number = 0
        self.filename = ""

    def tokenize(self, stream):
        self.reset()
        assert not isinstance(stream, str)
        if isinstance(stream, bytes):
            stream = BytesIO(stream)
        if not hasattr(stream, "name"):
            self.filename = ""
        else:
            self.filename = stream.name

        self.next_line_state = self.line_start_state
        for i, line in enumerate(stream):
            assert isinstance(line, bytes)
            self.state = self.next_line_state
            assert self.state is not None
            states = []
            self.next_line_state = None
            self.line_number = i + 1
            self.index = 0
            self.line = line.decode('utf-8').rstrip()
            assert isinstance(self.line, str)
            while self.state != self.eol_state:
                states.append(self.state)
                tokens = self.state()
                if tokens:
                    yield from tokens
            self.state()
        while True:
            yield (token_types.eof, None)

    def char(self):
        if self.index == len(self.line):
            return eol
        return self.line[self.index]

    def consume(self):
        if self.index < len(self.line):
            self.index += 1

    def peek(self, length):
        return self.line[self.index:self.index + length]

    def skip_whitespace(self):
        while self.char() == " ":
            self.consume()

    def eol_state(self):
        if self.next_line_state is None:
            self.next_line_state = self.line_start_state

    def line_start_state(self):
        self.skip_whitespace()
        if self.char() == eol:
            self.state = self.eol_state
            return
        if self.char() == "#":
            self.state = self.comment_state
            return
        if self.index > self.indent_levels[-1]:
            self.indent_levels.append(self.index)
            yield (token_types.group_start, None)
        else:
            if self.index < self.indent_levels[-1]:
                while self.index < self.indent_levels[-1]:
                    self.indent_levels.pop()
                    yield (token_types.group_end, None)
                # This is terrible; if we were parsing an expression
                # then the next_state will be expr_or_value but when we deindent
                # it must always be a heading or key next so we go back to data_line_state
                self.next_state = self.data_line_state
            if self.index != self.indent_levels[-1]:
                raise ParseError(self.filename, self.line_number, "Unexpected indent")

        self.state = self.next_state

    def data_line_state(self):
        if self.char() == "[":
            yield (token_types.paren, self.char())
            self.consume()
            self.state = self.heading_state
        else:
            self.state = self.key_state

    def heading_state(self):
        rv = ""
        while True:
            c = self.char()
            if c == "\\":
                rv += self.consume_escape()
            elif c == "]":
                break
            elif c == eol:
                raise ParseError(self.filename, self.line_number, "EOL in heading")
            else:
                rv += c
                self.consume()

        yield (token_types.string, decode(rv))
        yield (token_types.paren, "]")
        self.consume()
        self.state = self.line_end_state
        self.next_state = self.data_line_state

    def key_state(self):
        rv = ""
        while True:
            c = self.char()
            if c == " ":
                self.skip_whitespace()
                if self.char() != ":":
                    raise ParseError(self.filename, self.line_number, "Space in key name")
                break
            elif c == ":":
                break
            elif c == eol:
                raise ParseError(self.filename, self.line_number, "EOL in key name (missing ':'?)")
            elif c == "\\":
                rv += self.consume_escape()
            else:
                rv += c
                self.consume()
        yield (token_types.string, decode(rv))
        yield (token_types.separator, ":")
        self.consume()
        self.state = self.after_key_state

    def after_key_state(self):
        self.skip_whitespace()
        c = self.char()
        if c in {"#", eol}:
            self.next_state = self.expr_or_value_state
            self.state = self.line_end_state
        elif c == "[":
            self.state = self.list_start_state
        else:
            self.state = self.value_state

    def after_expr_state(self):
        self.skip_whitespace()
        c = self.char()
        if c in {"#", eol}:
            self.next_state = self.after_expr_state
            self.state = self.line_end_state
        elif c == "[":
            self.state = self.list_start_state
        else:
            self.state = self.value_state

    def list_start_state(self):
        yield (token_types.list_start, "[")
        self.consume()
        self.state = self.list_value_start_state

    def list_value_start_state(self):
        self.skip_whitespace()
        if self.char() == "]":
            self.state = self.list_end_state
        elif self.char() in ("'", '"'):
            quote_char = self.char()
            self.consume()
            yield (token_types.string, self.consume_string(quote_char))
            self.skip_whitespace()
            if self.char() == "]":
                self.state = self.list_end_state
            elif self.char() != ",":
                raise ParseError(self.filename, self.line_number, "Junk after quoted string")
            self.consume()
        elif self.char() in {"#", eol}:
            self.state = self.line_end_state
            self.next_line_state = self.list_value_start_state
        elif self.char() == ",":
            raise ParseError(self.filename, self.line_number, "List item started with separator")
        elif self.char() == "@":
            self.state = self.list_value_atom_state
        else:
            self.state = self.list_value_state

    def list_value_state(self):
        rv = ""
        spaces = 0
        while True:
            c = self.char()
            if c == "\\":
                escape = self.consume_escape()
                rv += escape
            elif c == eol:
                raise ParseError(self.filename, self.line_number, "EOL in list value")
            elif c == "#":
                raise ParseError(self.filename, self.line_number, "EOL in list value (comment)")
            elif c == ",":
                self.state = self.list_value_start_state
                self.consume()
                break
            elif c == " ":
                spaces += 1
                self.consume()
            elif c == "]":
                self.state = self.list_end_state
                self.consume()
                break
            else:
                rv += " " * spaces
                spaces = 0
                rv += c
                self.consume()

        if rv:
            yield (token_types.string, decode(rv))

    def list_value_atom_state(self):
        self.consume()
        for _, value in self.list_value_state():
            yield token_types.atom, value

    def list_end_state(self):
        self.consume()
        yield (token_types.list_end, "]")
        self.state = self.line_end_state

    def value_state(self):
        self.skip_whitespace()
        c = self.char()
        if c in ("'", '"'):
            quote_char = self.char()
            self.consume()
            yield (token_types.string, self.consume_string(quote_char))
            self.state = self.line_end_state
        elif c == "@":
            self.consume()
            for _, value in self.value_inner_state():
                yield token_types.atom, value
        elif c == "[":
            self.state = self.list_start_state
        else:
            self.state = self.value_inner_state

    def value_inner_state(self):
        rv = ""
        spaces = 0
        while True:
            c = self.char()
            if c == "\\":
                rv += self.consume_escape()
            elif c in {"#", eol}:
                self.state = self.line_end_state
                break
            elif c == " ":
                # prevent whitespace before comments from being included in the value
                spaces += 1
                self.consume()
            else:
                rv += " " * spaces
                spaces = 0
                rv += c
                self.consume()
        rv = decode(rv)
        if rv.startswith("if "):
            # Hack to avoid a problem where people write
            # disabled: if foo
            # and expect that to disable conditionally
            raise ParseError(self.filename, self.line_number, "Strings starting 'if ' must be quoted "
                             "(expressions must start on a newline and be indented)")
        yield (token_types.string, rv)

    def _consume_comment(self):
        assert self.char() == "#"
        self.consume()
        comment = ''
        while self.char() is not eol:
            comment += self.char()
            self.consume()
        return comment

    def comment_state(self):
        yield (token_types.comment, self._consume_comment())
        self.state = self.eol_state

    def inline_comment_state(self):
        yield (token_types.inline_comment, self._consume_comment())
        self.state = self.eol_state

    def line_end_state(self):
        self.skip_whitespace()
        c = self.char()
        if c == "#":
            self.state = self.inline_comment_state
        elif c == eol:
            self.state = self.eol_state
        else:
            raise ParseError(self.filename, self.line_number, "Junk before EOL %s" % c)

    def consume_string(self, quote_char):
        rv = ""
        while True:
            c = self.char()
            if c == "\\":
                rv += self.consume_escape()
            elif c == quote_char:
                self.consume()
                break
            elif c == eol:
                raise ParseError(self.filename, self.line_number, "EOL in quoted string")
            else:
                rv += c
                self.consume()

        return decode(rv)

    def expr_or_value_state(self):
        if self.peek(3) == "if ":
            self.state = self.expr_state
        else:
            self.state = self.value_state

    def expr_state(self):
        self.skip_whitespace()
        c = self.char()
        if c == eol:
            raise ParseError(self.filename, self.line_number, "EOL in expression")
        elif c in "'\"":
            self.consume()
            yield (token_types.string, self.consume_string(c))
        elif c == "#":
            raise ParseError(self.filename, self.line_number, "Comment before end of expression")
        elif c == ":":
            yield (token_types.separator, c)
            self.consume()
            self.state = self.after_expr_state
        elif c in parens:
            self.consume()
            yield (token_types.paren, c)
        elif c in ("!", "="):
            self.state = self.operator_state
        elif c in digits:
            self.state = self.digit_state
        else:
            self.state = self.ident_state

    def operator_state(self):
        # Only symbolic operators
        index_0 = self.index
        while True:
            c = self.char()
            if c == eol:
                break
            elif c in operator_chars:
                self.consume()
            else:
                self.state = self.expr_state
                break
        yield (token_types.ident, self.line[index_0:self.index])

    def digit_state(self):
        index_0 = self.index
        seen_dot = False
        while True:
            c = self.char()
            if c == eol:
                break
            elif c in digits:
                self.consume()
            elif c == ".":
                if seen_dot:
                    raise ParseError(self.filename, self.line_number, "Invalid number")
                self.consume()
                seen_dot = True
            elif c in parens:
                break
            elif c in operator_chars:
                break
            elif c == " ":
                break
            elif c == ":":
                break
            else:
                raise ParseError(self.filename, self.line_number, "Invalid character in number")

        self.state = self.expr_state
        yield (token_types.number, self.line[index_0:self.index])

    def ident_state(self):
        index_0 = self.index
        while True:
            c = self.char()
            if c == eol:
                break
            elif c == ".":
                break
            elif c in parens:
                break
            elif c in operator_chars:
                break
            elif c == " ":
                break
            elif c == ":":
                break
            else:
                self.consume()
        self.state = self.expr_state
        yield (token_types.ident, self.line[index_0:self.index])

    def consume_escape(self):
        assert self.char() == "\\"
        self.consume()
        c = self.char()
        self.consume()
        if c == "x":
            return self.decode_escape(2)
        elif c == "u":
            return self.decode_escape(4)
        elif c == "U":
            return self.decode_escape(6)
        elif c in ["a", "b", "f", "n", "r", "t", "v"]:
            return eval(r"'\%s'" % c)
        elif c is eol:
            raise ParseError(self.filename, self.line_number, "EOL in escape")
        else:
            return c

    def decode_escape(self, length):
        value = 0
        for i in range(length):
            c = self.char()
            value *= 16
            value += self.escape_value(c)
            self.consume()

        return chr(value)

    def escape_value(self, c):
        if '0' <= c <= '9':
            return ord(c) - ord('0')
        elif 'a' <= c <= 'f':
            return ord(c) - ord('a') + 10
        elif 'A' <= c <= 'F':
            return ord(c) - ord('A') + 10
        else:
            raise ParseError(self.filename, self.line_number, "Invalid character escape")

class Parser:
    def __init__(self):
        self.reset()

    def reset(self):
        self.token = None
        self.unary_operators = "!"
        self.binary_operators = frozenset(["&&", "||", "=="])
        self.tokenizer = Tokenizer()
        self.token_generator = None
        self.tree = Treebuilder(DataNode(None))
        self.expr_builder = None
        self.expr_builders = []
        self.comments = []

    def parse(self, input):
        try:
            self.reset()
            self.token_generator = self.tokenizer.tokenize(input)
            self.consume()
            self.manifest()
            return self.tree.node
        except Exception as e:
            if not isinstance(e, ParseError):
                raise ParseError(self.tokenizer.filename,
                                 self.tokenizer.line_number,
                                 str(e))
            raise

    def consume(self):
        self.token = next(self.token_generator)

    def expect(self, type, value=None):
        if self.token[0] != type:
            raise ParseError(self.tokenizer.filename, self.tokenizer.line_number,
                             f"Token '{self.token[0]}' doesn't equal expected type '{type}'")
        if value is not None:
            if self.token[1] != value:
                raise ParseError(self.tokenizer.filename, self.tokenizer.line_number,
                                 f"Token '{self.token[1]}' doesn't equal expected value '{value}'")

        self.consume()

    def maybe_consume_inline_comment(self):
        if self.token[0] == token_types.inline_comment:
            self.comments.append(self.token)
            self.consume()

    def consume_comments(self):
        while self.token[0] == token_types.comment:
            self.comments.append(self.token)
            self.consume()

    def flush_comments(self, target_node=None):
        """Transfer comments from the parser's buffer to a parse tree node.

        Use the tree's current node if no target node is explicitly specified.

        The comments are buffered because the target node they should belong to
        may not exist yet. For example:

            [heading]
              # comment to be attached to the subheading
              [subheading]
        """
        (target_node or self.tree.node).comments.extend(self.comments)
        self.comments.clear()

    def manifest(self):
        self.data_block()
        self.expect(token_types.eof)

    def data_block(self):
        while self.token[0] in {token_types.comment, token_types.string,
                                token_types.paren}:
            if self.token[0] == token_types.comment:
                self.consume_comments()
            elif self.token[0] == token_types.string:
                self.tree.append(KeyValueNode(self.token[1]))
                self.consume()
                self.expect(token_types.separator)
                self.maybe_consume_inline_comment()
                self.flush_comments()
                self.consume_comments()
                self.value_block()
                self.flush_comments()
                self.tree.pop()
            else:
                self.expect(token_types.paren, "[")
                if self.token[0] != token_types.string:
                    raise ParseError(self.tokenizer.filename,
                                     self.tokenizer.line_number,
                                     f"Token '{self.token[0]}' is not a string")
                self.tree.append(DataNode(self.token[1]))
                self.consume()
                self.expect(token_types.paren, "]")
                self.maybe_consume_inline_comment()
                self.flush_comments()
                self.consume_comments()
                if self.token[0] == token_types.group_start:
                    self.consume()
                    self.data_block()
                    self.eof_or_end_group()
                self.tree.pop()

    def eof_or_end_group(self):
        if self.token[0] != token_types.eof:
            self.expect(token_types.group_end)

    def value_block(self):
        if self.token[0] == token_types.list_start:
            self.consume()
            self.list_value()
        elif self.token[0] == token_types.string:
            self.value()
        elif self.token[0] == token_types.group_start:
            self.consume()
            self.expression_values()
            default_value = None
            if self.token[0] == token_types.string:
                default_value = self.value
            elif self.token[0] == token_types.atom:
                default_value = self.atom
            elif self.token[0] == token_types.list_start:
                self.consume()
                default_value = self.list_value
            if default_value:
                default_value()
            # For this special case where a group exists, attach comments to
            # the string/list value, not the key-value node. That is,
            #   key:
            #     ...
            #     # comment attached to condition default
            #     value
            #
            # should not read
            #   # comment attached to condition default
            #   key:
            #     ...
            #     value
            self.consume_comments()
            self.flush_comments(
                self.tree.node.children[-1] if default_value else None)
            self.eof_or_end_group()
        elif self.token[0] == token_types.atom:
            self.atom()
        else:
            raise ParseError(self.tokenizer.filename, self.tokenizer.line_number,
                             f"Token '{self.token[0]}' is not a known type")

    def list_value(self):
        self.tree.append(ListNode())
        self.maybe_consume_inline_comment()
        while self.token[0] in (token_types.atom, token_types.string):
            if self.token[0] == token_types.atom:
                self.atom()
            else:
                self.value()
        self.expect(token_types.list_end)
        self.maybe_consume_inline_comment()
        self.tree.pop()

    def expression_values(self):
        self.consume_comments()
        while self.token == (token_types.ident, "if"):
            self.consume()
            self.tree.append(ConditionalNode())
            self.expr_start()
            self.expect(token_types.separator)
            self.value_block()
            self.flush_comments()
            self.tree.pop()
            self.consume_comments()

    def value(self):
        self.tree.append(ValueNode(self.token[1]))
        self.consume()
        self.maybe_consume_inline_comment()
        self.tree.pop()

    def atom(self):
        if self.token[1] not in atoms:
            raise ParseError(self.tokenizer.filename, self.tokenizer.line_number, "Unrecognised symbol @%s" % self.token[1])
        self.tree.append(AtomNode(atoms[self.token[1]]))
        self.consume()
        self.maybe_consume_inline_comment()
        self.tree.pop()

    def expr_start(self):
        self.expr_builder = ExpressionBuilder(self.tokenizer)
        self.expr_builders.append(self.expr_builder)
        self.expr()
        expression = self.expr_builder.finish()
        self.expr_builders.pop()
        self.expr_builder = self.expr_builders[-1] if self.expr_builders else None
        if self.expr_builder:
            self.expr_builder.operands[-1].children[-1].append(expression)
        else:
            self.tree.append(expression)
            self.tree.pop()

    def expr(self):
        self.expr_operand()
        while (self.token[0] == token_types.ident and self.token[1] in binary_operators):
            self.expr_bin_op()
            self.expr_operand()

    def expr_operand(self):
        if self.token == (token_types.paren, "("):
            self.consume()
            self.expr_builder.left_paren()
            self.expr()
            self.expect(token_types.paren, ")")
            self.expr_builder.right_paren()
        elif self.token[0] == token_types.ident and self.token[1] in unary_operators:
            self.expr_unary_op()
            self.expr_operand()
        elif self.token[0] in [token_types.string, token_types.ident]:
            self.expr_value()
        elif self.token[0] == token_types.number:
            self.expr_number()
        else:
            raise ParseError(self.tokenizer.filename, self.tokenizer.line_number, "Unrecognised operand")

    def expr_unary_op(self):
        if self.token[1] in unary_operators:
            self.expr_builder.push_operator(UnaryOperatorNode(self.token[1]))
            self.consume()
        else:
            raise ParseError(self.tokenizer.filename, self.tokenizer.line_number, "Expected unary operator")

    def expr_bin_op(self):
        if self.token[1] in binary_operators:
            self.expr_builder.push_operator(BinaryOperatorNode(self.token[1]))
            self.consume()
        else:
            raise ParseError(self.tokenizer.filename, self.tokenizer.line_number, "Expected binary operator")

    def expr_value(self):
        node_type = {token_types.string: StringNode,
                     token_types.ident: VariableNode}[self.token[0]]
        self.expr_builder.push_operand(node_type(self.token[1]))
        self.consume()
        if self.token == (token_types.paren, "["):
            self.consume()
            self.expr_builder.operands[-1].append(IndexNode())
            self.expr_start()
            self.expect(token_types.paren, "]")

    def expr_number(self):
        self.expr_builder.push_operand(NumberNode(self.token[1]))
        self.consume()

class Treebuilder:
    def __init__(self, root):
        self.root = root
        self.node = root

    def append(self, node):
        assert isinstance(node, Node)
        self.node.append(node)
        self.node = node
        assert self.node is not None
        return node

    def pop(self):
        node = self.node
        self.node = self.node.parent
        assert self.node is not None
        return node

class ExpressionBuilder:
    def __init__(self, tokenizer):
        self.operands = []
        self.operators = [None]
        self.tokenizer = tokenizer

    def finish(self):
        while self.operators[-1] is not None:
            self.pop_operator()
        rv = self.pop_operand()
        assert self.is_empty()
        return rv

    def left_paren(self):
        self.operators.append(None)

    def right_paren(self):
        while self.operators[-1] is not None:
            self.pop_operator()
            if not self.operators:
                raise ParseError(self.tokenizer.filename, self.tokenizer.line,
                                 "Unbalanced parens")

        assert self.operators.pop() is None

    def push_operator(self, operator):
        assert operator is not None
        while self.precedence(self.operators[-1]) > self.precedence(operator):
            self.pop_operator()

        self.operators.append(operator)

    def pop_operator(self):
        operator = self.operators.pop()
        if isinstance(operator, BinaryOperatorNode):
            operand_1 = self.operands.pop()
            operand_0 = self.operands.pop()
            self.operands.append(BinaryExpressionNode(operator, operand_0, operand_1))
        else:
            operand_0 = self.operands.pop()
            self.operands.append(UnaryExpressionNode(operator, operand_0))

    def push_operand(self, node):
        self.operands.append(node)

    def pop_operand(self):
        return self.operands.pop()

    def is_empty(self):
        return len(self.operands) == 0 and all(item is None for item in self.operators)

    def precedence(self, operator):
        if operator is None:
            return 0
        return precedence(operator)

def parse(stream):
    p = Parser()
    return p.parse(stream)


text:
/* eslint-env jasmine, mocha */

var config = require('./feature-detects');

describe('[ModernizrWebpackPlugin] Browser Tests', function () {

  it('should contain an instance of Modernizr', function () {
    expect(window.Modernizr).to.be.an('object');
  });

  it('should have feature-detects specified in bundle options', function () {
    expect(window.Modernizr).to.have.all.keys(config);
  });
});


text:
package com.mopub.common;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.mopub.common.logging.MoPubLog;
import com.mopub.exceptions.IntentNotResolvableException;

import java.util.EnumSet;

import static com.mopub.common.util.Drawables.LEFT_ARROW;
import static com.mopub.common.util.Drawables.RIGHT_ARROW;
import static com.mopub.common.util.Drawables.UNLEFT_ARROW;
import static com.mopub.common.util.Drawables.UNRIGHT_ARROW;

class BrowserWebViewClient extends WebViewClient {

    private static final EnumSet<UrlAction> SUPPORTED_URL_ACTIONS = EnumSet.of(
            UrlAction.HANDLE_PHONE_SCHEME,
            UrlAction.OPEN_APP_MARKET,
            UrlAction.OPEN_IN_APP_BROWSER,
            UrlAction.HANDLE_SHARE_TWEET,
            UrlAction.FOLLOW_DEEP_LINK_WITH_FALLBACK,
            UrlAction.FOLLOW_DEEP_LINK
    );

    @NonNull
    private MoPubBrowser mMoPubBrowser;

    public BrowserWebViewClient(@NonNull final MoPubBrowser moPubBrowser) {
        mMoPubBrowser = moPubBrowser;
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description,
            String failingUrl) {
        MoPubLog.d("MoPubBrowser error: " + description);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }

        try {
            new UrlHandler.Builder()
                    .withSupportedUrlActions(SUPPORTED_URL_ACTIONS)
                    .withoutMoPubBrowser()
                    .withResultActions(new UrlHandler.ResultActions() {
                        @Override
                        public void urlHandlingSucceeded(@NonNull String url,
                                @NonNull UrlAction urlAction) {
                            if (urlAction.equals(UrlAction.OPEN_IN_APP_BROWSER)) {
                                mMoPubBrowser.getWebView().loadUrl(url);
                            } else {
                                // UrlAction opened in external app, so close MoPubBrowser
                                mMoPubBrowser.finish();
                            }
                        }

                        @Override
                        public void urlHandlingFailed(@NonNull String url,
                                @NonNull UrlAction lastFailedUrlAction) { }
                    })
                    .build().handleUrl(mMoPubBrowser.getApplicationContext(), url,
                            true, // = fromUserInteraction
                            true // = throwExceptionOnFailure
                        );
            return true;
        } catch (IntentNotResolvableException e) {
            return false;
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        mMoPubBrowser.getForwardButton()
                .setImageDrawable(UNRIGHT_ARROW.createDrawable(mMoPubBrowser));
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        Drawable backImageDrawable = view.canGoBack()
                ? LEFT_ARROW.createDrawable(mMoPubBrowser)
                : UNLEFT_ARROW.createDrawable(mMoPubBrowser);
        mMoPubBrowser.getBackButton().setImageDrawable(backImageDrawable);

        Drawable forwardImageDrawable = view.canGoForward()
                ? RIGHT_ARROW.createDrawable(mMoPubBrowser)
                : UNRIGHT_ARROW.createDrawable(mMoPubBrowser);
        mMoPubBrowser.getForwardButton().setImageDrawable(forwardImageDrawable);
    }
}


text:
'use strict';

const gulp = require('gulp');
const sass = require('gulp-sass');
const prefix = require('gulp-autoprefixer');
const plumber = require('gulp-plumber');
const browserSync = require('browser-sync').create();

gulp.task('sass', () =>{
    gulp.src('./sass/**/*.scss')
    .pipe(plumber())
    .pipe(sass())
    .pipe(prefix("last 2 version"))
    .pipe(gulp.dest('./css'))
    .pipe(browserSync.stream());
});

gulp.task('watch', () => {
  //watch sass files
  gulp.watch('sass/**/*.scss', ['sass']);
  gulp.watch("./*.html").on('change', browserSync.reload);
});
gulp.task('browser-sync', () =>{
  browserSync.init({
        server: "./"
    });
});

gulp.task('dev', ['browser-sync','watch']);


text:
'use strict';

var _ = require('lodash'),
    ComponentDefinition = require('./componentDefinition');

/**
 * Creates a new instance of a ComponentDefinitionBuilder which
 * provides a chainable fluent-api to create ComponentDefinition definitions
 *
 * @param name  the name of the ComponentDefinition
 *
 * @constructor
 */
function ComponentDefinitionBuilder(name) {
  _.extend(this, {
    name: name,
    options: {}
  });
}

_.extend(ComponentDefinitionBuilder.prototype, {

  /**
   * Allows you to specify the component's scope
   *
   * @param scope {String} a string that represents the scope of this component
   *
   * @returns {ComponentDefinitionBuilder} current instance of ComponentDefinitionBuilder
   */
  scopedAs: function (scope) {
    this.options.scope = scope;
    return this;
  },

  /**
   * Allows you to specify the component's initializer.
   *
   *
If initializer is specified as a string, it must be a function
   * on the component that is created.

   *
   *
Initializers are always invoked in the context of the component.

   *
   *
The return value of an initializer function is what will be used to inject into dependent components.

   *
   * @param initializer {Function|String} the initializer function to be used to initialize the component
   *
   * @returns {ComponentDefinitionBuilder} current instance of ComponentDefinitionBuilder.
   */
  initializeWith: function (initializer) {
    this.options.initializer = initializer;
    return this;
  },

  /**
   * Allows you to specify the component's dependencies.
   *
   * @param dependencies {*} names of one or more dependencies. Can be specified as an array, list of
   *                         strings or as a comma separated string
   *
   * @returns {ComponentDefinitionBuilder} current instance of ComponentDefinitionBuilder.
   */
  dependsOn: function (dependencies) {
    var a = arguments;

    if (!a.length) return this;

    if (a.length === 1 && _.isArray(dependencies)) {
      this.options.dependencies = dependencies;
      return this;
    }

    if (a.length === 1 && _.isString(dependencies)) {
      var lst = _.chain(dependencies.split(',')).reduce(function (r, i) {
        r.push(i.trim());
        return r;
      }, []).value();

      return this.dependsOn(lst);
    }

    return this.dependsOn(_.toArray(a));
  },

  /**
   * Returns a new instance of ComponentDefinition with the specified
   * name, scope, initializer and dependencies
   *
   * @returns {ComponentDefinition} a new instance of ComponentDefinition
   */
  build: function () {
    return new ComponentDefinition(this.name, this.options);
  }

});

module.exports = ComponentDefinitionBuilder;


text:
<?php

	$about = array(
		'name' => 'Română',
		'author' => array(
			'name' => 'Vlad Ghita',
			'email' => 'vlad.ghita@xandergroup.ro',
			'website' => ''
		),
		'release-date' => '2011-04-01'
	);

	/**
	 * Debug DevKit
	 */
	$dictionary = array(

		'Debug' =>
		'Depanare',

		'Failed to create cache folder. Please check "%s" is writable.' =>
		'Crearea directorului de cache a eşuat. Verificaţi permisiunea de scriere a "%s".',

		'Cache folder is not writable. Please check permissions on "%s".' =>
		'Directorul de cache nu poate fi scris. Verificaţi permisiunile pentru "%s".',

		'Params' =>
		'Parametri',

		'Result' =>
		'Rezultat',

	);


text:
'use strict';

const Helpers = require('../../helpers');

module.exports = Helpers.createRoute('one/a/item-two');


text:
/**
 * ExCella TransのSheet->Sqlモデルクラス群
 */
package org.bbreak.excella.trans.tag.sheet2sql.model;


text:
<ion-header>

  <ion-navbar>
    <ion-title>{{ 'SEARCH_TITLE' | translate }}</ion-title>
  </ion-navbar>

</ion-header>

<ion-content>
  <ion-searchbar (ionInput)="getItems($event)" placeholder="{{ 'SEARCH_PLACEHOLDER' | translate }}"></ion-searchbar>
  <ion-list>
    <button ion-item (click)="openItem(item)" *ngFor="let item of currentItems">
      <ion-avatar item-start>

      </ion-avatar>

{{item.name}}

{{item.about}}

      <ion-note item-end *ngIf="item.note">{{item.note}}</ion-note>
    </button>
  </ion-list>
</ion-content>


text:
import React from "react";
import { Link } from "react-router";
import { Line } from 'react-chartjs-2';

export default class Overview extends React.Component {

  componentWillMount() {
    this.props.fetchStacks()
    this.props.fetchContainers()
    this.props.fetchServices()
  }

	render() {

		const { containers, stacks, services, data } = this.props;

		return (

          <Link to="/stacks">

                  {stacks ? stacks.length : '0'} Projects Running

          </Link>

          <Link to="/services">

                  {services ? services.length : '0'} Services Running

          </Link>

          <Link to="/containers">

                  {containers ? containers.length : '0'} Containers Running

          </Link>

                 Network Usage

                	<Line height={60} data={data} />

                 CPU Usage

                  <Line height={60} data={data} />

                 Memory Usage

                  <Line height={60} data={data} />

		)
	}
}


text:
namespace ProjetFinalEval
{
    using System;
    using System.Collections.Generic;

    public partial class critere
    {
        public critere()
        {
            this.evaluation = new HashSet<evaluation>();
        }

        public int IDCRITERE { get; set; }
        public int IDFAMILLECRITERE { get; set; }
        public string NOMCRITERE { get; set; }

        public virtual famillecritere famillecritere { get; set; }
        public virtual ICollection<evaluation> evaluation { get; set; }
    }
}


text:
sap.ui.define([
	"sap/ui/test/Opa5",
	"./arrangements/Startup",
	"./NavigationJourneyPhone",
	"./NotFoundJourneyPhone",
	"./BusyJourneyPhone"
], function (Opa5, Startup) {
	"use strict";

	Opa5.extendConfig({
		arrangements: new Startup(),
		viewNamespace: "opensap.orders.view.",
		autoWait: true
	});
});


text:
cask "virtualbox-extension-pack" do
  version "7.0.4"
  sha256 "bf22f698075685e1d71845d76c3b393b45d72e4b0206d7d434338a99d610e14c"

  url "https://download.virtualbox.org/virtualbox/#{version}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack"
  name "Oracle VirtualBox Extension Pack"
  desc "Extend the functionality of VirtualBox"
  homepage "https://www.virtualbox.org/"

  livecheck do
    url "https://download.virtualbox.org/virtualbox/LATEST.TXT"
    regex(/(\d+(?:\.\d+)+)/i)
  end

  conflicts_with cask: "virtualbox-extension-pack-beta"
  depends_on cask: "virtualbox"
  container type: :naked

  stage_only true

  postflight do
    system_command "/usr/local/bin/VBoxManage",
                   args:  [
                     "extpack", "install",
                     "--replace", "#{staged_path}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack"
                   ],
                   input: "y",
                   sudo:  true
  end

  uninstall_postflight do
    next unless File.exist?("/usr/local/bin/VBoxManage")

    system_command "/usr/local/bin/VBoxManage",
                   args: [
                     "extpack", "uninstall",
                     "Oracle VM VirtualBox Extension Pack"
                   ],
                   sudo: true
  end

  caveats do
    license "https://www.virtualbox.org/wiki/VirtualBox_PUEL"
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace q44
{

    class Person
    {
        //フィールド
        public string lastName; //姓
        public string firstName; //名
        public string furiganaLastName; //姓ふりがな
        public string furiganaFirstName; //名ふりがな
        public DateTime birthday; //誕生日

        //メソッド
        public int getAge()
        {
            int age = 0;
            DateTime now = DateTime.Now;//現在
            //参考:http://dobon.net/vb/dotnet/system/getage.html
            age = now.Year - birthday.Year;
            //誕生日前だったら
            if (now.Month < birthday.Month ||
                (now.Month == birthday.Month && now.Day < birthday.Day))
            {
                age--;
            }
            return age;
        }
    }
}


text:
layout: post
title: "C# MD5 yöntemi ile metin şifreleme"
date: 2011-08-14 14:32
author: engin.polat
comments: true
category: [C#]
tags: [ComputeHash, crypto, csharp, encoding, foreach, getbytes, instance, md5, MD5CryptoServiceProvider, namespace, return, string, stringbuilder, System.Secuity.Cryptography, tostring, using]
---
Aşağıdaki küçük fonksiyon yardımıyla **string** tipindeki değişkenlerin içeriğini MD5 yöntemi ile şifreleyebiliriz.

Öncelikle kodumuzun **using** kısmına System.Security.Cryptography **namespace**'ini eklememiz lazım.

Böylece MD5CryptoServiceProvider sınıfından yeni bir *örnek* (**instance**) oluşturabilir, ve *şifreleme sağlayıcısı* (**crypto service provider**) olarak kullanabiliriz.

using System.Text;
using System.Security.Cryptography;

public static string Sifrele(string Metin)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

    byte[] ba = Encoding.UTF8.GetBytes(Metin);
    ba = md5.ComputeHash(ba);

    StringBuilder sb = new StringBuilder();
    foreach (byte b in ba)
    {
        sb.Append(b.ToString("x2").ToLower());
    }

    return sb.ToString();
}


text:
package org.insysu.groceryproject.persistence.dao;

import org.insysu.groceryproject.persistence.entity.Cuisine;

import java.util.List;

/**
 * Created by Souler on 2016/11/30.
 */
public interface CuisineDao {
    Cuisine findOne(long id);
    List<Cuisine> findAll();
    void create(Cuisine entity);
    Cuisine update(Cuisine entity);
    void delete(Cuisine entity);
    void deleteById(long entityId);
}


text:
import { createStore, compose } from 'redux';
import eventReducer from '../reducers/events';

const configureStore = initialState => {
  // take the order items off of the order so we can separate out the reducers
  return createStore(eventReducer, {
    ...initialState,
  }, compose(
    // enable dev tools
    window.devToolsExtension ? window.devToolsExtension() : f => f
  ));
};

export default configureStore;


text:
network interface satitstics

## Installation
* Install from source (after cloning):
```bash
sudo python setup.py
```

* Install latest version from github:
```bash
pip install git+ssh://git@github.com:aviramc/ifstat.git
```

## Usage
After installation, the ifstat tool is available in the PATH. Run ifstat for help


text:
package org.piccolo2d.examples;

import java.awt.Color;

import org.piccolo2d.PCanvas;
import org.piccolo2d.PNode;
import org.piccolo2d.event.PDragEventHandler;
import org.piccolo2d.extras.PFrame;
import org.piccolo2d.extras.nodes.PComposite;
import org.piccolo2d.nodes.PPath;
import org.piccolo2d.nodes.PText;

/**
 * This example shows how to create a composite node. A composite node is a
 * group of nodes that behave as a single node when interacted with.
 */
public class CompositeExample extends PFrame {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public CompositeExample() {
        this(null);
    }

    public CompositeExample(final PCanvas aCanvas) {
        super("CompositeExample", false, aCanvas);
    }

    public void initialize() {
        final PComposite composite = new PComposite();

        final PNode circle = PPath.createEllipse(0, 0, 100, 100);
        final PNode rectangle = PPath.createRectangle(50, 50, 100, 100);
        final PNode text = new PText("Hello world!");

        composite.addChild(circle);
        composite.addChild(rectangle);
        composite.addChild(text);

        rectangle.rotate(Math.toRadians(45));
        rectangle.setPaint(Color.RED);

        text.scale(2.0);
        text.setPaint(Color.GREEN);

        getCanvas().getLayer().addChild(composite);
        getCanvas().removeInputEventListener(getCanvas().getPanEventHandler());
        getCanvas().addInputEventListener(new PDragEventHandler());
    }

    public static void main(final String[] args) {
        new CompositeExample();
    }

}