text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data class="ActivityAmendPhoneBinding">

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/f2f2f2">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/white"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:theme="@style/ThemeOverlay.AppCompat.ActionBar"
                app:title=" ">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:layout_gravity="center"
                    android:text="修改手机号"
                    android:textColor="@color/color_333"
                    android:textSize="@dimen/page_18" />
            </android.support.v7.widget.Toolbar>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_below="@id/toolbar"
                android:background="@color/f2f2f2">

                <EditText
                    android:id="@+id/user_password"
                    style="@style/CircularEditStyle"
                    android:layout_height="50dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="70dp"
                    android:drawableLeft="@mipmap/phone"
                    android:drawablePadding="20dp"
                    android:hint="请输入新手机号码"
                    android:inputType="number"
                    android:paddingLeft="20dp"

                    android:textColor="@color/contents_text"
                    android:textColorHint="@color/color_999"
                    android:textSize="@dimen/page_18" />

                <RelativeLayout
                    android:id="@+id/rl_valinumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/user_password"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="20dp">

                    <EditText
                        android:id="@+id/user_valinumber"
                        style="@style/CircularEditStyle"
                        android:layout_height="50dp"
                        android:drawableLeft="@mipmap/cerification_img"
                        android:drawablePadding="20dp"
                        android:hint="验证码"
                        android:inputType="number"
                        android:paddingLeft="20dp"
                        android:textColor="@color/contents_text"
                        android:textColorHint="@color/color_999"
                        android:textSize="@dimen/page_18" />

                    <Button
                        android:layout_width="150dp"
                        android:layout_height="50dp"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:background="@null"
                        android:onClick="getCode"
                        android:text="获取验证码"
                        android:textColor="@color/color_999"
                        android:textSize="@dimen/page_18" />

                </RelativeLayout>

                <EditText
                    android:visibility="gone"
                    android:id="@+id/confirm_password"
                    style="@style/CircularEditStyle"
                    android:layout_height="50dp"
                    android:layout_below="@id/rl_valinumber"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="20dp"
                    android:drawableLeft="@mipmap/password"
                    android:drawablePadding="20dp"
                    android:hint="请输入新密码"
                    android:inputType="textPassword"
                    android:paddingLeft="20dp"
                    android:textColor="@color/contents_text"
                    android:textColorHint="@color/color_999"
                    android:textSize="@dimen/page_18" />

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    android:layout_alignParentBottom="true"
                    android:background="@drawable/btn_rectangle_background"
                    android:onClick="confrim"
                    android:text="确  认"
                    android:textColor="@color/white" />
            </RelativeLayout>
        </RelativeLayout>
    </LinearLayout>
</layout>


text:
#define VERSION "3.573c"

/* machine-specific stuff:
   based on a number of factors in the library stdlib.h, we will try
   to determine what kind of machine/compiler this program is being
   built on.  However, it doesn't always succeed.  However, if you have
   ANSI conforming C, it will probably work.

 we will try to figure out machine type
 based on defines in stdio, and compiler-defined things as well.: */

#ifdef  GNUDOS
#define DJGPP
#define DOS
#endif

#ifdef THINK_C
#define MAC
#else
#ifdef GENERATINGPOWERPC
#undef METRO
#undef MAC
#define METRO
#define MAC
#else
#ifdef GENERATING68K
#undef METRO
#undef MAC
#define METRO
#define MAC
#endif
#endif
#endif

#include <stdio.h>
#include <stdlib.h>

#ifdef __CMS_OPEN
#define CMS
#define EBCDIC true
#define INFILE "infile data"
#define OUTFILE "outfile data"
#define TREEFILE "treefile data"
#define FONTFILE "fontfile data"
#define PLOTFILE "plotfile data"
#define INTREE "intree data"
#define OUTTREE "outtree data"
#else
#define EBCDIC false
#define INFILE "infile"
#define OUTFILE "outfile"
#define TREEFILE "treefile"
#define FONTFILE "fontfile" /* on unix this might be /usr/local/lib/fontfile */
#define PLOTFILE "plotfile"
#define INTREE "intree"
#define OUTTREE "outtree"
#endif

#ifdef L_ctermid            /* try and detect for sysV or V7. */
#define SYSTEM_FIVE
#endif

#ifdef sequent
#define SYSTEM_FIVE
#endif

#ifndef SYSTEM_FIVE
#include <stdlib.h>
#if defined(_STDLIB_H_) || defined(_H_STDLIB) || defined(H_SCCSID) || defined(unix)
#define UNIX
#define MACHINE_TYPE "BSD Unix C"
#endif
#endif

#ifdef __STDIO_LOADED
#define VMS
#define MACHINE_TYPE "VAX/VMS C"
#define printf vax_printf_is_broken
#define fprintf vax_fprintf_is_broken
void vax_printf_is_broken(const char *fmt,...);
void vax_fprintf_is_broken(FILE *fp,const char *fmt,...);
void vax_tweak_fmt(char *);
#endif

#ifdef __WATCOMC__
#define QUICKC
#define WATCOM
#define DOS
#include "graph.h"
#endif
/* watcom-c has graphics library calls that are almost identical to    *
 * quick-c, so the "QUICKC" symbol name stays.                         */

#ifdef _QC
#define MACHINE_TYPE "MS-DOS / Quick C"
#define QUICKC
#include "graph.h"
#define DOS
#endif

#ifdef _DOS_MODE
#define MACHINE_TYPE "MS-DOS /Microsoft C "
#define DOS           /* DOS is  always defined if  on a dos machine */
#define MSC           /* MSC is defined for microsoft C              */
#endif

#ifdef __MSDOS__      /* TURBO c compiler, ONLY (no other DOS C compilers) */
#define DOS
#define TURBOC
#include<stdlib.h>
#include<graphics.h>
#endif

#ifdef DJGPP          /* DJ's gnu  C/C++ port */
#include<graphics.h>
#endif

#ifndef MACHINE_TYPE
#define MACHINE_TYPE "ANSI C"
#endif

#ifdef DOS
#define MALLOCRETURN void
#else
#define MALLOCRETURN void
#endif

#ifdef VMS
#define signed /* signed doesn't exist in VMS */
#endif

#ifdef DJGPP
#undef MALLOCRETURN
#define MALLOCRETURN void
#endif

/* includes: */
#ifdef UNIX
#include<strings.h>
#else
#include<string.h>
#endif

#include <math.h>
#include <ctype.h>

#ifdef MAC
#include "interface.h"
#endif

#define FClose(file) if (file) fclose(file) ; file=NULL
#define Malloc(x) mymalloc((long)x)

typedef void *Anyptr;
#define Signed     signed
#define Void       void      /* Void f() = procedure */
#define Const     const
#define Volatile  volatile
#define Char        char      /* Characters (not bytes) */
#define Static     static     /* Private global funcs and vars */
#define Local      static     /* Nested functions */

typedef unsigned char boolean;

#define true    1
#define false   0
#define SETBITS 32

#ifdef MAC
MALLOCRETURN    *mymalloc(long);
#else
MALLOCRETURN    *mymalloc();
#endif
int      eof();
int      eoln();
void     memerror();

redpajama_set_name: RedPajamaGithub


text:
using System.Data.Entity;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using TM.Data.Update;
using TM.Shared;
using TM.UI.MVC.Infrastructure;

namespace TM.UI.MVC.Models
{
   [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
   public class HomeViewModels
   {
      public class CatalogStatistic
      {
         public int TrainingProviderCount { get; set; }
         public int CategoryCount { get; set; }
         public int CourseCount { get; set; }
         public int AuthorCount { get; set; }
      }

      public class StatisticViewModel
      {
         public string Title { get; set; }
         public int Count { get; set; }
         public string Url { get; set; }
      }

      public class HomeViewModel
      {
         public HomeViewModel(UrlHelper urlHelper,CatalogStatistic catalogStatistic )
         {
            TrainingProvidersStatistic = new StatisticViewModel
            {
               Title = "Providers",
               Count = catalogStatistic.TrainingProviderCount,
               Url = urlHelper.RouteUrl(AppConstants.RouteNames.AllTrainingProviders)
            };

            CategoriesStatistic = new StatisticViewModel
            {
               Title = "Categories",
               Count = catalogStatistic.CategoryCount,
               Url = urlHelper.RouteUrl(AppConstants.RouteNames.AllCategories)
            };

            CoursesStatistic = new StatisticViewModel
            {
               Title = "Courses",
               Count = catalogStatistic.CourseCount,
               Url = urlHelper.RouteUrl(AppConstants.RouteNames.AllCourses)
            };

            AuthorsStatistic = new StatisticViewModel
            {
               Title = "Authors",
               Count = catalogStatistic.AuthorCount,
               Url = urlHelper.RouteUrl(AppConstants.RouteNames.AllAuthors)
            };
         }
         public StatisticViewModel TrainingProvidersStatistic { get; set; }
         public StatisticViewModel CategoriesStatistic { get; set; }
         public StatisticViewModel CoursesStatistic { get; set; }
         public StatisticViewModel AuthorsStatistic { get; set; }
      }

      public class HomeManager : CatalogManagerBase
      {
         public HomeManager()
         {
         }

         public HomeManager(UpdateDbContext context) : base(context)
         {
         }

         [SuppressMessage("ReSharper", "ExceptionNotDocumented")]
         public async Task<CatalogStatistic> GetCatalogStatisticAsync(Specializations? specializations)
         {
            var coursesQuery = GetCoursesQueryForSpecializations(specializations);

            var statistic = await (from needForBatch in coursesQuery
               select new CatalogStatistic
               {
                  TrainingProviderCount =
                     CatalogContext.TrainingProviders.Count(
                        tp => coursesQuery.Any(q => q.TrainingProviderId == tp.Id) && !tp.IsDeleted),
                  CategoryCount =
                     CatalogContext.Categories.Count(cat => coursesQuery.Any(q => q.CategoryId == cat.Id) && !cat.IsDeleted),
                  CourseCount = coursesQuery.Count(),
                  AuthorCount = CatalogContext.CourseAuthors
                     .Where(ca => coursesQuery.Any(q => q.Id == ca.CourseId) && !ca.IsDeleted)
                     .GroupBy(ca => ca.AuthorId).Count()
               }).FirstAsync();

            return statistic;
         }
      }
   }
}


text:
// Time:  O(1), per operation.
// Space: O(k), k is the capacity of cache.

#include <list>

class LFUCache{
public:
    // @param capacity, an integer
    LFUCache(int capacity) : capa_(capacity) {
    }

    int get(int key) {
        if (map_.find(key) != map_.end() && capa_) {
            // It key exists, update it.
            const auto value = map_[key]->value;
            update(key, value);
            return value;
        } else {
            return -1;
        }
    }

    void set(int key, int value)
        if (!capa_) {
            return;
        }
        // If cache is full while inserting, remove the last one.
        if (map_.find(key) == map_.end() && list_.size() == capa_) {
            auto del = list_.front(); list_.pop_front();
            map_.erase(del.key);
        }
        update(key, value);
    }

private:
    struct node {
        node(int k, int v, int f) : key(k), value(v), freq(f) {}
        int key;
        int value;
        int freq;
    };
    using List = list<node>;
    List list_; // key, value
    unordered_map<int, List::iterator> map_; // key, list iterator
    int capa_;

