Tributary
Tributary is an experimental environment for rapidly prototyping
visualization code. The environment provides several libraries useful
for this kind of coding, as well as a simple interface for live code
editing.
Sharing
The goal of Tributary is to reduce the friction involved in creating
something visual with code and sharing the result. Once you have
created something it should also be effortless to share, just click the
fork button and share the new URL with anyone. When you don't have to
worry about saving and tracking files, it becomes much easier to let go
and get creative, the fork button saves the code into a gist where you can always
access it.
Features
Tributary comes with
jQuery,
d3,
underscore and
backbone available in the code editor.
It is also possible to use
CoffeeScript. The editor is powered by
CodeMirror. The Bret Victor-like interactive slider and color picker are implemented in
Inlet and powered by
jQuery UI and
ColorPicker.
Help us add more! Check out the
source on github!
Attribution
Tributary is possible thanks to much harder work done by other people. We started with
Gabriel Florit's implementation of concepts introduced in
Bret Victor's talk.
The use of gists to drive the code in the view comes from Mike Bostock's
bl.ocks.org.
Tributary is primarily the work of
Ian Johnson and
EJ Fox, with contributions from
Kai Chang and
Nils Schlomann.


| OptionParserOption-class {optparse} | R Documentation |
Class to hold information about command-line options
short_flag
String of the desired short flag comprised of the “-” followed by a letter.
long_flag
String of the desired long flag comprised of “–” followed by a letter and then a sequence of alphanumeric characters.
action
A character string that describes the action optparse
should take when it encounters an option, either “store”,
“store_true”, or “store_false”. The default is “store”
which signifies that optparse
should store the specified following
value if the option is found on the command string. “store_true”
stores TRUE
if the option is found and “store_false” stores
FALSE
if the option is found.
type
A character string that describes specifies which data type
should be stored, either “logical”, “integer”, “double”,
“complex”, or “character”. Default is “logical” if
action %in% c("store_true", store_false)
, typeof(default)
if
action == "store"
and default is not NULL
and
“character” if action == "store"
and default is NULL
.
“numeric” will be converted to “double”.
dest
A character string that specifies what field in the list returned
by parse_args
should optparse
store option values. Default is
derived from the long flag in opt_str
.
default
The default value optparse
should use if it does not
find the option on the command line. Default is derived from the long flag
in opt_str
.
help
A character string describing the option to be used by
print_help
in generating a usage message. %default
will be
substituted by the value of default
.
metavar
A character string that stands in for the option argument when
printing help text. Default is the value of dest
.


Jadon Sancho’s response to supporter’s “Please sign for Manchester United” plea
by Jaikuran RandhawaEngland’s decision to live stream the senior squad’s training session recently appears to have added fuel to the fire that Jadon Sancho could potentially join Manchester United.
One Red Devils supporter asked the 19-year-old to “Please sign for United” and the Borussia Dortmund star laughed off the plea after taking a selfie with the fan.
According to the Metro, Liverpool, Manchester City, Real Madrid and Barcelona are all interested in the ace who is valued at a staggering £120m.
The Guardian understand that United are weighing up a move for the star after his recent troubles with Dortmund.
The ace was punished for returning to Germany late after the last international break and faced criticism from manager Lucien Favre last week.
Take a look at the United supporter’s plea to the tricky winger below:
Ole Gunnar Solskjaer is in serious need of bolstering his United squad, the Red Devils have a void at right-wing which Sancho’s signature would definitely fill.
The exciting youngster is establishing himself as an important player for the England team in the run-up to Euro 2020, the ace was very impressive in the Three Lions’ 7-0 win over Montenegro on Thursday night.


org.hecl.midp20.lcdui
Class CanvasEvent
java.lang.Object
org.hecl.midp20.lcdui.CanvasEvent
public class CanvasEvent
- extends java.lang.Object
|
Constructor Summary |
CanvasEvent(javax.microedition.lcdui.Canvas acanvas,
int reason)
|
CanvasEvent(javax.microedition.lcdui.Canvas acanvas,
int reason,
int x,
int y,
int width,
int height,
int keycode)
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
E_NONE
public static final int E_NONE
- See Also:
- Constant Field Values
E_PAINT
public static final int E_PAINT
- See Also:
- Constant Field Values
E_PPRESS
public static final int E_PPRESS
- See Also:
- Constant Field Values
E_PRELEASE
public static final int E_PRELEASE
- See Also:
- Constant Field Values
E_PDRAG
public static final int E_PDRAG
- See Also:
- Constant Field Values
E_KPRESS
public static final int E_KPRESS
- See Also:
- Constant Field Values
E_KRELEASE
public static final int E_KRELEASE
- See Also:
- Constant Field Values
E_KREPEAT
public static final int E_KREPEAT
- See Also:
- Constant Field Values
E_HIDE
public static final int E_HIDE
- See Also:
- Constant Field Values
E_SHOW
public static final int E_SHOW
- See Also:
- Constant Field Values
E_RESIZE
public static final int E_RESIZE
- See Also:
- Constant Field Values
E_UNKNOWN
public static final int E_UNKNOWN
- See Also:
- Constant Field Values
canvas
public javax.microedition.lcdui.Canvas canvas
reason
public int reason
x
public int x
y
public int y
width
public int width
height
public int height
keycode
public int keycode
consumed
public boolean consumed
CanvasEvent
public CanvasEvent(javax.microedition.lcdui.Canvas acanvas,
int reason)
CanvasEvent
public CanvasEvent(javax.microedition.lcdui.Canvas acanvas,
int reason,
int x,
int y,
int width,
int height,
int keycode)
eventOf
public static int eventOf(java.lang.String s)
eventName
public static java.lang.String eventName(int eventcode)
asString
public java.lang.String asString()
consume
public void consume()
isConsumed
public boolean isConsumed()


