text:
from murano.dsl import constants
from murano.dsl import dsl
from murano.dsl import dsl_types
from murano.dsl import exceptions
from murano.dsl import helpers
from murano.dsl.principal_objects import garbage_collector
from murano.dsl import yaql_integration

class MuranoObject(dsl_types.MuranoObject):
    def __init__(self, murano_class, owner, object_id=None, name=None,
                 known_classes=None, this=None, metadata=None):
        self._initialized = False
        self._destroyed = False
        if known_classes is None:
            known_classes = {}
        if this is None:
            self._owner = owner
        self._object_id = object_id or helpers.generate_id()
        self._type = murano_class
        self._properties = {}
        self._parents = {}
        self._this = this
        self._name = name
        self._extension = None
        self._executor = helpers.weak_ref(helpers.get_executor())
        self._config = murano_class.package.get_class_config(
            murano_class.name)
        self._metadata = metadata
        if not isinstance(self._config, dict):
            self._config = {}
        known_classes[murano_class.name] = self
        for parent_class in murano_class.parents:
            name = parent_class.name
            if name not in known_classes:
                obj = MuranoObject(
                    parent_class, owner,
                    object_id=self._object_id,
                    known_classes=known_classes, this=self.real_this)

                self._parents[name] = known_classes[name] = obj
            else:
                self._parents[name] = known_classes[name]
        self._destruction_dependencies = []

    @property
    def extension(self):
        return self._extension

    @property
    def name(self):
        return self.real_this._name

    @property
    def metadata(self):
        return self.real_this._metadata

    @extension.setter
    def extension(self, value):
        self._extension = value

    def initialize(self, context, params, used_names=None):
        context = context.create_child_context()
        context[constants.CTX_ALLOW_PROPERTY_WRITES] = True
        object_store = helpers.get_object_store()
        for property_name in self.type.properties:
            spec = self.type.properties[property_name]
            if spec.usage == dsl_types.PropertyUsages.Config:
                if property_name in self._config:
                    property_value = self._config[property_name]
                else:
                    property_value = dsl.NO_VALUE
                self.set_property(property_name, property_value,
                                  dry_run=self._initialized)

        init = self.type.methods.get('.init')
        used_names = used_names or set()
        names = set(self.type.properties)
        if init:
            names.update(init.arguments_scheme.keys())
        last_errors = len(names)
        init_args = {}
        while True:
            errors = 0
            for property_name in names:
                if init and property_name in init.arguments_scheme:
                    spec = init.arguments_scheme[property_name]
                    is_init_arg = True
                else:
                    spec = self.type.properties[property_name]
                    is_init_arg = False

                if property_name in used_names:
                    continue
                if spec.usage in (dsl_types.PropertyUsages.Config,
                                  dsl_types.PropertyUsages.Static):
                    used_names.add(property_name)
                    continue
                if spec.usage == dsl_types.PropertyUsages.Runtime:
                    if not spec.has_default:
                        used_names.add(property_name)
                        continue
                    property_value = dsl.NO_VALUE
                else:
                    property_value = params.get(property_name, dsl.NO_VALUE)
                try:
                    if is_init_arg:
                        init_args[property_name] = property_value
                    else:
                        self.set_property(
                            property_name, property_value, context,
                            dry_run=self._initialized)
                    used_names.add(property_name)
                except exceptions.UninitializedPropertyAccessError:
                    errors += 1
                except exceptions.ContractViolationException:
                    if spec.usage != dsl_types.PropertyUsages.Runtime:
                        raise
            if not errors:
                break
            if errors >= last_errors:
                raise exceptions.CircularExpressionDependenciesError()
            last_errors = errors

        if (not object_store.initializing and
                self._extension is None and
                not self._initialized and
                not self._destroyed and
                not helpers.is_objects_dry_run_mode()):
            method = self.type.methods.get('__init__')
            if method:
                filtered_params = yaql_integration.filter_parameters(
                    method.body, **params)
                yield lambda: method.invoke(
                    self, filtered_params[0], filtered_params[1], context)

        for parent in self._parents.values():
            for t in parent.initialize(context, params, used_names):
                yield t

        def run_init():
            if init:
                context[constants.CTX_ARGUMENT_OWNER] = self.real_this
                init.invoke(self.real_this, (), init_args,
                            context.create_child_context())
            self._initialized = True

        if (not object_store.initializing and
                not helpers.is_objects_dry_run_mode() and
                not self._initialized and
                not self._destroyed):
            yield run_init

    @property
    def object_id(self):
        return self._object_id

    @property
    def type(self):
        return self._type

    @property
    def owner(self):
        if self._this is None:
            return self._owner
        else:
            return self.real_this.owner

    @property
    def real_this(self):
        return self._this or self

    @property
    def executor(self):
        return self._executor()

    @property
    def initialized(self):
        return self._initialized

    @property
    def destruction_dependencies(self):
        return self._destruction_dependencies

    def load_dependencies(self, dependencies):
        self._destruction_dependencies = []
        if not dependencies:
            return
        destruction_dependencies = dependencies.get('onDestruction', [])
        object_store = helpers.get_object_store()
        for record in destruction_dependencies:
            subscriber_id = record['subscriber']
            subscriber = object_store.get(subscriber_id)
            if not subscriber:
                continue
            garbage_collector.GarbageCollector.subscribe_destruction(
                self, subscriber, record.get('handler'))

    def get_property(self, name, context=None):
        start_type, derived = self.type, False
        caller_class = None if not context else helpers.get_type(context)
        if caller_class is not None and caller_class.is_compatible(self):
            start_type, derived = caller_class, True

        declared_properties = start_type.find_properties(
            lambda p: p.name == name)
        if len(declared_properties) > 0:
            spec = self.real_this.type.find_single_property(name)
            if spec.usage == dsl_types.PropertyUsages.Static:
                return self.executor.get_static_property(
                    spec.declaring_type, name, context)
            else:
                return self.real_this._get_property_value(name)
        elif derived:
            return self.cast(caller_class)._get_property_value(name)
        else:
            raise exceptions.PropertyReadError(name, start_type)

    def _get_property_value(self, name):
        try:
            return self._properties[name]
        except KeyError:
            raise exceptions.UninitializedPropertyAccessError(
                name, self.type)

    def set_property(self, name, value, context=None, dry_run=False):
        start_type, derived = self.real_this.type, False
        caller_class = None if not context else helpers.get_type(context)
        if caller_class is not None and caller_class.is_compatible(self):
            start_type, derived = caller_class, True
        if context is None:
            context = self.executor.create_object_context(self)
        declared_properties = start_type.find_properties(
            lambda p: p.name == name)
        if len(declared_properties) > 0:
            ultimate_spec = self.real_this.type.find_single_property(name)
            property_list = list(self._list_properties(name))
            for spec in property_list:
                if (caller_class is not None and not
                        helpers.are_property_modifications_allowed(context) and
                        (spec.usage not in dsl_types.PropertyUsages.Writable or
                            not derived)):
                    raise exceptions.NoWriteAccessError(name)

                if spec.usage == dsl_types.PropertyUsages.Static:
                    default = None
                else:
                    default = self._config.get(name, spec.default)

                if spec is ultimate_spec:
                    value = spec.transform(
                        value, self.real_this,
                        self.real_this, context, default=default,
                        finalize=len(property_list) == 1)
                else:
                    spec.validate(value, self.real_this, context, default)
            if len(property_list) > 1:
                value = ultimate_spec.finalize(value, self.real_this, context)
            if ultimate_spec.usage == dsl_types.PropertyUsages.Static:
                self.executor.set_static_property(
                    ultimate_spec.declaring_type, name, value, context,
                    dry_run=dry_run)
            elif not dry_run:
                self.real_this._properties[name] = value
        elif derived:
            if not dry_run:
                obj = self.cast(caller_class)
                obj._properties[name] = value
        else:
            raise exceptions.PropertyWriteError(name, start_type)

    def cast(self, cls):
        for p in helpers.traverse(self, lambda t: t._parents.values()):
            if p.type == cls:
                return p
        raise TypeError('Cannot cast {0} to {1}'.format(self.type, cls))

    def _list_properties(self, name):
        for p in helpers.traverse(
                self.real_this, lambda t: t._parents.values()):
            if name in p.type.properties:
                yield p.type.properties[name]

    def __repr__(self):
        return '<{0}/{1} {2} ({3})>'.format(
            self.type.name, self.type.version, self.object_id, id(self))

    def to_dictionary(self, include_hidden=False,
                      serialization_type=dsl_types.DumpTypes.Serializable,
                      allow_refs=False, with_destruction_dependencies=False):
        context = helpers.get_context()
        result = {}
        for parent in self._parents.values():
            result.update(parent.to_dictionary(
                include_hidden, dsl_types.DumpTypes.Serializable,
                allow_refs))
        skip_usages = (dsl_types.PropertyUsages.Runtime,
                       dsl_types.PropertyUsages.Config)
        for property_name in self.type.properties:
            if property_name in self.real_this._properties:
                spec = self.type.properties[property_name]
                if spec.usage not in skip_usages or include_hidden:
                    prop_value = self.real_this._properties[property_name]
                    if isinstance(prop_value, MuranoObject) and allow_refs:
                        meta = [m for m in spec.get_meta(context)
                                if m.type.name == ('io.murano.metadata.'
                                                   'engine.Serialize')]
                        if meta and meta[0].get_property(
                                'as', context) == 'reference':
                            prop_value = prop_value.object_id
                    result[property_name] = prop_value
        if serialization_type == dsl_types.DumpTypes.Inline:
            result.pop('?')
            result = {
                self.type: result,
                'id': self.object_id,
                'name': self.name,
                'metadata': self.metadata
            }
            header = result
        else:
            if serialization_type == dsl_types.DumpTypes.Mixed:
                result.update({'?': {
                    'type': self.type,
                    'id': self.object_id,
                    'name': self.name,
                    'metadata': self.metadata
                }})
            else:
                result.update({'?': {
                    'type': helpers.format_type_string(self.type),
                    'id': self.object_id,
                    'name': self.name,
                    'metadata': self.metadata
                }})
            header = result['?']
        if self.destroyed:
            header['destroyed'] = True
        if with_destruction_dependencies:
            dds = []
            for record in self.destruction_dependencies:
                subscriber = record['subscriber']()
                if not subscriber or self.executor.object_store.is_doomed(
                        subscriber):
                    continue
                dds.append({
                    'subscriber': subscriber.object_id,
                    'handler': record['handler']
                })
            if dds:
                header.setdefault('dependencies', {})['onDestruction'] = dds
        return result

    def mark_destroyed(self, clear_data=False):
        self._destroyed = True
        self._suppress__del__ = None
        if clear_data or not self.initialized:
            self._extension = None
            self._properties = None
            self._owner = None
            self._destruction_dependencies = None
            self._this = None
        for p in self._parents.values():
            p.mark_destroyed(clear_data)

    @property
    def destroyed(self):
        return self._destroyed