    // Update (key, iterator of (key, value)) pair
    void update(int key, int value) {
        int freq = 0;
        auto l_it = list_.begin();
        auto it = map_.find(key);
        if (it != map_.end()) {
            freq = it->second->freq;
            l_it = next(it->second);
            list_.erase(it->second);
        }
        ++freq;
        while (l_it != list_.end() && freq >= l_it->freq) {
            ++l_it;
        }
        map_[key] = list_.emplace(l_it, node(key, value, freq));
    }
};

/**
 * Your LFUCache object will be instantiated and called as such:
 * LFUCache obj = new LFUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.set(key,value);
 */


text:
title: "Green strikes the glasses"
excerpt: "PaperFaces portrait of @bretto drawn with Paper by 53 on an iPad."
image:
  path: &image /assets/images/paperfaces-bretto-twitter-lg.jpg
  feature: *image
  teaser: /assets/images/paperfaces-bretto-twitter-teaser.jpg
  thumb: /assets/images/paperfaces-bretto-twitter-150.jpg
tags: [portrait, illustration, Paper by 53]
last_modified_at: 2017-01-17T14:45:13-05:00
---

PaperFaces portrait of [@bretto](http://twitter.com/bretto).

{% include boilerplate/paperfaces-2.md %}

Work in progress screen captures Made with Paper.


text:
layout: post
title: Video - Bitcoin Q and A Will Compliance With Regulation Benefit Bitcoin
description: Video - Bitcoin Q and A Will Compliance With Regulation Benefit Bitcoin
author: Andreas M. Antonopoulos
authorurl: /andreas-antonopoulos-bitcoin-expert/
published: true
---

The role of regulators and compliance; how could it benefit Bitcoin? Regulators have failed to protect consumers. Bitcoin protects consumers by giving them control. Privacy and user control is consumer protection. Regulators just help banks avoid competition.

TRANSCRIPT


text:
package opsworks

import (
	"github.com/gunosy/aws-sdk-go/aws"
	"github.com/gunosy/aws-sdk-go/internal/protocol/jsonrpc"
	"github.com/gunosy/aws-sdk-go/internal/signer/v4"
)

// Welcome to the AWS OpsWorks API Reference. This guide provides descriptions,
// syntax, and usage examples about AWS OpsWorks actions and data types, including
// common parameters and error codes.
//
// AWS OpsWorks is an application management service that provides an integrated
// experience for overseeing the complete application lifecycle. For information
// about this product, go to the AWS OpsWorks (http://aws.amazon.com/opsworks/)
// details page.
//
//  SDKs and CLI
//
// The most common way to use the AWS OpsWorks API is by using the AWS Command
// Line Interface (CLI) or by using one of the AWS SDKs to implement applications
// in your preferred language. For more information, see:
//
//   AWS CLI (http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)
//   AWS SDK for Java (http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/opsworks/AWSOpsWorksClient.html)
//   AWS SDK for .NET (http://docs.aws.amazon.com/sdkfornet/latest/apidocs/html/N_Amazon_OpsWorks.htm)
//   AWS SDK for PHP 2 (http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.OpsWorks.OpsWorksClient.html)
//   AWS SDK for Ruby (http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/OpsWorks/Client.html)
//   AWS SDK for Node.js (http://aws.amazon.com/documentation/sdkforjavascript/)
//   AWS SDK for Python(Boto) (http://docs.pythonboto.org/en/latest/ref/opsworks.html)
//    Endpoints
//
// AWS OpsWorks supports only one endpoint, opsworks.us-east-1.amazonaws.com
// (HTTPS), so you must connect to that endpoint. You can then use the API to
// direct AWS OpsWorks to create stacks in any AWS Region.
//
//  Chef Versions
//
// When you call CreateStack, CloneStack, or UpdateStack we recommend you use
// the ConfigurationManager parameter to specify the Chef version. The recommended
// value for Linux stacks, which is also the default value, is currently 11.10.
// Windows stacks use Chef 12.2. For more information, see Chef Versions (http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-chef11.html).
//
// You can also specify Chef 11.4 or Chef 0.9 for your Linux stack. However,
// Chef 0.9 has been deprecated. We do not recommend using Chef 0.9 for new
// stacks, and we recommend migrating your existing Chef 0.9 stacks to Chef
// 11.10 as soon as possible.
type OpsWorks struct {
	*aws.Service
}

// Used for custom service initialization logic
var initService func(*aws.Service)

// Used for custom request initialization logic
var initRequest func(*aws.Request)

// New returns a new OpsWorks client.
func New(config *aws.Config) *OpsWorks {
	service := &aws.Service{
		Config:       aws.DefaultConfig.Merge(config),
		ServiceName:  "opsworks",
		APIVersion:   "2013-02-18",
		JSONVersion:  "1.1",
		TargetPrefix: "OpsWorks_20130218",
	}
	service.Initialize()

	// Handlers
	service.Handlers.Sign.PushBack(v4.Sign)
	service.Handlers.Build.PushBack(jsonrpc.Build)
	service.Handlers.Unmarshal.PushBack(jsonrpc.Unmarshal)
	service.Handlers.UnmarshalMeta.PushBack(jsonrpc.UnmarshalMeta)
	service.Handlers.UnmarshalError.PushBack(jsonrpc.UnmarshalError)

	// Run custom service initialization if present
	if initService != nil {
		initService(service)
	}

	return &OpsWorks{service}
}

// newRequest creates a new request for a OpsWorks operation and runs any
// custom request initialization.
func (c *OpsWorks) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {
	req := aws.NewRequest(c.Service, op, params, data)

	// Run custom request initialization if present
	if initRequest != nil {
		initRequest(req)
	}

	return req
}


text:
<bill session="110" type="s" number="3512" updated="2009-01-09T19:12:48-05:00">
	<status><introduced date="1221624000" datetime="2008-09-17"/></status>

	<introduced date="1221624000" datetime="2008-09-17"/>
	<titles>
		<title type="short" as="introduced">Social Security Number Protection Act of 2008</title>
		<title type="official" as="introduced">A bill to require the Secretary of Health and Human Services to remove social security account numbers from Medicare identification cards and communications provided to Medicare beneficiaries in order to protect Medicare beneficiaries from identity theft.</title>
	</titles>
	<sponsor id="300038"/>
	<cosponsors>
		<cosponsor id="300009" joined="2008-09-17"/>
		<cosponsor id="300061" joined="2008-09-17"/>
		<cosponsor id="300037" joined="2008-10-01"/>
	</cosponsors>
	<actions>
		<action date="1221624000" datetime="2008-09-17"><text>Sponsor introductory remarks on measure. (CR S8954)</text></action>
		<action date="1221624000" datetime="2008-09-17"><text>Read twice and referred to the Committee on Finance.</text><reference label="text of measure as introduced" ref="CR S8955"/></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	9/17/2008--Introduced.
Social Security Number Protection Act of 2008 - Requires the Secretary of Health and Human Services to establish and begin to implement procedures to eliminate the unnecessary collection, use, and display of Social Security account numbers of Medicare beneficiaries on Medicare identification cards and communications. Prohibits a Social Security card also from storing a Social Security account number electronically. Allows the display of a Social Security number on written or electronic communications only if the Secretary determines that its inclusion on such communications is essential for the operation of the Medicare program.

</bill>


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

<title>org.apache.cassandra.utils.vint Class Hierarchy (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.cassandra.utils.vint

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.io.InputStream (implements java.io.Closeable)

org.apache.cassandra.io.util.AbstractDataInput (implements java.io.DataInput)

org.apache.cassandra.utils.vint.EncodedDataInputStream (implements java.io.DataInput)

java.io.OutputStream (implements java.io.Closeable, java.io.Flushable)

org.apache.cassandra.io.util.DataOutputStreamPlus (implements org.apache.cassandra.io.util.DataOutputPlus)

org.apache.cassandra.io.util.UnbufferedDataOutputStreamPlus

org.apache.cassandra.utils.vint.EncodedDataOutputStream

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
import re
import json

from django import forms

from starthinker.util.recipe import json_get_fields
from starthinker_ui.recipe.forms_fields import CommaSeparatedCharField, CommaSeparatedIntegerField, JsonField, TimezoneField, SwitchField

def load_config_data(config, path, default):
  current = config
  if isinstance(path, str):
    path = path.split('.')  # accept string or list as path
  for key in path:
    if not isinstance(key, int) and key.isdigit():
      key = int(key)  # cast string indexes to int
    try:
      current = current[key]
    except:
      return default
  return current

def get_field_kind(field):
  if field['kind'] == 'string':
    return forms.CharField(max_length=255, required=False)
  elif field['kind'] == 'email':
    return forms.EmailField(max_length=255, required=False)
  elif field['kind'] == 'integer':
    return forms.IntegerField(required=False)
  elif field['kind'] == 'boolean':
    return forms.BooleanField(required=False)
  elif field['kind'] == 'text':
    return forms.CharField(widget=forms.Textarea(), required=False)
  elif field['kind'] == 'choice':
    return forms.ChoiceField(choices=map(lambda c: (c, c), field['choices']))
  elif field['kind'] == 'timezones':
    return TimezoneField()
  elif field['kind'] == 'authentication':
    return SwitchField('user', 'service', required=True)
  elif field['kind'] == 'json':
    return JsonField(required=False)
  elif field['kind'] == 'integer_list':
    return CommaSeparatedIntegerField(required=False)
  elif field['kind'] == 'string_list':
    return CommaSeparatedCharField(required=False)
  else:
    return forms.CharField(max_length=255, required=False)

class ScriptJsonForm(forms.Form):
  script_sequence = forms.IntegerField(
      widget=forms.HiddenInput(attrs={'class': 'form_sequence'}))
  script_delete = forms.IntegerField(
      widget=forms.HiddenInput(attrs={'class': 'form_delete'}), initial=0)

  def __init__(self, sequence, script, values, *args, **kwargs):
    self.script = script
    self.values = values
    super(ScriptJsonForm, self).__init__(*args, **kwargs)
    self.fields['script_sequence'].initial = sequence
    x = script.get_tag()
    self.variables = json_get_fields(script.get_tasks())
    for variable in self.variables:
      if variable['name'].startswith('recipe_'):
        continue  # skip inputs that come from recipe constants
      self.fields[variable['name']] = get_field_kind(variable)
      self.fields[variable['name']].initial = values.get(
          variable['name'], variable.get('value', variable.get('default', '')))
      self.fields[variable['name']].required = variable.get('required', False)
      self.fields[variable['name']].help_text = variable.get('description', '')

  def get_description(self):
    return self.script.get_description(self.values)

  def get_instructions(self):
    return self.script.get_instructions(self.values)

  def get_script(self):
    # if marked for delete return nothing, will be filtered up stream
    if self.cleaned_data.get('script_delete', 0) == 1:
      return None
    # if saving, return values ( constants are not stored as they come from the recipe )
    else:
      values = {}
      for variable in self.variables:
        if variable['name'].startswith('recipe_'):
          continue  # skip inputs that come from recipe constants
        values[variable['name']] = self.cleaned_data[variable['name']]
      return {
          'tag': self.script.get_tag(),
          'values': values,
          'sequence': self.cleaned_data['script_sequence']
      }


text:
#include "application_manager/commands/mobile/on_button_event_notification.h"

#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"

namespace application_manager {

namespace commands {

namespace mobile {

OnButtonEventNotification::OnButtonEventNotification(
    const MessageSharedPtr& message, ApplicationManager& application_manager)
    : CommandNotificationImpl(message, application_manager) {}

OnButtonEventNotification::~OnButtonEventNotification() {}

void OnButtonEventNotification::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  const uint32_t btn_id = static_cast<uint32_t>(
      (*message_)[strings::msg_params][hmi_response::button_name].asInt());

  const bool is_app_id_exists =
      (*message_)[strings::msg_params].keyExists(strings::app_id);
  const ApplicationSharedPtr app = application_manager_.application(
      (*message_)[strings::msg_params][strings::app_id].asUInt());

  // CUSTOM_BUTTON notification
  if (static_cast<uint32_t>(mobile_apis::ButtonName::CUSTOM_BUTTON) == btn_id) {
    // app_id is mandatory for CUSTOM_BUTTON notification
    if (!is_app_id_exists) {
      LOG4CXX_ERROR(logger_, "CUSTOM_BUTTON OnButtonEvent without app_id.");
      return;
    }

    // custom_button_id is mandatory for CUSTOM_BUTTON notification
    if (false ==
        (*message_)[strings::msg_params].keyExists(
            hmi_response::custom_button_id)) {
      LOG4CXX_ERROR(logger_,
                    "CUSTOM_BUTTON OnButtonEvent without custom_button_id.");
      return;
    }

    if (!app) {
      LOG4CXX_ERROR(logger_, "Application doesn't exist.");
      return;
    }

    uint32_t custom_btn_id = 0;
    custom_btn_id =
        (*message_)[strings::msg_params][hmi_response::custom_button_id]
            .asUInt();

    if (false == app->IsSubscribedToSoftButton(custom_btn_id)) {
      LOG4CXX_ERROR(logger_,
                    "Application doesn't subscribed to this custom_button_id.");
      return;
    }

    SendButtonEvent(app);
    return;
  }

  const std::vector<ApplicationSharedPtr>& subscribed_apps =
      application_manager_.applications_by_button(btn_id);

  std::vector<ApplicationSharedPtr>::const_iterator it =
      subscribed_apps.begin();
  for (; subscribed_apps.end() != it; ++it) {
    ApplicationSharedPtr subscribed_app = *it;
    if (!subscribed_app) {
      LOG4CXX_WARN(logger_, "Null pointer to subscribed app.");
      continue;
    }

    // Send ButtonEvent notification only in HMI_FULL or HMI_LIMITED mode
    if ((mobile_api::HMILevel::HMI_FULL != subscribed_app->hmi_level()) &&
        (mobile_api::HMILevel::HMI_LIMITED != subscribed_app->hmi_level())) {
      LOG4CXX_WARN(logger_,
                   "OnButtonEvent notification is allowed only"
                       << "in FULL or LIMITED hmi level");
      continue;
    }
    // if "app_id" absent send notification only in HMI_FULL mode
    if (is_app_id_exists || subscribed_app->IsFullscreen()) {
      SendButtonEvent(subscribed_app);
    }
  }
}

void OnButtonEventNotification::SendButtonEvent(ApplicationConstSharedPtr app) {
  if (!app) {
    LOG4CXX_ERROR(logger_, "OnButtonEvent NULL pointer");
    return;
  }

  smart_objects::SmartObjectSPtr on_btn_event =
      new smart_objects::SmartObject();

  if (!on_btn_event) {
    LOG4CXX_ERROR(logger_, "OnButtonEvent NULL pointer");
    return;
  }

  (*on_btn_event)[strings::params][strings::connection_key] = app->app_id();

  (*on_btn_event)[strings::params][strings::function_id] =
      static_cast<int32_t>(mobile_apis::FunctionID::eType::OnButtonEventID);

  (*on_btn_event)[strings::msg_params][strings::button_name] =
      (*message_)[strings::msg_params][hmi_response::button_name];
  (*on_btn_event)[strings::msg_params][strings::button_event_mode] =
      (*message_)[strings::msg_params][hmi_response::button_mode];

  if ((*message_)[strings::msg_params].keyExists(
          hmi_response::custom_button_id)) {
    (*on_btn_event)[strings::msg_params][strings::custom_button_id] =
        (*message_)[strings::msg_params][strings::custom_button_id];
  }

  message_ = on_btn_event;
  SendNotification();
}

}  // namespace mobile

}  // namespace commands

}  // namespace application_manager


text:
package simplebft

import (
	"bytes"
	"fmt"
	"reflect"
)

func (s *SBFT) maybeSendNewView() {
	if s.lastNewViewSent != nil && s.lastNewViewSent.View == s.view {
		return
	}

	vset := make(map[uint64]*Signed)
	var vcs []*ViewChange

	for src, state := range s.replicaState {
		if state.viewchange != nil && state.viewchange.View == s.view {
			vset[uint64(src)] = state.signedViewchange
			vcs = append(vcs, state.viewchange)
		}
	}

	xset, _, ok := s.makeXset(vcs)
	if !ok {
		log.Debugf("replica %d: xset not yet sufficient", s.id)
		return
	}

	var batch *Batch
	if xset == nil {
		// no need for batches, it is contained in the vset
	} else if reflect.DeepEqual(s.cur.subject.Digest, xset.Digest) {
		batch = s.cur.preprep.Batch
	} else {
		log.Warningf("replica %d: forfeiting primary - do not have request in store for %d %x", s.id, xset.Seq.Seq, xset.Digest)
		xset = nil
	}

	nv := &NewView{
		View:  s.view,
		Vset:  vset,
		Xset:  xset,
		Batch: batch,
	}

	log.Noticef("replica %d: sending new view for %d", s.id, nv.View)
	s.lastNewViewSent = nv
	s.broadcast(&Msg{&Msg_NewView{nv}})
}

func (s *SBFT) checkNewViewSignatures(nv *NewView) ([]*ViewChange, error) {
	var vcs []*ViewChange
	for vcsrc, svc := range nv.Vset {
		vc := &ViewChange{}
		err := s.checkSig(svc, vcsrc, vc)
		if err == nil {
			_, err = s.checkBatch(vc.Checkpoint, false, true)
			if vc.View != nv.View {
				err = fmt.Errorf("view does not match")
			}
		}
		if err != nil {
			return nil, fmt.Errorf("viewchange from %d: %s", vcsrc, err)
		}
		vcs = append(vcs, vc)
	}

	return vcs, nil
}

func (s *SBFT) handleNewView(nv *NewView, src uint64) {
	if nv == nil {
		return
	}

	if nv.View < s.view {
		log.Debugf("replica %d: discarding old new view from %d for %d, we are in %d", s.id, src, nv.View, s.view)
		return
	}

	if nv.View == s.view && s.activeView {
		log.Debugf("replica %d: discarding new view from %d for %d, we are already active in %d", s.id, src, nv.View, s.view)
		return
	}

	if src != s.primaryIDView(nv.View) {
		log.Warningf("replica %d: invalid new view from %d for %d", s.id, src, nv.View)
		return
	}

	vcs, err := s.checkNewViewSignatures(nv)
	if err != nil {
		log.Warningf("replica %d: invalid new view from %d: %s", s.id, src, err)
		s.sendViewChange()
		return
	}

	xset, prevBatch, ok := s.makeXset(vcs)

	if !ok || !reflect.DeepEqual(nv.Xset, xset) {
		log.Warningf("replica %d: invalid new view from %d: xset incorrect: %v, %v", s.id, src, nv.Xset, xset)
		s.sendViewChange()
		return
	}

	if nv.Xset == nil {
		if nv.Batch != nil {
			log.Warningf("replica %d: invalid new view from %d: null request should come with null batches", s.id, src)
			s.sendViewChange()
			return
		}
	} else if nv.Batch == nil || !bytes.Equal(nv.Batch.Hash(), nv.Xset.Digest) {
		log.Warningf("replica %d: invalid new view from %d: batches head hash does not match xset: %x, %x, %v",
			s.id, src, hash(nv.Batch.Header), nv.Xset.Digest, nv)
		s.sendViewChange()
		return
	}

	if nv.Batch != nil {
		_, err = s.checkBatch(nv.Batch, true, false)
		if err != nil {
			log.Warningf("replica %d: invalid new view from %d: invalid batches, %s",
				s.id, src, err)
			s.sendViewChange()
			return
		}
	}

	s.view = nv.View
	s.discardBacklog(s.primaryID())

	// maybe deliver previous batches
	if s.sys.LastBatch(s.chainId).DecodeHeader().Seq < prevBatch.DecodeHeader().Seq {
		if prevBatch.DecodeHeader().Seq == s.cur.subject.Seq.Seq {
			// we just received a signature set for a request which we preprepared, but never delivered.
			// check first if the locally preprepared request matches the signature set
			if !reflect.DeepEqual(prevBatch.DecodeHeader().DataHash, s.cur.preprep.Batch.DecodeHeader().DataHash) {
				log.Warningf("replica %d: [seq %d] request checkpointed in a previous view does not match locally preprepared one, delivering batches without payload", s.id, s.cur.subject.Seq.Seq)
			} else {
				log.Debugf("replica %d: [seq %d] request checkpointed in a previous view with matching preprepare, completing and delivering the batches with payload", s.id, s.cur.subject.Seq.Seq)
				prevBatch.Payloads = s.cur.preprep.Batch.Payloads
			}
		}
		// TODO we should not do this here, as prevBatch was already delivered
		blockOK, committers := s.getCommittersFromBatch(prevBatch)
		if !blockOK {
			log.Panic("Replica %d: our last checkpointed batch is erroneous (block cutter).", s.id)
		}
		// TODO what should we do with the remaining?
		s.deliverBatch(prevBatch, committers)
	}

	// after a new-view message, prepare to accept new requests.
	s.activeView = true
	s.cur.checkpointDone = true
	s.cur.subject.Seq.Seq = 0

	log.Infof("replica %d now active in view %d; primary: %v", s.id, s.view, s.isPrimary())

	//process pre-prepare if piggybacked to new-view
	if nv.Batch != nil {
		pp := &Preprepare{
			Seq:   &SeqView{Seq: nv.Batch.DecodeHeader().Seq, View: s.view},
			Batch: nv.Batch,
		}
		blockOK, committers := s.getCommittersFromBatch(nv.Batch)
		if !blockOK {
			log.Debugf("Replica %d: new view %d batch erroneous (block cutter).", s.id, nv.View)
			s.sendViewChange()
		}

		s.handleCheckedPreprepare(pp, committers)
	} else {
		s.cancelViewChangeTimer()
		s.maybeSendNextBatch()
	}

	s.processBacklog()
}


text:
velstor package
===============

Subpackages
-----------

.. toctree::

    velstor.api
    velstor.vclc

Module contents
---------------

.. automodule:: velstor
    :members:
    :undoc-members:
    :show-inheritance:


text:
class AddUserToConversation < ActiveRecord::Migration
  def self.up
    add_column :conversations, :user_id, :integer
    add_index :conversations, :user_id

    #populate user_id in convo
    conversations = Conversation.find(:all)
    conversations.each do |convo|
      puts convo.id
      message = Message.find_by_conversation_id(convo.id, :order => "id ASC")
      user = message.user if message != nil
      convo.user_id = user.id if user != nil
      convo.save
    end

  end

  def self.down
    remove_index :conversations, :user_id
    remove_column :conversations, :user_id
  end
end


text:
<?php
/* @var $this MessagesController */
/* @var $data Messages */
?>

	<?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:
	<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('header')); ?>:
	<?php echo CHtml::encode($data->header); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('body')); ?>:
	<?php echo CHtml::encode($data->body); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('footer')); ?>:
	<?php echo CHtml::encode($data->footer); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('type')); ?>:
	<?php echo CHtml::encode($data->type); ?>

	<?php echo CHtml::encode($data->getAttributeLabel('user_id')); ?>:
	<?php echo CHtml::encode($data->user_id); ?>