on the stack. If `op` is `None`, this value must be `True`.
Raises:
ValueError: if op is None but ignore_existing is False.
Yields:
A context manager that specifies the op with which to colocate
newly created ops.
"""
if op is None and not ignore_existing:
raise ValueError("Trying to reset colocation (op is None) but "
"ignore_existing is not True")
if op is not None and not isinstance(op, Operation):
# We always want to colocate with the reference op.
op = internal_convert_to_tensor_or_indexed_slices(op, as_ref=True).op
# By default, colocate_with resets the device function stack,
# since colocate_with is typically used in specific internal
# library functions where colocation is intended to be "stronger"
# than device functions.
#
# In the future, a caller may specify that device_functions win
# over colocation, in which case we can add support.
device_fn_tmp = self._device_function_stack
self._device_function_stack = traceable_stack.TraceableStack()
if ignore_existing:
current_stack = self._colocation_stack
self._colocation_stack = traceable_stack.TraceableStack()
if op is not None:
# offset refers to the stack frame used for storing code location.
# We use 4, the sum of 1 to use our caller's stack frame and 3
# to jump over layers of context managers above us.
self._colocation_stack.push_obj(op, offset=4)
try:
yield
finally:
# Restore device function stack
self._device_function_stack = device_fn_tmp
if op is not None:
self._colocation_stack.pop_obj()
# Reset the colocation stack if requested.
if ignore_existing:
self._colocation_stack = current_stack
def _add_device_to_stack(self, device_name_or_function, offset=0):
"""Add device to stack manually, separate from a context manager."""
total_offset = 1 + offset
spec = _UserDeviceSpec(device_name_or_function)
self._device_function_stack.push_obj(spec, offset=total_offset)
return spec
@tf_contextlib.contextmanager
def device(self, device_name_or_function):
# pylint: disable=line-too-long
"""Returns a context manager that specifies the default device to use.
The `device_name_or_function` argument may either be a device name
string, a device function, or None:
* If it is a device name string, all operations constructed in
this context will be assigned to the device with that name, unless
overridden by a nested `device()` context.
* If it is a function, it will be treated as a function from
Operation objects to device name strings, and invoked each time
a new Operation is created. The Operation will be assigned to
the device with the returned name.
* If it is None, all `device()` invocations from the enclosing context
will be ignored.
For information about the valid syntax of device name strings, see
the documentation in
[`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h).
For example:
```python
with g.device('/device:GPU:0'):
# All operations constructed in this context will be placed
# on GPU 0.
with g.device(None):
# All operations constructed in this context will have no
# assigned device.
# Defines a function from `Operation` to device string.
def matmul_on_gpu(n):
if n.type == "MatMul":
return "/device:GPU:0"
else:
return "/cpu:0"
with g.device(matmul_on_gpu):
# All operations of type "MatMul" constructed in this context
# will be placed on GPU 0; all other operations will be placed
# on CPU 0.
```
**N.B.** The device scope may be overridden by op wrappers or
other library code. For example, a variable assignment op
`v.assign()` must be colocated with the `tf.Variable` `v`, and
incompatible device scopes will be ignored.
Args:
device_name_or_function: The device name or function to use in
the context.
Yields:
A context manager that specifies the default device to use for newly
created ops.
"""
self._add_device_to_stack(device_name_or_function, offset=2)
try:
yield
finally:
self._device_function_stack.pop_obj()
def _apply_device_functions(self, op):
"""Applies the current device function stack to the given operation."""
# Apply any device functions in LIFO order, so that the most recently
# pushed function has the first chance to apply a device to the op.
# We apply here because the result can depend on the Operation's
# signature, which is computed in the Operation constructor.
# pylint: disable=protected-access
for device_spec in self._device_function_stack.peek_objs():
if device_spec.function is None:
break
op._set_device(device_spec.function(op))
op._device_code_locations = self._snapshot_device_function_stack_metadata()
# pylint: enable=protected-access
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def container(self, container_name):
"""Returns a context manager that specifies the resource container to use.
Stateful operations, such as variables and queues, can maintain their
states on devices so that they can be shared by multiple processes.
A resource container is a string name under which these stateful
operations are tracked. These resources can be released or cleared
with `tf.Session.reset()`.
For example:
```python
with g.container('experiment0'):
# All stateful Operations constructed in this context will be placed
# in resource container "experiment0".
v1 = tf.Variable([1.0])
v2 = tf.Variable([2.0])
with g.container("experiment1"):
# All stateful Operations constructed in this context will be
# placed in resource container "experiment1".
v3 = tf.Variable([3.0])
q1 = tf.FIFOQueue(10, tf.float32)
# All stateful Operations constructed in this context will be
# be created in the "experiment0".
v4 = tf.Variable([4.0])
q1 = tf.FIFOQueue(20, tf.float32)
with g.container(""):
# All stateful Operations constructed in this context will be
# be placed in the default resource container.
v5 = tf.Variable([5.0])
q3 = tf.FIFOQueue(30, tf.float32)
# Resets container "experiment0", after which the state of v1, v2, v4, q1
# will become undefined (such as uninitialized).
tf.Session.reset(target, ["experiment0"])
```
Args:
container_name: container name string.
Returns:
A context manager for defining resource containers for stateful ops,
yields the container name.
"""
original_container = self._container
self._container = container_name
try:
yield self._container
finally:
self._container = original_container
# pylint: enable=g-doc-return-or-yield
class _ControlDependenciesController(object):
"""Context manager for `control_dependencies()`."""
def __init__(self, graph, control_inputs):
"""Create a new `_ControlDependenciesController`.
A `_ControlDependenciesController` is the context manager for
`with tf.control_dependencies()` blocks. These normally nest,
as described in the documentation for `control_dependencies()`.
The `control_inputs` argument list control dependencies that must be
added to the current set of control dependencies. Because of
uniquification the set can be empty even if the caller passed a list of
ops. The special value `None` indicates that we want to start a new
empty set of control dependencies instead of extending the current set.
In that case we also clear the current control flow context, which is an
additional mechanism to add control dependencies.
Args:
graph: The graph that this controller is managing.
control_inputs: List of ops to use as control inputs in addition
to the current control dependencies. None to indicate that
the dependencies should be cleared.
"""
self._graph = graph
if control_inputs is None:
self._control_inputs_val = []
self._new_stack = True
else:
self._control_inputs_val = control_inputs
self._new_stack = False
self._seen_nodes = set()
self._old_stack = None
self._old_control_flow_context = None
# pylint: disable=protected-access
def __enter__(self):
if self._new_stack:
# Clear the control_dependencies graph.
self._old_stack = self._graph._control_dependencies_stack
self._graph._control_dependencies_stack = []
# Clear the control_flow_context too.
self._old_control_flow_context = self._graph._get_control_flow_context()
self._graph._set_control_flow_context(None)
self._graph._push_control_dependencies_controller(self)
def __exit__(self, unused_type, unused_value, unused_traceback):
self._graph._pop_control_dependencies_controller(self)
if self._new_stack:
self._graph._control_dependencies_stack = self._old_stack
self._graph._set_control_flow_context(self._old_control_flow_context)
# pylint: enable=protected-access
@property
def control_inputs(self):
return self._control_inputs_val
def add_op(self, op):
self._seen_nodes.add(op)
def op_in_group(self, op):
return op in self._seen_nodes
def _push_control_dependencies_controller(self, controller):
self._control_dependencies_stack.append(controller)
def _pop_control_dependencies_controller(self, controller):
assert self._control_dependencies_stack[-1] is controller
self._control_dependencies_stack.pop()
def _current_control_dependencies(self):
ret = set()
for controller in self._control_dependencies_stack:
for op in controller.control_inputs:
ret.add(op)
return ret
def _control_dependencies_for_inputs(self, input_ops):
"""For an op that takes `input_ops` as inputs, compute control inputs.
The returned control dependencies should yield an execution that
is equivalent to adding all control inputs in
self._control_dependencies_stack to a newly created op. However,
this function attempts to prune the returned control dependencies
by observing that nodes created within the same `with
control_dependencies(...):` block may have data dependencies that make
the explicit approach redundant.
Args:
input_ops: The data input ops for an op to be created.
Returns:
A list of control inputs for the op to be created.
"""
ret = []
for controller in self._control_dependencies_stack:
# If any of the input_ops already depends on the inputs from controller,
# we say that the new op is dominated (by that input), and we therefore
# do not need to add control dependencies for this controller's inputs.
dominated = False
for op in input_ops:
if controller.op_in_group(op):
dominated = True
break
if not dominated:
# Don't add a control input if we already have a data dependency on i.
# NOTE(mrry): We do not currently track transitive data dependencies,
# so we may add redundant control inputs.
ret.extend([c for c in controller.control_inputs if c not in input_ops])
return ret
def _record_op_seen_by_control_dependencies(self, op):
"""Record that the given op depends on all registered control dependencies.
Args:
op: An Operation.
"""
for controller in self._control_dependencies_stack:
controller.add_op(op)
def control_dependencies(self, control_inputs):
"""Returns a context manager that specifies control dependencies.
Use with the `with` keyword to specify that all operations constructed
within the context should have control dependencies on
`control_inputs`. For example:
```python
with g.control_dependencies([a, b, c]):
# `d` and `e` will only run after `a`, `b`, and `c` have executed.
d = ...
e = ...
```
Multiple calls to `control_dependencies()` can be nested, and in
that case a new `Operation` will have control dependencies on the union
of `control_inputs` from all active contexts.
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `a`, `b`, `c`, and `d`.
```
You can pass None to clear the control dependencies:
```python
with g.control_dependencies([a, b]):
# Ops constructed here run after `a` and `b`.
with g.control_dependencies(None):
# Ops constructed here run normally, not waiting for either `a` or `b`.
with g.control_dependencies([c, d]):
# Ops constructed here run after `c` and `d`, also not waiting
# for either `a` or `b`.
```
*N.B.* The control dependencies context applies *only* to ops that
are constructed within the context. Merely using an op or tensor
in the context does not add a control dependency. The following
example illustrates this point:
```python
# WRONG
def my_func(pred, tensor):
t = tf.matmul(tensor, tensor)
with tf.control_dependencies([pred]):
# The matmul op is created outside the context, so no control
# dependency will be added.
return t
# RIGHT
def my_func(pred, tensor):
with tf.control_dependencies([pred]):
# The matmul op is created in the context, so a control dependency
# will be added.
return tf.matmul(tensor, tensor)
```
Also note that though execution of ops created under this scope will trigger
execution of the dependencies, the ops created under this scope might still
be pruned from a normal tensorflow graph. For example, in the following
snippet of code the dependencies are never executed:
```python
loss = model.loss()
with tf.control_dependencies(dependencies):
loss = loss + tf.constant(1) # note: dependencies ignored in the
# backward pass
return tf.gradients(loss, model.variables)
```
This is because evaluating the gradient graph does not require evaluating
the constant(1) op created in the forward pass.
Args:
control_inputs: A list of `Operation` or `Tensor` objects which
must be executed or computed before running the operations
defined in the context. Can also be `None` to clear the control
dependencies.
Returns:
A context manager that specifies control dependencies for all
operations constructed within the context.
Raises:
TypeError: If `control_inputs` is not a list of `Operation` or
`Tensor` objects.
"""
if control_inputs is None:
return self._ControlDependenciesController(self, None)
# First convert the inputs to ops, and deduplicate them.
# NOTE(mrry): Other than deduplication, we do not currently track direct
# or indirect dependencies between control_inputs, which may result in
# redundant control inputs.
control_ops = []
current = self._current_control_dependencies()
for c in control_inputs:
if isinstance(c, IndexedSlices):
c = c.op
c = self.as_graph_element(c)
if isinstance(c, Tensor):
c = c.op
elif not isinstance(c, Operation):
raise TypeError("Control input must be Operation or Tensor: %s" % c)
if c not in current:
control_ops.append(c)
current.add(c)
return self._ControlDependenciesController(self, control_ops)
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def _attr_scope(self, attr_map):
"""EXPERIMENTAL: A context manager for setting attributes on operators.
This context manager can be used to add additional
attributes to operators within the scope of the context.
For example:
with ops.Graph().as_default() as g:
f_1 = Foo() # No extra attributes
with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=False)}):
f_2 = Foo() # Additional attribute _a=False
with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=True)}):
f_3 = Foo() # Additional attribute _a=False
with g._attr_scope({"_a": None}):
f_4 = Foo() # No additional attributes.
Args:
attr_map: A dictionary mapping attr name strings to
AttrValue protocol buffers or None.
Returns:
A context manager that sets the kernel label to be used for one or more
ops created in that context.
Raises:
TypeError: If attr_map is not a dictionary mapping
strings to AttrValue protobufs.
"""
if not isinstance(attr_map, dict):
raise TypeError("attr_map must be a dictionary mapping "
"strings to AttrValue protocol buffers")
# The saved_attrs dictionary stores any currently-set labels that
# will be overridden by this context manager.
saved_attrs = {}
# Install the given attribute
for name, attr in attr_map.items():
if not (isinstance(name, six.string_types) and
(isinstance(attr, (type(None), attr_value_pb2.AttrValue)) or
callable(attr))):
raise TypeError("attr_map must be a dictionary mapping "
"strings to AttrValue protocol buffers or "
"callables that emit AttrValue protocol buffers")
try:
saved_attrs[name] = self._attr_scope_map[name]
except KeyError:
pass
if attr is None:
del self._attr_scope_map[name]
else:
self._attr_scope_map[name] = attr
try:
yield # The code within the context runs here.
finally:
# Remove the attributes set for this context, and restore any saved
# attributes.
for name, attr in attr_map.items():
try:
self._attr_scope_map[name] = saved_attrs[name]
except KeyError:
del self._attr_scope_map[name]
# pylint: enable=g-doc-return-or-yield
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def _kernel_label_map(self, op_to_kernel_label_map):
"""EXPERIMENTAL: A context manager for setting kernel labels.
This context manager can be used to select particular
implementations of kernels within the scope of the context.
For example:
with ops.Graph().as_default() as g:
f_1 = Foo() # Uses the default registered kernel for the Foo op.
with g.kernel_label_map({"Foo": "v_2"}):
f_2 = Foo() # Uses the registered kernel with label "v_2"
# for the Foo op.
with g.kernel_label_map({"Foo": "v_3"}):
f_3 = Foo() # Uses the registered kernel with label "v_3"
# for the Foo op.
with g.kernel_label_map({"Foo": ""}):
f_4 = Foo() # Uses the default registered kernel
# for the Foo op.
Args:
op_to_kernel_label_map: A dictionary mapping op type strings to
kernel label strings.
Returns:
A context manager that sets the kernel label to be used for one or more
ops created in that context.
Raises:
TypeError: If op_to_kernel_label_map is not a dictionary mapping
strings to strings.
"""
if not isinstance(op_to_kernel_label_map, dict):
raise TypeError("op_to_kernel_label_map must be a dictionary mapping "
"strings to strings")
# The saved_labels dictionary stores any currently-set labels that
# will be overridden by this context manager.
saved_labels = {}
# Install the given label
for op_type, label in op_to_kernel_label_map.items():
if not (isinstance(op_type, six.string_types) and
isinstance(label, six.string_types)):
raise TypeError("op_to_kernel_label_map must be a dictionary mapping "
"strings to strings")
try:
saved_labels[op_type] = self._op_to_kernel_label_map[op_type]
except KeyError:
pass
self._op_to_kernel_label_map[op_type] = label
try:
yield # The code within the context runs here.
finally:
# Remove the labels set for this context, and restore any saved labels.
for op_type, label in op_to_kernel_label_map.items():
try:
self._op_to_kernel_label_map[op_type] = saved_labels[op_type]
except KeyError:
del self._op_to_kernel_label_map[op_type]
# pylint: enable=g-doc-return-or-yield
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def gradient_override_map(self, op_type_map):
"""EXPERIMENTAL: A context manager for overriding gradient functions.
This context manager can be used to override the gradient function
that will be used for ops within the scope of the context.
For example:
```python
@tf.RegisterGradient("CustomSquare")
def _custom_square_grad(op, grad):
# ...
with tf.Graph().as_default() as g:
c = tf.constant(5.0)
s_1 = tf.square(c) # Uses the default gradient for tf.square.
with g.gradient_override_map({"Square": "CustomSquare"}):
s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the
# gradient of s_2.
```
Args:
op_type_map: A dictionary mapping op type strings to alternative op
type strings.
Returns:
A context manager that sets the alternative op type to be used for one
or more ops created in that context.
Raises:
TypeError: If `op_type_map` is not a dictionary mapping strings to
strings.
"""
if not isinstance(op_type_map, dict):
raise TypeError("op_type_map must be a dictionary mapping "
"strings to strings")
# The saved_mappings dictionary stores any currently-set mappings that
# will be overridden by this context manager.
saved_mappings = {}
# Install the given label
for op_type, mapped_op_type in op_type_map.items():
if not (isinstance(op_type, six.string_types) and
isinstance(mapped_op_type, six.string_types)):
raise TypeError("op_type_map must be a dictionary mapping "
"strings to strings")
try:
saved_mappings[op_type] = self._gradient_override_map[op_type]
except KeyError:
pass
self._gradient_override_map[op_type] = mapped_op_type
try:
yield # The code within the context runs here.
finally:
# Remove the labels set for this context, and restore any saved labels.
for op_type, mapped_op_type in op_type_map.items():
try:
self._gradient_override_map[op_type] = saved_mappings[op_type]
except KeyError:
del self._gradient_override_map[op_type]
# pylint: enable=g-doc-return-or-yield
def prevent_feeding(self, tensor):
"""Marks the given `tensor` as unfeedable in this graph."""
self._unfeedable_tensors.add(tensor)
def is_feedable(self, tensor):
"""Returns `True` if and only if `tensor` is feedable."""
return tensor not in self._unfeedable_tensors
def prevent_fetching(self, op):
"""Marks the given `op` as unfetchable in this graph."""
self._unfetchable_ops.add(op)
def is_fetchable(self, tensor_or_op):
"""Returns `True` if and only if `tensor_or_op` is fetchable."""
if isinstance(tensor_or_op, Tensor):
return tensor_or_op.op not in self._unfetchable_ops
else:
return tensor_or_op not in self._unfetchable_ops
def switch_to_thread_local(self):
"""Make device, colocation and dependencies stacks thread-local.
Device, colocation and dependencies stacks are not thread-local be default.
If multiple threads access them, then the state is shared. This means that
one thread may affect the behavior of another thread.
After this method is called, the stacks become thread-local. If multiple
threads access them, then the state is not shared. Each thread uses its own
value; a thread doesn't affect other threads by mutating such a stack.
The initial value for every thread's stack is set to the current value
of the stack when `switch_to_thread_local()` was first called.
"""
if not self._stack_state_is_thread_local:
self._stack_state_is_thread_local = True
@property
def _device_function_stack(self):
if self._stack_state_is_thread_local:
# This may be called from a thread where device_function_stack doesn't yet
# exist.
# pylint: disable=protected-access
if not hasattr(self._thread_local, "_device_function_stack"):
stack_copy_for_this_thread = self._graph_device_function_stack.copy()
self._thread_local._device_function_stack = stack_copy_for_this_thread
return self._thread_local._device_function_stack
# pylint: enable=protected-access
else:
return self._graph_device_function_stack
@property
def _device_functions_outer_to_inner(self):
user_device_specs = self._device_function_stack.peek_objs()
device_functions = [spec.function for spec in user_device_specs]
device_functions_outer_to_inner = list(reversed(device_functions))
return device_functions_outer_to_inner
def _snapshot_device_function_stack_metadata(self):
"""Return device function stack as a list of TraceableObjects.
Returns:
[traceable_stack.TraceableObject, ...] where each TraceableObject's .obj
member is a displayable name for the user's argument to Graph.device, and
the filename and lineno members point to the code location where
Graph.device was called directly or indirectly by the user.
"""
traceable_objects = self._device_function_stack.peek_traceable_objs()
snapshot = []
for obj in traceable_objects:
obj_copy = obj.copy_metadata()
obj_copy.obj = obj.obj.display_name
snapshot.append(obj_copy)
return snapshot
@_device_function_stack.setter
def _device_function_stack(self, device_function_stack):
if self._stack_state_is_thread_local:
# pylint: disable=protected-access
self._thread_local._device_function_stack = device_function_stack
# pylint: enable=protected-access
else:
self._graph_device_function_stack = device_function_stack
@property
def _colocation_stack(self):
"""Return thread-local copy of colocation stack."""
if self._stack_state_is_thread_local:
# This may be called from a thread where colocation_stack doesn't yet
# exist.
# pylint: disable=protected-access
if not hasattr(self._thread_local, "_colocation_stack"):
stack_copy_for_this_thread = self._graph_colocation_stack.copy()
self._thread_local._colocation_stack = stack_copy_for_this_thread
return self._thread_local._colocation_stack
# pylint: enable=protected-access
else:
return self._graph_colocation_stack
def _snapshot_colocation_stack_metadata(self):
"""Return colocation stack metadata as a dictionary."""
traceable_objects = self._colocation_stack.peek_traceable_objs()
return {obj.obj.name: obj.copy_metadata() for obj in traceable_objects}
@_colocation_stack.setter
def _colocation_stack(self, colocation_stack):
if self._stack_state_is_thread_local:
# pylint: disable=protected-access
self._thread_local._colocation_stack = colocation_stack
# pylint: enable=protected-access
else:
self._graph_colocation_stack = colocation_stack
@property
def _control_dependencies_stack(self):
if self._stack_state_is_thread_local:
# This may be called from a thread where control_dependencies_stack
# doesn't yet exist.
if not hasattr(self._thread_local, "_control_dependencies_stack"):
self._thread_local._control_dependencies_stack = (
self._graph_control_dependencies_stack[:])
return self._thread_local._control_dependencies_stack
else:
return self._graph_control_dependencies_stack
@_control_dependencies_stack.setter
def _control_dependencies_stack(self, control_dependencies):
if self._stack_state_is_thread_local:
self._thread_local._control_dependencies_stack = control_dependencies
else:
self._graph_control_dependencies_stack = control_dependencies
def _mutation_lock(self):
"""Returns a lock to guard code that creates & mutates ops.
See the comment for self._group_lock for more info.
"""
return self._group_lock.group(_MUTATION_LOCK_GROUP)
def _session_run_lock(self):
"""Returns a lock to guard code for Session.run.
See the comment for self._group_lock for more info.
"""
return self._group_lock.group(_SESSION_RUN_LOCK_GROUP)
# TODO(agarwal): currently device directives in an outer eager scope will not
# apply to inner graph mode code. Fix that.
@tf_export("device")
def device(device_name_or_function):
"""Wrapper for `Graph.device()` using the default graph.
See
@{tf.Graph.device}
for more details.
Args:
device_name_or_function: The device name or function to use in
the context.
Returns:
A context manager that specifies the default device to use for newly
created ops.
Raises:
RuntimeError: If eager execution is enabled and a function is passed in.
"""
if context.executing_eagerly():
# TODO(agarwal): support device functions in EAGER mode.
if callable(device_name_or_function):
raise RuntimeError(
"tf.device does not support functions when eager execution "
"is enabled.")
return context.device(device_name_or_function)
else:
return get_default_graph().device(device_name_or_function)
@tf_export("container")
def container(container_name):
"""Wrapper for `Graph.container()` using the default graph.
Args:
container_name: The container string to use in the context.
Returns:
A context manager that specifies the default container to use for newly
created stateful ops.
"""
return get_default_graph().container(container_name)
def _colocate_with_for_gradient(op, gradient_uid, ignore_existing=False):
if context.executing_eagerly():
if op is not None:
return device(op.device)
else:
return _NullContextmanager()
else:
default_graph = get_default_graph()
if isinstance(op, EagerTensor):
if default_graph.building_function:
return default_graph.device(op.device)
else:
raise ValueError("Encountered an Eager-defined Tensor during graph "
"construction, but a function was not being built.")
return default_graph._colocate_with_for_gradient(
op, gradient_uid=gradient_uid, ignore_existing=ignore_existing)
@tf_export("colocate_with")
def colocate_with(op, ignore_existing=False):
return _colocate_with_for_gradient(op, None, ignore_existing=ignore_existing)
@tf_export("control_dependencies")
def control_dependencies(control_inputs):
"""Wrapper for `Graph.control_dependencies()` using the default graph.
See @{tf.Graph.control_dependencies}
for more details.
When eager execution is enabled, any callable object in the `control_inputs`
list will be called.
Args:
control_inputs: A list of `Operation` or `Tensor` objects which
must be executed or computed before running the operations
defined in the context. Can also be `None` to clear the control
dependencies. If eager execution is enabled, any callable object in the
`control_inputs` list will be called.
Returns:
A context manager that specifies control dependencies for all
operations constructed within the context.
"""
if context.executing_eagerly():
if control_inputs:
# Excute any pending callables.
for control in control_inputs:
if callable(control):
control()
return _NullContextmanager()
else:
return get_default_graph().control_dependencies(control_inputs)
class _DefaultStack(threading.local):
"""A thread-local stack of objects for providing implicit defaults."""
def __init__(self):
super(_DefaultStack, self).__init__()
self._enforce_nesting = True
self.stack = []
def get_default(self):
return self.stack[-1] if len(self.stack) >= 1 else None
def reset(self):
self.stack = []
def is_cleared(self):
return not self.stack
@property
def enforce_nesting(self):
return self._enforce_nesting
@enforce_nesting.setter
def enforce_nesting(self, value):
self._enforce_nesting = value
@tf_contextlib.contextmanager
def get_controller(self, default):
"""A context manager for manipulating a default stack."""
self.stack.append(default)
try:
yield default
finally:
# stack may be empty if reset() was called
if self.stack:
if self._enforce_nesting:
if self.stack[-1] is not default:
raise AssertionError(
"Nesting violated for default stack of %s objects" %
type(default))
self.stack.pop()
else:
self.stack.remove(default)
_default_session_stack = _DefaultStack() # pylint: disable=protected-access
def default_session(session):
"""Python "with" handler for defining a default session.
This function provides a means of registering a session for handling
Tensor.eval() and Operation.run() calls. It is primarily intended for use
by session.Session, but can be used with any object that implements
the Session.run() interface.
Use with the "with" keyword to specify that Tensor.eval() and Operation.run()
invocations within the scope of a block should be executed by a particular
session.
The default session applies to the current thread only, so it is always
possible to inspect the call stack and determine the scope of a default
session. If you create a new thread, and wish to use the default session
in that thread, you must explicitly add a "with ops.default_session(sess):"
block in that thread's function.
Example:
The following code examples are equivalent:
# 1. Using the Session object directly:
sess = ...
c = tf.constant(5.0)
sess.run(c)
# 2. Using default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
result = c.eval()
# 3. Overriding default_session():
sess = ...
with ops.default_session(sess):
c = tf.constant(5.0)
with ops.default_session(...):
c.eval(session=sess)
Args:
session: The session to be installed as the default session.
Returns:
A context manager for the default session.
"""
return _default_session_stack.get_controller(session)
@tf_export("get_default_session")
def get_default_session():
"""Returns the default session for the current thread.
The returned `Session` will be the innermost session on which a
`Session` or `Session.as_default()` context has been entered.
NOTE: The default session is a property of the current thread. If you
create a new thread, and wish to use the default session in that
thread, you must explicitly add a `with sess.as_default():` in that
thread's function.
Returns:
The default `Session` being used in the current thread.
"""
return _default_session_stack.get_default()
def _eval_using_default_session(tensors, feed_dict, graph, session=None):
"""Uses the default session to evaluate one or more tensors.
Args:
tensors: A single Tensor, or a list of Tensor objects.
feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,
numpy ndarrays, TensorProtos, or strings.
graph: The graph in which the tensors are defined.
session: (Optional) A different session to use to evaluate "tensors".
Returns:
Either a single numpy ndarray if "tensors" is a single tensor; or a list
of numpy ndarrays that each correspond to the respective element in
"tensors".
Raises:
ValueError: If no default session is available; the default session
does not have "graph" as its graph; or if "session" is specified,
and it does not have "graph" as its graph.
"""
if session is None:
session = get_default_session()
if session is None:
raise ValueError("Cannot evaluate tensor using `eval()`: No default "
"session is registered. Use `with "
"sess.as_default()` or pass an explicit session to "
"`eval(session=sess)`")
if session.graph is not graph:
raise ValueError("Cannot use the default session to evaluate tensor: "
"the tensor's graph is different from the session's "
"graph. Pass an explicit session to "
"`eval(session=sess)`.")
else:
if session.graph is not graph:
raise ValueError("Cannot use the given session to evaluate tensor: "
"the tensor's graph is different from the session's "
"graph.")
return session.run(tensors, feed_dict)
def _run_using_default_session(operation, feed_dict, graph, session=None):
"""Uses the default session to run "operation".
Args:
operation: The Operation to be run.
feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,
numpy ndarrays, TensorProtos, or strings.
graph: The graph in which "operation" is defined.
session: (Optional) A different session to use to run "operation".
Raises:
ValueError: If no default session is available; the default session
does not have "graph" as its graph; or if "session" is specified,
and it does not have "graph" as its graph.
"""
if session is None:
session = get_default_session()
if session is None:
raise ValueError("Cannot execute operation using `run()`: No default "
"session is registered. Use `with "
"sess.as_default():` or pass an explicit session to "
"`run(session=sess)`")
if session.graph is not graph:
raise ValueError("Cannot use the default session to execute operation: "
"the operation's graph is different from the "
"session's graph. Pass an explicit session to "
"run(session=sess).")
else:
if session.graph is not graph:
raise ValueError("Cannot use the given session to execute operation: "
"the operation's graph is different from the session's "
"graph.")
session.run(operation, feed_dict)
class _DefaultGraphStack(_DefaultStack): # pylint: disable=protected-access
"""A thread-local stack of objects for providing an implicit default graph."""
def __init__(self):
super(_DefaultGraphStack, self).__init__()
self._global_default_graph = None
def get_default(self):
"""Override that returns a global default if the stack is empty."""
ret = super(_DefaultGraphStack, self).get_default()
if ret is None:
ret = self._GetGlobalDefaultGraph()
return ret
def _GetGlobalDefaultGraph(self):
if self._global_default_graph is None:
# TODO(mrry): Perhaps log that the default graph is being used, or set
# provide some other feedback to prevent confusion when a mixture of
# the global default graph and an explicit graph are combined in the
# same process.
self._global_default_graph = Graph()
return self._global_default_graph
def reset(self):
super(_DefaultGraphStack, self).reset()
self._global_default_graph = None
@tf_contextlib.contextmanager
def get_controller(self, default):
context.context().context_switches.push(
default.building_function, default.as_default)
try:
with super(_DefaultGraphStack, self).get_controller(
default) as g, context.graph_mode():
yield g
finally:
# If an exception is raised here it may be hiding a related exception in
# the try-block (just above).
context.context().context_switches.pop()
_default_graph_stack = _DefaultGraphStack()
# pylint: disable=g-doc-return-or-yield,line-too-long
@tf_contextlib.contextmanager
def init_scope():
"""A context manager that lifts ops out of control-flow scopes and function-building graphs.
There is often a need to lift variable initialization ops out of control-flow
scopes, function-building graphs, and gradient tapes. Entering an
`init_scope` is a mechanism for satisfying these desiderata. In particular,
entering an `init_scope` has three effects:
(1) All control dependencies are cleared the moment the scope is entered;
this is equivalent to entering the context manager returned from
`control_dependencies(None)`, which has the side-effect of exiting
control-flow scopes like `tf.cond` and `tf.while_loop`.
(2) All operations that are created while the scope is active are lifted
into the lowest context on the `context_stack` that is not building a
graph function. Here, a context is defined as either a graph or an eager
context. Every context switch, i.e., every installation of a graph as
the default graph and every switch into eager mode, is logged in a
thread-local stack called `context_switches`; the log entry for a
context switch is popped from the stack when the context is exited.
Entering an `init_scope` is equivalent to crawling up
`context_switches`, finding the first context that is not building a
graph function, and entering it. A caveat is that if graph mode is
enabled but the default graph stack is empty, then entering an
`init_scope` will simply install a fresh graph as the default one.
(3) The gradient tape is paused while the scope is active.
Raises:
RuntimeError: if graph state is incompatible with this initialization.
"""
# pylint: enable=g-doc-return-or-yield,line-too-long
if context.executing_eagerly():
# Fastpath.
with tape.stop_recording():
yield
else:
# Retrieve the active name scope: entering an `init_scope` preserves
# the name scope of the current context.
default_graph = get_default_graph()
scope = default_graph.get_name_scope()
if scope and scope[-1] != "/":
# Names that end with trailing slashes are treated by `name_scope` as
# absolute.
scope = scope + "/"
inner_device_stack = default_graph._device_function_stack # pylint: disable=protected-access
outer_context = None
if not _default_graph_stack.stack:
# If the default graph stack is empty, then we cannot be building a
# function. Install the global graph (which, in this case, is also the
# default graph) as the outer context.
if default_graph.building_function:
raise RuntimeError("The global graph is building a function.")
outer_context = default_graph.as_default
else:
# Find a context that is not building a function.
for stack_entry in reversed(context.context().context_switches.stack):
if not stack_entry.is_building_function:
outer_context = stack_entry.enter_context_fn
break
if outer_context is None:
# As a last resort, obtain the global default graph; this graph doesn't
# necessarily live on the graph stack (and hence it doesn't necessarily
# live on the context stack), but it is stored in the graph stack's
# encapsulating object.
outer_context = _default_graph_stack._GetGlobalDefaultGraph().as_default # pylint: disable=protected-access
if outer_context is None:
# Sanity check; this shouldn't be triggered.
raise RuntimeError("All graphs are building functions, and no "
"eager context was previously active.")
outer_graph = None
outer_device_stack = None
try:
with outer_context(), name_scope(scope), control_dependencies(
None), tape.stop_recording():
if not context.executing_eagerly():
# The device stack is preserved when lifting into a graph. Eager
# execution doesn't implement device stacks and in particular it
# doesn't support device functions, so in general it's not possible
# to do the same when lifting into the eager context.
outer_graph = get_default_graph()
outer_device_stack = outer_graph._device_function_stack # pylint: disable=protected-access
outer_graph._device_function_stack = inner_device_stack # pylint: disable=protected-access
yield
finally:
# If an exception is raised here it may be hiding a related exception in
# try-block (just above).
if outer_graph is not None:
outer_graph._device_function_stack = outer_device_stack # pylint: disable=protected-access
@tf_export("enable_eager_execution")
def enable_eager_execution(config=None,
device_policy=None,
execution_mode=None):
"""Enables eager execution for the lifetime of this program.
Eager execution provides an imperative interface to TensorFlow. With eager
execution enabled, TensorFlow functions execute operations immediately (as
opposed to adding to a graph to be executed later in a @{tf.Session}) and
return concrete values (as opposed to symbolic references to a node in a
computational graph).
For example:
```python
tf.enable_eager_execution()
# After eager execution is enabled, operations are executed as they are
# defined and Tensor objects hold concrete values, which can be accessed as
# numpy.ndarray`s through the numpy() method.
assert tf.multiply(6, 7).numpy() == 42
```
Eager execution cannot be enabled after TensorFlow APIs have been used to
create or execute graphs. It is typically recommended to invoke this function
at program startup and not in a library (as most libraries should be usable
both with and without eager execution).
Args:
config: (Optional.) A @{tf.ConfigProto} to use to configure the environment
in which operations are executed. Note that @{tf.ConfigProto} is also
used to configure graph execution (via @{tf.Session}) and many options
within `tf.ConfigProto` are not implemented (or are irrelevant) when
eager execution is enabled.
device_policy: (Optional.) Policy controlling how operations requiring
inputs on a specific device (e.g., a GPU 0) handle inputs on a different
device (e.g. GPU 1 or CPU). When set to None, an appropriate value will be
picked automatically. The value picked may change between TensorFlow
releases.
Valid values:
- tf.contrib.eager.DEVICE_PLACEMENT_EXPLICIT: raises an error if the
placement is not correct.
- tf.contrib.eager.DEVICE_PLACEMENT_WARN: copies the tensors which are not
on the right device but logs a warning.
- tf.contrib.eager.DEVICE_PLACEMENT_SILENT: silently copies the tensors.
Note that this may hide performance problems as there is no notification
provided when operations are blocked on the tensor being copied between
devices.
- tf.contrib.eager.DEVICE_PLACEMENT_SILENT_FOR_INT32: silently copies
int32 tensors, raising errors on the other ones.
execution_mode: (Optional.) Policy controlling how operations dispatched are
actually executed. When set to None, an appropriate value will be picked
automatically. The value picked may change between TensorFlow releases.
Valid values:
- tf.contrib.eager.SYNC: executes each operation synchronously.
- tf.contrib.eager.ASYNC: executes each operation asynchronously. These
operations may return "non-ready" handles.
Raises:
ValueError: If eager execution is enabled after creating/executing a
TensorFlow graph, or if options provided conflict with a previous call
to this function.
"""
return enable_eager_execution_internal(
config=config,
device_policy=device_policy,
execution_mode=execution_mode,
server_def=None)
def enable_eager_execution_internal(config=None,
device_policy=None,
execution_mode=None,
server_def=None):
"""Enables eager execution for the lifetime of this program.
Most of the doc string for enable_eager_execution is relevant here as well.
Args:
config: See enable_eager_execution doc string
device_policy: See enable_eager_execution doc string
execution_mode: See enable_eager_execution doc string
server_def: (Optional.) A tensorflow::ServerDef proto.
Enables execution on remote devices. GrpcServers need to be started by
creating an identical server_def to this, and setting the appropriate
task_indexes, so that the servers can communicate. It will then be
possible to execute operations on remote devices.
Raises:
ValueError
"""
if config is not None and not isinstance(config, config_pb2.ConfigProto):
raise TypeError(
"config must be a tf.ConfigProto, but got %s" % type(config))
if device_policy not in (None, context.DEVICE_PLACEMENT_EXPLICIT,
context.DEVICE_PLACEMENT_WARN,
context.DEVICE_PLACEMENT_SILENT,
context.DEVICE_PLACEMENT_SILENT_FOR_INT32):
raise ValueError(
"device_policy must be one of None, tf.contrib.eager.DEVICE_PLACEMENT_*"
)
if execution_mode not in (None, context.SYNC, context.ASYNC):
raise ValueError(
"execution_mode must be one of None, tf.contrib.eager.SYNC, "
"tf.contrib.eager.ASYNC")
# pylint: disable=protected-access
if context._default_mode == context.GRAPH_MODE:
graph_mode_has_been_used = (
_default_session_stack.stack
or len(get_default_graph().get_operations()) > 0) # pylint: disable=g-explicit-length-test
if graph_mode_has_been_used:
raise ValueError(
"tf.enable_eager_execution must be called at program startup.")
context._default_mode = context.EAGER_MODE
if context._context is None:
context._context = context.Context(
config=config,
device_policy=device_policy,
execution_mode=execution_mode,
server_def=server_def)
elif ((config is not None and config is not context._context._config) or
(device_policy is not None and
device_policy is not context._context._device_policy) or
(execution_mode is not None and
execution_mode is not context._context._execution_mode)):
raise ValueError("Trying to change the options of an active eager"
" execution. Context config: %s, specified config:"
" %s. Context device policy: %s, specified device"
" policy: %s. Context execution mode: %s, "
" specified execution mode %s." %
(context._context._config, config,
context._context._device_policy, device_policy,
context._context._execution_mode, execution_mode))
else:
raise ValueError(
"tf.enable_eager_execution must be called at program startup.")
# Monkey patch to get rid of an unnecessary conditional since the context is
# now initialized.
context.context = context.context_safe
def eager_run(main=None, argv=None):
"""Runs the program with an optional main function and argv list.
The program will run with eager execution enabled.
Example:
```python
import tensorflow as tf
# Import subject to future changes:
from tensorflow.contrib.eager.python import tfe
def main(_):
u = tf.constant(6.0)
v = tf.constant(7.0)
print(u * v)
if __name__ == "__main__":
tfe.run()
```
Args:
main: the main function to run.
argv: the arguments to pass to it.
"""
enable_eager_execution()
app.run(main, argv)
@tf_export("reset_default_graph")
def reset_default_graph():
"""Clears the default graph stack and resets the global default graph.
NOTE: The default graph is a property of the current thread. This
function applies only to the current thread. Calling this function while
a `tf.Session` or `tf.InteractiveSession` is active will result in undefined
behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects
after calling this function will result in undefined behavior.
Raises:
AssertionError: If this function is called within a nested graph.
"""
if not _default_graph_stack.is_cleared():
raise AssertionError("Do not use tf.reset_default_graph() to clear "
"nested graphs. If you need a cleared graph, "
"exit the nesting and create a new graph.")
_default_graph_stack.reset()
@tf_export("get_default_graph")
def get_default_graph():
"""Returns the default graph for the current thread.
The returned graph will be the innermost graph on which a
`Graph.as_default()` context has been entered, or a global default
graph if none has been explicitly created.
NOTE: The default graph is a property of the current thread. If you
create a new thread, and wish to use the default graph in that
thread, you must explicitly add a `with g.as_default():` in that
thread's function.
Returns:
The default `Graph` being used in the current thread.
"""
return _default_graph_stack.get_default()
def has_default_graph():
"""Returns True if there is a default graph."""
return len(_default_graph_stack.stack) >= 1
def get_name_scope():
"""Returns the current name scope in the default_graph.
For example:
```python
with tf.name_scope('scope1'):
with tf.name_scope('scope2'):
print(tf.get_name_scope())
```
would print the string `scope1/scope2`.
Returns:
A string representing the current name scope.
"""
if context.executing_eagerly():
return context.context().scope_name.rstrip("/")
return get_default_graph().get_name_scope()
def _assert_same_graph(original_item, item):
"""Fail if the 2 items are from different graphs.
Args:
original_item: Original item to check against.
item: Item to check.
Raises:
ValueError: if graphs do not match.
"""
if original_item.graph is not item.graph:
raise ValueError("%s must be from the same graph as %s." % (item,
original_item))
def _get_graph_from_inputs(op_input_list, graph=None):
"""Returns the appropriate graph to use for the given inputs.
This library method provides a consistent algorithm for choosing the graph
in which an Operation should be constructed:
1. If the default graph is being used to construct a function, we
use the default graph.
2. If the "graph" is specified explicitly, we validate that all of the inputs
in "op_input_list" are compatible with that graph.
3. Otherwise, we attempt to select a graph from the first Operation-
or Tensor-valued input in "op_input_list", and validate that all other
such inputs are in the same graph.
4. If the graph was not specified and it could not be inferred from
"op_input_list", we attempt to use the default graph.
Args:
op_input_list: A list of inputs to an operation, which may include `Tensor`,
`Operation`, and other objects that may be converted to a graph element.
graph: (Optional) The explicit graph to use.
Raises:
TypeError: If op_input_list is not a list or tuple, or if graph is not a
Graph.
ValueError: If a graph is explicitly passed and not all inputs are from it,
or if the inputs are from multiple graphs, or we could not find a graph
and there was no default graph.
Returns:
The appropriate graph to use for the given inputs.
"""
if get_default_graph().building_function:
return get_default_graph()
op_input_list = tuple(op_input_list) # Handle generators correctly
if graph and not isinstance(graph, Graph):
raise TypeError("Input graph needs to be a Graph: %s" % graph)
# 1. We validate that all of the inputs are from the same graph. This is
# either the supplied graph parameter, or the first one selected from one
# the graph-element-valued inputs. In the latter case, we hold onto
# that input in original_graph_element so we can provide a more
# informative error if a mismatch is found.
original_graph_element = None
for op_input in op_input_list:
# Determine if this is a valid graph_element.
# TODO(josh11b): Note that we exclude subclasses of Tensor. Need to clean this
# up.
graph_element = None
if (isinstance(op_input, (Operation, _TensorLike)) and
((not isinstance(op_input, Tensor)) or type(op_input) == Tensor)): # pylint: disable=unidiomatic-typecheck
graph_element = op_input
else:
graph_element = _as_graph_element(op_input)
if graph_element is not None:
if not graph:
original_graph_element = graph_element
graph = graph_element.graph
elif original_graph_element is not None:
_assert_same_graph(original_graph_element, graph_element)
elif graph_element.graph is not graph:
raise ValueError("%s is not from the passed-in graph." % graph_element)
# 2. If all else fails, we use the default graph, which is always there.
return graph or get_default_graph()
@tf_export("GraphKeys")
class GraphKeys(object):
"""Standard names to use for graph collections.
The standard library uses various well-known names to collect and
retrieve values associated with a graph. For example, the
`tf.Optimizer` subclasses default to optimizing the variables
collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is
specified, but it is also possible to pass an explicit list of
variables.
The following standard keys are defined:
* `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared
across distributed environment (model variables are subset of these). See
@{tf.global_variables}
for more details.
Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`,
and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`.
* `LOCAL_VARIABLES`: the subset of `Variable` objects that are local to each
machine. Usually used for temporarily variables, like counters.
Note: use `tf.contrib.framework.local_variable` to add to this collection.
* `MODEL_VARIABLES`: the subset of `Variable` objects that are used in the
model for inference (feed forward). Note: use
`tf.contrib.framework.model_variable` to add to this collection.
* `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will
be trained by an optimizer. See
@{tf.trainable_variables}
for more details.
* `SUMMARIES`: the summary `Tensor` objects that have been created in the
graph. See
@{tf.summary.merge_all}
for more details.
* `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to
produce input for a computation. See
@{tf.train.start_queue_runners}
for more details.
* `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also
keep moving averages. See
@{tf.moving_average_variables}
for more details.
* `REGULARIZATION_LOSSES`: regularization losses collected during graph
construction.
The following standard keys are _defined_, but their collections are **not**
automatically populated as many of the others are:
* `WEIGHTS`
* `BIASES`
* `ACTIVATIONS`
"""
# Key to collect Variable objects that are global (shared across machines).
# Default collection for all variables, except local ones.
GLOBAL_VARIABLES = "variables"
# Key to collect local variables that are local to the machine and are not
# saved/restored.
LOCAL_VARIABLES = "local_variables"
# Key to collect local variables which are used to accumulate interal state
# to be used in tf.metrics.*.
METRIC_VARIABLES = "metric_variables"
# Key to collect model variables defined by layers.
MODEL_VARIABLES = "model_variables"
# Key to collect Variable objects that will be trained by the
# optimizers.
TRAINABLE_VARIABLES = "trainable_variables"
# Key to collect summaries.
SUMMARIES = "summaries"
# Key to collect QueueRunners.
QUEUE_RUNNERS = "queue_runners"
# Key to collect table initializers.
TABLE_INITIALIZERS = "table_initializer"
# Key to collect asset filepaths. An asset represents an external resource
# like a vocabulary file.
ASSET_FILEPATHS = "asset_filepaths"
# Key to collect Variable objects that keep moving averages.
MOVING_AVERAGE_VARIABLES = "moving_average_variables"
# Key to collect regularization losses at graph construction.
REGULARIZATION_LOSSES = "regularization_losses"
# Key to collect concatenated sharded variables.
CONCATENATED_VARIABLES = "concatenated_variables"
# Key to collect savers.
SAVERS = "savers"
# Key to collect weights
WEIGHTS = "weights"
# Key to collect biases
BIASES = "biases"
# Key to collect activations
ACTIVATIONS = "activations"
# Key to collect update_ops
UPDATE_OPS = "update_ops"
# Key to collect losses
LOSSES = "losses"
# Key to collect BaseSaverBuilder.SaveableObject instances for checkpointing.
SAVEABLE_OBJECTS = "saveable_objects"
# Key to collect all shared resources used by the graph which need to be
# initialized once per cluster.
RESOURCES = "resources"
# Key to collect all shared resources used in this graph which need to be
# initialized once per session.
LOCAL_RESOURCES = "local_resources"
# Trainable resource-style variables.
TRAINABLE_RESOURCE_VARIABLES = "trainable_resource_variables"
# Key to indicate various ops.
INIT_OP = "init_op"
LOCAL_INIT_OP = "local_init_op"
READY_OP = "ready_op"
READY_FOR_LOCAL_INIT_OP = "ready_for_local_init_op"
SUMMARY_OP = "summary_op"
GLOBAL_STEP = "global_step"
# Used to count the number of evaluations performed during a single evaluation
# run.
EVAL_STEP = "eval_step"
TRAIN_OP = "train_op"
# Key for control flow context.
COND_CONTEXT = "cond_context"
WHILE_CONTEXT = "while_context"
# Used to store v2 summary names.
_SUMMARY_COLLECTION = "_SUMMARY_V2"
# List of all collections that keep track of variables.
_VARIABLE_COLLECTIONS = [
GLOBAL_VARIABLES,
LOCAL_VARIABLES,
METRIC_VARIABLES,
MODEL_VARIABLES,
TRAINABLE_VARIABLES,
MOVING_AVERAGE_VARIABLES,
CONCATENATED_VARIABLES,
TRAINABLE_RESOURCE_VARIABLES,
]
# Key for streaming model ports.
# NOTE(yuanbyu): internal and experimental.
_STREAMING_MODEL_PORTS = "streaming_model_ports"
@decorator_utils.classproperty
def VARIABLES(cls): # pylint: disable=no-self-argument
logging.log_first_n(logging.WARN,
"VARIABLES collection name is deprecated, please use "
"GLOBAL_VARIABLES instead; VARIABLES will be removed "
"after 2017-03-02.", 1)
return cls.GLOBAL_VARIABLES
@tf_export("add_to_collection")
def add_to_collection(name, value):
"""Wrapper for `Graph.add_to_collection()` using the default graph.
See @{tf.Graph.add_to_collection}
for more details.
Args:
name: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collection.
@compatibility(eager)
Collections are only supported in eager when variables are created inside an
EagerVariableStore (e.g. as part of a layer or template).
@end_compatibility
"""
get_default_graph().add_to_collection(name, value)
@tf_export("add_to_collections")
def add_to_collections(names, value):
"""Wrapper for `Graph.add_to_collections()` using the default graph.
See @{tf.Graph.add_to_collections}
for more details.
Args:
names: The key for the collections. The `GraphKeys` class
contains many standard names for collections.
value: The value to add to the collections.
@compatibility(eager)
Collections are only supported in eager when variables are created inside an
EagerVariableStore (e.g. as part of a layer or template).
@end_compatibility
"""
get_default_graph().add_to_collections(names, value)
@tf_export("get_collection_ref")
def get_collection_ref(key):
"""Wrapper for `Graph.get_collection_ref()` using the default graph.
See @{tf.Graph.get_collection_ref}
for more details.
Args:
key: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
Returns:
The list of values in the collection with the given `name`, or an empty
list if no value has been added to that collection. Note that this returns
the collection list itself, which can be modified in place to change the
collection.
@compatibility(eager)
Collections are not supported when eager execution is enabled.
@end_compatibility
"""
return get_default_graph().get_collection_ref(key)
@tf_export("get_collection")
def get_collection(key, scope=None):
"""Wrapper for `Graph.get_collection()` using the default graph.
See @{tf.Graph.get_collection}
for more details.
Args:
key: The key for the collection. For example, the `GraphKeys` class
contains many standard names for collections.
scope: (Optional.) If supplied, the resulting list is filtered to include
only items whose `name` attribute matches using `re.match`. Items
without a `name` attribute are never returned if a scope is supplied and
the choice or `re.match` means that a `scope` without special tokens
filters by prefix.
Returns:
The list of values in the collection with the given `name`, or
an empty list if no value has been added to that collection. The
list contains the values in the order under which they were
collected.
@compatibility(eager)
Collections are not supported when eager execution is enabled.
@end_compatibility
"""
return get_default_graph().get_collection(key, scope)
def get_all_collection_keys():
"""Returns a list of collections used in the default graph."""
return get_default_graph().get_all_collection_keys()
name_scope_cache = {}
# Named like a function for backwards compatibility with the
# @tf_contextlib.contextmanager version, which was switched to a class to avoid
# some object creation overhead.
@tf_export("name_scope", "keras.backend.name_scope")
class name_scope(object): # pylint: disable=invalid-name
"""A context manager for use when defining a Python op.
This context manager validates that the given `values` are from the
same graph, makes that graph the default graph, and pushes a
name scope in that graph (see
@{tf.Graph.name_scope}
for more details on that).
For example, to define a new Python op called `my_op`:
```python
def my_op(a, b, c, name=None):
with tf.name_scope(name, "MyOp", [a, b, c]) as scope:
a = tf.convert_to_tensor(a, name="a")
b = tf.convert_to_tensor(b, name="b")
c = tf.convert_to_tensor(c, name="c")
# Define some computation that uses `a`, `b`, and `c`.
return foo_op(..., name=scope)
```
"""
@property
def name(self):
return self._name
def __init__(self, name, default_name=None, values=None):
"""Initialize the context manager.
Args:
name: The name argument that is passed to the op function.
default_name: The default name to use if the `name` argument is `None`.
values: The list of `Tensor` arguments that are passed to the op function.
"""
self._name = default_name if name is None else name
self._default_name = default_name
self._values = values
self._ctx = context.context()
self._in_eager_mode = self._ctx.executing_eagerly()
def __enter__(self):
"""Start the scope block.
Returns:
The scope name.
Raises:
ValueError: if neither `name` nor `default_name` is provided
but `values` are.
"""
if self._in_eager_mode:
self._old_name = self._ctx.scope_name
if not self._name:
scope_name = ""
else:
cache_key = self._name, self._old_name, self._default_name
if cache_key in name_scope_cache:
self._ctx.scope_name = name_scope_cache[cache_key]
return self._ctx.scope_name
elif self._name[-1] == "/":
# A trailing slash breaks out of nested name scopes, indicating a
# fully specified scope name, for compatibility with Graph.name_scope.
scope_name = self._name
else:
name_with_trailing_slash = self._name + "/"
scope_name = (
self._old_name + name_with_trailing_slash
if self._old_name else name_with_trailing_slash)
name_scope_cache[cache_key] = scope_name
self._ctx.scope_name = scope_name
return scope_name
else:
if self._name is None and self._values is not None:
# We only raise an error if values is not None (provided) because
# currently tf.name_scope(None) (values=None then) is sometimes used as
# an idiom to reset to top scope.
raise ValueError(
"At least one of name (%s) and default_name (%s) must be provided."
% (self._name, self._default_name))
if self._values is None:
self._values = []
g = _get_graph_from_inputs(self._values)
self._g_manager = g.as_default()
self._g_manager.__enter__()
try:
self._name_scope = g.name_scope(self._name)
return self._name_scope.__enter__()
except:
self._g_manager.__exit__(*sys.exc_info())
raise
def __exit__(self, type_arg, value_arg, traceback_arg):
if self._in_eager_mode:
self._ctx.scope_name = self._old_name
else:
self._name_scope.__exit__(type_arg, value_arg, traceback_arg)
self._g_manager.__exit__(type_arg, value_arg, traceback_arg)
return False # False values do not suppress exceptions
def strip_name_scope(name, export_scope):
"""Removes name scope from a name.
Args:
name: A `string` name.
export_scope: Optional `string`. Name scope to remove.
Returns:
Name with name scope removed, or the original name if export_scope
is None.
"""
if export_scope:
if export_scope[-1] == "/":
export_scope = export_scope[:-1]
try:
# Strips export_scope/, export_scope///,
# ^export_scope/, loc:@export_scope/.
str_to_replace = r"([\^]|loc:@|^)" + export_scope + r"[\/]+(.*)"
return re.sub(str_to_replace, r"\1\2", compat.as_str(name), count=1)
except TypeError as e:
# If the name is not of a type we can process, simply return it.
logging.warning(e)
return name
else:
return name
def prepend_name_scope(name, import_scope):
"""Prepends name scope to a name.
Args:
name: A `string` name.
import_scope: Optional `string`. Name scope to add.
Returns:
Name with name scope added, or the original name if import_scope
is None.
"""
if import_scope:
if import_scope[-1] == "/":
import_scope = import_scope[:-1]
try:
str_to_replace = r"([\^]|loc:@|^)(.*)"
return re.sub(str_to_replace, r"\1" + import_scope + r"/\2",
compat.as_str(name))
except TypeError as e:
# If the name is not of a type we can process, simply return it.
logging.warning(e)
return name
else:
return name
# pylint: disable=g-doc-return-or-yield
# pylint: disable=not-context-manager
@tf_export("op_scope")
@tf_contextlib.contextmanager
def op_scope(values, name, default_name=None):
"""DEPRECATED. Same as name_scope above, just different argument order."""
logging.warn("tf.op_scope(values, name, default_name) is deprecated,"
" use tf.name_scope(name, default_name, values)")
with name_scope(name, default_name=default_name, values=values) as scope:
yield scope
_proto_function_registry = registry.Registry("proto functions")
def register_proto_function(collection_name,
proto_type=None,
to_proto=None,
from_proto=None):
"""Registers `to_proto` and `from_proto` functions for collection_name.
`to_proto` function converts a Python object to the corresponding protocol
buffer, and returns the protocol buffer.
`from_proto` function converts protocol buffer into a Python object, and
returns the object..
Args:
collection_name: Name of the collection.
proto_type: Protobuf type, such as `saver_pb2.SaverDef`,
`variable_pb2.VariableDef`, `queue_runner_pb2.QueueRunnerDef`..
to_proto: Function that implements Python object to protobuf conversion.
from_proto: Function that implements protobuf to Python object conversion.
"""
if to_proto and not callable(to_proto):
raise TypeError("to_proto must be callable.")
if from_proto and not callable(from_proto):
raise TypeError("from_proto must be callable.")
_proto_function_registry.register((proto_type, to_proto, from_proto),
collection_name)
def get_collection_proto_type(collection_name):
"""Returns the proto_type for collection_name."""
try:
return _proto_function_registry.lookup(collection_name)[0]
except LookupError:
return None
def get_to_proto_function(collection_name):
"""Returns the to_proto function for collection_name."""
try:
return _proto_function_registry.lookup(collection_name)[1]
except LookupError:
return None
def get_from_proto_function(collection_name):
"""Returns the from_proto function for collection_name."""
try:
return _proto_function_registry.lookup(collection_name)[2]
except LookupError:
return None
def _operation_conversion_error(op, dtype=None, name=None, as_ref=False):
"""Produce a nice error if someone converts an Operation to a Tensor."""
raise TypeError(("Can't convert Operation '%s' to Tensor "
"(target dtype=%r, name=%r, as_ref=%r)") % (op.name, dtype,
name, as_ref))
register_tensor_conversion_function(Operation, _operation_conversion_error)


6.6 Implementation and Analysis of
Queues
The structure
Queue is the queue data structure. It is
implemented as a typedef to List (see Example
6.3), just as was described for stacks.
Example 6.3.
Header for the Queue Abstract Datatype /*****************************************************************************
* *
* ------------------------------- queue.h -------------------------------- *
* *
*****************************************************************************/
#ifndef QUEUE_H
#define QUEUE_H
#include <stdlib.h>
#include "list.h"
/*****************************************************************************
* *
* Implement queues as linked lists. *
* *
*****************************************************************************/
typedef List Queue;
/*****************************************************************************
* *
* --------------------------- Public Interface --------------------------- *
* *
*****************************************************************************/
#define queue_init list_init
#define queue_destroy list_destroy
int queue_enqueue(Queue *queue, const void *data);
int queue_dequeue(Queue *queue, void **data);
#define queue_peek(queue) ((queue)->head == NULL ? NULL : (queue)->head->data)
#define queue_size list_size
#endif
6.6.1 queue_init
The queue_init operation initializes a
queue so that it can be used in other operations (see Example
6.3). Since a queue is a linked list and requires the same
initialization, queue_init is
defined to list_init.
The runtime complexity of queue_init is the same as list_init, or O (1).
6.6.2 queue_destroy
The queue_destroy operation destroys a
queue (see Example
6.3). Since a queue is a linked list and requires being
destroyed in the same manner, queue_destroy is defined to list_destroy.
The runtime complexity of queue_destroy is the same as list_destroy, or O (n),
where n is the number of
elements in the queue.
6.6.3 queue_enqueue
The queue_enqueue operation enqueues an
element at the tail of a queue by calling list_ins_next to insert an element pointing to
data at the tail of the list (see Example
6.4).
The runtime complexity of queue_enqueue is the same as list_ins_next, or O (1).
6.6.4 queue_dequeue
The queue_dequeue operation dequeues an
element from the head of a queue by calling list_rem_next to remove the element at the head of the
list (see Example
6.4). The list_rem_next
operation sets data to point to the data from
the element removed.
The runtime complexity of queue_dequeue is the same as list_rem_next, or O (1).
6.6.5 queue_ peek, queue_size
These macros implement two simple queue
operations (see Example
6.3). The queue_ peek macro
provides a way to inspect the element at the head of a queue
without actually dequeuing it, and queue_size evaluates to the size of a
queue. Both of these operations work by accessing members of
the Queue structure.
The runtime complexity of these operations is
O (1) because accessing members
of a structure is a simple task that runs in a constant amount
of time.
Example 6.4.
Implementation of the Queue Abstract Datatype /*****************************************************************************
* *
* ------------------------------- queue.c -------------------------------- *
* *
*****************************************************************************/
#include <stdlib.h>
#include "list.h"
#include "queue.h"
/*****************************************************************************
* *
* ----------------------------- queue_enqueue ---------------------------- *
* *
*****************************************************************************/
int queue_enqueue(Queue *queue, const void *data) {
/*****************************************************************************
* *
* Enqueue the data. *
* *
*****************************************************************************/
return list_ins_next(queue, list_tail(queue), data);
}
/*****************************************************************************
* *
* ----------------------------- queue_dequeue ---------------------------- *
* *
*****************************************************************************/
int queue_dequeue(Queue *queue, void **data) {
/*****************************************************************************
* *
* Dequeue the data. *
* *
*****************************************************************************/
return list_rem_next(queue, NULL, data);
}
|


Thanks for submitting a message to me.
As long as there's no typos in the email you've provided and your message is genuine, please wait within 24 up to 48 hours for a response.
However, in case if you don't hear back from me within 48 hours, please send me another email and thanks for your patience!


singleton route, on that route the logger is provided with .forChild call You can register a monitor, then log to make sure the monitor is active After that you can go back on main route and see that this monitor is working and not the app monitor anymore This is because LoggerModule is used in singleton mode


WebRTC pseudo simulcast receiver, with hand signaling for Firefox-Firefox(49) or Chrome-Chrome(51)
Connect
Hang Up
Stats
SDP to send:
SDP to send
SDP to receive:
Receive SDP


A Google engineer, speaking to an audience of Google engineers, once described the newly invented Git as:
"a version control system which is expressly designed to make you feel less intelligent" (source)
... but it gets easier with practice!
Nearly all commands follow a common pattern with 3 main parts.
$ ls -l ~
cd
: change directoryls
: list all the filesmkdir
: make directoryrmdir
: remove/delete directorytouch
: create a filerm
: remove a filepwd
: find out the file path of current directory you are in, from the rootterminology note: directory === folder
A little further explanation...
cd folder_name
: moves down into the foldercd path_name
: moves down into the last folder listedcd ..
: moves up one folder levelcd ../../../
: moves up three folderlevelscd ~
: moves to your home directory, no matter where you areGoal: Create a folder named kittens_project
on my desktop
$ cd Desktop
$ mkdir kittens_project
$ cd kittens_project
$ pwd
Version control is a tool that allows you to...
Create anything with other people, from academic papers to entire websites and applications.
Mistakes happen. Wouldn't it be nice if you could see the changes that have been made and go back in time to fix something that went wrong?
Do you have files somewhere that look like this?
Resume-September2016.docx
Resume-for-Duke-job.docx
ResumeOLD.docx
ResumeNEW.docx
ResumeREALLYREALLYNEW.docx
One central server, each client (person) checks out and merges changes to main server
Examples: CVS, Subversion (SVN), Perforce
Each client (person) has a local repository, which they can then reconcile with the main server.
Examples: Git, Mercurial
Set up name and email in gitconfig
$ git config --global user.name "Your Name Here"
# Sets the default name for Git to use when you commit
$ git config --global user.email<EMAIL_ADDRESS># Sets the default email for Git to use when you commit
$ git config --list
Essentially, a Git version of project folder.
Git will track any changes inside of a repository.
$ pwd
$ git status
# should show an error because
# we haven't made it a repository yet!
$ git init
$ git status
git init
will transform any folder into a Git repostiory.git status
returns no errors, it means your folder has successfully been Git-ified!Each of the states of Git corresponds to an area of the Git repo, so here's some vocab:
kitten.txt
$ touch kitten.txt
git status
$ git status
When you make changes to a file or add a new file but haven't added or committed yet
$ git add kitten.txt
git status
$ git status
When you use git add
to let Git know that these are the files you want to 'stage' or prepare for committing.
git status
. Make sure that the changes listed represent exactly what you want to commit.
$ git status
$ git commit -m "Add kitten.txt to repository"
Success!
...a commit is like a snapshot of your project at a current time
Git’s default text editor is vim, and you may sometimes find yourself in there accidentally.
Here are some basic commands:
i
- puts you in editor mode, so you can type the content of your file:wq
- from normal mode, saves and exits:q!
- from normal mode, exits without saving$ git log
commit 6853adc0b6bc35f1a8ca0a6aa5e59c978148819b
Author: Your name<EMAIL_ADDRESS>Date: Tues May 23 16:01:22 2017 -0700
First commit. Added kitten.txt to repository.
:
Type q
to exit the log.
Include a descriptive but succinct message of the changes you have made, in the present tense
$ git commit -m "Add capitalization function for header text"
Main point is: other people need to be able to read your commit history and understand what you were accomplishing at each step of the way
Article: Art of the commitgit init
: turns a folder into a Git repositorygit status
: checks the status of your filesgit add file_name
: adds file to the staging areagit commit -m "your commit message"
: commits your changesgit log
: see your commits so farDon't worry. Git is your friend.
You made some changes to some files (have not git added or committed yet), and realize you don't want those changes!
Open kitten.txt and make some changes or add something new.
You git add
a modified or new file, but realized you don't want it your next commit!
In your text editor, create a new file, and name it possum.txt. Then:
$ git add possum.txt
$ git status
$ git reset possum.txt
$ git status
The file is removed from staging, but your working copy will be unchanged.
You made a commit, but then realize that a piece of code doesn't work, so you just want to uncommit!
Open kitten.txt and make some changes.

Heads up—there are many, many different ways to undo changes. That's what's powerful about Git. Learn more at Atlassian tutorial
A branch is essentially another copy of your repo that will allow you to isolate changes and leave the original copy untouched. You can later choose to combine these changes in whole or part with the "master" copy, or not.
Branches are good for features!
Can be something as big as adding a new section to a site or an app, to a small functionality (a carousel on the homepage)
Branches are cheap!
So, you want to develop a new feature:
Create a new branch called feature
$ git branch
// you should see only * master
$ git checkout -b feature
$ git branch
// you should see * feature and master
git branch
: tells you what branches you have, and *
indicates which branch you are currently ongit checkout -b branch-name
: the -b
creates a new branch, and checkout
will hop you over to that branchAdd new lines to kitten.txt
$ git add kitten.txt
$ git commit -m "Adding changes to feature"
$ git log --oneline
$ git branch
Switch to master branch and look at the commit history
$ git checkout master
$ git log --oneline
Switch to feature branch and look at the commit history
$ git checkout feature
$ git log --oneline
Switch to master and merge changes
$ git checkout master
$ git merge feature
$ git log --oneline
When you merge, you create a new commit on the branch you just merged into
Since your code from your feature branch is merged into master, you don't need the branch anymore!
$ git branch -d feature-branch
Hint: Make sure not to be on the branch you are deleting.
git branch
: lists all your branchesgit branch branch_name
: creates a new branchgit checkout branch_name
: switch to another branchgit checkout -b branch_name
: creates a new branch and hops over to itgit merge branch_name
: merges branch into the current branchgit branch -d branch_name
: deletes branchYou will see this in the affected file your text editor
Here are lines that are either unchanged from the common ancestor,
or cleanly resolved because only one side changed.
<<<<<<< yours:sample.txt
Your changes are reflected here in this section.
=======
Their changes are here in this section, in conflict with yours.
>>>>>>> theirs:sample.txt
And here is another line that is cleanly resolved or unmodified.
Go back to your kittens_project on your desktop
Change the first line in kitten.txt in master branch
$ git add kitten.txt
$ git commit -m "Changing kitten in master"
Now change the first line in kitten.txt in feature branch
$ git checkout feature
# open kitten.txt and change the first line
$ git add kitten.txt
$ git commit -m "Changing kitten in feature"
Merge the changes from master into the feature branch
$ git merge master #remember, you are on the feature branch here
You will be notified of a conflict. Go to the file in your editor and fix the problem. Then add and commit your edits.
The merge conflict occurred because the feature branch (which is based off of master) both had divergent histories for the same file.
GitHub is a Web-based service for storing, sharing, and collaborating on projects managed with Git
Like a social media profile for your code
You can add information and change settings for:
The header of a GitHub repository page includes features that GitHub adds on to Git.
The file listing displays information common to all Git repositories.
Each row contains:
GitHub treats some files as special based on their filenames.
These files are designed to help with collaboration.
Explore the contents of the GDI Dayton website repository
Click the ➕ icon in the upper right corner, and select New repository.
Give the repo a name and a description.
Private repositories require a paid account.
GitHub can create some files for you.
In the button bar above the list of files, select Create new file.
Enter a filename, and your file contents.
When you're finished, write a commit message and commit the new file.
We'll talk about committing directly or creating a new branch later.
You can also upload files that aren't text, like images or videos. (These are called binary files.)
In the button bar above the list of files, select Create new file.
Drag or select one or more files, and commit the changes as you would for creating a file.
Navigate to the file you want to change, and select the pencil icon at the top of the file.
The editor view will open, where you can edit the text and commit your changes.
Markdown is a simple markup language that many tools use to convert to styled text.
Different symbols translate to different HTML elements.
GitHub displays all markdown files as styled HTML. Select the Preview changes tab to see how your file will look.
When you create or edit a file, its path is displayed next to the filename.
At the beginning of the filename field, type the name of the folder followed by /
.
The folder will be added to the path.
You can do this multiple times, and you can delete folders from the path, too.
Binary files like images can't be edited in GitHub, so you can't change their paths!
Instead, you'll have to:
When you try to make changes in a repo you don't control, GitHub will make a fork.
You can also make a fork by selecting the Fork button at the top of the page.
Forking makes a copy of the repo in your account, where you can make changes to your copy however you like. A fork remembers where it came from.
However, new changes in the original repo (usually called the "upstream") will not affect your fork, and changes in your fork will not affect the upstream repo.
You can propose that changes on your fork be applied to the upstream repo by opening a pull request.
If you try to edit a file in the upstream repo, it will give you this option automatically.
Before you make a pull request, GitHub will compare the changes you're proposing (on the 'head') against the repo you want to change (the 'base').
The comparison looks at a specific branch in each repo. (More on those later.)
The comparison also includes a detailed view of all of the changes, called a diff.
When you create a pull request (or PR), you add a comment, explaining your change to the maintainers.
You can work in a branch without affecting the rest of the repo. For example, the "patch-1" branch has changes that the "master" branch does not.
To start making a group of changes together, create a new branch.
The new branch will include all of the changes from the branch you were on when you created it. Usually you will create the branch from "master," or the main branch.
With your new branch selected, you can make changes as usual. When you commit new changes, you'll have the option to commit to the new branch.
When you start committing to the new branch, GitHub will show a prompt to start a new pull request. You can ignore this until you've made all of your changes.
When you create the pull request from your new branch, the diff will show all commits, to all files.
Create a fork of https://github.com/gdidayton/memehub
To merge a pull request, click the Merge pull request button near the bottom of the Conversation tab of the PR.
The changes will be added to the master branch.
Merge conflicts happen when two commits try to change the same thing, and Git isn't sure which change to use.
This often happens when two people PR changes to the same file, and one gets merged first.
When resolving merge conflicts, Git shows the file with both conflicting changes included, bound in special characters.
Edit the file to incorporate the changes as you like, delete the special characters, and mark the file resolved. You'll commit the revised file.
No more merge conflicts! The pull request is ready to merge.
GitHub issues are where collaborators track bugs, propose features, and discuss changes. They are for conversation, and do not actually change code.
Anyone can open or comment on an issue.
Reading a repo's issues is a great way to find out where you can contribute.
GitHub has several options for searching and filtering issues, like finding all issues with a "newbies-only" label.
If you find an issue you'd like to work on, avoid duplicating work by commenting to say you'll volunteer.
Feel free to ask questions if you need clarification before starting!
Make your first open source contribution to the GDI Dayton resources repo!
Some tools for finding newbie-friendly projects and issues:
Some friendly repos for making contributions with little or no code:
Other resources for learning about Git, GitHub, and open source:
Go forth and contribute!


Customize gestures
RMouse + drag left to
RMouse + drag right to
RMouse + drag up to
RMouse + drag down to
Customize key modified gestures
Ctrl + RMouse + drag left to
Ctrl + RMouse + drag right to
Ctrl + RMouse + drag up to
Ctrl + RMouse + drag down to
Gesture detection options
Minimal delta:


SVL_USER_INFO
You can retrieve data about Amazon Redshift database users with the SVL_USER_INFO view.
Table Columns
| Column Name | Data Type | Description |
|---|---|---|
| usename | text | The user name for the role. |
| usesysid | integer | The user ID for the user. |
| usecreatedb | boolean | A value that indicates whether the user has permissions to create databases. |
| usesuper | boolean | A value that indicates whether the user is a superuser. |
| usecatupd | boolean | A value that indicates whether the user can update system catalogs. |
| useconnlimit | text | The number of connections that the user can open. |
| syslogaccess | text | A value that indicates whether the user has access
to the system logs. The two possible values are
RESTRICTED and UNRESTRICTED .
RESTRICTED means that users that are not superusers
can see their own records. UNRESTICTED means that user
that are not superusers can see all records in the system views and
tables to which they have SELECT privileges.
|
| last_ddl_ts | timestamp | The timestamp for the last data definition language (DDL) create statement run by the user. |
Sample Queries
The following command retrieves user information from SVL_USER_INFO.
SELECT * FROM SVL_USER_INFO;


{% extends 'imagersite/layout.html' %} {% block body %}
You have successfully completed registration to IMAGE-Nation
To get started, why not edit your profile, so we can get to know you.


-
endodontist in abingdon virginia
Coins for Anything - Custom Coins, Challenge Coins, Military ...
AT COINS FOR ANYTHING, we can help. you create your own collectible coin. We. have our own Graphic artists who are. ready and able to help your coin .
http://coinsforanything.com/
-
find the main facility override halo
How to Make Your Own Coins on Demand
Oct 14, 2007 . The Australian Royal Mint at Canberra has a really cool machine that lets you make your own coins on demand! It's a huge coin-press, that .
http://coins.about.com/b/2007/10/14/make-your-own-coins-on-demand.htm
-
customized windows boot cd
Custom Copper Minting
Historically used to wage wars and build empires we now bring you die-struck copper coins and medallions that will work to establish and build your own .
http://www.wendellsinc.com/minting/materials/copper.html
-
britannia stakes heritage stakes class 2
7 Biggest Mistakes Coin Collectors Make
Don't make these 7 mistakes that can lessen the value of your collection. 7 tips for coin collectors to build better collections and more fully enjoy the hobby. . teaching someone else about coins is the best way to expand your own knowledge.
http://www.wizardcoinsupply.com/articles/7-biggest-mistakes-coin-collectors-make.html
-
rocket dogs shoe brand
How to make your own Coin Pusher + Measurements - YouTube
Nov 8, 2012 . How to make your own coin pusher (Close-up photos)by coinpushernl 210 views · 7:48. Watch Later coin pushing machine, how to make .
http://www.youtube.com/watch?v=LiRz4_QVU8o
-
government program lost job overseas unemployment
Custom Coins
Let all the members see the draft design first and ask for opinions and suggestions. Remember, this coin will not be for your own use only; it will be used by each .
http://www.ukchallengecoins.com/custom_coins_15.html
-
super mario throwing a fireball
Real life coin block
Mar 22, 2011 . Or maybe you just want a cool place to store your coi. . for the perfect size of the coins can be hard, so we are making our own cardboard tube.
http://www.instructables.com/id/Coin-block/
-
labcorp locations after hours south austin
Quality/Comparison : S.O.S. Coins Custom Coins, Challenge ...
We are not saying that all manufactures that make die struck coins have poor . Send us the artwork you wish to have made into your own coin, and we can get it .
http://www.customcoins.com/custom-coins-qualitycomparison-c-1_66.html
-
journal topics for mp3
Make Your Own Coin | MetaFilter
Aug 1, 2007 . I put the piece of tail on the "heads" side of the coin. This way, I should always get to break when playing pool. Just for good measure, I put the .
http://www.metafilter.com/63462/Make-Your-Own-Coin
-
tuttle christian church tuttle oklahoma
Challenge Coin Design | Challenge Coins R Us
Jan 3, 2012 . We create custom challenge coins that fit your needs. . area with the general challenge coin design, it still demands its own level of attention.
http://www.challengecoinsrus.com/tag/challenge-coin-design/
-
flash cs5 viper download
All Things GIMP: GIMP Tutorial: Making Your Own Coins
Jan 31, 2010 . GIMP Tutorial: Making Your Own Coins. I found Sara's YouTube video on Gimpology.com, unfortunately it was in Italian?(not sure, exactly) and .
http://www.mahvin.com/2010/01/gimp-tutorial-making-your-own-coins.html
-
domino amjet anaheim ca
Coin Supplies - Make Your Own Dansco Album
Dansco Coin Albums & Accessories. Supreme "World Coin Library". Create your own album using pages and blank binders.
http://www.centercoin.com/coin_supplies/dansco_albums/dansco_make_your_own_albums.htm
-
ringtones for blackberry verizon wireless phones
How to Make Your Own Coins & Medallions | eHow.co.uk
How to Make Your Own Coins & Medallions. You don't have to be a precious metalsmith or work in a mint to create your own custom coins and medallions with .
http://www.ehow.co.uk/how_5513591_make-own-coins-medallions.html
-
abengoa quality systems manager
Custom Coins | Challenge Coins | Custom Commemorative Coins
You can use your own artwork, or allow Crown to create a custom coin design for you. These custom coins are perfect for sports, employee recognition, service .
http://www.crownawards.com/StoreFront/PRR.Custom_Coins.cat
-
cannot save pagemaker default file
Making Your Own Geocoin
Geocoins have become very popular items for geocachers to create and use for swag, trade, traveling, and collecting. At some point you might want to create .
http://www.crakeproductions.com/coins/makeyourown.html
-
prosthetic purchasin wit the v a
Coins PinSource Lapel pins
Everyone loves coins. They are great for collecting, showcasing designs and promoting companies and products. Our coins can be made from simple designs or .
http://www.pinsource.com/products/coins/
-
repairing steering pump seals
Design Your Challenge Coin
Custom challenge coins created with free design consultation.
http://www.aviatorgear.com/p-2871-design-your-own-coin.aspx
-
word of grace church pineville
How to Become a Coin Dealer: 12 steps - wikiHow
Many people who become coin dealers do not have specialized training. . a dealer without a collecting background, then you can still build your skill set. . able to buy out the dealer after a while or you may go on to have your own business.
http://www.wikihow.com/Become-a-Coin-Dealer
-
used prijon sea kayak
H.I.P. Pocket Change Web Site - Fun With Coins
There are lots of ways to have fun with coins at home. Below you will find some great activities including arts and . + "Penny for Your Thoughts" Note Cards .
http://www.usmint.gov/Kids/campcoin/funWithCoins.cfm
-
art carved palladium rings
Military Challenge Coins - BUILD-A-COIN.com
Military challenge coins for air force, army and navy available at best prices. . All Navy challenge coins will be different as each unit typically creates their own design. . To quote a request for your military challenge coins visit our QUOTE .
http://www.build-a-coin.com/military-challenge-coins.html


Remember what they are?
Insert
Visual
Command Line
Normal
Remember any commands?
w W
e E
b B
gg G
Remember the commands?
y
p
Insert
'i'
You can start writing behind where your cursor is
'I'
This is like lowercase 'i'
but instead of where you are, you can start writing at the beginning of the line
A good way to remember both of these is:
Insert
'a'
You can start writing right in front of where your cursor is
'A'
This is like lowercase 'a'
but instead of writing where you are
you are able to start writing at the end of the line
A good way to remember both of these is:
append
'o'
This will shift all your text down one line
create an empty line below where you are
and put you in insert mode
'O'
This is like lowercase 'o'
but include your current line in the shift
and put you in insert mode
A good way to remember both of these is:
open
'u'
This one is not a way to go into insert mode
but I figured it would be a good idea to mention
This is a simple one
all it is, is an undo
'U'
Not as used but good to know
This will undo a whole line
'ctrl-r'
since we talked about undo
probably a good idea to mention redo
A good way to remember this one is:
control redo?
Questions ?