class RecyclableMuranoObject(MuranoObject):
    def __init__(self, *args, **kwargs):
        # Create self-reference to prevent __del__ from being called
        # automatically when there are no other objects referring to this one.
        # Without this reference __del__ will get called immediately after
        # reference counter will go to 0 and the object will put itself into
        # pending list creating another reference to itself and thus preventing
        # its child objects from being deleted. After the .destroy method
        # child objects will become eligible for destruction but will be
        # unable to use find() method since their owner will be destroyed
        # and collected at that point. With this reference gc.collect()
        # will collect the whole object graph at once and then we could
        # sort it and destroy in the correct order so that child objects
        # will be destroyed first.

        self._suppress__del__ = self
        super(RecyclableMuranoObject, self).__init__(*args, **kwargs)

    def __del__(self):
        # For Py2 the purpose of __del__ (in combination with _suppress__del__)
        # method is just to prevent object from being released automatically.
        # In Py3 the gc.collect list will be empty and __del__ will be called
        # for objects that were not destroyed yet.
        if self._this is None and self._initialized and not self._destroyed:
            self.executor.object_store.schedule_object_destruction(self)

    def mark_destroyed(self, clear_data=False):
        self.executor.attribute_store.forget_object(self)
        super(RecyclableMuranoObject, self).mark_destroyed(clear_data)


text:
package com.nisoft.inspectortools.ui.base;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.nisoft.inspectortools.R;
import com.nisoft.inspectortools.ui.settings.ContactsFragment;

/**
 * Created by NewIdeaSoft on 2017/7/9.
 */

public class ChooseMemberDialog extends DialogFragment {

    public static ChooseMemberDialog newInstance(String parentId) {
        Bundle args = new Bundle();
        args.putString("parent_id",parentId);
        ChooseMemberDialog fragment = new ChooseMemberDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_contacts, container, false);
        FragmentManager fm = getChildFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.contact_fragment_content);
        if (fragment == null) {
            String parentId = getArguments().getString("parent_id");
            fragment = ContactsFragment.newInstance(parentId);
            fragment.setTargetFragment(getTargetFragment(),getTargetRequestCode());
            fm.beginTransaction().add(R.id.contact_fragment_content, fragment).commit();
        }
//        this.setStyle(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_DeviceDefault_DialogWhenLarge);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.95),(int) (dm.heightPixels * 0.80) );
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

final class DifferentialExportPatchFieldSpecification
  extends DifferentialFieldSpecification {

  public function shouldAppearOnRevisionView() {
    return true;
  }

  public function renderLabelForRevisionView() {
    return 'Export Patch:';
  }

  public function renderValueForRevisionView() {
    $revision = $this->getRevision();
    return phutil_tag(
      'tt',
      array(),
      'arc export --revision '.$revision->getID());
  }

}


text:
package com.ramzcalender.sample;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.ramzcalender.RWeekCalendar;

/**
 * Created by munnaz on 24/12/16.
 */

public class SelectionActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selection_row);

    }

    /*Select the normal calender*/
    public void normalCalender(View v)
    {
        startActivity(new Intent(SelectionActivity.this,Sample.class).putExtra(RWeekCalendar.CALENDER_TYPE,RWeekCalendar.NORMAL_CALENDER));
    }

    /*Select the fdf calender*/
    public void dayCalender(View v)
    {
        startActivity(new Intent(SelectionActivity.this,Sample.class).putExtra(RWeekCalendar.CALENDER_TYPE,RWeekCalendar.FDF_CALENDER));
    }
}


text:
layout: post
title:  "Creating a Theme"
date:   2016-12-15
categories: [jekyll, update]
comments: true
featured: true
---

Jekyll has an extensive theme system, which allows you to leverage community-maintained templates and styles to customize your site's presentation. Jekyll themes package layouts, includes, and stylesheets in a way that can be overridden by your site's content.

Installing a theme

To install a theme, first, add the theme to your site's Gemfile:
		{% highlight code %}gem "my-awesome-theme"{% endhighlight %}

Save the changes to you Gemfile

Run the command bundle install to install the theme

Finally, activate the theme by adding the following to your site's _config.yml:
		{% highlight code %}theme: my-awesome-theme{% endhighlight %}

You can have multiple themes listed in your site's Gemfile, but only one theme can be selected in your site's _config.yml.

Overriding theme defaults

Jekyll themes set default layouts, includes, and stylesheets, that can be overridden by your site's content. For example, if your selected theme has a page layout, you can override the theme's layout by creating your own page layout in the _layouts folder (e.g., _layouts/page.html).

Jekyll will look first to your site's content, before looking to the theme's defaults, for any requested file in the following folders:

/_assets

/_layouts

/_includes

/_sass

Refer to your selected theme's documentation and source repository for more information on what files you can override.

To locate theme's files on your computer, run bundle show followed by the name of the theme's gem, e.g. bundle show minima for default Jekyll's theme. Then copy the files you want to override, from the returned path to your root folder.

Creating a theme

Jekyll themes are distributed as Ruby gems. Don't worry, Jekyll will help you scaffold a new theme with the new-theme command. Just run jekyll new-theme with the theme name as an argument:

{% highlight code %}
jekyll new-theme my-awesome-theme
             create /path/to/my-awesome-theme/_layouts
             create /path/to/my-awesome-theme/_includes
             create /path/to/my-awesome-theme/_sass
             create /path/to/my-awesome-theme/_layouts/page.html
             create /path/to/my-awesome-theme/_layouts/post.html
             create /path/to/my-awesome-theme/_layouts/default.html
             create /path/to/my-awesome-theme/Gemfile
             create /path/to/my-awesome-theme/my-awesome-theme.gemspec
             create /path/to/my-awesome-theme/README.md
             create /path/to/my-awesome-theme/LICENSE.txt
         initialize /path/to/my-awesome-theme/.git
             create /path/to/my-awesome-theme/.gitignore
Your new Jekyll theme, my-awesome-theme, is ready for you in /path/to/my-awesome-theme!
For help getting started, read /path/to/my-awesome-theme/README.md.
{% endhighlight %}

Add your template files in the corresponding folders, complete the .gemspec and the README files according to your needs.

Layouts and includes

Theme layouts and includes work just like they work in any Jekyll site. Place layouts in your theme's /_layouts folder, and place includes in your themes /_includes folder.

For example, if your theme has a /_layouts/page.html file, and a page has layout: page in its YAML front matter, Jekyll will first look to the site's _layouts folder for a the page layout, and if none exists, will use your theme's page layout.

Assets

Any file in /assets will be copied over to the user's site upon build unless they have a file with the same relative path. You may ship any kind of asset here: SCSS, an image, a webfont, etc. These files behave just like pages and static files in Jekyll: if the file has YAML front matter at the top, then it will be rendered. If it does not have YAML front matter, it will simply be copied over into the resulting site. This allows theme creators to ship a default /assets/styles.scss file which their layouts can depend on as /assets/styles.css.

All files in /assets will be output into the compiled site in the /assets folder just as you'd expect from using Jekyll on your sites.

Stylesheets

Your theme's stylesheets should be placed in your theme's /_sass folder, again, just as you would when authoring a Jekyll site. Your theme's styles can be included in the user's stylesheet using the @import directive.

Documenting your theme

Your theme should include a /README.md file, which explains how site authors can install and use your theme. What layouts are included? What includes? Do they need to add anything special to their site's configuration file?

Adding a screenshot

Themes are visual. Show users what your theme looks like by including a screenshot as /screenshot.png within your theme's repository where it can be retrieved programatically. You can also include this screenshot within your theme's documentation.

Previewing your theme

To preview your theme as you're authoring it, it may be helpful to add dummy content in, for example, /index.html and page.html files. This will allow you to use the jekyll build and jekyll serve commands to preview your theme, just as you'd preview a Jekyll site.

If you do preview your theme locally, be sure to add /_site to your theme's .gitignore file to prevent the compiled site from also being included when you distribute your theme.

Publishing your theme

Themes are published via [RubyGems.org][rubygems]. You'll need a [RubyGems account][rubygems-account], which you can create for free.

First, package your theme, by running the following command, replacing my-awesome-theme with the name of your theme:
		{% highlight code %}gem build my-awesome-theme.gemspec{% endhighlight %}

Next, push your packaged theme up to the RubyGems service, by running the following command, again replacing my-awesome-theme with the name of your theme:
		{% highlight code %}gem push my-awesome-theme-*.gem {% endhighlight %}

To release a new version of your theme, simply update the version number in the gemspec file, ( my-awesome-jekyll-theme.gemspec in this example ), and then repeat Steps 1 & 2 above. We recommend that you follow Semantic Versioning while bumping your theme-version.

[rubygems]: https://rubygems.org
[rubygems-account]: https://rubygems.org/sign_up
[semver]: https://semver.org


text:
* Hot module replacement for
    * Javascript over Fable (with source map support)
    * Css over stylus preprocessor
* Templating of your `index.html`
* Serving static files from `img/` folder


text:
/* 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.
 */
package org.camunda.bpm.engine.impl.interceptor;

import org.camunda.bpm.engine.impl.cfg.TransactionContextFactory;

/**
 *
This {@link CommandContextFactory} allows to explicitly pass in a {@link TransactionContextFactory}.

 *
 * @author Daniel Meyer
 *
 */
public class TxContextCommandContextFactory extends CommandContextFactory {

  protected TransactionContextFactory transactionContextFactory;

  public TxContextCommandContextFactory() {
  }