text:
import requests
import argparse

# get the inputted links
parser = argparse.ArgumentParser(description='Query spoopy.link to filter out bad links')
parser.add_argument("links", metavar="Link", help="links to filter")
args = parser.parse_args()
input_links = args.links

# function for checking the links (can of course be called separately for use in other code)
def check_links(links):
    bad_links = []

    for link in links:
        reasons = []

        # query the spoopy.link api
        resp = requests.get(f"https://spoopy.link/api/{link}")
        resp.raise_for_status()

        # read the response
        resp_json = resp.json()
        for c in resp_json['chain']:
            if not c['safe']:
                reasons.append(c['reasons'])

        # decide if the link is dangerous or not
        if reasons:
            bad_links.append({
                "link": link,
                "reason": ", ".join(reasons)
            })

    # return the links that are dangerous
    return bad_links

# get the links that are dangerous
checked_bad_links = check_links(input_links)

# return the bad links and their reason for being dangerous, or say that they're all safe
if checked_bad_links:
    return_text = "The following links are dangerous:\n"
    for bad_link in checked_bad_links:
        return_text += f"{bad_link['link']} raised: {bad_link['reason']}"
    print(return_text)
else:
    print("all links are safe!")


text:
<?php

namespace OSC\Apps\PayPal\PayPal\Module\Admin\Config\LOGIN;

