function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def __init__(self):
self.status = c_api.TF_NewStatus() | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def __init__(self):
self.graph = c_api.TF_NewGraph()
# Note: when we're destructing the global context (i.e when the process is
# terminating) we may have already deleted other modules. By capturing the
# DeleteGraph function here, we retain the ability to cleanly destroy the
# graph at shutdown, which satisfies leak checkers.
self.deleter = c_api.TF_DeleteGraph | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def __init__(self):
self.options = c_api.TF_NewImportGraphDefOptions() | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def __init__(self, results):
self.results = results | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def __init__(self, func):
self.func = func
# Note: when we're destructing the global context (i.e when the process is
# terminating) we may have already deleted other modules. By capturing the
# DeleteFunction function here, we retain the ability to cleanly destroy the
# Function at shutdown, which satisfies leak checkers.
self.deleter = c_api.TF_DeleteFunction | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def has_been_garbage_collected(self):
return self.func is None | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def __init__(self, buf_string):
self.buffer = c_api.TF_NewBufferFromString(compat.as_bytes(buf_string)) | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def __init__(self):
op_def_proto = op_def_pb2.OpList()
buf = c_api.TF_GetAllOpList()
try:
op_def_proto.ParseFromString(c_api.TF_GetBuffer(buf))
self._api_def_map = c_api.TF_NewApiDefMap(buf)
finally:
c_api.TF_DeleteBuffer(buf)
self._op_per_name = {}
for op in op_def_proto.op:
self._op_per_name[op.name] = op | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def put_api_def(self, text):
c_api.TF_ApiDefMapPut(self._api_def_map, text, len(text)) | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def get_op_def(self, op_name):
if op_name in self._op_per_name:
return self._op_per_name[op_name]
raise ValueError(f"No op_def found for op name {op_name}.") | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def tf_buffer(data=None):
"""Context manager that creates and deletes TF_Buffer.
Example usage:
with tf_buffer() as buf:
# get serialized graph def into buf
...
proto_data = c_api.TF_GetBuffer(buf)
graph_def.ParseFromString(compat.as_bytes(proto_data))
# buf has been deleted
with tf_buffer(some_string) as buf:
c_api.TF_SomeFunction(buf)
# buf has been deleted
Args:
data: An optional `bytes`, `str`, or `unicode` object. If not None, the
yielded buffer will contain this data.
Yields:
Created TF_Buffer
"""
if data:
buf = c_api.TF_NewBufferFromString(compat.as_bytes(data))
else:
buf = c_api.TF_NewBuffer()
try:
yield buf
finally:
c_api.TF_DeleteBuffer(buf) | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def tf_operations(graph):
"""Generator that yields every TF_Operation in `graph`.
Args:
graph: Graph
Yields:
wrapped TF_Operation
"""
# pylint: disable=protected-access
pos = 0
c_op, pos = c_api.TF_GraphNextOperation(graph._c_graph, pos)
while c_op is not None:
yield c_op
c_op, pos = c_api.TF_GraphNextOperation(graph._c_graph, pos)
# pylint: enable=protected-access | tensorflow/tensorflow | [
171949,
87931,
171949,
2300,
1446859160
] |
def setUp(self):
self.asn1Spec = rfc2314.CertificationRequest() | catapult-project/catapult | [
1835,
570,
1835,
1039,
1429033745
] |
def add_arguments(self, parser):
"""
Add arguments to the command parser.
"""
parser.add_argument(
'--course-id', '--course_id',
dest='course_ids',
action='append',
help=u'Migrates transcripts for the list of courses.'
)
parser.add_argument(
'--all-courses', '--all', '--all_courses',
dest='all_courses',
action='store_true',
default=DEFAULT_ALL_COURSES,
help=u'Migrates transcripts to the configured django storage for all courses.'
)
parser.add_argument(
'--from-settings', '--from_settings',
dest='from_settings',
help='Migrate Transcripts with settings set via django admin',
action='store_true',
default=False,
)
parser.add_argument(
'--force-update', '--force_update',
dest='force_update',
action='store_true',
default=DEFAULT_FORCE_UPDATE,
help=u'Force migrate transcripts for the requested courses, overwrite if already present.'
)
parser.add_argument(
'--commit',
dest='commit',
action='store_true',
default=DEFAULT_COMMIT,
help=u'Commits the discovered video transcripts to django storage. '
u'Without this flag, the command will return the transcripts discovered for migration.'
) | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def _get_migration_options(self, options):
"""
Returns the command arguments configured via django admin.
"""
force_update = options['force_update']
commit = options['commit']
courses_mode = get_mutually_exclusive_required_option(options, 'course_ids', 'all_courses', 'from_settings')
if courses_mode == 'all_courses':
course_keys = [course.id for course in modulestore().get_course_summaries()]
elif courses_mode == 'course_ids':
course_keys = map(self._parse_course_key, options['course_ids'])
else:
if self._latest_settings().all_courses:
course_keys = [course.id for course in modulestore().get_course_summaries()]
else:
course_keys = parse_course_keys(self._latest_settings().course_ids.split())
force_update = self._latest_settings().force_update
commit = self._latest_settings().commit
return course_keys, force_update, commit | Stanford-Online/edx-platform | [
41,
19,
41,
1,
1374606346
] |
def main():
opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
for o, a in opts:
if o == '-D':
defs.append(a)
if o == '-U':
undefs.append(a)
if not args:
args = ['-']
for filename in args:
if filename == '-':
process(sys.stdin, sys.stdout)
else:
f = open(filename, 'r')
process(f, sys.stdout)
f.close() | google/google-ctf | [
3196,
457,
3196,
1,
1524844563
] |
def process(fpi, fpo):
keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif')
ok = 1
stack = []
while 1:
line = fpi.readline()
if not line: break
while line[-2:] == '\\\n':
nextline = fpi.readline()
if not nextline: break
line = line + nextline
tmp = line.strip()
if tmp[:1] != '#':
if ok: fpo.write(line)
continue
tmp = tmp[1:].strip()
words = tmp.split()
keyword = words[0]
if keyword not in keywords:
if ok: fpo.write(line)
continue
if keyword in ('ifdef', 'ifndef') and len(words) == 2:
if keyword == 'ifdef':
ko = 1
else:
ko = 0
word = words[1]
if word in defs:
stack.append((ok, ko, word))
if not ko: ok = 0
elif word in undefs:
stack.append((ok, not ko, word))
if ko: ok = 0
else:
stack.append((ok, -1, word))
if ok: fpo.write(line)
elif keyword == 'if':
stack.append((ok, -1, ''))
if ok: fpo.write(line)
elif keyword == 'else' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
else:
s_ko = not s_ko
ok = s_ok
if not s_ko: ok = 0
stack[-1] = s_ok, s_ko, s_word
elif keyword == 'endif' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
del stack[-1]
ok = s_ok
else:
sys.stderr.write('Unknown keyword %s\n' % keyword)
if stack:
sys.stderr.write('stack: %s\n' % stack) | google/google-ctf | [
3196,
457,
3196,
1,
1524844563
] |
def uart_tx():
# fmt: off
# Block with TX deasserted until data available
pull()
# Initialise bit counter, assert start bit for 8 cycles
set(x, 7) .side(0) [7]
# Shift out 8 data bits, 8 execution cycles per bit
label("bitloop")
out(pins, 1) [6]
jmp(x_dec, "bitloop")
# Assert stop bit for 8 cycles total (incl 1 for pull())
nop() .side(1) [6]
# fmt: on | pfalcon/micropython | [
741,
72,
741,
28,
1388317127
] |
def pio_uart_print(sm, s):
for c in s:
sm.put(ord(c)) | pfalcon/micropython | [
741,
72,
741,
28,
1388317127
] |
def assumed_state(self):
"""Return True if unable to access real state of entity."""
return self.gateway.optimistic | tchellomello/home-assistant | [
7,
1,
7,
6,
1467778429
] |
def is_closed(self):
"""Return True if cover is closed."""
set_req = self.gateway.const.SetReq
if set_req.V_DIMMER in self._values:
return self._values.get(set_req.V_DIMMER) == 0
return self._values.get(set_req.V_LIGHT) == STATE_OFF | tchellomello/home-assistant | [
7,
1,
7,
6,
1467778429
] |
def current_cover_position(self):
"""Return current position of cover.
None is unknown, 0 is closed, 100 is fully open.
"""
set_req = self.gateway.const.SetReq
return self._values.get(set_req.V_DIMMER) | tchellomello/home-assistant | [
7,
1,
7,
6,
1467778429
] |
def __init__(self, **kwargs):
super(_Merge, self).__init__(**kwargs)
self.supports_masking = True | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _compute_elemwise_op_output_shape(self, shape1, shape2):
"""Computes the shape of the resultant of an elementwise operation.
Arguments:
shape1: tuple or None. Shape of the first tensor
shape2: tuple or None. Shape of the second tensor
Returns:
expected output shape when an element-wise operation is
carried out on 2 tensors with shapes shape1 and shape2.
tuple or None.
Raises:
ValueError: if shape1 and shape2 are not compatible for
element-wise operations.
"""
if None in [shape1, shape2]:
return None
elif len(shape1) < len(shape2):
return self._compute_elemwise_op_output_shape(shape2, shape1)
elif not shape2:
return shape1
output_shape = list(shape1[:-len(shape2)])
for i, j in zip(shape1[-len(shape2):], shape2):
if i is None or j is None:
output_shape.append(None)
elif i == 1:
output_shape.append(j)
elif j == 1:
output_shape.append(i)
else:
if i != j:
raise ValueError('Operands could not be broadcast '
'together with shapes ' + str(shape1) + ' ' +
str(shape2))
output_shape.append(i)
return tuple(output_shape) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def call(self, inputs):
if self._reshape_required:
reshaped_inputs = []
input_ndims = list(map(K.ndim, inputs))
if None not in input_ndims:
# If ranks of all inputs are available,
# we simply expand each of them at axis=1
# until all of them have the same rank.
max_ndim = max(input_ndims)
for x in inputs:
x_ndim = K.ndim(x)
for _ in range(max_ndim - x_ndim):
x = K.expand_dims(x, 1)
reshaped_inputs.append(x)
return self._merge_function(reshaped_inputs)
else:
# Transpose all inputs so that batch size is the last dimension.
# (batch_size, dim1, dim2, ... ) -> (dim1, dim2, ... , batch_size)
transposed = False
for x in inputs:
x_ndim = K.ndim(x)
if x_ndim is None:
x_shape = K.shape(x)
batch_size = x_shape[0]
new_shape = K.concatenate([x_shape[1:], K.expand_dims(batch_size)])
x_transposed = K.reshape(x,
K.stack([batch_size, K.prod(x_shape[1:])]))
x_transposed = K.permute_dimensions(x_transposed, (1, 0))
x_transposed = K.reshape(x_transposed, new_shape)
reshaped_inputs.append(x_transposed)
transposed = True
elif x_ndim > 1:
dims = list(range(1, x_ndim)) + [0]
reshaped_inputs.append(K.permute_dimensions(x, dims))
transposed = True
else:
# We don't transpose inputs if they are 1D vectors or scalars.
reshaped_inputs.append(x)
y = self._merge_function(reshaped_inputs)
y_ndim = K.ndim(y)
if transposed:
# If inputs have been transposed, we have to transpose the output too.
if y_ndim is None:
y_shape = K.shape(y)
y_ndim = K.shape(y_shape)[0]
batch_size = y_shape[y_ndim - 1]
new_shape = K.concatenate(
[K.expand_dims(batch_size), y_shape[:y_ndim - 1]])
y = K.reshape(y, (-1, batch_size))
y = K.permute_dimensions(y, (1, 0))
y = K.reshape(y, new_shape)
elif y_ndim > 1:
dims = [y_ndim - 1] + list(range(y_ndim - 1))
y = K.permute_dimensions(y, dims)
return y
else:
return self._merge_function(inputs) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def compute_mask(self, inputs, mask=None):
if mask is None:
return None
if not isinstance(mask, list):
raise ValueError('`mask` should be a list.')
if not isinstance(inputs, list):
raise ValueError('`inputs` should be a list.')
if len(mask) != len(inputs):
raise ValueError('The lists `inputs` and `mask` '
'should have the same length.')
if all([m is None for m in mask]):
return None
masks = [K.expand_dims(m, 0) for m in mask if m is not None]
return K.all(K.concatenate(masks, axis=0), axis=0, keepdims=False) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _merge_function(self, inputs):
output = inputs[0]
for i in range(1, len(inputs)):
output += inputs[i]
return output | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _merge_function(self, inputs):
output = inputs[0]
for i in range(1, len(inputs)):
output *= inputs[i]
return output | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _merge_function(self, inputs):
output = inputs[0]
for i in range(1, len(inputs)):
output += inputs[i]
return output / len(inputs) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def _merge_function(self, inputs):
output = inputs[0]
for i in range(1, len(inputs)):
output = K.maximum(output, inputs[i])
return output | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def __init__(self, axis=-1, **kwargs):
super(Concatenate, self).__init__(**kwargs)
self.axis = axis
self.supports_masking = True | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def call(self, inputs):
if not isinstance(inputs, list):
raise ValueError('A `Concatenate` layer should be called '
'on a list of inputs.')
return K.concatenate(inputs, axis=self.axis) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def compute_mask(self, inputs, mask=None):
if mask is None:
return None
if not isinstance(mask, list):
raise ValueError('`mask` should be a list.')
if not isinstance(inputs, list):
raise ValueError('`inputs` should be a list.')
if len(mask) != len(inputs):
raise ValueError('The lists `inputs` and `mask` '
'should have the same length.')
if all([m is None for m in mask]):
return None
# Make a list of masks while making sure
# the dimensionality of each mask
# is the same as the corresponding input.
masks = []
for input_i, mask_i in zip(inputs, mask):
if mask_i is None:
# Input is unmasked. Append all 1s to masks,
# but cast it to bool first
masks.append(K.cast(K.ones_like(input_i), 'bool'))
elif K.ndim(mask_i) < K.ndim(input_i):
# Mask is smaller than the input, expand it
masks.append(K.expand_dims(mask_i))
else:
masks.append(mask_i)
concatenated = K.concatenate(masks, axis=self.axis)
return K.all(concatenated, axis=-1, keepdims=False) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def __init__(self, axes, normalize=False, **kwargs):
super(Dot, self).__init__(**kwargs)
if not isinstance(axes, int):
if not isinstance(axes, (list, tuple)):
raise TypeError('Invalid type for `axes` - '
'should be a list or an int.')
if len(axes) != 2:
raise ValueError('Invalid format for `axes` - '
'should contain two elements.')
if not isinstance(axes[0], int) or not isinstance(axes[1], int):
raise ValueError('Invalid format for `axes` - '
'list elements should be "int".')
self.axes = axes
self.normalize = normalize
self.supports_masking = True | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def call(self, inputs):
x1 = inputs[0]
x2 = inputs[1]
if isinstance(self.axes, int):
if self.axes < 0:
axes = [self.axes % K.ndim(x1), self.axes % K.ndim(x2)]
else:
axes = [self.axes] * 2
else:
axes = []
for i in range(len(self.axes)):
if self.axes[i] < 0:
axes.append(self.axes[i] % K.ndim(inputs[i]))
else:
axes.append(self.axes[i])
if self.normalize:
x1 = K.l2_normalize(x1, axis=axes[0])
x2 = K.l2_normalize(x2, axis=axes[1])
output = K.batch_dot(x1, x2, axes)
return output | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def compute_mask(self, inputs, mask=None):
return None | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def add(inputs, **kwargs):
"""Functional interface to the `Add` layer.
Arguments:
inputs: A list of input tensors (at least 2).
**kwargs: Standard layer keyword arguments.
Returns:
A tensor, the sum of the inputs.
"""
return Add(**kwargs)(inputs) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def average(inputs, **kwargs):
"""Functional interface to the `Average` layer.
Arguments:
inputs: A list of input tensors (at least 2).
**kwargs: Standard layer keyword arguments.
Returns:
A tensor, the average of the inputs.
"""
return Average(**kwargs)(inputs) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def concatenate(inputs, axis=-1, **kwargs):
"""Functional interface to the `Concatenate` layer.
Arguments:
inputs: A list of input tensors (at least 2).
axis: Concatenation axis.
**kwargs: Standard layer keyword arguments.
Returns:
A tensor, the concatenation of the inputs alongside axis `axis`.
"""
return Concatenate(axis=axis, **kwargs)(inputs) | unnikrishnankgs/va | [
1,
5,
1,
10,
1496432585
] |
def __init__(self, fp):
self.palette = [(i, i, i) for i in range(256)]
while True:
s = fp.readline()
if not s:
break
if s[0:1] == b"#":
continue
if len(s) > 100:
raise SyntaxError("bad palette file")
v = [int(x) for x in s.split()]
try:
[i, r, g, b] = v
except ValueError:
[i, r] = v
g = b = r
if 0 <= i <= 255:
self.palette[i] = o8(r) + o8(g) + o8(b)
self.palette = b"".join(self.palette) | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def __init__(self):
self._num_rows = 3
self._num_columns = 2
self._data = [["hello" for j in range(self._num_columns)] for i in range(self._num_rows)] | jeremiedecock/snippets | [
20,
6,
20,
1,
1433499549
] |
def get_num_columns(self):
return self._num_columns | jeremiedecock/snippets | [
20,
6,
20,
1,
1433499549
] |
def set_data(self, row_index, column_index, value):
self._data[row_index][column_index] = value | jeremiedecock/snippets | [
20,
6,
20,
1,
1433499549
] |
def __init__(self, data, parent=None):
super().__init__(parent)
self._data = data # DON'T CALL THIS ATTRIBUTE "data", A QAbstractItemModel METHOD ALREADY HAVE THIS NAME (model.data(index, role)) !!! | jeremiedecock/snippets | [
20,
6,
20,
1,
1433499549
] |
def columnCount(self, parent):
return self._data.get_num_columns() | jeremiedecock/snippets | [
20,
6,
20,
1,
1433499549
] |
def setData(self, index, value, role):
if role == Qt.EditRole:
try:
self._data.set_data(index.row(), index.column(), value)
# The following line are necessary e.g. to dynamically update the QSortFilterProxyModel
self.dataChanged.emit(index, index, [Qt.EditRole])
except Exception as e:
print(e)
return False
return True | jeremiedecock/snippets | [
20,
6,
20,
1,
1433499549
] |
def changedCallback():
print("changed") | jeremiedecock/snippets | [
20,
6,
20,
1,
1433499549
] |
def _redirect_event_creation(category_id, event_type):
anchor = f'create-event:{event_type}:{category_id}'
return redirect(url_for('.display', category_id=category_id, _anchor=anchor)) | indico/indico | [
1446,
358,
1446,
649,
1311774990
] |
def _redirect_to_bootstrap():
# No users in Indico yet? Redirect from index page to bootstrap form
if (request.endpoint == 'categories.display' and not request.view_args['category_id'] and
not User.query.filter_by(is_system=False).has_rows()):
return redirect(url_for('bootstrap.index')) | indico/indico | [
1446,
358,
1446,
649,
1311774990
] |
def __init__(self, x):
self.val = x
self.left = None
self.right = None | jiadaizhao/LeetCode | [
39,
21,
39,
2,
1502171846
] |
def __init__(self, obj):
return obj | thonkify/thonkify | [
17,
1,
17,
3,
1501859450
] |
def __init__(
self, plotly_name="opacitysrc", parent_name="scattercarpet.marker", **kwargs | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
def arrangeWords(self, text: str) -> str:
words = text.split()
table = collections.defaultdict(list)
for word in words:
table[len(word)].append(word)
result = []
for key in sorted(table):
result.extend(table[key])
return ' '.join(result).capitalize() | jiadaizhao/LeetCode | [
39,
21,
39,
2,
1502171846
] |
def __init__(
self,
plotly_name="familysrc",
parent_name="funnelarea.hoverlabel.font",
**kwargs | plotly/plotly.py | [
13052,
2308,
13052,
1319,
1385013188
] |
def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.__init__(self, *args, **kw)
self.log = log
self.value = None | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def GetValue(self):
#self.log.write('MyCustomRenderer.GetValue\n')
return self.value | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def Render(self, rect, dc, state):
if state != 0:
self.log.write('Render: %s, %d\n' % (rect, state))
if not state & dv.DATAVIEW_CELL_SELECTED:
# we'll draw a shaded background to see if the rect correctly
# fills the cell
dc.SetBrush(wx.Brush('light grey'))
dc.SetPen(wx.TRANSPARENT_PEN)
rect.Deflate(1, 1)
dc.DrawRoundedRectangle(rect, 2)
# And then finish up with this helper function that draws the
# text for us, dealing with alignment, font and color
# attributes, etc
value = self.value if self.value else ""
self.RenderText(value,
4, # x-offset, to compensate for the rounded rectangles
rect,
dc,
state # wxDataViewCellRenderState flags
)
return True | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def HasEditorCtrl(self):
self.log.write('HasEditorCtrl')
return True | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def GetValueFromEditorCtrl(self, editor):
self.log.write('GetValueFromEditorCtrl: %s' % editor)
value = editor.GetValue()
return True, value | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def LeftClick(self, pos, cellRect, model, item, col):
self.log.write('LeftClick')
return False | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def __init__(self, parent, log, model=None, data=None):
self.log = log
wx.Panel.__init__(self, parent, -1)
# Create a dataview control
self.dvc = dv.DataViewCtrl(self, style=wx.BORDER_THEME
| dv.DV_ROW_LINES
#| dv.DV_HORIZ_RULES
| dv.DV_VERT_RULES
| dv.DV_MULTIPLE
)
# Create an instance of the model
if model is None:
self.model = TestModel(data, log)
else:
self.model = model
self.dvc.AssociateModel(self.model)
# Now we create some columns.
c0 = self.dvc.AppendTextColumn("Id", 0, width=40)
c0.Alignment = wx.ALIGN_RIGHT
c0.MinWidth = 40
# We'll use our custom renderer for these columns
for title, col, width in [ ('Artist', 1, 170),
('Title', 2, 260),
('Genre', 3, 80)]:
renderer = MyCustomRenderer(self.log, mode=dv.DATAVIEW_CELL_EDITABLE)
column = dv.DataViewColumn(title, renderer, col, width=width)
column.Alignment = wx.ALIGN_LEFT
self.dvc.AppendColumn(column)
# Layout
self.Sizer = wx.BoxSizer(wx.VERTICAL)
self.Sizer.Add(self.dvc, 1, wx.EXPAND) | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def main():
from data import musicdata
app = wx.App()
frm = wx.Frame(None, title="CustomRenderer sample", size=(700,500))
pnl = TestPanel(frm, sys.stdout, data=musicdata)
frm.Show()
app.MainLoop() | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def list_at_resource_group_level(
self,
resource_group_name: str,
filter: Optional[str] = None,
**kwargs: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def prepare_request(next_link=None):
if not next_link: | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def list_at_resource_level(
self,
resource_group_name: str,
resource_provider_namespace: str,
parent_resource_path: str,
resource_type: str,
resource_name: str,
filter: Optional[str] = None,
**kwargs: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def prepare_request(next_link=None):
if not next_link: | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def list_at_subscription_level(
self,
filter: Optional[str] = None,
**kwargs: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def prepare_request(next_link=None):
if not next_link: | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def list_by_scope(
self,
scope: str,
filter: Optional[str] = None,
**kwargs: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def prepare_request(next_link=None):
if not next_link: | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def __init__(self):
self._state = None | tailhook/tilenol | [
60,
11,
60,
7,
1333893143
] |
def update(self):
nval = self._read()
if nval != self._state:
self._state = nval
return True | tailhook/tilenol | [
60,
11,
60,
7,
1333893143
] |
def groups(self):
return self._state | tailhook/tilenol | [
60,
11,
60,
7,
1333893143
] |
def __init__(self, *, filled=False, first_letter=False, right=False):
super().__init__(right=right)
self.filled = filled
self.first_letter = first_letter | tailhook/tilenol | [
60,
11,
60,
7,
1333893143
] |
def check_state(self):
if self.state.dirty:
self.bar.redraw.emit() | tailhook/tilenol | [
60,
11,
60,
7,
1333893143
] |
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def _create_or_update_initial(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
parameters, # type: "_models.IpGroup"
**kwargs # type: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def begin_create_or_update(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
parameters, # type: "_models.IpGroup"
**kwargs # type: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('IpGroup', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def update_groups(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
parameters, # type: "_models.TagsObject"
**kwargs # type: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def _delete_initial(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
**kwargs # type: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def begin_delete(
self,
resource_group_name, # type: str
ip_groups_name, # type: str
**kwargs # type: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {}) | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def list_by_resource_group(
self,
resource_group_name, # type: str
**kwargs # type: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_resource_group.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.Error, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def list(
self,
**kwargs # type: Any | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.Error, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
def __init__(
self, model, inducing_points, variational_distribution, learn_inducing_locations=True, mean_var_batch_dim=None | jrg365/gpytorch | [
3035,
485,
3035,
323,
1497019700
] |
def _expand_inputs(self, x, inducing_points):
# If we haven't explicitly marked a dimension as batch, add the corresponding batch dimension to the input
if self.mean_var_batch_dim is None:
x = x.unsqueeze(-3)
else:
x = x.unsqueeze(self.mean_var_batch_dim - 2)
return super()._expand_inputs(x, inducing_points) | jrg365/gpytorch | [
3035,
485,
3035,
323,
1497019700
] |
def is_number(number, topping_list):
"""Will check that what the user enters is really a number and not a letter, also that it is within our list"""
if number in "0123456789":
number = int(number)
if number <= len(topping_list)-1:
return number | frastlin/PyAudioGame | [
5,
4,
5,
2,
1420973210
] |
def add_topping(key):
"""Will add a topping to your pizza"""
number = is_number(key, storage.toppings)
if number or number == 0:
storage.your_toppings.append(storage.toppings[number])
spk("You added %s to your pizza. Your pizza currently has %s on top" % (storage.toppings[number], storage.your_toppings)) | frastlin/PyAudioGame | [
5,
4,
5,
2,
1420973210
] |
def logic(actions):
"""Press a and d to switch from adding and removing toppings, press 0-9 to deal with the toppings and press space to eat the pizza"""
key = actions['key']
if key == "d":
spk("Press a number to remove a topping from your pizza, press a to add toppings again")
storage.screen[0] = "remove"
storage.did_run = False
elif key == "a":
spk("Press a number to add a topping to your pizza. Press d to remove a topping you don't like")
storage.screen[0] = "add"
storage.did_run = False
elif key == "space":
spk("You sit down to enjoy a yummy pizza. You eat... eat... eat... eat... and are finally done. That was good! Now it's time for another!")
storage.your_toppings = ['cheese']
storage.did_run = False
elif storage.screen[0] == "start":
spk("Welcom to pizza madness! Here you can build your own pizza to eat! Press a to add toppings, press d to remove them and when you are done, press space to eat your yummy pizza!!!")
storage.screen.remove("start")
storage.screen.append("add")
elif storage.screen[0] == "add":
say_message("Please choose a number of toppings to add! Press d to start removing toppings. Toppings are %s" % storage.toppings)
if key:
add_topping(key)
elif storage.screen[0] == "remove" and key:
remove_topping(key) | frastlin/PyAudioGame | [
5,
4,
5,
2,
1420973210
] |
def prng():
global x
x = math.fmod((x + math.pi) ** 2.0, 1.0)
return x | ActiveState/code | [
1884,
686,
1884,
41,
1500923597
] |
def c(n, k):
if k == 0: return 1
if n == 0: return 0
return c(n - 1, k - 1) + c(n - 1, k) | ActiveState/code | [
1884,
686,
1884,
41,
1500923597
] |
def __init__(self, head, codes):
self._head = '' if head == '' else head + ' '
self._codes = codes | cupy/cupy | [
6731,
672,
6731,
478,
1477994085
] |
def __init__(
self, plotly_name="showexponent", parent_name="parcats.line.colorbar", **kwargs | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config | Azure/azure-sdk-for-python | [
3526,
2256,
3526,
986,
1335285972
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.