  public CommandContext createCommandContext(Command<?> cmd) {
    return new CommandContext(cmd, processEngineConfiguration, transactionContextFactory);
  }

  public TransactionContextFactory getTransactionContextFactory() {
    return transactionContextFactory;
  }

  public void setTransactionContextFactory(TransactionContextFactory transactionContextFactory) {
    this.transactionContextFactory = transactionContextFactory;
  }

}


text:
* 编辑 `project.properties`,写入一个 `Proguard` 配置. Example:
```
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
```

* 编辑这个文件,填入以下内容:

```
# Fyber

-keep class com.fyber.** { *; }
-dontwarn com.fyber.**
-keep class com.sponsorpay.mediation.** { *;}
-keepattributes JavascriptInterface
-keep class com.sponsorpay.publisher.mbe.mediation.SPBrandEngageMediationJSInterface {
    void setValue(java.lang.String);
}
-keep class android.webkit.JavascriptInterface

# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# google play service
-keep class com.google.android.gms.** { *; }
-dontwarn com.google.android.gms.**

-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}

#sdkbox
-keep class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**
```

 __注意:__ 混淆只在 __Release__ 模式下有效 (比如 `cocos run -m release`), 在 debug 模式下,不会调到混淆规则.


text:
function putContent(collectionId, path, content, success, error, recursive) {
  postContent(collectionId, path, content, true, recursive,
    onSuccess = function () {
      if(success) {
        success();
      }
    },
    onError = function (response) {
      if (error) {
        error(response);
      }
      else {
        handleApiError(response);
      }
    }
  );
}


text:
layout: post
title: Vertical hopper compositions paper out on IJRR
categories: [robots, papers]
---

Explain the paper


text:
package br.edu.ladoss.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "motivo")
@Entity
@Table(name = "tb_motivo")
@NamedQuery(name = "Motivo.getAll", query = "from Motivo")
public class Motivo {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id_motivo")
	private Integer id;

	@Column(name = "nm_motivo")
	private String nome;

	@Column(name = "is_definitivo", columnDefinition = "boolean default false",
			nullable = false, insertable = true, updatable = true)
	private boolean defitivo;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public boolean isDefitivo() {
		return defitivo;
	}

	public void setDefitivo(boolean defitivo) {
		this.defitivo = defitivo;
	}

	@Override
	public String toString() {
		return "Motivo [id=" + id
				+ ", nome=" + nome
				+ ", definitivo=" + defitivo
				+ "]";
	}
}


text:
Services

Print and Production

Already have a designed project and need to hand it off to get bids, printing and finishing? I can manage your project. Or want to know more? See my prepress class materials

Design and Illustration

Need help from the concept phase? I can help design and implement your project from start to print and beyond.

Web Design

Want a site designed for web and mobile?


text:
package org.tiefaces.exception;

/**
 * Exception Object.
 *
 * @author Jason Jiang
 */
public class AddRowException extends RuntimeException {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/**
	 * Instantiates a new evaluation exception.
	 */
	public AddRowException() {
		super();
	}

	/**
	 * Instantiates a new evaluation exception.
	 *
	 * @param message
	 *            the message
	 * @param cause
	 *            the cause
	 */
	public AddRowException(final String message, final Throwable cause) {
		super(message, cause);
	}

    /**
     * Instantiates a new evaluation exception.
     *
     * @param message
     *            the message
     */
    public AddRowException(final String message) {
        super(message);
    }

}


text:
#import <UIKit/UIKit.h>

@interface UIImage (Snapshot)

/// Uses renderInContext: to get a snapshot of the layer.
+ (UIImage *)fb_imageForLayer:(CALayer *)layer;

/// Uses renderInContext: to get a snapshot of the view layer.
+ (UIImage *)fb_imageForViewLayer:(UIView *)view;

/// Uses drawViewHierarchyInRect: to get a snapshot of the view and adds the view into a window if needed.
+ (UIImage *)fb_imageForView:(UIView *)view;

@end


text:
package com.datastax.oss.driver.api.querybuilder.schema;

import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.type.DataType;
import com.datastax.oss.driver.api.core.type.DataTypes;
import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
import edu.umd.cs.findbugs.annotations.NonNull;

public interface OngoingCreateType {

  /**
   * Adds a field definition in the CREATE TYPE statement.
   *
   *
Fields keys are added in the order of their declaration.
   *
   *
To create the data type, use the constants and static methods in {@link DataTypes}, or
   * {@link SchemaBuilder#udt(CqlIdentifier, boolean)}.
   */
  @NonNull
  CreateType withField(@NonNull CqlIdentifier identifier, @NonNull DataType dataType);

  /**
   * Shortcut for {@link #withField(CqlIdentifier, DataType)} (CqlIdentifier, DataType)
   * withField(CqlIdentifier.asCql(columnName), dataType)}.
   */
  @NonNull
  default CreateType withField(@NonNull String columnName, @NonNull DataType dataType) {
    return withField(CqlIdentifier.fromCql(columnName), dataType);
  }
}


text:
import React from 'react';
import { keyframes } from 'emotion';
import styled from 'react-emotion';
import PropTypes from 'prop-types';
import { withTheme } from 'theming';

const type = keyframes`
  from { width: 0; }
`;
const TypingDiv = styled('p')`
  font-family: 'Courier';
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0 0 10px;
  white-space: nowrap;
  overflow: hidden;
  width: 30em;
  animation: ${type} 4s 1s ease infinite;
`;

const Typing = ({ text }) => <TypingDiv>{text}</TypingDiv>;

/* Props Check */
Typing.propTypes = {
  /**
   * Typing text
   */
  text: PropTypes.string,
};

/* Deafult Props */
Typing.defaultProps = {
  text: 'Typing text content',
};

export default withTheme(Typing);


text:
use itertools::FoldWhile::{Continue, Done};

use itertools::Itertools;

/// Map across the iterator, terminating early if a mapping returns None
pub fn map_while_some<A, E>(iter: &mut Iterator<Item = E>, f: &Fn(E) -> Option<A>) -> Option<Vec<A>> {
    let mut results: Vec<A> = Vec::new();
    for x in iter {
        if let Some(result) = f(x) {
            results.push(result);
        } else {
            return None;
        }
    }
    return Some(results);
}

pub fn fold_while_some<A, E>(init_acc: A, iter: &mut Iterator<Item = E>, f: &Fn(A, E) -> Option<A>) -> Option<A> {
    iter.fold_while(Some(init_acc), |acc, x| match f(acc.unwrap(), x) {
        Some(value) => Continue(Some(value)),
        None => Done(None),
    })
}

/// Create a string with the specified number of tabs
pub fn concat_tabs(ntabs: usize) -> String {
    let tabv: Vec<String> = (0..ntabs).map(|_| "\t".to_string()).collect();
    tabv.join("")
}


text:
'use strict';
/**
 * Log management.
 */

const BbPromise = require('bluebird');
const _ = require('lodash');
const chalk = require('chalk');
const moment = require('moment');
const os = require('os');

function getApiLogGroupName(apiId, alias) {
	return `API-Gateway-Execution-Logs_${apiId}/${alias}`;
}