use OSC\OM\OSCOM;

class LOGIN extends \OSC\Apps\PayPal\PayPal\Module\Admin\Config\ConfigAbstract
{
    protected $_cm_code = 'login/cm_paypal_login';

    public $is_uninstallable = true;
    public $is_migratable = true;
    public $sort_order = 1000;

    protected function init()
    {
        $this->title = $this->app->getDef('module_login_title');
        $this->short_title = $this->app->getDef('module_login_short_title');
        $this->introduction = $this->app->getDef('module_login_introduction');

        $this->is_installed = defined('OSCOM_APP_PAYPAL_LOGIN_STATUS') && (trim(OSCOM_APP_PAYPAL_LOGIN_STATUS) != '');

        if (!function_exists('curl_init')) {
            $this->req_notes[] = $this->app->getDef('module_login_error_curl');
        }

        if (defined('OSCOM_APP_PAYPAL_LOGIN_STATUS')) {
            if (((OSCOM_APP_PAYPAL_LOGIN_STATUS == '1') && (!tep_not_null(OSCOM_APP_PAYPAL_LOGIN_LIVE_CLIENT_ID) || !tep_not_null(OSCOM_APP_PAYPAL_LOGIN_LIVE_SECRET))) || ((OSCOM_APP_PAYPAL_LOGIN_STATUS == '0') && (!tep_not_null(OSCOM_APP_PAYPAL_LOGIN_SANDBOX_CLIENT_ID) || !tep_not_null(OSCOM_APP_PAYPAL_LOGIN_SANDBOX_SECRET)))) {
                $this->req_notes[] = $this->app->getDef('module_login_error_credentials');
            }

            $this->req_notes[] = $this->app->getDef('module_login_notice_paypal_app_return_url', [
                'return_url' => OSCOM::link('Shop/login.php', 'action=paypal_login', false)
            ]);
        }
    }

    public function install()
    {
        parent::install();

        $installed = explode(';', MODULE_CONTENT_INSTALLED);
        $installed[] = 'login/' . $this->app->vendor . '\\' . $this->app->code . '\\' . $this->code;

        $this->app->saveCfgParam('MODULE_CONTENT_INSTALLED', implode(';', $installed));
    }

    public function uninstall()
    {
        parent::uninstall();

        $installed = explode(';', MODULE_CONTENT_INSTALLED);
        $installed_pos = array_search('login/' . $this->app->vendor . '\\' . $this->app->code . '\\' . $this->code, $installed);

        if ($installed_pos !== false) {
            unset($installed[$installed_pos]);

            $this->app->saveCfgParam('MODULE_CONTENT_INSTALLED', implode(';', $installed));
        }
    }

    public function canMigrate()
    {
        $class = basename($this->_cm_code);

        if (is_file(OSCOM::getConfig('dir_root', 'Shop') . 'includes/modules/content/' . $this->_cm_code . '.php')) {
            if (!class_exists($class)) {
                include(OSCOM::getConfig('dir_root', 'Shop') . 'includes/modules/content/' . $this->_cm_code . '.php');
            }

            $module = new $class();

            if (isset($module->signature)) {
                $sig = explode('|', $module->signature);

                if (isset($sig[0]) && ($sig[0] == 'paypal') && isset($sig[1]) && ($sig[1] == 'paypal_login') && isset($sig[2])) {
                    return version_compare($sig[2], 4) >= 0;
                }
            }
        }

        return false;
    }

    public function migrate()
    {
        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE')) {
            $server = (MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE == 'Live') ? 'LIVE' : 'SANDBOX';

            if (defined('MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID')) {
                if (tep_not_null(MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID)) {
                    if (!defined('OSCOM_APP_PAYPAL_LOGIN_' . $server . '_CLIENT_ID') || !tep_not_null(constant('OSCOM_APP_PAYPAL_LOGIN_' . $server . '_CLIENT_ID'))) {
                        $this->app->saveCfgParam('OSCOM_APP_PAYPAL_LOGIN_' . $server . '_CLIENT_ID', MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID);
                    }
                }

                $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID');
            }

            if (defined('MODULE_CONTENT_PAYPAL_LOGIN_SECRET')) {
                if (tep_not_null(MODULE_CONTENT_PAYPAL_LOGIN_SECRET)) {
                    if (!defined('OSCOM_APP_PAYPAL_LOGIN_' . $server . '_SECRET') || !tep_not_null(constant('OSCOM_APP_PAYPAL_LOGIN_' . $server . '_SECRET'))) {
                        $this->app->saveCfgParam('OSCOM_APP_PAYPAL_LOGIN_' . $server . '_SECRET', MODULE_CONTENT_PAYPAL_LOGIN_SECRET);
                    }
                }

                $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_SECRET');
            }
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_THEME')) {
            $this->app->saveCfgParam('OSCOM_APP_PAYPAL_LOGIN_THEME', MODULE_CONTENT_PAYPAL_LOGIN_THEME);
            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_THEME');
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_ATTRIBUTES')) {
            $this->app->saveCfgParam('OSCOM_APP_PAYPAL_LOGIN_ATTRIBUTES', MODULE_CONTENT_PAYPAL_LOGIN_ATTRIBUTES);
            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_ATTRIBUTES');
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_CONTENT_WIDTH')) {
            $this->app->saveCfgParam('OSCOM_APP_PAYPAL_LOGIN_CONTENT_WIDTH', MODULE_CONTENT_PAYPAL_LOGIN_CONTENT_WIDTH, 'Content Width', 'Should the content be shown in a full or half width container?', 'tep_cfg_select_option(array(\'Full\', \'Half\'), ');
            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_CONTENT_WIDTH');
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_SORT_ORDER')) {
            $this->app->saveCfgParam('OSCOM_APP_PAYPAL_LOGIN_SORT_ORDER', MODULE_CONTENT_PAYPAL_LOGIN_SORT_ORDER, 'Sort Order', 'Sort order of display (lowest to highest).');
            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_SORT_ORDER');
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_STATUS')) {
            $status = '-1';

            if ((MODULE_CONTENT_PAYPAL_LOGIN_STATUS == 'True') && defined('MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE')) {
                if (MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE == 'Live') {
                    $status = '1';
                } else {
                    $status = '0';
                }
            }

            $this->app->saveCfgParam('OSCOM_APP_PAYPAL_LOGIN_STATUS', $status);
            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_STATUS');
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE')) {
            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE');
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_VERIFY_SSL')) {
            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_VERIFY_SSL');
        }

        if (defined('MODULE_CONTENT_PAYPAL_LOGIN_PROXY')) {
            if (!empty(MODULE_CONTENT_PAYPAL_LOGIN_PROXY) && empty(OSCOM_HTTP_PROXY)) {
                $this->app->saveCfgParam('OSCOM_HTTP_PROXY', MODULE_CONTENT_PAYPAL_LOGIN_PROXY);
            }

            $this->app->deleteCfgParam('MODULE_CONTENT_PAYPAL_LOGIN_PROXY');
        }
    }
}


text:
using System.Collections.Generic;
using System.Linq;

namespace NeoSmart.Unicode
{
    // We hereby declare emoji to be a zero plural marker noun (in short, "emoji" is both the
    // singular and the plural form). This class refers to emoji in the plural.
    public static partial class Emoji
    {
        static Emoji()
        {
            // Populate the list of available emoji in the system font.
            // For now, the font is hard-coded to Segoe UI Emoji.
        }

        /// <summary>
        /// ZWJ is used to combine multiple emoji codepoints into a single emoji symbol.
        /// </summary>
        public static readonly Codepoint ZeroWidthJoiner = Codepoints.ZWJ;

        public static readonly Codepoint ObjectReplacementCharacter = Codepoints.ORC;

        public static readonly Codepoint Keycap = Codepoints.Keycap;

        /// <summary>
        /// The Emoji VS indicates that the preceding (non-emoji) unicode codepoint should be represented as an emoji.
        /// </summary>
        public static readonly Codepoint VariationSelector = Codepoints.VariationSelectors.EmojiSymbol;

        public static class SkinTones
        {
            public static readonly Codepoint Light = new Codepoint("U+1F3FB");
            public static readonly Codepoint Fitzpatrick12 = Light;
            public static readonly Codepoint MediumLight = new Codepoint("U+1F3FC");
            public static readonly Codepoint Fitzpatrick3 = MediumLight;
            public static readonly Codepoint Medium = new Codepoint("U+1F3FD");
            public static readonly Codepoint Fitzpatrick4 = Medium;
            public static readonly Codepoint MediumDark = new Codepoint("U+1F3FE");
            public static readonly Codepoint Fitzpatrick5 = MediumDark;
            public static readonly Codepoint Dark = new Codepoint("U+1F3FF");
            public static readonly Codepoint Fitzpatrick6 = Dark;

            /// <summary>
            /// Helper object, most useful for checking if a codepoint is a skin tone quickly.
            /// </summary>
            public static readonly List<Codepoint> All = new List<Codepoint>() { Light, MediumLight, Medium, MediumDark, Dark };
        }

        /// <summary>
        /// Combines multiple emoji with a zero-width-joiner to (potentially) create a new symbol
        /// </summary>
        /// <param name="emoji"></param>
        /// <returns></returns>
        public static string Combine(IEnumerable<SingleEmoji> emoji)
        {
#if !NET20
            return string.Join(ZeroWidthJoiner.AsString(), emoji);
#else
            return string.Join(ZeroWidthJoiner.AsString(), emoji.Select(e => e.ToString()).ToArray());
#endif

        }

        /// <summary>
        /// Combines multiple emoji with a zero-width-joiner to (potentially) create a new symbol
        /// </summary>
        /// <param name="emoji"></param>
        /// <returns></returns>
        public static string Combine(params SingleEmoji[] emoji)
        {
            return Combine((IEnumerable<SingleEmoji>)emoji);
        }

        /// <summary>
        /// Determines whether a string is comprised solely of emoji, optionally with a maximum number of drawn symbols.
        /// Can be used to determine whether a message consists of ≦ x emoji for purposes such as displaying at a larger size. Since one emoji symbol can be formed
        /// from many separate emoji "characters" combined with zero-width joiners or even non-emoji characters followed by a "use emoji representation" marker, this
        /// cannot be determined solely from the codepoints.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="maxSymbolCount"></param>
        /// <returns></returns>
        public static bool IsEmoji(string message, int maxSymbolCount = int.MaxValue)
        {
            var codepoints = message.Codepoints();

            bool nextMustBeVS = false;
            string zwj = ZeroWidthJoiner.AsString();
            string variationSelector = VariationSelector.AsString();
            bool ignoreNext = false;
            int count = 0;
            foreach (var cp in codepoints)
            {
                // We used to have `message = message.trim()` previously. This avoids the extra
                // allocation, hepful in case of long messages. This was not premature optimization,
                // it came out of necessity.
                if (cp == "\n" || cp == "\r" || cp == "\t" || cp == " ")
                {
                    continue;
                }

                if (nextMustBeVS)
                {
                    nextMustBeVS = false;
                    if (cp != variationSelector)
                    {
                        // A non-emoji codepoint was found and this (the codepoint after it) is not
                        // the variation selector
                        return false;
                    }
                }
                if (cp.In(SkinTones.All))
                {
                    // Don't count the skin tone as part of the length
                    continue;
                }

                if (cp == zwj)
                {
                    ignoreNext = true;
                    continue;
                }

                if (cp == variationSelector)
                {
                    continue;
                }

                if (cp == Codepoints.ObjectReplacementCharacter)
                {
                    // This is explicitly blacklisted for UI purposes
                    return false;
                }

                if (cp == Keycap)
                {
                    // This is not in the UTR, but is used to box symbols in an icon.
                    // Do not consider it part of the length.
                    continue;
                }

                if (!ignoreNext)
                {
                    ++count;
                    if (count > maxSymbolCount)
                    {
                        return false;
                    }
                    // By default, the UTR lists numbers, the asterisk, and the number sign as
                    // emoji, but we won't consider them as such unless they are followed by a VS.
                    if (Languages.ArabicNumerals.Contains(cp) || cp == "#" || cp == "*")
                    {
                        nextMustBeVS = true;
                        continue;
                    }
                    else if (Languages.Emoji.Contains(cp))
                    {
                        continue;
                    }
                    else
                    {
                        // We've either encountered a non-emoji character OR a non-emoji codepoint
                        // that should be treated as an emoji if followed by the variation selector
                        // codepoint.
                        nextMustBeVS = true;
                        continue;
                    }
                }
                ignoreNext = false;
            }

            if (nextMustBeVS)
            {
                return false;
            }

            return count > 0 && count <= maxSymbolCount;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Core\Resolver;

use InvalidArgumentException;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Addressing\Matcher\ZoneMatcherInterface;
use Sylius\Component\Addressing\Model\ZoneInterface;
use Sylius\Component\Core\Model\AddressInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Core\Model\ShippingMethodInterface;
use Sylius\Component\Core\Repository\ShippingMethodRepositoryInterface;
use Sylius\Component\Shipping\Checker\Eligibility\ShippingMethodEligibilityCheckerInterface;
use Sylius\Component\Shipping\Exception\UnresolvedDefaultShippingMethodException;
use Sylius\Component\Shipping\Model\ShipmentInterface as BaseShipmentInterface;
use Sylius\Component\Shipping\Resolver\DefaultShippingMethodResolverInterface;

final class EligibleDefaultShippingMethodResolverSpec extends ObjectBehavior
{
    function let(
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShippingMethodEligibilityCheckerInterface $shippingMethodEligibilityChecker,
        ZoneMatcherInterface $zoneMatcher,
    ): void {
        $this->beConstructedWith(
            $shippingMethodRepository,
            $shippingMethodEligibilityChecker,
            $zoneMatcher,
        );
    }

    function it_implements_default_shipping_method_resolver_interface()
    {
        $this->shouldImplement(DefaultShippingMethodResolverInterface::class);
    }

    function it_returns_first_enabled_and_eligible_shipping_method_from_shipment_order_channel_as_default(
        ChannelInterface $channel,
        OrderInterface $order,
        ShipmentInterface $shipment,
        ShippingMethodInterface $firstShippingMethod,
        ShippingMethodInterface $secondShippingMethod,
        ShippingMethodInterface $thirdShippingMethod,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShippingMethodEligibilityCheckerInterface $shippingMethodEligibilityChecker,
    ): void {
        $shipment->getOrder()->willReturn($order);
        $order->getChannel()->willReturn($channel);
        $order->getShippingAddress()->willReturn(null);

        $shippingMethodRepository
            ->findEnabledForChannel($channel)
            ->willReturn([$firstShippingMethod, $secondShippingMethod])
        ;

        $shippingMethodEligibilityChecker->isEligible($shipment, $firstShippingMethod)->willReturn(false);
        $shippingMethodEligibilityChecker->isEligible($shipment, $secondShippingMethod)->willReturn(true);
        $shippingMethodEligibilityChecker->isEligible($shipment, $thirdShippingMethod)->willReturn(true);

        $this->getDefaultShippingMethod($shipment)->shouldReturn($secondShippingMethod);
    }

    function it_returns_enabled_and_eligible_shipping_method_from_shipment_order_channel_and_shipping_zone_as_default(
        ChannelInterface $channel,
        OrderInterface $order,
        ShipmentInterface $shipment,
        ShippingMethodInterface $firstShippingMethod,
        ShippingMethodInterface $secondShippingMethod,
        ShippingMethodInterface $thirdShippingMethod,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShippingMethodEligibilityCheckerInterface $shippingMethodEligibilityChecker,
        AddressInterface $shippingAddress,
        ZoneMatcherInterface $zoneMatcher,
        ZoneInterface $zone,
    ): void {
        $shipment->getOrder()->willReturn($order);
        $order->getChannel()->willReturn($channel);
        $order->getShippingAddress()->willReturn($shippingAddress);

        $zoneMatcher->matchAll($shippingAddress)->willReturn([$zone]);

        $shippingMethodRepository
            ->findEnabledForZonesAndChannel([$zone], $channel)
            ->willReturn([$firstShippingMethod, $secondShippingMethod])
        ;

        $shippingMethodEligibilityChecker->isEligible($shipment, $firstShippingMethod)->willReturn(false);
        $shippingMethodEligibilityChecker->isEligible($shipment, $secondShippingMethod)->willReturn(true);
        $shippingMethodEligibilityChecker->isEligible($shipment, $thirdShippingMethod)->willReturn(true);

        $this->getDefaultShippingMethod($shipment)->shouldReturn($secondShippingMethod);
    }

    function it_throws_an_exception_if_there_is_shipping_method_cannot_be_resolved(
        ChannelInterface $channel,
        OrderInterface $order,
        ShipmentInterface $shipment,
        ShippingMethodInterface $firstShippingMethod,
        ShippingMethodInterface $secondShippingMethod,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShippingMethodEligibilityCheckerInterface $shippingMethodEligibilityChecker,
    ): void {
        $shipment->getOrder()->willReturn($order);
        $order->getChannel()->willReturn($channel);
        $order->getShippingAddress()->willReturn(null);

        $shippingMethodRepository
            ->findEnabledForChannel($channel)
            ->willReturn([$firstShippingMethod, $secondShippingMethod])
        ;

        $shippingMethodEligibilityChecker->isEligible($shipment, $firstShippingMethod)->willReturn(false);
        $shippingMethodEligibilityChecker->isEligible($shipment, $secondShippingMethod)->willReturn(false);

        $this
            ->shouldThrow(UnresolvedDefaultShippingMethodException::class)
            ->during('getDefaultShippingMethod', [$shipment])
        ;
    }

    function it_throws_an_exception_if_passed_shipment_is_not_core_shipment_object(BaseShipmentInterface $shipment): void
    {
        $this->shouldThrow(InvalidArgumentException::class)->during('getDefaultShippingMethod', [$shipment]);
    }
}


text:
"""Read button.

Make gpio input and enable pull-up resistor.
"""

import os
import sys

if not os.getegid() == 0:
    sys.exit('Script must be run as root')

from pyA20.gpio import gpio
from pyA20.gpio import connector
from pyA20.gpio import port

__author__ = "Stefan Mavrodiev"
__copyright__ = "Copyright 2014, Olimex LTD"
__credits__ = ["Stefan Mavrodiev"]
__license__ = "GPL"
__version__ = "2.0"
__maintainer__ = __author__
__email__ = "support@olimex.com"

led = connector.gpio0p0     # This is the same as port.PH2
button = connector.gpio3p40

"""Init gpio module"""
gpio.init()

"""Set directions"""
gpio.setcfg(led, gpio.OUTPUT)
gpio.setcfg(button, gpio.INPUT)

"""Enable pullup resistor"""
gpio.pullup(button, gpio.PULLUP)
#gpio.pullup(button, gpio.PULLDOWN)     # Optionally you can use pull-down resistor

try:
    print ("Press CTRL+C to exit")
    while True:
        state = gpio.input(button)      # Read button state

        """Since we use pull-up the logic will be inverted"""
        gpio.output(led, not state)

except KeyboardInterrupt:
    print ("Goodbye.")


text:
.. ---------------------------------------------------------------------------
.. Copyright 2015 Nervana Systems Inc.
.. Licensed under the Apache License, Version 2.0 (the "License");
.. you may not use this file except in compliance with the License.
.. You may obtain a copy of the License at
..
..      http://www.apache.org/licenses/LICENSE-2.0
..
.. Unless required by applicable law or agreed to in writing, software
.. distributed under the License is distributed on an "AS IS" BASIS,
.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
.. See the License for the specific language governing permissions and
.. limitations under the License.
.. ---------------------------------------------------------------------------

Op-Tree
========

Op-tree (as in OpTreeNode class) is a graph representation of numerical
operations. We are going to start by looking at a minimal example:

.. code:: python

    from neon.backends import gen_backend

    be = gen_backend('cpu')
    x0 = be.ones((2, 2), name='x0')
    x1 = be.ones((2, 2), name='x1')
    f = x0 + x1               # op-tree creation
    f_val = be.empty((2, 2))  # output buffer allocation
    f_val[:] = f              # execution

    print(f)                  # print the op-tree tuple
    print(f_val.get())        # get the device tenser

this gives:

.. parsed-literal::

    ({'shape': (2, 2), 'op': 'add'}, x0, x1)
    [[ 2.  2.]
     [ 2.  2.]]

The tuple ``({'shape': (2, 2), 'op': 'add'}, x0, x1)`` is the op-tree.
There are two different type of nodes in an op-tree. The dict {'shape':
(2, 2), 'op': 'add'} is the "op", containing the operations, properties
of the operation (such as axis) and the shape of the output. The other
two nodes are the "numeric node", containing Tensor or constant (float,
int).

Relation between OpTreeNode and op-tree
---------------------------------------

-  OpTreeNode is the class inherited from tuple. An OpTreeNode is a
   tuple of length 3. The first element is a dict specifying the
   operation, and the second and third elements specify the operands.
-  From an op-tree's tree perspective, think about the the 3 elements as
   3 nodes. The second and third element are the left and right child of
   the first element (the dict).

Op-Tree Creation
----------------

1. **Operator overload.** Most of the common numerical operators between Tensor
and OpTreeNode are overloaded. Operations between a Tensor and an OpTreeNode
will produce an OpTreeNode. For example, we can do:

.. code:: python

    # f are OpTreeNode in the following example
    f = x1 + x2 # Tensor + Tensor
    f = x1 + t1 # Tensor + OpTreeNode
    f = t1 + t2 # OpTreeNode + OpTreeNode

2. **Backend functions.** Op-tree can be built from calling backend functions
using syntax similar to numpy, for example:

.. code:: python

    f = ng.mean(x) # f is an optree

3. **`OpTreeNode.build()`.** The `OpTreeNode.build()` is called internally by
the first two cases. The build function do the type checking and append the shape
to the op_dict. When the first op is 'assign', the op-tree will be executed automatically.

.. code:: python

    OpTreeNode.build("add", a, b) # binary ops
    OpTreeNode.build("sqrt", a, None, out=out_buffer) # unary ops

4. **OpTreeNode's init function.** Lastly, we could build an op-tree from the
initializer or the OpTreeNode class. It is also usually called internally. This
gives us complete control of the contents of the OpTree, but it does not give
the type checking and shape calculation. So be careful.

.. code:: python

    OpTreeNode(op_dict, a, b)

Op-Tree Execution
-----------------

Usually, the execution of an op-tree is triggered by assignment:

.. code:: python

    f_val[:] = f

Here is what happens under the hood:

- An new op-tree with assignment is built based on `f`:

.. code:: python

    OpTreeNode.build("assign", f_val, f)

- Then this new op-tree is executed:

.. code:: python

    OpTreeNode.build("assign", f_val, f).execute()

- The corresponding backend's execute function will be called and the value of `f`
  will be written to Tensor `f_val`.

Property of the op-tree
-----------------------

The OpTreeNode class is inherited from tuple, making OpTreeNode efficient and
immutable. If we want to modify the op-tree (for example swapping all instance
of Tensor `x1` to `x2`), consider modifying the post-order stack (which is a list)
of the optree directly.

Tree structure & number of operands
-----------------------------------

An op-tree is a binary tree. It has the following properties:

- Except for the root node, every node has exactly one parent.
- All leaf nodes are "numeric nodes" and all internal nodes are "op nodes".
- An "op node" can have zero, one or two children, depending on whether it is a
  zero-operand, unary or binary operation.


text:
/**
 * Created by Kristof on 5/11/2015.
 */
define('Database', [
    'IDBDatabase',
    'IDBTransaction',
    'IDBTransactionMode',
    'util'
], function(IDBDatabase,
            IDBTransaction,
            IDBTransactionMode,
            util){
    var Database = function(name){
        this.name = name;
        this.version = 0;
        this.objectStoreNames = [];
        this.objectStores = [];
        this.connections = [];
    },
    Snapshot = function(objectStores, objectStoreNames){
        this.objectStores = util.clone(objectStores);
        this.objectStoreNames = util.clone(objectStoreNames);
    };

    Snapshot.prototype = (function(){
        function AddObjectStore(objectStore){
            this.objectStores.push(objectStore);
            this.objectStoreNames.push(objectStore.name);
        }
        function RemoveObjectStore(objectStoreName){
            for (var i = 0; i < this.objectStores.length; i++) {
                if(this.objectStores[i].name === objectStoreName){
                    this.objectStores.splice(i, 1);
                    break;
                }
            }
            this.objectStoreNames.splice(this.objectStoreNames.indexOf(objectStoreName), 1);
        }

        return {
            addObjectStore: AddObjectStore,
            removeObjectStore: RemoveObjectStore
        };
    })();

    Database.prototype = (function(){
        function AddConnection(connection){
            this.connections.push(connection);
        }
        function RemoveConnection(connection){
            for (var i = 0; i < this.connections.length; i++) {
                if(this.connections[i].__connectionId === connection.__connectionId){
                    this.connections.splice(i, 1);
                    break;
                }
            }
        }
        function Upgrade(openDBRequest, version, connection, successCallback, failCallback){
            for (var i = 0; i < this.connections.length; i++) {
                if (this.connections[i].__connectionId !== connection.__connectionId) {
                    this.connections[i].__versionchange(version);
                }
            }

            upgradeInternal(this, openDBRequest, connection.version, version, connection, successCallback, failCallback);
        }
        function TakeSnapshot(){
           return new Snapshot(this.objectStores, this.objectStoreNames);
        }
        function CommitSnapshot(snapshot){
            this.objectStores = util.clone(snapshot.objectStores);
            this.objectStoreNames = util.clone(snapshot.objectStoreNames);
        }

        function upgradeInternal(db, openDBRequest, currentVersion, version, connection, successCallback, failCallback) {
            if(db.connections.length > 0 && db.connections[0].__connectionId !== connection.__connectionId){
                openDBRequest.__blocked(version, currentVersion);
                setTimeout(upgradeInternal, 10, db, openDBRequest, currentVersion, version, connection, successCallback, failCallback);
                return;
            }

            if(version !== null) { // Delete request
                connection.version = version;
                db.version = version;
                openDBRequest.__upgradeneeded(connection, connection.transaction(db.objectStoreNames, IDBTransactionMode.versionchange), version, currentVersion);
            }

            setTimeout(function (_db, _openDBRequest, _successCallback, _failCallback) {
                if(_openDBRequest.transaction && _openDBRequest.transaction.__aborted) {
                    _openDBRequest.__error({
                        name: "AbortError",
                        message: "The transaction was aborted."
                    }, 8);
                    if(util.isFunction(_failCallback)) {
                        _failCallback(_openDBRequest, _db);
                    }
                }
                else {
                    if(util.isFunction(_successCallback)) {
                        _successCallback(_openDBRequest, _db);
                    }
                }
            }, util.timeout, db, openDBRequest, successCallback, failCallback);
        }

        return {
            addConnection: AddConnection,
            removeConnection: RemoveConnection,
            snapshot: TakeSnapshot,
            commitSnapshot: CommitSnapshot,
            upgrade: Upgrade
        };
    })();

    return Database;
});


text:
class Tag < ActiveRecord::Base
  include PgSearch::Model
  has_many :tagged_resources
  has_many :projects, through: :tagged_resources, source: :resource, source_type: "Project"
  has_many :organizations, through: :tagged_resources, source: :resource, source_type: "Organization"

  validates :name, uniqueness: { case_sensitive: false }, presence: true

  before_validation :downcase_name

  pg_search_scope :search_tags,
    against: :name,
    using: :trigram,
    ranked_by: ":trigram"

  def downcase_name
    self.name = name.try(:downcase)
  end
end


text:
@interface ViewController ()

@property (nonatomic, weak) IBOutlet UIButton * settingsButton;
@property (nonatomic, weak) IBOutlet UITextField * billTotalField;
@property (nonatomic, weak) IBOutlet UIButton * clearButton;
@property (nonatomic, weak) IBOutlet UIView * numberPeopleView;
@property (nonatomic, weak) IBOutlet UILabel * numberPeopleLabel;
@property (nonatomic, weak) IBOutlet UICollectionView * tipCalculatedCollectionView;

@property (nonatomic, strong) NSIndexPath * tipPercentageToScrollToIndexPath;

@end

@implementation ViewController

#pragma mark - UIViewController cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.billTotalField.delegate = self;
    self.tipCalculatedCollectionView.delegate = self;
    self.tipCalculatedCollectionView.dataSource = self;
    UINib *tipCellNib = [UINib nibWithNibName:[TipCalculatedCollectionViewCell nibName] bundle:nil];
    [self.tipCalculatedCollectionView registerNib:tipCellNib forCellWithReuseIdentifier:[TipCalculatedCollectionViewCell reuseIdentifier]];

    [self.navigationController setNavigationBarHidden:YES];

    UISwipeGestureRecognizer * swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeNumberPeople:)];
    UISwipeGestureRecognizer * swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeNumberPeople:)];
    UISwipeGestureRecognizer * swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeNumberPeople:)];
    UISwipeGestureRecognizer * swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeNumberPeople:)];
    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [swipeUp setDirection:UISwipeGestureRecognizerDirectionUp];
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [swipeDown setDirection:UISwipeGestureRecognizerDirectionDown];

    [self.numberPeopleView addGestureRecognizer:swipeRight];
    [self.numberPeopleView addGestureRecognizer:swipeUp];
    [self.numberPeopleView addGestureRecognizer:swipeLeft];
    [self.numberPeopleView addGestureRecognizer:swipeDown];

    // Make keyboard show
    [self.billTotalField becomeFirstResponder];

    self.tipPercentageToScrollToIndexPath = nil;
    [self loadLatestData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.billTotalField becomeFirstResponder];
    [self loadDefaultData];
    [self clearLatestData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.tipCalculatedCollectionView scrollToItemAtIndexPath:self.tipPercentageToScrollToIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate protocol methods

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text containsString:@"."]) {

    }
    if ([string isEqualToString:@"."] && [textField.text containsString:@"."]) {
        return NO;
    } else {
        [self updateTipCalculations:[textField.text stringByReplacingCharactersInRange:range withString:string] withSplit:self.numberPeopleLabel.text];
        return YES;
    }
}