module.exports = {

	logsValidate() {
		this._lambdaName = this._serverless.service.getFunction(this.options.function).name;
		this._options.logGroupName = this._provider.naming.getLogGroupName(this._lambdaName);
		this._options.interval = this._options.interval || 1000;

		return BbPromise.resolve();
	},

	apiLogsValidate() {
		if (this.options.function) {
			return BbPromise.reject(new this.serverless.classes.Error('--function is not supported for API logs.'));
		}

		// Retrieve APIG id
		return this.aliasStacksDescribeResource('ApiGatewayRestApi')
		.then(resources => {
			if (_.isEmpty(resources.StackResources)) {
				return BbPromise.reject(new this.serverless.classes.Error('service does not contain any API'));
			}

			const apiResource = _.first(resources.StackResources);
			const apiId = apiResource.PhysicalResourceId;
			this._apiLogsLogGroup = getApiLogGroupName(apiId, this._alias);
			this._options.interval = this._options.interval || 1000;

			this.options.verbose && this.serverless.cli.log(`API id: ${apiId}`);
			this.options.verbose && this.serverless.cli.log(`Log group: ${this._apiLogsLogGroup}`);

			return BbPromise.resolve();
		});
	},

	logsGetLogStreams() {
		const params = {
			logGroupName: this._options.logGroupName,
			descending: true,
			limit: 50,
			orderBy: 'LastEventTime',
		};

		let aliasGetAliasFunctionVersion;
		// Check if --version is specified
		if (this._options.version) {
			aliasGetAliasFunctionVersion = BbPromise.resolve(this._options.version);
		} else {
			aliasGetAliasFunctionVersion = this.aliasGetAliasLatestFunctionVersionByFunctionName(this._alias, this._lambdaName);
		}
		// Get currently deployed function version for the alias to
		// setup the stream filter correctly
		return aliasGetAliasFunctionVersion
		.then(version => {
			if (!version) {
				return BbPromise.reject(new this.serverless.classes.Error('Function alias not found.'));
			}

			return this.provider
				.request('CloudWatchLogs',
					'describeLogStreams',
					params,
					this.options.stage,
					this.options.region)
				.then(reply => {
					if (!reply || _.isEmpty(reply.logStreams)) {
						throw new this.serverless.classes
							.Error('No existing streams for the function alias');
					}
					const logStreamNames = _.map(
						_.filter(reply.logStreams, stream => _.includes(stream.logStreamName, `[${version}]`)),
						stream => stream.logStreamName);

					if (_.isEmpty(logStreamNames)) {
						return BbPromise.reject(new this.serverless.classes.Error('No existing streams for this function version. If you want to view logs of a specific function version, please use --version'));
					}
					return logStreamNames;
				});
		});
	},

	apiLogsGetLogStreams() {
		const params = {
			logGroupName: this._apiLogsLogGroup,
			descending: true,
			limit: 50,
			orderBy: 'LastEventTime',
		};

		return this.provider.request(
			'CloudWatchLogs',
			'describeLogStreams',
			params,
			this.options.stage,
			this.options.region
		)
		.then(reply => {
			if (!reply || _.isEmpty(reply.logStreams)) {
				return BbPromise.reject(new this.serverless.classes.Error('No logs exist for the API'));
			}

			return _.map(reply.logStreams, stream => stream.logStreamName);
		});

	},

	apiLogsShowLogs(logStreamNames) {
		const formatApiLogEvent = event => {
			const dateFormat = 'YYYY-MM-DD HH:mm:ss.SSS (Z)';
			const timestamp = chalk.green(moment(event.timestamp).format(dateFormat));

			const parsedMessage = /\((.*?)\) .*/.exec(event.message);
			const header = `${timestamp} ${chalk.yellow(parsedMessage[1])}${os.EOL}`;
			const message = chalk.gray(_.replace(event.message, /\(.*?\) /, ''));
			return `${header}${message}${os.EOL}`;
		};

		return this.logsShowLogs(logStreamNames, formatApiLogEvent, this.apiLogsGetLogStreams.bind(this));
	},

	functionLogsShowLogs(logStreamNames) {
		const formatLambdaLogEvent = event => {
			const msgParam = event.message;
			let msg = msgParam;
			const dateFormat = 'YYYY-MM-DD HH:mm:ss.SSS (Z)';

			if (_.startsWith(msg, 'REPORT')) {
				msg += os.EOL;
			}

			if (_.startsWith(msg, 'START') || _.startsWith(msg, 'END') || _.startsWith(msg, 'REPORT')) {
				return chalk.gray(msg);
			} else if (_.trim(msg) === 'Process exited before completing request') {
				return chalk.red(msg);
			}

			const splitted = _.split(msg, '\t');

			if (splitted.length < 3 || new Date(splitted[0]) === 'Invalid Date') {
				return msg;
			}
			const reqId = splitted[1];
			const time = chalk.green(moment(splitted[0]).format(dateFormat));
			const text = _.split(msg, `${reqId}\t`)[1];

			return `${time}\t${chalk.yellow(reqId)}\t${text}`;
		};

		return this.logsShowLogs(logStreamNames, formatLambdaLogEvent, this.logsGetLogStreams.bind(this));
	},

	logsShowLogs(logStreamNames, formatter, getLogStreams) {
		if (!logStreamNames || !logStreamNames.length) {
			if (this.options.tail) {
				return setTimeout((() => getLogStreams()
					.then(nextLogStreamNames => this.logsShowLogs(nextLogStreamNames, formatter, getLogStreams))),
				this.options.interval);
			}
		}

		const params = {
			logGroupName: this.options.logGroupName || this._apiLogsLogGroup,
			interleaved: true,
			logStreamNames,
			startTime: this.options.startTime,
		};

		if (this.options.filter) params.filterPattern = this.options.filter;
		if (this.options.nextToken) params.nextToken = this.options.nextToken;
		if (this.options.startTime) {
			const since = _.includes(['m', 'h', 'd'],
				this.options.startTime[this.options.startTime.length - 1]);
			if (since) {
				params.startTime = moment().subtract(
					_.replace(this.options.startTime, /\D/g, ''),
					_.replace(this.options.startTime, /\d/g, '')).valueOf();
			} else {
				params.startTime = moment.utc(this.options.startTime).valueOf();
			}
		}

		return this.provider
			.request('CloudWatchLogs',
				'filterLogEvents',
				params,
				this.options.stage,
				this.options.region)
			.then(results => {
				if (results.events) {
					_.forEach(results.events, e => {
						process.stdout.write(formatter(e));
					});
				}

				if (results.nextToken) {
					this.options.nextToken = results.nextToken;
				} else {
					delete this.options.nextToken;
				}

				if (this.options.tail) {
					if (results.events && results.events.length) {
						this.options.startTime = _.last(results.events).timestamp + 1;
					}

					return setTimeout((() => getLogStreams()
							.then(nextLogStreamNames => this.logsShowLogs(nextLogStreamNames, formatter, getLogStreams))),
					this.options.interval);
				}

				return BbPromise.resolve();
			});
	},

};


text:
'use strict';

describe('taskListService', function() {
  var service;
  var rootScope;

  beforeEach(function() {
    module('whatNowApp');

    inject(function($rootScope, taskListService) {
      rootScope = $rootScope;
      service = taskListService;
    });
  });

  describe('#addTask', function() {
    it('should be defined', function() {
      expect(service.addTask).toBeDefined();
    });

    it('should add a task to the task list when passed into it', function() {
      var task = 'some task';
      service.addTask(task);

      var tasks = service.getTaskList();
      expect(tasks.length).toBe(1);
      expect(tasks[0].name).toBe(task);
    });

    it('should not add the same task twice', function() {
      var task = new Task('test task');

      service.addTask(task);
      expect(service.getTaskList().length).toBe(1);

      service.addTask(task);
      expect(service.getTaskList().length).toBe(1);
    });

    it('should select the task', function() {
      var task = new Task('task');

      service.addTask(task);

      expect(task.isSelected).toBe(true);
    });

    it('should update the tasks to execute next', function() {
      var task1 = new Task('1');

      service.addTask(task1);
      rootScope.$digest();

      expect(task1.isSuggested).toBe(true);

      var task2 = new Task('2');
      task1.addPrevious(task2);
      service.addTask(task2);
      rootScope.$digest();

      expect(task1.isSuggested).toBe(false);
      expect(task2.isSuggested).toBe(true);

      var task3 = new Task('3');
      task2.addPrevious(task3);
      service.addTask(task3);
      rootScope.$digest();

      expect(task1.isSuggested).toBe(false);
      expect(task2.isSuggested).toBe(false);
      expect(task3.isSuggested).toBe(true);
    });

    it('should indicate two tasks as possible suggestions', function() {
      var task1 = new Task('1');
      var task2 = new Task('2');

      service.addTask(task1);
      rootScope.$digest();

      expect(task1.isSuggested).toBe(true);

      service.addTask(task2);
      rootScope.$digest();

      expect(task1.isSuggested).toBe(true);
      expect(task2.isSuggested).toBe(true);
    });
  });

  describe('#removeTask', function() {
    it('should be defined', function() {
      expect(service.removeTask).toBeDefined();
    });

    it('should remove the passed task from the task list', function() {
      var testTask = new Task('Testing');

      service.addTask(testTask);

      service.removeTask(testTask);

      expect(service.getTaskList().length).toBe(0);
    });

    it('should remove the dependencies for the tasks once a task is removed', function() {
      var task1 = new Task('1');
      var task2 = new Task('2');
      task2.addPrevious(task1);

      service.addTask(task1);
      service.addTask(task2);

      service.removeTask(task1);

      expect(task1.previous.length).toBe(0);
    });

    it('should throw an error if it tries to remove a task that\'s not on the list', function() {
      var task = { name: 'Testing' };

      var tryRemove = function() {
        service.removeTask(task);
      };

      expect(tryRemove).toThrow();
    });
  });

  describe('#selectTask', function() {
    it('should be defined', function() {
      expect(service.selectTask).toBeDefined();
    });

    it('should set the isSelected property on the task', function() {
      var task = new Task('test');

      service.addTask(task);
      service.selectTask(task);

      expect(task.isSelected).toBe(true);
    });

    it('should remove the isSelected property on other tasks', function() {
      var task1 = new Task('task1');
      var task2 = new Task('task2');
      task2.isSelected = true;

      service.addTask(task1);
      service.addTask(task2);

      service.selectTask(task1);

      expect(task2.isSelected).toBe(false);
    });

    it('should broadcast an event notifying the application that this task has been selected', function() {
      var task = new Task('test');
      spyOn(rootScope, '$broadcast');

      service.selectTask(task);

      expect(rootScope.$broadcast).toHaveBeenCalledWith('taskSelected', task);
    });
  });

  describe('#getPossibleDependencies', function() {
    it('should be defined', function() {
      expect(service.getPossibleDependencies).toBeDefined();
    });

    it('should return a list of tasks filtered by name', function() {
      var task1 = new Task('A');
      var task2 = new Task('B1');
      var task3 = new Task('B2');
      var task4 = new Task('task4');

      service.addTask(task1);
      service.addTask(task2);
      service.addTask(task3);
      service.addTask(task4);

      var aFiltered = service.getPossibleDependencies(task4, 'A');
      expect(aFiltered).toBeDefined();
      expect(aFiltered.length).toBe(1);
      expect(aFiltered[0]).toBe(task1);

      var bFiltered = service.getPossibleDependencies(task4, 'B');
      expect(bFiltered).toBeDefined();
      expect(bFiltered.length).toBe(2);
      expect(bFiltered[0]).toBe(task2);
      expect(bFiltered[1]).toBe(task3);
    });

    it('should not differentiate based on casing', function() {
      var task1 = new Task('A');
      var task2 = new Task('B');

      service.addTask(task1);

      var filtered = service.getPossibleDependencies(task2, 'a');

      expect(filtered.length).toBe(1);
      expect(filtered[0]).toBe(task1);
    });

    it('should not return the task being passed as an available dependency', function() {
      var task1 = new Task('A1');
      var task2 = new Task('A2');

      service.addTask(task1);
      service.addTask(task2);

      var filteredTaskList = service.getPossibleDependencies(task1, 'A');

      expect(filteredTaskList.length).toBe(1);
      expect(filteredTaskList[0]).toBe(task2);
    });

    it('should not return a task that would generate cycles if added', function() {
      // task3 --> task1 --> task2
      var task1 = new Task('A1');
      var task2 = new Task('A2');
      var task3 = new Task('A3');

      task3.addNext(task1);
      task1.addNext(task2);

      service.addTask(task1);
      service.addTask(task2);
      service.addTask(task3);

      var filteredTaskList = service.getPossibleDependencies(task3, 'A');

      expect(filteredTaskList.length).toBe(0);
    });

    it('should allow new tasks to have dependencies', function() {
      var task1 = new Task('A');
      var task2 = new Task('B');

      service.addTask(task1);

      var filteredTaskList = service.getPossibleDependencies(task2, 'A');

      expect(filteredTaskList.length).toBe(1);
      expect(filteredTaskList[0]).toBe(task1);
    });
  }); // #getPossibleDependencies
});


text:
<?php

namespace Nocks\SDK\Transformer;

use Nocks\SDK\Model\Model;
use Nocks\SDK\Model\BalanceTransfer;

class BalanceTransferTransformer implements Transformer {