#pragma mark - UICollectionViewDataSource protocol methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 100;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[TipCalculatedCollectionViewCell reuseIdentifier] forIndexPath:indexPath];
    TipCalculatedCollectionViewCell * tipCell = nil;
    if ([cell isKindOfClass:[TipCalculatedCollectionViewCell class]]) {
        tipCell = (TipCalculatedCollectionViewCell *) cell;
    }
    if(tipCell) {
        tipCell.tipPercentage = [NSNumber numberWithInteger:indexPath.row];
        [tipCell updateCell:[self.billTotalField.text doubleValue] withSplit:[self.numberPeopleLabel.text intValue]];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout protocol methods

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake([UIScreen mainScreen].bounds.size.width / 2.0, self.tipCalculatedCollectionView.frame.size.height);
}

#pragma mark - IBAction

- (IBAction)clearButtonPressed:(id)sender {
    [self.billTotalField setText:@""];
    [self.numberPeopleLabel setText:@"1"];
    [self updateTipCalculations:@"" withSplit:@"1"];
}

- (void)handleSwipeNumberPeople:(UISwipeGestureRecognizer *)swipe {
    int numberOfPeople = [self.numberPeopleLabel.text intValue];
    if (swipe.direction == UISwipeGestureRecognizerDirectionRight || swipe.direction == UISwipeGestureRecognizerDirectionUp) {
        [self.numberPeopleLabel setText:[NSString stringWithFormat:@"%d", numberOfPeople + 1]];
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionLeft || swipe.direction == UISwipeGestureRecognizerDirectionDown) {
        if (numberOfPeople > 1) {
            [self.numberPeopleLabel setText:[NSString stringWithFormat:@"%d", numberOfPeople - 1]];
        }
    }
    [self updateTipCalculations:self.billTotalField.text withSplit:self.numberPeopleLabel.text];
}

#pragma mark - Helpers

- (void) recordLastTipPercentageSettings {
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.billTotalField.text forKey:kLastBillTotal];

    [defaults setInteger:[self centerTipPercentageIndexPath].row forKey:kLastTipPercentage];

    [defaults setObject:self.numberPeopleLabel.text forKey:kLastBillSplitNumber];
    [defaults synchronize];
}

- (NSIndexPath *) centerTipPercentageIndexPath {
    NSArray * visibleCells = [self.tipCalculatedCollectionView visibleCells];
    CGFloat centerX = self.tipCalculatedCollectionView.contentOffset.x + [UIScreen mainScreen].bounds.size.width/2;
    CGRect centerRect = CGRectMake(centerX, self.tipCalculatedCollectionView.frame.size.height / 2, 1, 1);
    for (UICollectionViewCell * cell in visibleCells) {
        BOOL isCellCenter = CGRectIntersectsRect(centerRect, cell.frame);
        if (isCellCenter) {
            return [self.tipCalculatedCollectionView indexPathForCell:cell];
        }
    }
    return nil;
}

- (void) updateTipCalculations:(NSString *)newBillValue withSplit:(NSString *)numberOfPeople {
    NSArray * cellsToUpdate = [self.tipCalculatedCollectionView visibleCells];
    int people = [numberOfPeople intValue];
    for (UICollectionViewCell * cell in cellsToUpdate) {
        if ([cell isKindOfClass:[TipCalculatedCollectionViewCell class]]) {
            TipCalculatedCollectionViewCell * tipCell = (TipCalculatedCollectionViewCell *)cell;
            [tipCell updateCell:[newBillValue doubleValue] withSplit:people];
        }
    }
}

- (void) loadLatestData {
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    NSDate * lastDate = (NSDate *)[defaults objectForKey:kLastCloseDate];
    NSTimeInterval timeDiff = [[NSDate date] timeIntervalSinceDate:lastDate];

    NSInteger lastTipPercentage = [defaults integerForKey:kLastTipPercentage];
    NSString * lastBillTotal = [defaults objectForKey:kLastBillTotal];
    NSString * lastBillSplitNumber = [defaults stringForKey:kLastBillSplitNumber];

    // If less than 10 minutes have passed and something has been recorded, set bill total, number of people to split by, and tip percentage to what was last present
    if (timeDiff < 600 && lastTipPercentage && lastBillTotal && lastBillSplitNumber) {
        self.tipPercentageToScrollToIndexPath = [NSIndexPath indexPathForRow:lastTipPercentage inSection:0];
        [self.billTotalField setText:lastBillTotal];
        [self.numberPeopleLabel setText:lastBillSplitNumber];
    }
}

- (void) loadDefaultData {
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSInteger lastTipPercentage = [defaults integerForKey:kLastTipPercentage];
    NSString * lastBillTotal = [defaults objectForKey:kLastBillTotal];
    NSString * lastBillSplitNumber = [defaults stringForKey:kLastBillSplitNumber];

    if (!lastTipPercentage && !lastBillTotal && !lastBillSplitNumber) {
        // Load default percentage from settings
        NSNumber * tipPercentage = [defaults objectForKey:kTipPercentageDefault];
        // Default is 15 if it hasn't already been set
        if (!tipPercentage) {
            tipPercentage = @15;
        }
        self.tipPercentageToScrollToIndexPath = [NSIndexPath indexPathForRow:[tipPercentage integerValue] inSection:0];

        // Load default number of people to split bill by
        NSString * billSplitNumberDefault = [defaults stringForKey:kBillSplitNumberDefault];
        if (!billSplitNumberDefault) {
            billSplitNumberDefault = @"1";
        }
        [self.numberPeopleLabel setText:billSplitNumberDefault];
        [self updateTipCalculations:self.billTotalField.text withSplit:billSplitNumberDefault];
    }
}

- (void) clearLatestData {
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    // Clear last recorded numbers
    [defaults removeObjectForKey:kLastBillTotal];
    [defaults removeObjectForKey:kLastTipPercentage];
    [defaults removeObjectForKey:kLastBillSplitNumber];
    [defaults synchronize];
}

@end


text:
Scheduler application built for Kent State University Capstone course using Dotnet Core.

## Getting up and running
1. [Install dotnet core](https://www.microsoft.com/net/core)
2. Clone this repo: `git clone https://github.com/mzrimsek/scheduler.git`

There are build scripts set up for local development.
* On Windows: ```./build.ps1```
* On Linux/Mac: ```./build.sh```

For both scripts there are two optional arguments you can pass in.
* ```build``` - executes the build step to compile, bundle, and minify your code (passing in no arguments defaults to this option)
* ```run``` - does the same as ```build``` except it will also serve the application at ```localhost:5000```


text:
require 'test/unit'
require_relative 'envutil'

class TestClass < Test::Unit::TestCase
  # ------------------
  # Various test classes
  # ------------------

  class ClassOne
    attr :num_args
    @@subs = []
    def initialize(*args)
      @num_args = args.size
      @args = args
    end
    def [](n)
      @args[n]
    end
    def ClassOne.inherited(klass)
      @@subs.push klass
    end
    def subs
      @@subs
    end
  end

  class ClassTwo < ClassOne
  end

  class ClassThree < ClassOne
  end

  class ClassFour < ClassThree
  end

  # ------------------
  # Start of tests
  # ------------------

  def test_s_inherited
    assert_equal([ClassTwo, ClassThree, ClassFour], ClassOne.new.subs)
  end

  def test_s_new
    c = Class.new
    assert_same(Class, c.class)
    assert_same(Object, c.superclass)

    c = Class.new(Fixnum)
    assert_same(Class, c.class)
    assert_same(Fixnum, c.superclass)
  end

  def test_00_new_basic
    a = ClassOne.new
    assert_equal(ClassOne, a.class)
    assert_equal(0, a.num_args)

    a = ClassOne.new(1, 2, 3)
    assert_equal(3, a.num_args)
    assert_equal(1, a[0])
  end

  def test_01_new_inherited
    a = ClassTwo.new
    assert_equal(ClassTwo, a.class)
    assert_equal(0, a.num_args)

    a = ClassTwo.new(1, 2, 3)
    assert_equal(3, a.num_args)
    assert_equal(1, a[0])
  end

  def test_superclass
    assert_equal(ClassOne, ClassTwo.superclass)
    assert_equal(Object,   ClassTwo.superclass.superclass)
    assert_equal(BasicObject, ClassTwo.superclass.superclass.superclass)
  end

  def test_class_cmp
    assert_raise(TypeError) { Class.new <= 1 }
    assert_raise(TypeError) { Class.new >= 1 }
    assert_nil(Class.new <=> 1)
  end

  def test_class_initialize
    assert_raise(TypeError) do
      Class.new.instance_eval { initialize }
    end
  end

  def test_instanciate_singleton_class
    c = class << Object.new; self; end
    assert_raise(TypeError) { c.new }
  end

  def test_superclass_of_basicobject
    assert_equal(nil, BasicObject.superclass)
  end

  def test_module_function
    c = Class.new
    assert_raise(TypeError) do
      Module.instance_method(:module_function).bind(c).call(:foo)
    end
  end

  def test_check_inheritable
    assert_raise(TypeError) { Class.new(Object.new) }

    o = Object.new
    c = class << o; self; end
    assert_raise(TypeError) { Class.new(c) }

    assert_nothing_raised { Class.new(Class) } # is it OK?
    assert_raise(TypeError) { eval("class Foo < Class; end") }
  end

  def test_initialize_copy
    c = Class.new
    assert_raise(TypeError) { c.instance_eval { initialize_copy(1) } }

    o = Object.new
    c = class << o; self; end
    assert_raise(TypeError) { c.dup }
  end

  def test_singleton_class
    assert_raise(TypeError) { 1.extend(Module.new) }
    assert_raise(TypeError) { :foo.extend(Module.new) }

    assert_in_out_err([], <<-INPUT, %w(:foo :foo true true), [])
      module Foo; def foo; :foo; end; end
      false.extend(Foo)
      true.extend(Foo)
      p false.foo
      p true.foo
      p FalseClass.include?(Foo)
      p TrueClass.include?(Foo)
    INPUT
  end

  def test_uninitialized
    assert_raise(TypeError) { Class.allocate.new }
    assert_raise(TypeError) { Class.allocate.superclass }
  end
end


text:
Status bar indicators to monitor your Mac.

I was using the wonderful MenuMeters by Alex Harper, but it has been broken by the new OSX El Capitan. So I choose to create my own status bar icons to monitor my computer.

Please note that the project is at an early stage, a lot of things remain to be done.

Actually the colors of the indicators are suited for the Apple Dark theme, but you are now able to customize the colors in the settings window!

![alt text](ScreenShot.png)


text:
#region copyright
// <copyright file="BlockStatusResponse.cs" >
// Copyright (c) 2016 All Rights Reserved
// Licensed under MIT
// </copyright>
// <author>Raj Bandi</author>
// <date>26/6/2016</date>
// <summary></summary>
#endregion
using System.Runtime.Serialization;
using RiseSharp.Core.Api.Messages.Common;

namespace RiseSharp.Core.Api.Messages.Node
{
    [DataContract]
    public class BlockStatusResponse : BaseResponse
    {
        [DataMember(Name = "height")]
        public int Height { get; set; }

        [DataMember(Name = "fee")]
        public int Fee { get; set; }

        [DataMember(Name = "milestone")]
        public int Milestone { get; set; }

        [DataMember(Name = "reward")]
        public int Reward { get; set; }

        [DataMember(Name = "supply")]
        public long Supply { get; set; }

    }
}


text:
import '@kadira/storybook/addons';

import '@kadira/storybook-addon-knobs/register';
import '@kadira/storybook-addon-notes/register';


text:
using std::map;
using std::move;
using std::string;
using std::vector;

namespace tcframe {

class Verifier {
private:
    ConstraintSuite constraintSuite_;

public:
    virtual ~Verifier() = default;

    explicit Verifier(ConstraintSuite constraintSuite)
            : constraintSuite_(move(constraintSuite)) {}

    virtual ConstraintsVerificationResult verifyConstraints(const set<int>& subtaskIds) {
        map<int, vector<string>> unsatisfiedConstraintDescriptionsBySubtaskId;
        set<int> satisfiedButNotAssignedSubtaskIds;

        for (const Subtask& subtask : constraintSuite_.constraints()) {
            vector<string> unsatisfiedConstraintDescriptions;
            for (const Constraint& constraint : subtask.constraints()) {
                if (!constraint.predicate()()) {
                    unsatisfiedConstraintDescriptions.push_back(constraint.description());
                }
            }

            if (subtask.id() == Subtask::MAIN_ID || subtaskIds.count(subtask.id())) {
                if (!unsatisfiedConstraintDescriptions.empty()) {
                    unsatisfiedConstraintDescriptionsBySubtaskId[subtask.id()] = unsatisfiedConstraintDescriptions;
                }
            } else {
                if (unsatisfiedConstraintDescriptions.empty()) {
                    satisfiedButNotAssignedSubtaskIds.insert(subtask.id());
                }
            }
        }
        return {unsatisfiedConstraintDescriptionsBySubtaskId, satisfiedButNotAssignedSubtaskIds};
    }

    virtual MultipleTestCasesConstraintsVerificationResult verifyMultipleTestCasesConstraints() {
        set<string> unsatisfiedConstraintDescriptions;
        for (const Constraint& constraint : constraintSuite_.multipleTestCasesConstraints()) {
            if (!constraint.predicate()()) {
                unsatisfiedConstraintDescriptions.insert(constraint.description());
            }
        }
        return MultipleTestCasesConstraintsVerificationResult(unsatisfiedConstraintDescriptions);
    }
};

}


text:
from ctypes import *
from comtypes import IUnknown, COMObject, COMError
from comtypes.hresult import *
from comtypes.typeinfo import LoadRegTypeLib
from comtypes.connectionpoints import IConnectionPoint
from comtypes.automation import IDispatch

import logging
logger = logging.getLogger(__name__)

__all__ = ["ConnectableObjectMixin"]

class ConnectionPointImpl(COMObject):
    """This object implements a connectionpoint"""
    _com_interfaces_ = [IConnectionPoint]

    def __init__(self, sink_interface, sink_typeinfo):
        super(ConnectionPointImpl, self).__init__()
        self._connections = {}
        self._cookie = 0
        self._sink_interface = sink_interface
        self._typeinfo = sink_typeinfo

    # per MSDN, all interface methods *must* be implemented, E_NOTIMPL
    # is no allowed return value

    def IConnectionPoint_Advise(self, this, pUnk, pdwCookie):
        if not pUnk or not pdwCookie:
            return E_POINTER
        logger.debug("Advise")
        try:
            ptr = pUnk.QueryInterface(self._sink_interface)
        except COMError:
            return CONNECT_E_CANNOTCONNECT
        pdwCookie[0] = self._cookie = self._cookie + 1
        self._connections[self._cookie] = ptr
        return S_OK

    def IConnectionPoint_Unadvise(self, this, dwCookie):
        logger.debug("Unadvise %s", dwCookie)
        try:
            del self._connections[dwCookie]
        except KeyError:
            return CONNECT_E_NOCONNECTION
        return S_OK

    def IConnectionPoint_GetConnectionPointContainer(self, this, ppCPC):
        return E_NOTIMPL

    def IConnectionPoint_GetConnectionInterface(self, this, pIID):
        return E_NOTIMPL

    def _call_sinks(self, name, *args, **kw):
        results = []
        logger.debug("_call_sinks(%s, %s, *%s, **%s)", self, name, args, kw)
        # Is it an IDispatch derived interface?  Then, events have to be delivered
        # via Invoke calls (even if it is a dual interface).
        if hasattr(self._sink_interface, "Invoke"):
            # for better performance, we could cache the dispids.
            dispid = self._typeinfo.GetIDsOfNames(name)[0]
            for key, p in self._connections.items():
                try:
                    result = p.Invoke(dispid, *args, **kw)
                except COMError, details:
                    if details.hresult == -2147023174:
                        logger.warning("_call_sinks(%s, %s, *%s, **%s) failed; removing connection",
                                       self, name, args, kw,
                                       exc_info=True)
                        try:
                            del self._connections[key]
                        except KeyError:
                            pass # connection already gone
                    else:
                        logger.warning("_call_sinks(%s, %s, *%s, **%s)", self, name, args, kw,
                                       exc_info=True)
                else:
                    results.append(result)
        else:
            for p in self._connections.values():
                try:
                    result = getattr(p, name)(*args, **kw)
                except COMError, details:
                    if details.hresult == -2147023174:
                        logger.warning("_call_sinks(%s, %s, *%s, **%s) failed; removing connection",
                                       self, name, args, kw,
                                       exc_info=True)
                        del self._connections[key]
                    else:
                        logger.warning("_call_sinks(%s, %s, *%s, **%s)", self, name, args, kw,
                                       exc_info=True)
                else:
                    results.append(result)
        return results

class ConnectableObjectMixin(object):
    """Mixin which implements IConnectionPointContainer.

    Call Fire_Event(interface, methodname, *args, **kw) to fire an
    event.  <interface> can either be the source interface, or an
    integer index into the _outgoing_interfaces_ list.
    """
    def __init__(self):
        super(ConnectableObjectMixin, self).__init__()
        self.__connections = {}

        tlib = LoadRegTypeLib(*self._reg_typelib_)
        for itf in self._outgoing_interfaces_:
            typeinfo = tlib.GetTypeInfoOfGuid(itf._iid_)
            self.__connections[itf] = ConnectionPointImpl(itf, typeinfo)

    def IConnectionPointContainer_EnumConnectionPoints(self, this, ppEnum):
        # according to MSDN, E_NOTIMPL is specificially disallowed
        # because, without typeinfo, there's no way for the caller to
        # find out.
        return E_NOTIMPL

    def IConnectionPointContainer_FindConnectionPoint(self, this, refiid, ppcp):
        iid = refiid[0]
        logger.debug("FindConnectionPoint %s", iid)
        if not ppcp:
            return E_POINTER
        for itf in self._outgoing_interfaces_:
            if itf._iid_ == iid:
                # 'byref' will not work in this case, since the QueryInterface
                # method implementation is called on Python directly. There's
                # no C layer between which will convert the second parameter
                # from byref() to pointer().
                conn = self.__connections[itf]
                result = conn.IUnknown_QueryInterface(None, pointer(IConnectionPoint._iid_), ppcp)
                logger.debug("connectionpoint found, QI() -> %s", result)
                return result
        logger.debug("No connectionpoint found")
        return CONNECT_E_NOCONNECTION

    def Fire_Event(self, itf, name, *args, **kw):
        # Fire event 'name' with arguments *args and **kw.
        # Accepts either an interface index or an interface as first argument.
        # Returns a list of results.
        logger.debug("Fire_Event(%s, %s, *%s, **%s)", itf, name, args, kw)
        if isinstance(itf, int):
            itf = self._outgoing_interfaces_[itf]
        return self.__connections[itf]._call_sinks(name, *args, **kw)


text:
:- module(server, []).
:- use_module(answers).
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_log)).