	private $currencyTransformer;
	private $dateTransformer;
	private $paymentMethodTransformer;

	public function __construct() {
		$this->currencyTransformer = new CurrencyTransformer();
		$this->dateTransformer = new DateTransformer();
		$this->paymentMethodTransformer = new PaymentMethodTransformer();
	}

	/**
	 * Transform balanceTransfer
	 *
	 * @param $data
	 *
	 * @return mixed
	 */
	public function transform(array $data) {
		if (isset($data['payment_method']) && isset($data['payment_method']['data'])) {
			$data['payment_method'] = $this->paymentMethodTransformer->transform($data['payment_method']['data']);
		}

		return new BalanceTransfer($this->dateTransformer->transform($this->currencyTransformer->transform($data)));
	}

	/**
	 * Reverse transform balanceTransfer
	 *
	 * @param $balanceTransfer
	 *
	 * @return mixed
	 */
	public function reverseTransform(Model $balanceTransfer) {
		return $balanceTransfer->getData();
	}
}


text:
/**
 * Containers
 */

import ProfileView from './profile/ProfileView';
import ChangePassword from './profile/ChangePassword';
import ImageGallery from './image/ImageGallery';
import AboutView from './about/AboutView';
import ImagePreview from './image/ImagePreview';
import VideoPlayer from './video/VideoPlayer';
import CropImage from './profile/CropImage';

import Application from '../constants/config';

import NavBackAbs from '../chat/ui/NavBackAbs';
import NavBarBack from '../chat/ui/NavBarBack';

if (!Application.containers.find(item => item.key === 'aboutView')) {
  // lets init reusable containers
  // key, title, subTitle, component, nav, tab, navBar
  Application.addContainer('aboutView', 'About', '', AboutView, true, true, NavBarBack);
  Application.addContainer('profileView', 'Profile', '', ProfileView, true, true, NavBarBack);
  Application.addContainer('changePassword', 'Change Password', '', ChangePassword, true, true, null);
  Application.addContainer('imageGallery', 'Image Preview', '', ImageGallery, true, false, NavBackAbs);
  Application.addContainer('captureImagePreview', 'Image Preview', '', ImagePreview, true, true, NavBackAbs);
  Application.addContainer('videoPreviewSend', 'Video Preview Send', '', VideoPlayer, true, true, NavBackAbs);
  Application.addContainer('cropImage', 'CropImage', '', CropImage, true, true, NavBackAbs);
}

export { AboutView, ImageGallery, ProfileView, ImagePreview };


text:
	Enter your name
	<input type="text"
		[value]="item.name"
   	(change)="handleChangeName(seat, $event)"></input>
	<button (click)="greet()">Press Me</button>

{{item.greeting}}


text:
module.exports = {
  extends: "airbnb",
  env: {
    browser: true,
    jest: true,
  },
  rules: {
    "react/jsx-filename-extension": [
      1,
      {
        extensions: [
          ".js",
          ".jsx"
        ]
      }
    ],
    // Disabled until eslint-plugin-import gets proper support for webpack externals
    // https://github.com/benmosher/eslint-plugin-import/issues/479
    // https://github.com/benmosher/eslint-plugin-import/issues/605
    "import/no-extraneous-dependencies": 0,
    "import/extensions": 0,
  },
  settings: {
    "import/resolver": {
      webpack: {
        config: "webpack.config.js"
      }
    }
  }
}


text:
package network;

import java.io.PrintWriter;

public class Packet03Start extends Packet {

	public void writePacketData(PrintWriter pw) {
		pw.println(this.getPacketId());
	}

	public void readPacketData(String s) {}

}


text:
using namespace llvm;

#define DEBUG_TYPE "ipconstprop"

STATISTIC(NumArgumentsProped, "Number of args turned into constants");
STATISTIC(NumReturnValProped, "Number of return values turned into constants");

namespace {
  /// IPCP - The interprocedural constant propagation pass
  ///
  struct IPCP : public ModulePass {
    static char ID; // Pass identification, replacement for typeid
    IPCP() : ModulePass(ID) {
      initializeIPCPPass(*PassRegistry::getPassRegistry());
    }

    bool runOnModule(Module &M) override;
  private:
    bool PropagateConstantsIntoArguments(Function &F);
    bool PropagateConstantReturn(Function &F);
  };
}

char IPCP::ID = 0;
INITIALIZE_PASS(IPCP, "ipconstprop",
                "Interprocedural constant propagation", false, false)

ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }

bool IPCP::runOnModule(Module &M) {
  bool Changed = false;
  bool LocalChange = true;

  // FIXME: instead of using smart algorithms, we just iterate until we stop
  // making changes.
  while (LocalChange) {
    LocalChange = false;
    for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
      if (!I->isDeclaration()) {
        // Delete any klingons.
        I->removeDeadConstantUsers();
        if (I->hasLocalLinkage())
          LocalChange |= PropagateConstantsIntoArguments(*I);
        Changed |= PropagateConstantReturn(*I);
      }
    Changed |= LocalChange;
  }
  return Changed;
}

/// PropagateConstantsIntoArguments - Look at all uses of the specified
/// function.  If all uses are direct call sites, and all pass a particular
/// constant in for an argument, propagate that constant in as the argument.
///
bool IPCP::PropagateConstantsIntoArguments(Function &F) {
  if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.

  // For each argument, keep track of its constant value and whether it is a
  // constant or not.  The bool is driven to true when found to be non-constant.
  SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
  ArgumentConstants.resize(F.arg_size());

  unsigned NumNonconstant = 0;
  for (Use &U : F.uses()) {
    User *UR = U.getUser();
    // Ignore blockaddress uses.
    if (isa<BlockAddress>(UR)) continue;

    // Used by a non-instruction, or not the callee of a function, do not
    // transform.
    if (!isa<CallInst>(UR) && !isa<InvokeInst>(UR))
      return false;

    CallSite CS(cast<Instruction>(UR));
    if (!CS.isCallee(&U))
      return false;

    // Check out all of the potentially constant arguments.  Note that we don't
    // inspect varargs here.
    CallSite::arg_iterator AI = CS.arg_begin();
    Function::arg_iterator Arg = F.arg_begin();
    for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
         ++i, ++AI, ++Arg) {

      // If this argument is known non-constant, ignore it.
      if (ArgumentConstants[i].second)
        continue;

      Constant *C = dyn_cast<Constant>(*AI);
      if (C && ArgumentConstants[i].first == nullptr) {
        ArgumentConstants[i].first = C;   // First constant seen.
      } else if (C && ArgumentConstants[i].first == C) {
        // Still the constant value we think it is.
      } else if (*AI == &*Arg) {
        // Ignore recursive calls passing argument down.
      } else {
        // Argument became non-constant.  If all arguments are non-constant now,
        // give up on this function.
        if (++NumNonconstant == ArgumentConstants.size())
          return false;
        ArgumentConstants[i].second = true;
      }
    }
  }

  // If we got to this point, there is a constant argument!
  assert(NumNonconstant != ArgumentConstants.size());
  bool MadeChange = false;
  Function::arg_iterator AI = F.arg_begin();
  for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
    // Do we have a constant argument?
    if (ArgumentConstants[i].second || AI->use_empty() ||
        AI->hasInAllocaAttr() || (AI->hasByValAttr() && !F.onlyReadsMemory()))
      continue;

    Value *V = ArgumentConstants[i].first;
    if (!V) V = UndefValue::get(AI->getType());
    AI->replaceAllUsesWith(V);
    ++NumArgumentsProped;
    MadeChange = true;
  }
  return MadeChange;
}

// Check to see if this function returns one or more constants. If so, replace
// all callers that use those return values with the constant value. This will
// leave in the actual return values and instructions, but deadargelim will
// clean that up.
//
// Additionally if a function always returns one of its arguments directly,
// callers will be updated to use the value they pass in directly instead of
// using the return value.
bool IPCP::PropagateConstantReturn(Function &F) {
  if (F.getReturnType()->isVoidTy())
    return false; // No return value.

  // If this function could be overridden later in the link stage, we can't
  // propagate information about its results into callers.
  if (F.mayBeOverridden())
    return false;

  // Check to see if this function returns a constant.
  SmallVector<Value *,4> RetVals;
  StructType *STy = dyn_cast<StructType>(F.getReturnType());
  if (STy)
    for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
      RetVals.push_back(UndefValue::get(STy->getElementType(i)));
  else
    RetVals.push_back(UndefValue::get(F.getReturnType()));

  unsigned NumNonConstant = 0;
  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
      for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
        // Already found conflicting return values?
        Value *RV = RetVals[i];
        if (!RV)
          continue;

        // Find the returned value
        Value *V;
        if (!STy)
          V = RI->getOperand(0);
        else
          V = FindInsertedValue(RI->getOperand(0), i);

        if (V) {
          // Ignore undefs, we can change them into anything
          if (isa<UndefValue>(V))
            continue;

          // Try to see if all the rets return the same constant or argument.
          if (isa<Constant>(V) || isa<Argument>(V)) {
            if (isa<UndefValue>(RV)) {
              // No value found yet? Try the current one.
              RetVals[i] = V;
              continue;
            }
            // Returning the same value? Good.
            if (RV == V)
              continue;
          }
        }
        // Different or no known return value? Don't propagate this return
        // value.
        RetVals[i] = nullptr;
        // All values non-constant? Stop looking.
        if (++NumNonConstant == RetVals.size())
          return false;
      }
    }

  // If we got here, the function returns at least one constant value.  Loop
  // over all users, replacing any uses of the return value with the returned
  // constant.
  bool MadeChange = false;
  for (Use &U : F.uses()) {
    CallSite CS(U.getUser());
    Instruction* Call = CS.getInstruction();

    // Not a call instruction or a call instruction that's not calling F
    // directly?
    if (!Call || !CS.isCallee(&U))
      continue;

    // Call result not used?
    if (Call->use_empty())
      continue;

    MadeChange = true;

    if (!STy) {
      Value* New = RetVals[0];
      if (Argument *A = dyn_cast<Argument>(New))
        // Was an argument returned? Then find the corresponding argument in
        // the call instruction and use that.
        New = CS.getArgument(A->getArgNo());
      Call->replaceAllUsesWith(New);
      continue;
    }

    for (auto I = Call->user_begin(), E = Call->user_end(); I != E;) {
      Instruction *Ins = cast<Instruction>(*I);

      // Increment now, so we can remove the use
      ++I;

      // Find the index of the retval to replace with
      int index = -1;
      if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
        if (EV->hasIndices())
          index = *EV->idx_begin();

      // If this use uses a specific return value, and we have a replacement,
      // replace it.
      if (index != -1) {
        Value *New = RetVals[index];
        if (New) {
          if (Argument *A = dyn_cast<Argument>(New))
            // Was an argument returned? Then find the corresponding argument in
            // the call instruction and use that.
            New = CS.getArgument(A->getArgNo());
          Ins->replaceAllUsesWith(New);
          Ins->eraseFromParent();
        }
      }
    }
  }

  if (MadeChange) ++NumReturnValProped;
  return MadeChange;
}