server(Port) :-
    http_server(http_dispatch, [port(Port)]).

%%  Set up a dispatch server on the 8080 port.
:- server(1337).

%%  A predicate that sends a request to our answering predicate.
response(Request) :-
    %%  The query string from the GET-request is split into
    %%  'name/value pairs'-list and is contained in the search
    %%  term. We get value of 'q' by claiming that Request contains
    %%  search as a member and that it has a list of 1 name/value
    %%  pair, which is the pair q=Question.
    member(search([q=Question]), Request),
    %%  Log the Question to the standard httpd.log file.
    http_log('~w ~n', [Question]),
    %%  Ask for the answer to the question. The answer predicate is
    %%  defined in the answers module.
    answer(Question, Answer),
    %%  answer should return an atom so we print that atom to the log
    %%  and to the response.
    %%  The response begins with content type text/plain.
    format('Content-type: text/plain~n~n'),
    http_log('~a~n', [Answer]),
    format('~a~n', [Answer]).

%% If the response fails, just return an empty message. It is better
%% to return the wrong thing than not return anything at all.
response(_) :-
    format('Content-type: text/plain~n~n'),
    format('The wrong answer~n').

%%  Add response as the handler for the / path.
:- http_handler(/, response, []).


text:
namespace BagLib
{
    using System;
    using System.Text;
    using System.Collections.Generic;

    using CatalogueLib;
    using ExceptionLib;
    using CatalogueLib.Products;
    using CatalogueLib.Products.Enumerations;

    public class Bag : IChangeable
    {
        private ICollection<Product> productsInBag;

        public Bag()
        {
            this.ProductsInBag = new List<Product>();
            //test the bag content
            productsInBag.Add(new Laptop(44, 33, true, Brand.HP, "cpu", 3334, "video", "win", 22, 445, 6));

        }

        public ICollection<Product> ProductsInBag
        {
            get
            {
                return new List<Product>(this.productsInBag);
            }
            private set
            {
                this.productsInBag = value;
            }
        }

        public void AddProduct(Product product)
        {
            this.productsInBag.Add(product);
        }

        public void RemoveProduct(int id, Product p)
        {
            bool hasBeenRemoved = false;
            foreach (var product in this.productsInBag)
            {
                if (product.ID == id)
                {
                    this.productsInBag.Remove(product);
                    hasBeenRemoved = true;
                    break;
                }
            }
            if (!hasBeenRemoved)
            {
                throw new ProductNotFoundException("There is not such a product in your bag.");
            }
        }

        public void RemoveAll()
        {
            productsInBag.Clear();
        }

        public decimal Pay()
        {
            decimal sum = 0M;
            foreach (var product in this.productsInBag)
            {
                sum += product.Price;
            }
            RemoveAll();
            return sum;
        }

        public override string ToString()
        {
            StringBuilder products = new StringBuilder();
            foreach (var product in productsInBag)
            {
                products.Append(product.ToString());

            }
            return products.ToString();
        }
    }
}


text:
title : InformationWeek July 17, 2018
publishedBy : InformationWeek
publishedOn : July 17, 2018
link : https://www.informationweek.com/cloud/how-clouds-will-crystallize-around-blockchain/a/d-id/1332305
weight: 36
articleName : How Clouds Will Crystallize Around Blockchain
class : pressArticle
---


text:
from django.utils.importlib import import_module

from organizations.app_settings import (ORGS_INVITATION_BACKEND,
        ORGS_REGISTRATION_BACKEND)

def invitation_backend():
    # TODO exception handling
    class_module, class_name = ORGS_INVITATION_BACKEND.rsplit('.', 1)
    mod = import_module(class_module)
    return getattr(mod, class_name)()

def registration_backend():
    class_module, class_name = ORGS_REGISTRATION_BACKEND.rsplit('.', 1)
    mod = import_module(class_module)
    return getattr(mod, class_name)()


text:
package org.fife.rsta.ac.demo;

import java.awt.Toolkit;
import javax.swing.*;

/**
 * Stand-alone version of the demo.
 *
 * @author Robert Futrell
 * @version 1.0
 */
public class DemoApp extends JFrame {

	public DemoApp() {
		setRootPane(new DemoRootPane());
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setTitle("RSTA Language Support Demo Application");
		pack();
	}

	/**
	 * Called when we are made visible.  Here we request that the
	 * {@link RSyntaxTextArea} is given focus.
	 *
	 * @param visible Whether this frame should be visible.
	 */
	@Override
	public void setVisible(boolean visible) {
		super.setVisible(visible);
		if (visible) {
			((DemoRootPane)getRootPane()).focusTextArea();
		}
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					UIManager.setLookAndFeel(UIManager.
											getSystemLookAndFeelClassName());
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
				} catch (Exception e) {
					e.printStackTrace(); // Never happens
				}
				Toolkit.getDefaultToolkit().setDynamicLayout(true);
				new DemoApp().setVisible(true);
			}
		});
	}

}