text:
#include <stdlib.h>
#include <string.h>

#include <misc/offset.h>
#include <misc/debug.h>
#include <misc/balloc.h>
#include <structure/LinkedList1.h>
#include <structure/LinkedList3.h>

#include <ncd/module_common.h>

#include <generated/blog_channel_ncd_depend.h>

struct provide {
    NCDModuleInst *i;
    MemRef name;
    int is_queued;
    union {
        struct {
            LinkedList3Node queued_node; // node in list which begins with provide.queued_provides_firstnode
        };
        struct {
            LinkedList1Node provides_node; // node in provides
            LinkedList1 depends;
            LinkedList3Node queued_provides_firstnode;
            int dying;
        };
    };
};

struct depend {
    NCDModuleInst *i;
    MemRef name;
    struct provide *p;
    LinkedList1Node node;
};

struct global {
    LinkedList1 provides;
    LinkedList1 free_depends;
};

static struct provide * find_provide (struct global *g, MemRef name)
{
    for (LinkedList1Node *n = LinkedList1_GetFirst(&g->provides); n; n = LinkedList1Node_Next(n)) {
        struct provide *p = UPPER_OBJECT(n, struct provide, provides_node);
        ASSERT(!p->is_queued)

        if (MemRef_Equal(p->name, name)) {
            return p;
        }
    }

    return NULL;
}

static void provide_promote (struct provide *o)
{
    struct global *g = ModuleGlobal(o->i);
    ASSERT(!find_provide(g, o->name))

    // set not queued
    o->is_queued = 0;

    // insert to provides list
    LinkedList1_Append(&g->provides, &o->provides_node);

    // init depends list
    LinkedList1_Init(&o->depends);

    // set not dying
    o->dying = 0;

    // attach free depends with this name
    LinkedList1Node *n = LinkedList1_GetFirst(&g->free_depends);
    while (n) {
        LinkedList1Node *next = LinkedList1Node_Next(n);
        struct depend *d = UPPER_OBJECT(n, struct depend, node);
        ASSERT(!d->p)

        if (!MemRef_Equal(d->name, o->name)) {
            n = next;
            continue;
        }

        // remove from free depends list
        LinkedList1_Remove(&g->free_depends, &d->node);

        // insert to provide's list
        LinkedList1_Append(&o->depends, &d->node);

        // set provide
        d->p = o;

        // signal up
        NCDModuleInst_Backend_Up(d->i);

        n = next;
    }
}

static int func_globalinit (struct NCDInterpModuleGroup *group, const struct NCDModuleInst_iparams *params)
{
    // allocate global state structure
    struct global *g = BAlloc(sizeof(*g));
    if (!g) {
        BLog(BLOG_ERROR, "BAlloc failed");
        return 0;
    }

    // set group state pointer
    group->group_state = g;

    // init provides list
    LinkedList1_Init(&g->provides);

    // init free depends list
    LinkedList1_Init(&g->free_depends);

    return 1;
}

static void func_globalfree (struct NCDInterpModuleGroup *group)
{
    struct global *g = group->group_state;
    ASSERT(LinkedList1_IsEmpty(&g->free_depends))
    ASSERT(LinkedList1_IsEmpty(&g->provides))

    // free global state structure
    BFree(g);
}

static void provide_func_new_templ (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params, int event)
{
    struct global *g = ModuleGlobal(i);
    struct provide *o = vo;
    o->i = i;

    // read arguments
    NCDValRef name_arg;
    if (!NCDVal_ListRead(params->args, 1, &name_arg)) {
        ModuleLog(o->i, BLOG_ERROR, "wrong arity");
        goto fail0;
    }
    if (!NCDVal_IsString(name_arg)) {
        ModuleLog(o->i, BLOG_ERROR, "wrong type");
        goto fail0;
    }
    o->name = NCDVal_StringMemRef(name_arg);

    // signal up.
    // This comes above provide_promote(), so that effects on related depend statements are
    // computed before this process advances, avoiding problems like failed variable resolutions.
    NCDModuleInst_Backend_Up(o->i);

    // check for existing provide with this name
    struct provide *ep = find_provide(g, o->name);
    if (ep) {
        ASSERT(!ep->is_queued)

        if (!event) {
            ModuleLog(o->i, BLOG_ERROR, "a provide with this name already exists");
            goto fail0;
        }

        // set queued
        o->is_queued = 1;

        // insert to existing provide's queued provides list
        LinkedList3Node_InitAfter(&o->queued_node, &ep->queued_provides_firstnode);
    } else {
        // init first node for queued provides list
        LinkedList3Node_InitLonely(&o->queued_provides_firstnode);

        // promote provide
        provide_promote(o);
    }

    return;

fail0:
    NCDModuleInst_Backend_DeadError(i);
}

static void provide_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
    provide_func_new_templ(vo, i, params, 0);
}

static void provide_event_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
    provide_func_new_templ(vo, i, params, 1);
}

static void provide_free (struct provide *o)
{
    struct global *g = ModuleGlobal(o->i);
    ASSERT(o->is_queued || LinkedList1_IsEmpty(&o->depends))

    if (o->is_queued) {
        // remove from existing provide's queued provides list
        LinkedList3Node_Free(&o->queued_node);
    } else {
        // remove from provides list
        LinkedList1_Remove(&g->provides, &o->provides_node);

        // if we have provides queued, promote the first one
        if (LinkedList3Node_Next(&o->queued_provides_firstnode)) {
            // get first queued provide
            struct provide *qp = UPPER_OBJECT(LinkedList3Node_Next(&o->queued_provides_firstnode), struct provide, queued_node);
            ASSERT(qp->is_queued)

            // make it the head of the queued provides list
            LinkedList3Node_Free(&qp->queued_node);
            LinkedList3Node_InitAfter(&qp->queued_provides_firstnode, &o->queued_provides_firstnode);
            LinkedList3Node_Free(&o->queued_provides_firstnode);

            // promote provide
            provide_promote(qp);
        }
    }

    NCDModuleInst_Backend_Dead(o->i);
}

static void provide_func_die (void *vo)
{
    struct provide *o = vo;
    ASSERT(o->is_queued || !o->dying)

    // if we are queued or have no depends, die immediately
    if (o->is_queued || LinkedList1_IsEmpty(&o->depends)) {
        provide_free(o);
        return;
    }

    // set dying
    o->dying = 1;

    // signal our depends down
    for (LinkedList1Node *n = LinkedList1_GetFirst(&o->depends); n; n = LinkedList1Node_Next(n)) {
        struct depend *d = UPPER_OBJECT(n, struct depend, node);
        ASSERT(d->p == o)

        // signal down
        NCDModuleInst_Backend_Down(d->i);
    }
}

static void depend_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
    struct global *g = ModuleGlobal(i);
    struct depend *o = vo;
    o->i = i;

    // read arguments
    NCDValRef name_arg;
    if (!NCDVal_ListRead(params->args, 1, &name_arg)) {
        ModuleLog(o->i, BLOG_ERROR, "wrong arity");
        goto fail0;
    }
    if (!NCDVal_IsString(name_arg)) {
        ModuleLog(o->i, BLOG_ERROR, "wrong type");
        goto fail0;
    }
    o->name = NCDVal_StringMemRef(name_arg);

    // find a provide with our name
    struct provide *p = find_provide(g, o->name);
    ASSERT(!p || !p->is_queued)

    if (p && !p->dying) {
        // insert to provide's list
        LinkedList1_Append(&p->depends, &o->node);

        // set provide
        o->p = p;

        // signal up
        NCDModuleInst_Backend_Up(o->i);
    } else {
        // insert to free depends list
        LinkedList1_Append(&g->free_depends, &o->node);

        // set no provide
        o->p = NULL;
    }

    return;

fail0:
    NCDModuleInst_Backend_DeadError(i);
}

static void depend_free (struct depend *o)
{
    struct global *g = ModuleGlobal(o->i);
    ASSERT(!o->p || !o->p->is_queued)

    if (o->p) {
        // remove from provide's list
        LinkedList1_Remove(&o->p->depends, &o->node);

        // if provide is dying and is empty, let it die
        if (o->p->dying && LinkedList1_IsEmpty(&o->p->depends)) {
            provide_free(o->p);
        }
    } else {
        // remove free depends list
        LinkedList1_Remove(&g->free_depends, &o->node);
    }

    NCDModuleInst_Backend_Dead(o->i);
}

static void depend_func_die (void *vo)
{
    struct depend *o = vo;

    depend_free(o);
}

static void depend_func_clean (void *vo)
{
    struct depend *o = vo;
    struct global *g = ModuleGlobal(o->i);
    ASSERT(!o->p || !o->p->is_queued)

    if (!(o->p && o->p->dying)) {
        return;
    }

    struct provide *p = o->p;

    // remove from provide's list
    LinkedList1_Remove(&p->depends, &o->node);

    // insert to free depends list
    LinkedList1_Append(&g->free_depends, &o->node);

    // set no provide
    o->p = NULL;

    // if provide is empty, let it die
    if (LinkedList1_IsEmpty(&p->depends)) {
        provide_free(p);
    }
}

static int depend_func_getobj (void *vo, NCD_string_id_t objname, NCDObject *out_object)
{
    struct depend *o = vo;
    ASSERT(!o->p || !o->p->is_queued)

    if (!o->p) {
        return 0;
    }

    return NCDModuleInst_Backend_GetObj(o->p->i, objname, out_object);
}

static struct NCDModule modules[] = {
    {
        .type = "provide",
        .func_new2 = provide_func_new,
        .func_die = provide_func_die,
        .alloc_size = sizeof(struct provide)
    }, {
        .type = "provide_event",
        .func_new2 = provide_event_func_new,
        .func_die = provide_func_die,
        .alloc_size = sizeof(struct provide)
    }, {
        .type = "depend",
        .func_new2 = depend_func_new,
        .func_die = depend_func_die,
        .func_clean = depend_func_clean,
        .func_getobj = depend_func_getobj,
        .flags = NCDMODULE_FLAG_CAN_RESOLVE_WHEN_DOWN,
        .alloc_size = sizeof(struct depend)
    }, {
        .type = NULL
    }
};

const struct NCDModuleGroup ncdmodule_depend = {
    .func_globalinit = func_globalinit,
    .func_globalfree = func_globalfree,
    .modules = modules
};


text:
@interface SPVideoViewController ()

@end

@implementation SPVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}
@end


text:
/* Generated by the protocol buffer compiler.  DO NOT EDIT! */
/* Generated from: pg_logicaldec.proto */

#ifndef PROTOBUF_C_pg_5flogicaldec_2eproto__INCLUDED
#define PROTOBUF_C_pg_5flogicaldec_2eproto__INCLUDED

#include <protobuf-c/protobuf-c.h>

PROTOBUF_C__BEGIN_DECLS

#if PROTOBUF_C_VERSION_NUMBER < 1000000
# error This file was generated by a newer version of protoc-c which is incompatible with your libprotobuf-c headers. Please update your headers.
#elif 1001001 < PROTOBUF_C_MIN_COMPILER_VERSION
# error This file was generated by an older version of protoc-c which is incompatible with your libprotobuf-c headers. Please regenerate this file with a newer version of protoc-c.
#endif

typedef struct _Decoderbufs__Point Decoderbufs__Point;
typedef struct _Decoderbufs__DatumMessage Decoderbufs__DatumMessage;
typedef struct _Decoderbufs__RowMessage Decoderbufs__RowMessage;

/* --- enums --- */

typedef enum _Decoderbufs__Op {
  DECODERBUFS__OP__INSERT = 0,
  DECODERBUFS__OP__UPDATE = 1,
  DECODERBUFS__OP__DELETE = 2
    PROTOBUF_C__FORCE_ENUM_TO_BE_INT_SIZE(DECODERBUFS__OP)
} Decoderbufs__Op;

/* --- messages --- */

struct  _Decoderbufs__Point
{
  ProtobufCMessage base;
  double x;
  double y;
};
#define DECODERBUFS__POINT__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&decoderbufs__point__descriptor) \
    , 0, 0 }

struct  _Decoderbufs__DatumMessage
{
  ProtobufCMessage base;
  char *column_name;
  protobuf_c_boolean has_column_type;
  int64_t column_type;
  protobuf_c_boolean has_datum_int32;
  int32_t datum_int32;
  protobuf_c_boolean has_datum_int64;
  int64_t datum_int64;
  protobuf_c_boolean has_datum_float;
  float datum_float;
  protobuf_c_boolean has_datum_double;
  double datum_double;
  protobuf_c_boolean has_datum_bool;
  protobuf_c_boolean datum_bool;
  char *datum_string;
  protobuf_c_boolean has_datum_bytes;
  ProtobufCBinaryData datum_bytes;
  Decoderbufs__Point *datum_point;
};
#define DECODERBUFS__DATUM_MESSAGE__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&decoderbufs__datum_message__descriptor) \
    , NULL, 0,0, 0,0, 0,0, 0,0, 0,0, 0,0, NULL, 0,{0,NULL}, NULL }

struct  _Decoderbufs__RowMessage
{
  ProtobufCMessage base;
  protobuf_c_boolean has_commit_time;
  uint64_t commit_time;
  protobuf_c_boolean has_log_position;
  uint64_t log_position;
  char *table;
  protobuf_c_boolean has_op;
  Decoderbufs__Op op;
  size_t n_new_tuple;
  Decoderbufs__DatumMessage **new_tuple;
  size_t n_old_tuple;
  Decoderbufs__DatumMessage **old_tuple;
};
#define DECODERBUFS__ROW_MESSAGE__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&decoderbufs__row_message__descriptor) \
    , 0,0, 0,0, NULL, 0,0, 0,NULL, 0,NULL }

/* Decoderbufs__Point methods */
void   decoderbufs__point__init
                     (Decoderbufs__Point         *message);
size_t decoderbufs__point__get_packed_size
                     (const Decoderbufs__Point   *message);
size_t decoderbufs__point__pack
                     (const Decoderbufs__Point   *message,
                      uint8_t             *out);
size_t decoderbufs__point__pack_to_buffer
                     (const Decoderbufs__Point   *message,
                      ProtobufCBuffer     *buffer);
Decoderbufs__Point *
       decoderbufs__point__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   decoderbufs__point__free_unpacked
                     (Decoderbufs__Point *message,
                      ProtobufCAllocator *allocator);
/* Decoderbufs__DatumMessage methods */
void   decoderbufs__datum_message__init
                     (Decoderbufs__DatumMessage         *message);
size_t decoderbufs__datum_message__get_packed_size
                     (const Decoderbufs__DatumMessage   *message);
size_t decoderbufs__datum_message__pack
                     (const Decoderbufs__DatumMessage   *message,
                      uint8_t             *out);
size_t decoderbufs__datum_message__pack_to_buffer
                     (const Decoderbufs__DatumMessage   *message,
                      ProtobufCBuffer     *buffer);
Decoderbufs__DatumMessage *
       decoderbufs__datum_message__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   decoderbufs__datum_message__free_unpacked
                     (Decoderbufs__DatumMessage *message,
                      ProtobufCAllocator *allocator);
/* Decoderbufs__RowMessage methods */
void   decoderbufs__row_message__init
                     (Decoderbufs__RowMessage         *message);
size_t decoderbufs__row_message__get_packed_size
                     (const Decoderbufs__RowMessage   *message);
size_t decoderbufs__row_message__pack
                     (const Decoderbufs__RowMessage   *message,
                      uint8_t             *out);
size_t decoderbufs__row_message__pack_to_buffer
                     (const Decoderbufs__RowMessage   *message,
                      ProtobufCBuffer     *buffer);
Decoderbufs__RowMessage *
       decoderbufs__row_message__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   decoderbufs__row_message__free_unpacked
                     (Decoderbufs__RowMessage *message,
                      ProtobufCAllocator *allocator);
/* --- per-message closures --- */

typedef void (*Decoderbufs__Point_Closure)
                 (const Decoderbufs__Point *message,
                  void *closure_data);
typedef void (*Decoderbufs__DatumMessage_Closure)
                 (const Decoderbufs__DatumMessage *message,
                  void *closure_data);
typedef void (*Decoderbufs__RowMessage_Closure)
                 (const Decoderbufs__RowMessage *message,
                  void *closure_data);

/* --- services --- */

/* --- descriptors --- */

extern const ProtobufCEnumDescriptor    decoderbufs__op__descriptor;
extern const ProtobufCMessageDescriptor decoderbufs__point__descriptor;
extern const ProtobufCMessageDescriptor decoderbufs__datum_message__descriptor;
extern const ProtobufCMessageDescriptor decoderbufs__row_message__descriptor;

PROTOBUF_C__END_DECLS

#endif  /* PROTOBUF_C_pg_5flogicaldec_2eproto__INCLUDED */


text:
title: Add Integers
author:

subject: Mathematics
category: Common Core Basics
chapter: 4
section: 4.2
tag: Integers

excerpt:

section_overview:
-
  title: Materials
  content:
  - CCB Mathematics pages 108 - 113
-
  title: Standards
  content:
  - MP.2
  - Apply and extend previous understandings of numbers to the system of rational numbers.
  - Apply and extend previous understandings of operations with fractions to add, subtract, multiply, and divide rational numbers.
-
  title: Objectives
  content:
  - Use a number line to find the sum of two integers
  - Use integer addition rules to find the sum of two integers
-
  title: Key Concept
  content: "Two ways to find the sum of two integers include using a number line and using a sequence of rules "
-
  title: Vocabulary
  content:
    Tier 2:
    - Negative
    - Positive
    - Sign
    Tier 3:
    - Addend
    Test Words:
    - Illustrate
    - Sequence

---
## Before Lesson

Draw or have volunteers draw number lines from 0 to positive 25 on the board. Ask students to use the number lines to add positive whole numbers. Observe their work, intervening if necessary.

## Background

Remind students that a number line continues infinitely in opposite directions, representing both negative and positive integers. Also remind them that absolute value is the distance between 0 and a number on the number line, whether positive or negative.

## Guided Practice

- Use A Number Line to Add Integers
- Use Rules to Add Integers

## Core Skill

**Reason Abstractly:** Allow students time to read and think about the sidebar. Ask if they can think of other math examples that are abstract. One example is a number line. It is an abstraction that students can use to manipulate numbers, but it doesn't really exist as an object. Ask students to brainstorm other examples of abstractions they can use to work with numbers and values. Students may say, for example, that coordinate grids don't really exist, but they are abstractions that show the relationships between pairs of numbers.

**Perform Operations:** Have students read the sidebar independently. Remind them to refer to the number line in Example 3 as they read, to help them understand the text. After students have written their explanations, ask them to share their ideas.

For students who need an alternative to a number line to illustrate integer addition, give students counters in two colors. Let one color represent positive numbers and the other color represent negative numbers. Have students use the counters to practice finding zero sums. You can use small objects such as paper clips and erasers if counters are not available.

## Extension

**Build Vocabulary:** Invite students to play a game. Use tape to draw a number line along one edge of a table. Mark the center of the tape 0. Mark numbers to the right as positive integers and numbers to the left as negative integers. Have a volunteer stand in front of the 0 and push a paper clip or counter in a positive direction. Ask the student to announce the distance the counter moved. Then have the volunteer push it back in the opposite direction, again announcing how far the counter moved. Have a volunteer record the measurements on the board. Then ask the player to determine how far the counter moved in all while explaining the problem solving process using the vocabulary words. Invite other students to play.

**Classify Concepts:** Have students research the use of submersibles to explore the layers or zones of the ocean, from the surface, or Sunlight Zone, to the trenches, or Hadalpelagic Zone. Have students use their research to explain the concept of positive and negative integers.


text:
weapsy.admin.createRole = weapsy.admin.createRole || {};

weapsy.admin.createRole = (function ($) {

}(jQuery));


text:
<?php

/**
 * W3 CloudFlareAdmin plugin
 */
if (!defined('W3TC')) {
    die();
}

w3_require_once(W3TC_LIB_W3_DIR . '/Plugin.php');

/**
 * Class W3_Plugin_CloudFlareAdmin
 */
class W3_Plugin_CloudFlareAdmin extends W3_Plugin{
    function run() {
        $this->check_ip_versions();

        w3_require_once(W3TC_LIB_W3_DIR . '/Request.php');
        $page = W3_Request::get_string('page');
        if ($page && strpos($page, 'w3tc_') !== false) {
            /**
             * Only admin can see W3TC notices and errors
             */
            add_action('admin_notices', array(
                &$this,
                'admin_notices'
            ));
            add_action('network_admin_notices', array(
                &$this,
                'admin_notices'
            ));
        }
        add_action('wp_ajax_w3tc_cloudflare_api_request', array($this, 'action_cloudflare_api_request'));

    }

    /**
     * Check if last check has expired. If so update CloudFlare ips
     */
    function check_ip_versions() {
        $checked = get_transient('w3tc_cloudflare_ip_check');

        if (false === $checked) {
            $cf = w3_instance('W3_CloudFlare');
            try {
                $cf->update_ip_ranges();
            } catch (Exception $ex) {}
            set_transient('w3tc_cloudflare_ip_check', time(), 3600*24);
        }
    }

    function admin_notices() {
        $plugins = get_plugins();
        if (array_key_exists('cloudflare/cloudflare.php', $plugins) && $this->_config->get_boolean('notes.cloudflare_plugin')) {
            w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/other.php');
            echo sprintf('

%s %s

', __('CloudFlare plugin detected. We recommend removing the
            plugin as it offers no additional capabilities when W3 Total Cache is installed. This message will disappear
            when CloudFlare is removed.', 'w3-total-cache'),
                w3tc_button_hide_note('Hide this message', 'cloudflare_plugin')
            );
        }
    }

    /**
     * Send CloudFlare API request
     *
     * @return void
     */
    function action_cloudflare_api_request() {
        $result = false;
        $response = null;

        $actions = array(
            'devmode',
            'sec_lvl',
            'fpurge_ts'
        );

        w3_require_once(W3TC_LIB_W3_DIR . '/Request.php');

        $email = W3_Request::get_string('email');
        $key = W3_Request::get_string('key');
        $zone = W3_Request::get_string('zone');
        $action = W3_Request::get_string('command');
        $value = W3_Request::get_string('value');
        $nonce = W3_Request::get_string('_wpnonce');

        if (!wp_verify_nonce($nonce, 'w3tc')) {
            $error ='Access denied.';
        } elseif (!$email) {
            $error = 'Empty email.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email.';
        } elseif (!$key) {
            $error = 'Empty key.';
        } elseif (!$zone) {
            $error = 'Empty zone.';
        } elseif (strpos($zone, '.') === false) {
            $error = 'Invalid domain.';
        } elseif (!in_array($action, $actions)) {
            $error = 'Invalid action.';
        } else {
            $config = array(
                'email' => $email,
                'key' => $key,
                'zone' => $zone
            );

            w3_require_once(W3TC_LIB_W3_DIR . '/CloudFlare.php');
            @$w3_cloudflare = new W3_CloudFlare($config);

            @set_time_limit($this->_config->get_integer('timelimit.cloudflare_api_request'));

            $response = $w3_cloudflare->api_request($action, $value);

            if ($response) {
                if ($response->result == 'success') {
                    $result = true;
                    $error = 'OK';
                } else {
                    $error = $response->msg;
                }
            } else {
                $error = 'Unable to make CloudFlare API request.';
            }
        }

        $return = array(
            'result' => $result,
            'error' => $error,
            'response' => $response
        );

        echo json_encode($return);
        exit;
    }
}


text:
<?php

namespace Mage\Task\BuiltIn\Deployment\Strategy;

use Mage\Task\Releases\IsReleaseAware;

/**
 * Task for using Git Working Copy as the Deployed Code
 *
 * @author Oscar Reales <oreales@gmail.com>
 */
class GitRebaseTask extends BaseStrategyTaskAbstract implements IsReleaseAware
{
    /**
     * (non-PHPdoc)
     * @see \Mage\Task\AbstractTask::getName()
     */
    public function getName()
    {
        return 'Deploy via Git Rebase [built-in]';
    }

    /**
     * Rebases the Git Working Copy as the Deployed Code
     * @see \Mage\Task\AbstractTask::run()
     */
    public function run()
    {
        $this->checkOverrideRelease();

        if ($this->getConfig()->release('enabled', false) === true) {
            $releasesDirectory = $this->getConfig()->release('directory', 'releases');

            $deployToDirectory = rtrim($this->getConfig()->deployment('to'), '/')
                . '/' . $releasesDirectory
                . '/' . $this->getConfig()->getReleaseId();
            $this->runCommandRemote('mkdir -p ' . $deployToDirectory);
        }

        $branch = $this->getParameter('branch', 'master');
        $remote = $this->getParameter('remote', 'origin');

        // Fetch Remote
        $command = $this->getReleasesAwareCommand('git fetch ' . $remote);
        $result = $this->runCommandRemote($command);

        if ($result === false) {
            $repository = $this->getConfig()->deployment('repository');
            if ($repository) {
                $command = $this->getReleasesAwareCommand('git clone ' . $repository . ' .');
                $result = $this->runCommandRemote($command);

                $command = $this->getReleasesAwareCommand('git fetch ' . $remote);
                $result = $this->runCommandRemote($command);
            }
        }

        // Checkout
        $command = $this->getReleasesAwareCommand('git checkout ' . $branch);
        $result = $this->runCommandRemote($command) && $result;

        // Check Working Copy status
        $stashed = false;
        $status = '';
        $command = $this->getReleasesAwareCommand('git checkout ' . $branch);
        $result = $this->runCommandRemote($command) && $result;

        // Stash if Working Copy is not clean
        if (!$status) {
            $stashResult = '';
            $command = $this->getReleasesAwareCommand('git stash');
            $result = $this->runCommandRemote($command, $stashResult) && $result;
            if ($stashResult != "No local changes to save") {
                $stashed = true;
            }
        }

        // Rebase
        $command = $this->getReleasesAwareCommand('git rebase ' . $remote . '/' . $branch);
        $result = $this->runCommandRemote($command) && $result;

        // If Stashed, restore.
        if ($stashed) {
            $command = $this->getReleasesAwareCommand('git stash pop');
            $result = $this->runCommandRemote($command) && $result;
        }

        return $result;
    }
}


text:
(function () {
  'use strict';

  angular
    .module('core')
    .controller('HomeController', HomeController);
  HomeController.$inject = ['$scope', '$state', 'Authentication', 'menuService'];
  function HomeController($scope,$state,Authentication,menuService) {
    var vm = this;
    var _video = null,
        patData = null;

    $scope.showDemos = false;
    $scope.edgeDetection = false;
    $scope.mono = false;
    $scope.invert = false;

    $scope.patOpts = {x: 0, y: 0, w: 25, h: 25};

    // Setup a channel to receive a video property
    // with a reference to the video element
    // See the HTML binding in main.html
    $scope.channel = {video:null};

    $scope.webcamError = false;
    $scope.onError = function (err) {
        $scope.$apply(
            function() {
                $scope.webcamError = err;
            }
        );
    };

    $scope.onSuccess = function () {
        // The video element contains the captured camera data
        console.log("On onSuccess WORKED"+$scope.channel.video);
        _video = $scope.channel.video;

        $scope.$apply(function() {
            $scope.patOpts.w = _video.width;
            $scope.patOpts.h = _video.height;
            $scope.showDemos = true;
            console.log("On onSuccess WORKED"+$scope.channel.video);
        });
    };

    $scope.onStream = function (stream) {
        // You could do something manually with the stream.
    };

    /**
     * Make a snapshot of the camera data and show it in another canvas.
     */
    $scope.makeSnapshot = function makeSnapshot() {

            var patCanvas = document.querySelector('#snapshot');
            if (!patCanvas) return;

            patCanvas.width = _video.width;
            patCanvas.height = _video.height;
            var ctxPat = patCanvas.getContext('2d');

            var idata = getVideoData($scope.patOpts.x, $scope.patOpts.y, $scope.patOpts.w, $scope.patOpts.h);
            ctxPat.putImageData(idata, 0, 0);

           // sendSnapshotToServer(patCanvas.toDataURL());

            patData = idata;
            console.log("WORKED");

    };

    /**
     * Redirect the browser to the URL given.
     * Used to download the image by passing a dataURL string
     */
    $scope.downloadSnapshot = function downloadSnapshot(dataURL) {
        window.location.href = dataURL;
    };

    var getVideoData = function getVideoData(x, y, w, h) {
        var hiddenCanvas = document.createElement('canvas');
        hiddenCanvas.width = _video.width;
        hiddenCanvas.height = _video.height;
        var ctx = hiddenCanvas.getContext('2d');
        ctx.drawImage(_video, 0, 0, _video.width, _video.height);
        return ctx.getImageData(x, y, w, h);
    };

    /**
     * This function could be used to send the image data
     * to a backend server that expects base64 encoded images.
     *
     * In this example, we simply store it in the scope for display.
     */
    var sendSnapshotToServer = function sendSnapshotToServer(imgBase64) {
        $scope.snapshotData = imgBase64;
    };

    // var getPixelData = function getPixelData(data, width, col, row, offset) {
    //     return data[((row*(width*4)) + (col*4)) + offset];
    // };

    // var setPixelData = function setPixelData(data, width, col, row, offset, value) {
    //     data[((row*(width*4)) + (col*4)) + offset] = value;
    // };

    (function() {
      var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                                  window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
      window.requestAnimationFrame = requestAnimationFrame;
    })();

    var start = Date.now();

    /**
     * Apply a simple edge detection filter.
     */

  }
}());